text
stringlengths 5
1.04M
|
|---|
#include "pch.h"
#include "Game.h"
// base on the video "Let's make 16 games in C++: Arkanoid" by FamTrinli
// https://www.youtube.com/watch?v=U7vSIvLLZi0
//
int main() {
srand((unsigned int)time(0)); // seed random number generator
Game game;
game.run();
return EXIT_SUCCESS;
}
|
//==================================================================================================
/**
Copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_SCALAR_MASK2LOGICAL_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_SCALAR_MASK2LOGICAL_HPP_INCLUDED
#include <boost/simd/function/definition/mask2logical.hpp>
#include <boost/simd/arch/common/generic/function/mask2logical.hpp>
#include <boost/simd/arch/common/scalar/function/mask2logical.hpp>
#endif
|
//
// LocalSearchBase.cpp
// GA
//
// Created by Tom den Ottelander on 07/01/2020.
// Copyright © 2020 Tom den Ottelander. All rights reserved.
//
#include "LocalSearchBase.hpp"
using namespace std;
LocalSearchBase::LocalSearchBase (FitnessFunction * fitFunc, Utility::Order localSearchOrder, float stochasticity, bool loop) : GA(fitFunc), stochasticity(stochasticity), loop(loop), localSearchOrder(localSearchOrder){
isLocalSearchAlgorithm = true;
}
void LocalSearchBase::round(){
Individual ind = population[0];
ind.initialize(fitFunc_ptr->problemType->alphabet);
doLocalSearch(ind, fitFunc_ptr);
roundsCount++;
}
void LocalSearchBase::doLocalSearch(Individual &ind, FitnessFunction * fitfunc, int maxRandomFlips){
bool converged = false;
int randomFlips = 0;
vector<int> alphabet = fitfunc->problemType->alphabet;
do {
converged = true;
int probSize = fitfunc->totalProblemLength;
vector<int> order = Utility::getOrderedArray(probSize, localSearchOrder);
for(int index : order){
int originalLayer = ind.genotype[index];
int newLayer = originalLayer;
if((randomFlips < maxRandomFlips || maxRandomFlips == -1) && Utility::getRand() < stochasticity){
newLayer = Utility::getRand(0, alphabet.size());
ind.genotype[index] = newLayer;
fitfunc->evaluate(ind);
randomFlips += 1;
} else {
float bestFitness = ind.fitness[0];
for(int layertype : alphabet){
if(layertype != originalLayer) {
ind.genotype[index] = layertype;
vector<float> fitness = fitfunc->evaluate(ind);
if(fitness[0] > bestFitness){
newLayer = layertype;
bestFitness = fitness[0];
}
}
}
ind.genotype[index] = newLayer;
ind.fitness[0] = bestFitness;
}
if (newLayer != originalLayer){
converged = false;
}
}
} while(!converged && loop);
}
|
//
// Created by Leonard Koll on 16.05.21.
//
#include "FlyData.h"
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<string, string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vii;
typedef vector<ll> vl;
typedef vector<vl> vvl;
double EPS=1e-9;
int INF=1000000005;
long long INFF=1000000000000000005ll;
double PI=acos(-1);
int dirx[8]={ -1, 0, 0, 1, -1, -1, 1, 1 };
int diry[8]={ 0, 1, -1, 0, -1, 1, -1, 1 };
const ll MOD = 1000000007;
ll sum() { return 0; }
template<typename T, typename... Args>
T sum(T a, Args... args) { return a + sum(args...); }
#define DEBUG fprintf(stderr, "====TESTING====\n")
#define VALUE(x) cerr << "The value of " << #x << " is " << x << endl
#define OUT(x) cout << x << endl
#define OUTH(x) cout << x << " "
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define READ(x) for(auto &(z):x) cin >> z;
#define FOR(a, b, c) for (int(a)=(b); (a) < (c); ++(a))
#define FORN(a, b, c) for (int(a)=(b); (a) <= (c); ++(a))
#define FORD(a, b, c) for (int(a)=(b); (a) >= (c); --(a))
#define FORSQ(a, b, c) for (int(a)=(b); (a) * (a) <= (c); ++(a))
#define FORC(a, b, c) for (char(a)=(b); (a) <= (c); ++(a))
#define EACH(a, b) for (auto&(a) : (b))
#define REP(i, n) FOR(i, 0, n)
#define REPN(i, n) FORN(i, 1, n)
#define MAX(a, b) a=max(a, b)
#define MIN(a, b) a=min(a, b)
#define SQR(x) ((ll)(x) * (x))
#define RESET(a, b) memset(a, b, sizeof(a))
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ALL(v) v.begin(), v.end()
#define ALLA(arr, sz) arr, arr + sz
#define SIZE(v) (int)v.size()
#define SORT(v) sort(ALL(v))
#define REVERSE(v) reverse(ALL(v))
#define SORTA(arr, sz) sort(ALLA(arr, sz))
#define REVERSEA(arr, sz) reverse(ALLA(arr, sz))
#define PERMUTE next_permutation
#define TC(t) while (t--)
#define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL)
#define what_is(x) cerr << #x << " is " << x << endl;
void solve() {
}
int main()
{
FAST_INP;
// #ifndef ONLINE_JUDGE
// freopen("input.txt","r", stdin);
// freopen("output.txt","w", stdout);
// #endif
// int tc; cin >> tc;
// TC(tc) solve();
int n; cin >> n;
vi a(n);
READ(a);
REVERSE(a);
REP(i,n) {
if(i) cout << " ";
cout << a[i];
}
return 0;
}
|
// Copyright 2021 Apex.AI, 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.
#ifndef REFERENCE_SYSTEM__SAMPLE_MANAGEMENT_HPP_
#define REFERENCE_SYSTEM__SAMPLE_MANAGEMENT_HPP_
#include <algorithm>
#include <chrono>
#include <map>
#include <string>
#include <iostream>
#include "reference_system/msg_types.hpp"
bool set_benchmark_mode(const bool has_benchmark_mode, const bool set_value = true)
{
static bool value{false};
if (set_value) {value = has_benchmark_mode;}
return value;
}
bool is_in_benchmark_mode()
{
return set_benchmark_mode(false, false);
}
template<typename SampleTypePointer>
void set_sample(const std::string & node_name, SampleTypePointer & sample)
{
if (is_in_benchmark_mode() ) {return;}
if (sample.size >= message_t::STATS_CAPACITY) {
return;
}
uint64_t idx = sample.size;
++sample.size;
memcpy(
sample.stats[idx].node_name.data(), node_name.data(),
std::min(
node_name.size(),
reference_interfaces::msg::TransmissionStats::NODE_NAME_LENGTH));
sample.stats[idx].timestamp = static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
template<typename SampleTypePointer>
uint64_t get_sample_timestamp(SampleTypePointer & sample)
{
if (is_in_benchmark_mode() || sample->size == 0) {
return 0;
} else {
return sample->stats[sample->size - 1].timestamp;
}
}
template<typename SampleTypePointer, typename SourceType>
void fuse_samples(
const std::string & node_name, SampleTypePointer & destination,
const SourceType & source)
{
if (is_in_benchmark_mode() ) {return;}
destination.size = source->size;
destination.stats = source->stats;
set_sample(node_name, destination);
}
template<typename SampleTypePointer, typename SourceType>
void fuse_samples(
const std::string & node_name, SampleTypePointer & destination,
const SourceType & source1, const SourceType & source2)
{
if (is_in_benchmark_mode() ) {return;}
uint64_t elements_to_copy =
std::min(message_t::STATS_CAPACITY, source1->size + source2->size);
destination.size = elements_to_copy;
destination.stats = source1->stats;
memcpy(
destination.stats.data() + source1->size, source2->stats.data(),
sizeof(reference_interfaces::msg::TransmissionStats) *
(elements_to_copy - source1->size));
set_sample(node_name, destination);
}
template<typename SampleTypePointer>
void print_sample_path(
const std::string & node_name,
const SampleTypePointer & sample)
{
if (is_in_benchmark_mode() || sample->size <= 0) {return;}
struct sample_statistic_t
{
uint64_t number_of_received_samples = 0;
uint64_t number_of_hot_path_samples = 0;
uint64_t timepoint_of_first_received_sample = 0;
struct statistic_value_t
{
uint64_t average = 0;
uint64_t min = std::numeric_limits<uint64_t>::max();
uint64_t max = 0;
void set(const uint64_t value, const uint64_t total_number)
{
average = ((total_number - 1) * average + value) / total_number;
min = std::min(min, value);
max = std::max(max, value);
}
};
statistic_value_t latency;
statistic_value_t hot_path_latency;
};
static std::map<std::string, sample_statistic_t> advanced_statistics;
auto iter = advanced_statistics.find(node_name);
if (iter == advanced_statistics.end() ) {
advanced_statistics[node_name].timepoint_of_first_received_sample =
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
}
advanced_statistics[node_name].number_of_received_samples++;
const uint64_t timestamp_in_ns = static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
std::cout << "----------------------------------------------------------" <<
std::endl;
std::cout << "sample path: " << std::endl;
std::cout << " timepoint node name" << std::endl;
std::map<uint64_t, uint64_t> timestamp2Order;
uint64_t min_time_stamp = std::numeric_limits<uint64_t>::max();
uint64_t max_time_stamp = 0;
for (uint64_t i = 0; i < sample->size; ++i) {
timestamp2Order[sample->stats[i].timestamp] = 0;
min_time_stamp = std::min(min_time_stamp, sample->stats[i].timestamp);
max_time_stamp = std::max(max_time_stamp, sample->stats[i].timestamp);
}
uint64_t i = 0;
for (auto & e : timestamp2Order) {
e.second = i++;
}
for (uint64_t i = 0; i < sample->size; ++i) {
std::cout << " [";
std::cout.width(2);
std::cout << timestamp2Order[sample->stats[i].timestamp];
std::cout << "] " << sample->stats[i].timestamp << " : " <<
sample->stats[i].node_name.data() << std::endl;
}
uint64_t hot_path_latency_in_ns = 0;
bool does_contain_hot_path = false;
for (uint64_t i = 0; i < sample->size; ++i) {
uint64_t idx = sample->size - i - 1;
std::string current_node_name(
reinterpret_cast<const char *>(sample->stats[idx].node_name.data()));
if (current_node_name == "EuclideanClusterDetector") {
hot_path_latency_in_ns = sample->stats[idx].timestamp;
} else if (current_node_name == "FrontLidarDriver" &&
hot_path_latency_in_ns != 0)
{
hot_path_latency_in_ns = hot_path_latency_in_ns - sample->stats[idx].timestamp;
does_contain_hot_path = true;
break;
}
}
uint64_t latency_in_ns = max_time_stamp - min_time_stamp;
advanced_statistics[node_name].latency.set(latency_in_ns,
advanced_statistics[node_name].number_of_received_samples);
uint64_t latency_min_in_ns = advanced_statistics[node_name].latency.min;
uint64_t latency_max_in_ns = advanced_statistics[node_name].latency.max;
uint64_t latency_average_in_ns = advanced_statistics[node_name].latency.average;
std::cout << std::endl;
std::cout << "Statistics:" << std::endl;
std::cout << " destination: " << node_name << std::endl;
std::cout << " current time: " << timestamp_in_ns << std::endl;
std::cout << " latency: " << static_cast<double>(latency_in_ns) / 1000000.0 << " ms" <<
" [ min = " << static_cast<double>(latency_min_in_ns) / 1000000.0 << " ms, max = " <<
static_cast<double>(latency_max_in_ns) / 1000000.0 << " ms, average = " <<
static_cast<double>(latency_average_in_ns) / 1000000.0 << " ms ]" << std::endl;
if (does_contain_hot_path) {
advanced_statistics[node_name].number_of_hot_path_samples++;
advanced_statistics[node_name].hot_path_latency.set(hot_path_latency_in_ns,
advanced_statistics[node_name].number_of_hot_path_samples);
uint64_t hot_path_min_in_ns = advanced_statistics[node_name].hot_path_latency.min;
uint64_t hot_path_max_in_ns = advanced_statistics[node_name].hot_path_latency.max;
uint64_t hot_path_average_in_ns = advanced_statistics[node_name].hot_path_latency.average;
std::cout << " hot path: FrontLidarDriver -> EuclideanClusterDetector" << std::endl;
std::cout << " hot path latency: " <<
static_cast<double>(hot_path_latency_in_ns) / 1000000.0 << " ms" <<
" [ min = " << static_cast<double>(hot_path_min_in_ns) / 1000000.0 << " ms, max = " <<
static_cast<double>(hot_path_max_in_ns) / 1000000.0 << " ms, average = " <<
static_cast<double>(hot_path_average_in_ns) / 1000000.0 << " ms ]" << std::endl;
}
std::cout << "----------------------------------------------------------" <<
std::endl;
std::cout << std::endl;
}
#endif // REFERENCE_SYSTEM__SAMPLE_MANAGEMENT_HPP_
|
#include "App.xaml.h"
#include "OpenGLESPage.xaml.h"
using namespace cocos2d;
App::App()
{
InitializeComponent();
}
void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
{
if (mPage == nullptr)
{
mPage = ref new OpenGLESPage(&mOpenGLES);
}
// Place the page in the current window and ensure that it is active.
Windows::UI::Xaml::Window::Current->Content = mPage;
Windows::UI::Xaml::Window::Current->Activate();
}
|
#include "DataFormats/ForwardDetId/interface/HFNoseDetId.h"
#include "DataFormats/ForwardDetId/interface/HGCalDetId.h"
#include "DataFormats/ForwardDetId/interface/HGCSiliconDetId.h"
#include "DataFormats/ForwardDetId/interface/HGCScintillatorDetId.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "Geometry/HGCalCommonData/interface/HGCalTypes.h"
#include "Geometry/CaloTopology/interface/HGCalTopology.h"
#include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"
//#define EDM_ML_DEBUG
HGCalTopology::HGCalTopology(const HGCalDDDConstants& hdcons, int det) : hdcons_(hdcons) {
sectors_ = hdcons_.sectors();
layers_ = hdcons_.layers(true);
cells_ = hdcons_.maxCells(true);
mode_ = hdcons_.geomMode();
cellMax_ = hdcons_.maxCellUV();
waferOff_ = hdcons_.waferUVMax();
waferMax_ = 2 * waferOff_ + 1;
kHGhalf_ = sectors_ * layers_ * cells_;
firstLay_ = hdcons_.firstLayer();
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
det_ = DetId::Forward;
subdet_ = (ForwardSubdetector)(det);
kHGeomHalf_ = sectors_ * layers_;
types_ = 2;
} else if (det == (int)(DetId::Forward)) {
det_ = DetId::Forward;
subdet_ = HFNose;
kHGeomHalf_ = sectors_ * layers_;
types_ = 3;
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
det_ = (DetId::Detector)(det);
subdet_ = ForwardEmpty;
kHGeomHalf_ = sectors_ * layers_ * cellMax_;
types_ = 2;
} else {
det_ = (DetId::Detector)(det);
subdet_ = ForwardEmpty;
kHGeomHalf_ = sectors_ * layers_;
types_ = 3;
}
kSizeForDenseIndexing = (unsigned int)(2 * kHGhalf_);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "HGCalTopology initialized for detector " << det_ << ":" << subdet_ << " having "
<< sectors_ << " Sectors, " << layers_ << " Layers from " << firstLay_ << ", " << cells_
<< " cells and total channels " << kSizeForDenseIndexing << ":" << (2 * kHGeomHalf_)
<< std::endl;
#endif
}
unsigned int HGCalTopology::allGeomModules() const {
return ((mode_ == HGCalGeometryMode::Trapezoid) ? (unsigned int)(2 * hdcons_.numberCells(true))
: (unsigned int)(2 * hdcons_.wafers()));
}
std::vector<DetId> HGCalTopology::neighbors(const DetId& idin) const {
std::vector<DetId> ids;
HGCalTopology::DecodedDetId id = decode(idin);
if ((mode_ == HGCalGeometryMode::Hexagon8) || (mode_ == HGCalGeometryMode::Hexagon8Full)) {
HGCalTypes::CellType celltype = hdcons_.cellType(id.iType, id.iCell1, id.iCell2);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Type:WaferU:WaferV " << id.iType << ":" << id.iCell1 << ":" << id.iCell2
<< " CellType "
<< static_cast<std::underlying_type<HGCalTypes::CellType>::type>(celltype);
#endif
switch (celltype) {
case (HGCalTypes::CellType::CentralType): {
// cell within the wafer
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 0";
#endif
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 + 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2 + 1);
break;
}
case (HGCalTypes::CellType::BottomLeftEdge): {
// bottom left edge
int wu1(id.iSec1), wv1(id.iSec2 - 1);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int v1 = hdcons_.modifyUV(id.iCell2, id.iType, t1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 1 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << v1;
#endif
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, 2 * N1 - 1, v1 + N1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, 2 * N1 - 1, v1 + N1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 + 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2 + 1);
break;
}
case (HGCalTypes::CellType::LeftEdge): {
// left edege
int wu1(id.iSec1 + 1), wv1(id.iSec2);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int u1 = hdcons_.modifyUV(id.iCell1, id.iType, t1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 2 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << u1;
#endif
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, u1 + N1, 2 * N1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, u1 + N1 - 1, 2 * N1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 + 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2 + 1);
break;
}
case (HGCalTypes::CellType::TopLeftEdge): {
// top left edge
int wu1(id.iSec1 + 1), wv1(id.iSec2 + 1);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int v1 = hdcons_.modifyUV(id.iCell2, id.iType, t1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 3 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << v1;
#endif
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, v1 + 1, v1 + N1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, v1, v1 + N1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 + 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2 + 1);
break;
}
case (HGCalTypes::CellType::TopRightEdge): {
// top right edge
int wu1(id.iSec1), wv1(id.iSec2 + 1);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int v1 = hdcons_.modifyUV(id.iCell2, id.iType, t1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 4 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << v1;
#endif
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, 0, v1 - N1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 + 1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, 0, v1 - N1 + 1);
break;
}
case (HGCalTypes::CellType::RightEdge): {
// right edge
int wu1(id.iSec1 - 1), wv1(id.iSec2);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int u1 = hdcons_.modifyUV(id.iCell1, id.iType, t1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 5 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << u1;
#endif
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, u1 - N1, 0);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, u1 - N1 + 1, 0);
break;
}
case (HGCalTypes::CellType::BottomRightEdge): {
// bottom right edge
int wu1(id.iSec1 - 1), wv1(id.iSec2 - 1);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int u1 = hdcons_.modifyUV(id.iCell1, id.iType, t1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 6 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << u1;
#endif
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, u1 + N1 - 1, u1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, u1 + N1, u1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2 + 1);
break;
}
case (HGCalTypes::CellType::BottomCorner): {
// bottom corner
int wu1(id.iSec1), wv1(id.iSec2 - 1);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int v1 = hdcons_.modifyUV(id.iCell2, id.iType, t1);
int wu2(id.iSec1 - 1), wv2(id.iSec2 - 1);
int t2 = hdcons_.getTypeHex(id.iLay, wu2, wv2);
int N2 = hdcons_.getUVMax(t2);
int u2 = hdcons_.modifyUV(id.iCell1, id.iType, t2);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 11 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << v1 << ":" << t2
<< ":" << N2 << ":" << u2;
#endif
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, 2 * N1 - 1, v1 + N1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, 2 * N1 - 1, v1 + N1);
addHGCSiliconId(ids, id.det, id.zSide, t2, id.iLay, wu2, wv2, u2 + N2, u2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2 + 1);
break;
}
case (HGCalTypes::CellType::BottomLeftCorner): {
// bottom left corner
int wu1(id.iSec1 + 1), wv1(id.iSec2);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int u1 = hdcons_.modifyUV(id.iCell1, id.iType, t1);
int wu2(id.iSec1), wv2(id.iSec2 - 1);
int t2 = hdcons_.getTypeHex(id.iLay, wu2, wv2);
int N2 = hdcons_.getUVMax(t2);
int v2 = hdcons_.modifyUV(id.iCell2, id.iType, t2);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 12 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << u1 << ":" << t2
<< ":" << N2 << ":" << v2;
#endif
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, u1 + N1, 2 * N1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t2, id.iLay, wu2, wv2, 2 * N2 - 1, v2 + N2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t2, id.iLay, wu2, wv2, 2 * N2 - 1, v2 + N2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 + 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2 + 1);
break;
}
case (HGCalTypes::CellType::TopLeftCorner): {
// top left corner
int wu1(id.iSec1 + 1), wv1(id.iSec2 + 1);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int v1 = hdcons_.modifyUV(id.iCell2, id.iType, t1);
int wu2(id.iSec1 + 1), wv2(id.iSec2);
int t2 = hdcons_.getTypeHex(id.iLay, wu2, wv2);
int N2 = hdcons_.getUVMax(t2);
int u2 = hdcons_.modifyUV(id.iCell1, id.iType, t2);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 13 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << v1 << ":" << t2
<< ":" << N2 << ":" << u2;
#endif
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, v1 + 1, N1 + v1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, v1, N1 + v1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t2, id.iLay, wu2, wv2, u2 + N2 - 1, 2 * N2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 + 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2 + 1);
break;
}
case (HGCalTypes::CellType::TopCorner): {
// top corner
int wu1(id.iSec1 + 1), wv1(id.iSec2 + 1);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int v1 = hdcons_.modifyUV(id.iCell2, id.iType, t1);
int wu2(id.iSec1), wv2(id.iSec2 + 1);
int t2 = hdcons_.getTypeHex(id.iLay, wu2, wv2);
int N2 = hdcons_.getUVMax(t2);
int v2 = hdcons_.modifyUV(id.iCell2, id.iType, t2);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 14 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << v1 << ":" << t2
<< ":" << N2 << ":" << v2;
#endif
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, v1 + 1, v1 + N1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, v1, v1 + N1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 + 1);
addHGCSiliconId(ids, id.det, id.zSide, t2, id.iLay, wu2, wv2, 0, v2 - N2 + 1);
break;
}
case (HGCalTypes::CellType::TopRightCorner): {
// top right corner
int wu1(id.iSec1), wv1(id.iSec2 + 1);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int v1 = hdcons_.modifyUV(id.iCell2, id.iType, t1);
int wu2(id.iSec1 - 1), wv2(id.iSec2);
int t2 = hdcons_.getTypeHex(id.iLay, wu2, wv2);
int N2 = hdcons_.getUVMax(t2);
int u2 = hdcons_.modifyUV(id.iCell1, id.iType, t2);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 15 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << v1 << ":" << t2
<< ":" << N2 << ":" << u2;
#endif
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, 0, v1 - N1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, t2, id.iLay, wu2, wv2, u2 - N2, 0);
addHGCSiliconId(ids, id.det, id.zSide, t2, id.iLay, wu2, wv2, u2 - N2 + 1, 0);
break;
}
case (HGCalTypes::CellType::BottomRightCorner): {
// bottom right corner
int wu1(id.iSec1 - 1), wv1(id.iSec2 - 1);
int t1 = hdcons_.getTypeHex(id.iLay, wu1, wv1);
int N1 = hdcons_.getUVMax(t1);
int u1 = hdcons_.modifyUV(id.iCell1, id.iType, t1);
int wu2(id.iSec1 - 1), wv2(id.iSec2);
int t2 = hdcons_.getTypeHex(id.iLay, wu2, wv2);
int N2 = hdcons_.getUVMax(t2);
int u2 = hdcons_.modifyUV(id.iCell1, id.iType, t2);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Cell Type 16 "
<< ":" << wu1 << ":" << wv1 << ":" << t1 << ":" << N1 << ":" << u1 << ":" << t2
<< ":" << N2 << ":" << u2;
#endif
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 + 1, id.iCell2);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, id.iType, id.iLay, id.iSec1, id.iSec2, id.iCell1 - 1, id.iCell2 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t1, id.iLay, wu1, wv1, u1 + N1 - 1, u1 - 1);
addHGCSiliconId(ids, id.det, id.zSide, t2, id.iLay, wu2, wv2, u2 - N2, 0);
addHGCSiliconId(ids, id.det, id.zSide, t2, id.iLay, wu2, wv2, u2 - N2 + 1, 0);
break;
}
default:
// Not valid u, v
int N = hdcons_.getUVMax(id.iType);
edm::LogWarning("HGCalGeom") << "u:v " << id.iCell1 << ":" << id.iCell2 << " Tests " << (id.iCell1 > 2 * N - 1)
<< ":" << (id.iCell2 > 2 * N - 1) << ":" << (id.iCell2 >= (id.iCell1 + N)) << ":"
<< (id.iCell1 > (id.iCell2 + N)) << " ERROR";
}
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
int iphi1 = (id.iCell1 > 1) ? id.iCell1 - 1 : hdcons_.getUVMax(id.iType);
int iphi2 = (id.iCell1 < hdcons_.getUVMax(id.iType)) ? id.iCell1 + 1 : 1;
addHGCSCintillatorId(ids, id.zSide, id.iType, id.iLay, id.iSec1 - 1, id.iCell1);
addHGCSCintillatorId(ids, id.zSide, id.iType, id.iLay, id.iSec1 - 1, iphi1);
addHGCSCintillatorId(ids, id.zSide, id.iType, id.iLay, id.iSec1, iphi1);
addHGCSCintillatorId(ids, id.zSide, id.iType, id.iLay, id.iSec1 + 1, iphi1);
addHGCSCintillatorId(ids, id.zSide, id.iType, id.iLay, id.iSec1 + 1, id.iCell1);
addHGCSCintillatorId(ids, id.zSide, id.iType, id.iLay, id.iSec1 + 1, iphi2);
addHGCSCintillatorId(ids, id.zSide, id.iType, id.iLay, id.iSec1, iphi2);
addHGCSCintillatorId(ids, id.zSide, id.iType, id.iLay, id.iSec1 - 1, iphi2);
}
return ids;
}
uint32_t HGCalTopology::detId2denseId(const DetId& idin) const {
HGCalTopology::DecodedDetId id = decode(idin);
uint32_t idx;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
int type = (id.iType > 0) ? 1 : 0;
idx = (uint32_t)(((id.zSide > 0) ? kHGhalf_ : 0) +
((((id.iCell1 - 1) * layers_ + id.iLay - 1) * sectors_ + id.iSec1) * types_ + type));
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Input Hex " << id.zSide << ":" << id.iLay << ":" << id.iSec1 << ":" << id.iCell1
<< ":" << id.iType << " Constants " << kHGeomHalf_ << ":" << layers_ << ":"
<< sectors_ << ":" << types_ << " o/p " << idx;
#endif
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
idx =
(uint32_t)(((id.zSide > 0) ? kHGhalf_ : 0) +
((((id.iCell1 - 1) * layers_ + id.iLay - firstLay_) * sectors_ + id.iSec1 - 1) * types_ + id.iType));
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Input Trap " << id.zSide << ":" << id.iLay << ":" << id.iSec1 << ":" << id.iCell1
<< ":" << id.iType << " Constants " << kHGeomHalf_ << ":" << layers_ << ":"
<< sectors_ << ":" << types_ << " o/p " << idx;
#endif
} else {
idx =
(uint32_t)(((id.zSide > 0) ? kHGhalf_ : 0) +
(((((id.iCell1 * cellMax_ + id.iCell2) * layers_ + id.iLay - 1) * waferMax_ + id.iSec1 + waferOff_) *
waferMax_ +
id.iSec2 + waferOff_) *
types_ +
id.iType));
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Input Hex8 " << id.zSide << ":" << id.iLay << ":" << id.iSec1 << ":" << id.iSec2
<< ":" << id.iCell1 << ":" << id.iCell2 << ":" << id.iType << " Constants "
<< kHGeomHalf_ << ":" << cellMax_ << ":" << layers_ << ":" << waferMax_ << ":"
<< waferOff_ << ":" << types_ << " o/p " << idx;
#endif
}
return idx;
}
DetId HGCalTopology::denseId2detId(uint32_t hi) const {
HGCalTopology::DecodedDetId id;
if (validHashIndex(hi)) {
id.zSide = ((int)(hi) < kHGhalf_ ? -1 : 1);
int di = ((int)(hi) % kHGhalf_);
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
int type = (di % types_);
id.iType = (type == 0 ? -1 : 1);
id.iSec1 = (((di - type) / types_) % sectors_);
id.iLay = (((((di - type) / types_) - id.iSec1 + 1) / sectors_) % layers_ + 1);
id.iCell1 = (((((di - type) / types_) - id.iSec1 + 1) / sectors_ - id.iLay + 1) / layers_ + 1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Input Hex " << hi << " o/p " << id.zSide << ":" << id.iLay << ":" << id.iType
<< ":" << id.iSec1 << ":" << id.iCell1;
#endif
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
int type = (di % types_);
id.iType = type;
id.iSec1 = (((di - type) / types_) % sectors_) + 1;
id.iLay = (((((di - type) / types_) - id.iSec1 + 1) / sectors_) % layers_ + firstLay_);
id.iCell1 = (((((di - type) / types_) - id.iSec1 + 1) / sectors_ - id.iLay + firstLay_) / layers_ + 1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Input Trap " << hi << " o/p " << id.zSide << ":" << id.iLay << ":" << id.iType
<< ":" << id.iSec1 << ":" << id.iCell1;
#endif
} else {
int type = (di % types_);
id.iType = type;
di = (di - type) / types_;
id.iSec2 = (di % waferMax_) - waferOff_;
di = (di - id.iSec2 - waferOff_) / waferMax_;
id.iSec1 = (di % waferMax_) - waferOff_;
di = (di - id.iSec1 - waferOff_) / waferMax_;
id.iLay = (di % layers_) + 1;
di = (di - id.iLay + 1) / layers_;
id.iCell2 = (di % cellMax_);
id.iCell1 = (di - id.iCell2) / cellMax_;
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Input Hex8 " << hi << " o/p " << id.zSide << ":" << id.iLay << ":" << id.iType
<< ":" << id.iSec1 << ":" << id.iSec2 << ":" << id.iCell1 << ":" << id.iCell2;
#endif
}
}
return encode(id);
}
uint32_t HGCalTopology::detId2denseGeomId(const DetId& idin) const {
HGCalTopology::DecodedDetId id = decode(idin);
uint32_t idx;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
idx = (uint32_t)(((id.zSide > 0) ? kHGeomHalf_ : 0) + (id.iLay - 1) * sectors_ + id.iSec1);
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Geom Hex I/P " << id.zSide << ":" << id.iLay << ":" << id.iSec1 << ":" << id.iType
<< " Constants " << kHGeomHalf_ << ":" << layers_ << ":" << sectors_ << " o/p "
<< idx;
#endif
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
idx = (uint32_t)(((id.zSide > 0) ? kHGeomHalf_ : 0) +
(((id.iLay - firstLay_) * sectors_ + id.iSec1 - 1) * cellMax_ + id.iCell1 - 1));
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Geom Trap I/P " << id.zSide << ":" << id.iLay << ":" << id.iSec1 << ":"
<< id.iCell1 << ":" << id.iType << " Constants " << kHGeomHalf_ << ":" << layers_
<< ":" << firstLay_ << ":" << sectors_ << ":" << cellMax_ << " o/p " << idx;
#endif
} else {
idx = (uint32_t)(((id.zSide > 0) ? kHGeomHalf_ : 0) +
(((id.iLay - 1) * waferMax_ + id.iSec1 + waferOff_) * waferMax_ + id.iSec2 + waferOff_));
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Geom Hex8 I/P " << id.zSide << ":" << id.iLay << ":" << id.iSec1 << ":"
<< id.iSec2 << ":" << id.iType << " Constants " << kHGeomHalf_ << ":" << layers_
<< ":" << waferMax_ << ":" << waferOff_ << " o/p " << idx;
#endif
}
return idx;
}
bool HGCalTopology::valid(const DetId& idin) const {
HGCalTopology::DecodedDetId id = decode(idin);
bool flag;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
flag = (idin.det() == det_ && idin.subdetId() == (int)(subdet_) && id.iCell1 >= 0 && id.iCell1 < cells_ &&
id.iLay > 0 && id.iLay <= layers_ && id.iSec1 >= 0 && id.iSec1 <= sectors_);
if (flag)
flag = hdcons_.isValidHex(id.iLay, id.iSec1, id.iCell1, true);
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
flag = ((idin.det() == det_) && hdcons_.isValidTrap(id.iLay, id.iSec1, id.iCell1));
} else {
flag = ((idin.det() == det_) && hdcons_.isValidHex8(id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2));
}
return flag;
}
bool HGCalTopology::valid(const DetId& idin, int cornerMin) const {
if ((mode_ == HGCalGeometryMode::Hexagon8) || (mode_ == HGCalGeometryMode::Hexagon8Full)) {
HGCalTopology::DecodedDetId id = decode(idin);
bool mask = (cornerMin < HGCalTypes::WaferCornerMin) ? false : hdcons_.maskCell(idin, cornerMin);
bool flag = ((idin.det() == det_) &&
hdcons_.isValidHex8(
id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2, (cornerMin >= HGCalTypes::WaferCornerMin)));
return (flag && (!mask));
} else {
return valid(idin);
}
}
bool HGCalTopology::validModule(const DetId& idin, int cornerMin) const {
if (idin.det() != det_) {
return false;
} else if ((idin.det() == DetId::HGCalEE) || (idin.det() == DetId::HGCalHSi)) {
HGCalTopology::DecodedDetId id = decode(idin);
return hdcons_.isValidHex8(id.iLay, id.iSec1, id.iSec2, (cornerMin >= HGCalTypes::WaferCornerMin));
} else {
return valid(idin);
}
}
DetId HGCalTopology::offsetBy(const DetId startId, int nrStepsX, int nrStepsY) const {
if (startId.det() == DetId::Forward && startId.subdetId() == (int)(subdet_)) {
DetId id = changeXY(startId, nrStepsX, nrStepsY);
if (valid(id))
return id;
}
return DetId(0);
}
DetId HGCalTopology::switchZSide(const DetId startId) const {
HGCalTopology::DecodedDetId id_ = decode(startId);
id_.zSide = -id_.zSide;
DetId id = encode(id_);
if (valid(id))
return id;
else
return DetId(0);
}
HGCalTopology::DecodedDetId HGCalTopology::geomDenseId2decId(const uint32_t& hi) const {
HGCalTopology::DecodedDetId id;
if (hi < totalGeomModules()) {
id.zSide = ((int)(hi) < kHGeomHalf_ ? -1 : 1);
int di = ((int)(hi) % kHGeomHalf_);
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
id.iSec1 = (di % sectors_);
di = (di - id.iSec1) / sectors_;
id.iLay = (di % layers_) + 1;
id.iType = ((di - id.iLay + 1) / layers_ == 0) ? -1 : 1;
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Geom Hex I/P " << hi << " O/P " << id.zSide << ":" << id.iType << ":" << id.iLay
<< ":" << id.iSec1;
#endif
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
id.iCell1 = (di % cellMax_) + 1;
di = (di - id.iCell1 + 1) / cellMax_;
id.iSec1 = (di % sectors_) + 1;
di = (di - id.iSec1 + 1) / sectors_;
id.iLay = (di % layers_) + firstLay_;
id.iType = (di - id.iLay + firstLay_) / layers_;
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Geom Trap I/P " << hi << " O/P " << id.zSide << ":" << id.iType << ":"
<< id.iLay << ":" << id.iSec1 << ":" << id.iCell1;
#endif
} else {
id.iSec2 = (di % waferMax_) - waferOff_;
di = (di - id.iSec2 - waferOff_) / waferMax_;
id.iSec1 = (di % waferMax_) - waferOff_;
di = (di - id.iSec1 - waferOff_) / waferMax_;
id.iLay = (di % layers_) + 1;
id.iType = (di - id.iLay + 1) / layers_;
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "Geom Hex8 I/P " << hi << " O/P " << id.zSide << ":" << id.iType << ":"
<< id.iLay << ":" << id.iSec1 << ":" << id.iSec2;
#endif
}
}
return id;
}
void HGCalTopology::addHGCSCintillatorId(
std::vector<DetId>& ids, int zside, int type, int lay, int iradius, int iphi) const {
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "addHGCSCintillatorId " << zside << ":" << type << ":" << lay << ":" << iradius
<< ":" << iphi << " ==> Validity " << hdcons_.isValidTrap(lay, iradius, iphi);
#endif
if (hdcons_.isValidTrap(lay, iradius, iphi)) {
HGCScintillatorDetId id(type, lay, zside * iradius, iphi);
ids.emplace_back(DetId(id));
}
}
void HGCalTopology::addHGCSiliconId(
std::vector<DetId>& ids, int det, int zside, int type, int lay, int waferU, int waferV, int cellU, int cellV) const {
#ifdef EDM_ML_DEBUG
edm::LogVerbatim("HGCalGeom") << "addHGCSiliconId " << det << ":" << zside << ":" << type << ":" << lay << ":"
<< waferU << ":" << waferV << ":" << cellU << ":" << cellV << " ==> Validity "
<< hdcons_.isValidHex8(lay, waferU, waferV, cellU, cellV);
#endif
if (hdcons_.isValidHex8(lay, waferU, waferV, cellU, cellV)) {
HGCSiliconDetId id((DetId::Detector)(det), zside, type, lay, waferU, waferV, cellU, cellV);
ids.emplace_back(DetId(id));
}
}
HGCalTopology::DecodedDetId HGCalTopology::decode(const DetId& startId) const {
HGCalTopology::DecodedDetId idx;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
HGCalDetId id(startId);
idx.iCell1 = id.cell();
idx.iCell2 = 0;
idx.iLay = id.layer();
idx.iSec1 = id.wafer();
idx.iSec2 = 0;
idx.iType = id.waferType();
idx.zSide = id.zside();
idx.det = id.subdetId();
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
HGCScintillatorDetId id(startId);
idx.iCell1 = id.iphi();
idx.iCell2 = 0;
idx.iLay = id.layer();
idx.iSec1 = id.ietaAbs();
idx.iSec2 = 0;
idx.iType = id.type();
idx.zSide = id.zside();
idx.det = (int)(id.subdet());
} else if (det_ == DetId::Forward && subdet_ == ForwardSubdetector::HFNose) {
HFNoseDetId id(startId);
idx.iCell1 = id.cellU();
idx.iCell2 = id.cellV();
idx.iLay = id.layer();
idx.iSec1 = id.waferU();
idx.iSec2 = id.waferV();
idx.iType = id.type();
idx.zSide = id.zside();
idx.det = (int)(id.subdet());
} else {
HGCSiliconDetId id(startId);
idx.iCell1 = id.cellU();
idx.iCell2 = id.cellV();
idx.iLay = id.layer();
idx.iSec1 = id.waferU();
idx.iSec2 = id.waferV();
idx.iType = id.type();
idx.zSide = id.zside();
idx.det = (int)(id.subdet());
}
return idx;
}
DetId HGCalTopology::encode(const HGCalTopology::DecodedDetId& idx) const {
DetId id;
if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) {
id =
HGCalDetId((ForwardSubdetector)(idx.det), idx.zSide, idx.iLay, ((idx.iType > 0) ? 1 : 0), idx.iSec1, idx.iCell1)
.rawId();
} else if (mode_ == HGCalGeometryMode::Trapezoid) {
id = HGCScintillatorDetId(idx.iType, idx.iLay, idx.zSide * idx.iSec1, idx.iCell1).rawId();
} else if (det_ == DetId::Forward && subdet_ == ForwardSubdetector::HFNose) {
id = HFNoseDetId(idx.zSide, idx.iType, idx.iLay, idx.iSec1, idx.iSec2, idx.iCell1, idx.iCell2).rawId();
} else {
id = HGCSiliconDetId(
(DetId::Detector)(idx.det), idx.zSide, idx.iType, idx.iLay, idx.iSec1, idx.iSec2, idx.iCell1, idx.iCell2)
.rawId();
}
return id;
}
DetId HGCalTopology::changeXY(const DetId& id, int nrStepsX, int nrStepsY) const { return DetId(); }
DetId HGCalTopology::changeZ(const DetId& id, int nrStepsZ) const { return DetId(); }
#include "FWCore/Utilities/interface/typelookup.h"
TYPELOOKUP_DATA_REG(HGCalTopology);
|
//===-- llvm-diff.cpp - Module comparator command-line driver ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the command-line driver for the difference engine.
//
//===----------------------------------------------------------------------===//
#include "DiffLog.h"
#include "DifferenceEngine.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
#include <utility>
using namespace llvm;
/// Reads a module from a file. On error, messages are written to stderr
/// and null is returned.
static Module *ReadModule(LLVMContext &Context, StringRef Name) {
SMDiagnostic Diag;
Module *M = ParseIRFile(Name, Diag, Context);
if (!M)
Diag.print("llvm-diff", errs());
return M;
}
static void diffGlobal(DifferenceEngine &Engine, Module *L, Module *R,
StringRef Name) {
// Drop leading sigils from the global name.
if (Name.startswith("@")) Name = Name.substr(1);
Function *LFn = L->getFunction(Name);
Function *RFn = R->getFunction(Name);
if (LFn && RFn)
Engine.diff(LFn, RFn);
else if (!LFn && !RFn)
errs() << "No function named @" << Name << " in either module\n";
else if (!LFn)
errs() << "No function named @" << Name << " in left module\n";
else
errs() << "No function named @" << Name << " in right module\n";
}
static cl::opt<std::string> LeftFilename(cl::Positional,
cl::desc("<first file>"),
cl::Required);
static cl::opt<std::string> RightFilename(cl::Positional,
cl::desc("<second file>"),
cl::Required);
static cl::list<std::string> GlobalsToCompare(cl::Positional,
cl::desc("<globals to compare>"));
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv);
LLVMContext Context;
// Load both modules. Die if that fails.
Module *LModule = ReadModule(Context, LeftFilename);
Module *RModule = ReadModule(Context, RightFilename);
if (!LModule || !RModule) return 1;
DiffConsumer Consumer;
DifferenceEngine Engine(Consumer);
// If any global names were given, just diff those.
if (!GlobalsToCompare.empty()) {
for (unsigned I = 0, E = GlobalsToCompare.size(); I != E; ++I)
diffGlobal(Engine, LModule, RModule, GlobalsToCompare[I]);
// Otherwise, diff everything in the module.
} else {
Engine.diff(LModule, RModule);
}
delete LModule;
delete RModule;
return Consumer.hadDifferences();
}
|
#include <memory>
#include <string>
#include "common/buffer/buffer_impl.h"
#include "common/http/header_map_impl.h"
#include "extensions/filters/http/dynamo/dynamo_filter.h"
#include "test/mocks/http/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/stats/mocks.h"
#include "test/test_common/printers.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::NiceMock;
using testing::Property;
using testing::Return;
using testing::ReturnRef;
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace Dynamo {
namespace {
class DynamoFilterTest : public testing::Test {
public:
void setup(bool enabled) {
ON_CALL(loader_.snapshot_, featureEnabled("dynamodb.filter_enabled", 100))
.WillByDefault(Return(enabled));
EXPECT_CALL(loader_.snapshot_, featureEnabled("dynamodb.filter_enabled", 100));
filter_ = std::make_unique<DynamoFilter>(loader_, stat_prefix_, stats_,
decoder_callbacks_.dispatcher().timeSource());
filter_->setDecoderFilterCallbacks(decoder_callbacks_);
filter_->setEncoderFilterCallbacks(encoder_callbacks_);
}
~DynamoFilterTest() { filter_->onDestroy(); }
std::unique_ptr<DynamoFilter> filter_;
NiceMock<Runtime::MockLoader> loader_;
std::string stat_prefix_{"prefix."};
NiceMock<Stats::MockStore> stats_;
NiceMock<Http::MockStreamDecoderFilterCallbacks> decoder_callbacks_;
NiceMock<Http::MockStreamEncoderFilterCallbacks> encoder_callbacks_;
};
TEST_F(DynamoFilterTest, operatorPresent) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.Get"}, {"random", "random"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, true));
Http::MetadataMap metadata_map{{"metadata", "metadata"}};
EXPECT_EQ(Http::FilterMetadataStatus::Continue, filter_->decodeMetadata(metadata_map));
EXPECT_EQ(Http::FilterMetadataStatus::Continue, filter_->encodeMetadata(metadata_map));
Http::TestHeaderMapImpl continue_headers{{":status", "100"}};
EXPECT_EQ(Http::FilterHeadersStatus::Continue,
filter_->encode100ContinueHeaders(continue_headers));
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation_missing")).Times(0);
EXPECT_CALL(stats_, counter("prefix.dynamodb.table_missing"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.Get.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.Get.upstream_rq_total_200"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.Get.upstream_rq_total"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.Get.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.Get.upstream_rq_time_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.Get.upstream_rq_time"));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.operation.Get.upstream_rq_time_2xx"), _));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.operation.Get.upstream_rq_time_200"), _));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.operation.Get.upstream_rq_time"), _));
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, true));
}
TEST_F(DynamoFilterTest, jsonBodyNotWellFormed) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.GetItem"},
{"random", "random"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
Buffer::OwnedImpl buffer;
buffer.add("test", 4);
buffer.add("test2", 5);
EXPECT_CALL(stats_, counter("prefix.dynamodb.invalid_req_body"));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(buffer, true));
}
TEST_F(DynamoFilterTest, bothOperationAndTableIncorrect) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version"}, {"random", "random"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, true));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation_missing"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table_missing"));
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, true));
}
TEST_F(DynamoFilterTest, handleErrorTypeTableMissing) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version"}, {"random", "random"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, true));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation_missing"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table_missing"));
Http::TestHeaderMapImpl response_headers{{":status", "400"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->encodeHeaders(response_headers, false));
Buffer::InstancePtr error_data(new Buffer::OwnedImpl());
std::string internal_error =
"{\"__type\":\"com.amazonaws.dynamodb.v20120810#ValidationException\"}";
error_data->add(internal_error);
EXPECT_CALL(stats_, counter("prefix.dynamodb.error.no_table.ValidationException"));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(*error_data, true));
error_data->add("}", 1);
EXPECT_EQ(Http::FilterDataStatus::StopIterationAndBuffer,
filter_->encodeData(*error_data, false));
EXPECT_CALL(encoder_callbacks_, encodingBuffer()).WillRepeatedly(Return(error_data.get()));
EXPECT_CALL(stats_, counter("prefix.dynamodb.invalid_resp_body"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation_missing"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table_missing"));
EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->encodeTrailers(request_headers));
}
TEST_F(DynamoFilterTest, HandleErrorTypeTablePresent) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.GetItem"},
{"random", "random"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
Buffer::OwnedImpl buffer;
std::string buffer_content = "{\"TableName\":\"locations\"}";
buffer.add(buffer_content);
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(buffer, true));
Http::TestHeaderMapImpl response_headers{{":status", "400"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->encodeHeaders(response_headers, false));
Buffer::OwnedImpl error_data;
std::string internal_error =
"{\"__type\":\"com.amazonaws.dynamodb.v20120810#ValidationException\"}";
error_data.add(internal_error);
EXPECT_CALL(stats_, counter("prefix.dynamodb.error.locations.ValidationException"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.GetItem.upstream_rq_total"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.GetItem.upstream_rq_total_4xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.GetItem.upstream_rq_total_400"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.GetItem.upstream_rq_time"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.GetItem.upstream_rq_time_4xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.GetItem.upstream_rq_time_400"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.GetItem.upstream_rq_time_4xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.GetItem.upstream_rq_time_400"),
_));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.operation.GetItem.upstream_rq_time"), _));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total_4xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total_400"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time_4xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time_400"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.table.locations.upstream_rq_time_4xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.table.locations.upstream_rq_time_400"),
_));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.table.locations.upstream_rq_time"), _));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(error_data, true));
}
TEST_F(DynamoFilterTest, BatchMultipleTables) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.BatchGetItem"},
{"random", "random"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
Buffer::InstancePtr buffer(new Buffer::OwnedImpl());
std::string buffer_content = R"EOF(
{
"RequestItems": {
"table_1": { "test1" : "something" },
"table_2": { "test2" : "something" }
}
}
)EOF";
buffer->add(buffer_content);
EXPECT_EQ(Http::FilterDataStatus::StopIterationAndBuffer, filter_->decodeData(*buffer, false));
EXPECT_CALL(decoder_callbacks_, decodingBuffer()).WillRepeatedly(Return(buffer.get()));
EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_headers));
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_CALL(stats_, counter("prefix.dynamodb.multiple_tables"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"),
_));
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, true));
}
TEST_F(DynamoFilterTest, BatchMultipleTablesUnprocessedKeys) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.BatchGetItem"},
{"random", "random"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
Buffer::InstancePtr buffer(new Buffer::OwnedImpl());
std::string buffer_content = R"EOF(
{
"RequestItems": {
"table_1": { "test1" : "something" },
"table_2": { "test2" : "something" }
}
}
)EOF";
buffer->add(buffer_content);
EXPECT_EQ(Http::FilterDataStatus::StopIterationAndBuffer, filter_->decodeData(*buffer, false));
EXPECT_CALL(decoder_callbacks_, decodingBuffer()).WillRepeatedly(Return(buffer.get()));
EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_headers));
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_CALL(stats_, counter("prefix.dynamodb.multiple_tables"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"),
_));
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->encodeHeaders(response_headers, false));
Buffer::OwnedImpl empty_data;
Buffer::InstancePtr response_data(new Buffer::OwnedImpl());
std::string response_content = R"EOF(
{
"UnprocessedKeys": {
"table_1": { "test1" : "something" },
"table_2": { "test2" : "something" }
}
}
)EOF";
response_data->add(response_content);
EXPECT_CALL(stats_, counter("prefix.dynamodb.error.table_1.BatchFailureUnprocessedKeys"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.error.table_2.BatchFailureUnprocessedKeys"));
EXPECT_CALL(encoder_callbacks_, encodingBuffer()).WillRepeatedly(Return(response_data.get()));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(empty_data, true));
}
TEST_F(DynamoFilterTest, BatchMultipleTablesNoUnprocessedKeys) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.BatchGetItem"},
{"random", "random"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
Buffer::InstancePtr buffer(new Buffer::OwnedImpl());
std::string buffer_content = R"EOF(
{
"RequestItems": {
"table_1": { "test1" : "something" },
"table_2": { "test2" : "something" }
}
}
)EOF";
buffer->add(buffer_content);
EXPECT_EQ(Http::FilterDataStatus::StopIterationAndBuffer, filter_->decodeData(*buffer, false));
EXPECT_CALL(decoder_callbacks_, decodingBuffer()).WillRepeatedly(Return(buffer.get()));
EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_headers));
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_CALL(stats_, counter("prefix.dynamodb.multiple_tables"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"),
_));
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->encodeHeaders(response_headers, false));
Buffer::OwnedImpl empty_data;
Buffer::InstancePtr response_data(new Buffer::OwnedImpl());
std::string response_content = R"EOF(
{
"UnprocessedKeys": {
}
}
)EOF";
response_data->add(response_content);
EXPECT_CALL(encoder_callbacks_, encodingBuffer()).WillOnce(Return(response_data.get()));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(empty_data, true));
}
TEST_F(DynamoFilterTest, BatchMultipleTablesInvalidResponseBody) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.BatchGetItem"},
{"random", "random"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
Buffer::InstancePtr buffer(new Buffer::OwnedImpl());
std::string buffer_content = R"EOF(
{
"RequestItems": {
"table_1": { "test1" : "something" },
"table_2": { "test2" : "something" }
}
}
)EOF";
buffer->add(buffer_content);
EXPECT_EQ(Http::FilterDataStatus::StopIterationAndBuffer, filter_->decodeData(*buffer, false));
EXPECT_CALL(decoder_callbacks_, decodingBuffer()).WillRepeatedly(Return(buffer.get()));
EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_headers));
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_CALL(stats_, counter("prefix.dynamodb.multiple_tables"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"),
_));
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->encodeHeaders(response_headers, false));
Buffer::OwnedImpl empty_data;
Buffer::InstancePtr response_data(new Buffer::OwnedImpl());
std::string response_content = R"EOF(
{
"UnprocessedKeys": {
"table_1": { "test1" : "something" },
"table_2": { "test2" : "something" }
}
}
)EOF";
response_data->add(response_content);
response_data->add("}", 1);
EXPECT_CALL(stats_, counter("prefix.dynamodb.invalid_resp_body"));
EXPECT_CALL(encoder_callbacks_, encodingBuffer()).WillOnce(Return(response_data.get()));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(empty_data, true));
}
TEST_F(DynamoFilterTest, bothOperationAndTableCorrect) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.GetItem"}};
Buffer::InstancePtr buffer(new Buffer::OwnedImpl());
std::string buffer_content = "{\"TableName\":\"locations\"";
buffer->add(buffer_content);
EXPECT_CALL(decoder_callbacks_, decodingBuffer()).WillRepeatedly(Return(buffer.get()));
Buffer::OwnedImpl data;
data.add("}", 1);
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
EXPECT_EQ(Http::FilterDataStatus::StopIterationAndBuffer, filter_->decodeData(data, false));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(data, true));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.GetItem.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.GetItem.upstream_rq_total_200"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.GetItem.upstream_rq_total"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.GetItem.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.GetItem.upstream_rq_time_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.GetItem.upstream_rq_time"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.GetItem.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.GetItem.upstream_rq_time_200"),
_));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.operation.GetItem.upstream_rq_time"), _));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total_200"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.table.locations.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.table.locations.upstream_rq_time_200"),
_));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.table.locations.upstream_rq_time"), _));
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, true));
}
TEST_F(DynamoFilterTest, operatorPresentRuntimeDisabled) {
setup(false);
EXPECT_CALL(stats_, counter(_)).Times(0);
EXPECT_CALL(stats_, deliverHistogramToSinks(_, _)).Times(0);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.operator"},
{"random", "random"}};
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true));
EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->encodeHeaders(response_headers, true));
EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->encodeTrailers(response_headers));
}
TEST_F(DynamoFilterTest, PartitionIdStats) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.GetItem"}};
Buffer::InstancePtr buffer(new Buffer::OwnedImpl());
std::string buffer_content = "{\"TableName\":\"locations\"";
buffer->add(buffer_content);
ON_CALL(decoder_callbacks_, decodingBuffer()).WillByDefault(Return(buffer.get()));
Buffer::OwnedImpl data;
data.add("}", 1);
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
EXPECT_EQ(Http::FilterDataStatus::StopIterationAndBuffer, filter_->decodeData(data, false));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(data, true));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.GetItem.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.GetItem.upstream_rq_total_200"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.GetItem.upstream_rq_total"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.GetItem.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.GetItem.upstream_rq_time_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.GetItem.upstream_rq_time"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.GetItem.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.GetItem.upstream_rq_time_200"),
_));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.operation.GetItem.upstream_rq_time"), _));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total_200"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.table.locations.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.table.locations.upstream_rq_time_200"),
_));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.table.locations.upstream_rq_time"), _));
EXPECT_CALL(stats_,
counter("prefix.dynamodb.table.locations.capacity.GetItem.__partition_id=ition_1"))
.Times(1);
EXPECT_CALL(stats_,
counter("prefix.dynamodb.table.locations.capacity.GetItem.__partition_id=ition_2"))
.Times(1);
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->encodeHeaders(response_headers, false));
Buffer::OwnedImpl empty_data;
Buffer::InstancePtr response_data(new Buffer::OwnedImpl());
std::string response_content = R"EOF(
{
"ConsumedCapacity": {
"Partitions": {
"partition_1" : 0.5,
"partition_2" : 3.0
}
}
}
)EOF";
response_data->add(response_content);
EXPECT_CALL(encoder_callbacks_, encodingBuffer()).WillOnce(Return(response_data.get()));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(empty_data, true));
}
TEST_F(DynamoFilterTest, NoPartitionIdStatsForMultipleTables) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.BatchGetItem"}};
Buffer::InstancePtr buffer(new Buffer::OwnedImpl());
std::string buffer_content = R"EOF(
{
"RequestItems": {
"table_1": { "test1" : "something" },
"table_2": { "test2" : "something" }
}
}
)EOF";
buffer->add(buffer_content);
ON_CALL(decoder_callbacks_, decodingBuffer()).WillByDefault(Return(buffer.get()));
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
EXPECT_EQ(Http::FilterDataStatus::StopIterationAndBuffer, filter_->decodeData(*buffer, false));
EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_headers));
EXPECT_CALL(stats_, counter("prefix.dynamodb.multiple_tables"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"),
_));
EXPECT_CALL(
stats_,
counter("prefix.dynamodb.table.locations.capacity.BatchGetItem.__partition_id=ition_1"))
.Times(0);
EXPECT_CALL(
stats_,
counter("prefix.dynamodb.table.locations.capacity.BatchGetItem.__partition_id=ition_2"))
.Times(0);
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->encodeHeaders(response_headers, false));
Buffer::OwnedImpl empty_data;
Buffer::InstancePtr response_data(new Buffer::OwnedImpl());
std::string response_content = R"EOF(
{
"ConsumedCapacity": {
"Partitions": {
"partition_1" : 0.5,
"partition_2" : 3.0
}
}
}
)EOF";
response_data->add(response_content);
EXPECT_CALL(encoder_callbacks_, encodingBuffer()).WillOnce(Return(response_data.get()));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(empty_data, true));
}
TEST_F(DynamoFilterTest, PartitionIdStatsForSingleTableBatchOperation) {
setup(true);
Http::TestHeaderMapImpl request_headers{{"x-amz-target", "version.BatchGetItem"}};
Buffer::InstancePtr buffer(new Buffer::OwnedImpl());
std::string buffer_content = R"EOF(
{
"RequestItems": {
"locations": { "test1" : "something" }
}
}
)EOF";
buffer->add(buffer_content);
ON_CALL(decoder_callbacks_, decodingBuffer()).WillByDefault(Return(buffer.get()));
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->decodeHeaders(request_headers, false));
EXPECT_EQ(Http::FilterDataStatus::StopIterationAndBuffer, filter_->decodeData(*buffer, false));
EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_headers));
EXPECT_CALL(stats_, counter("prefix.dynamodb.multiple_tables")).Times(0);
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.operation.BatchGetItem.upstream_rq_total_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time_200"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.operation.BatchGetItem.upstream_rq_time"),
_));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total_2xx"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total_200"));
EXPECT_CALL(stats_, counter("prefix.dynamodb.table.locations.upstream_rq_total"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time_2xx"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time_200"));
EXPECT_CALL(stats_, histogram("prefix.dynamodb.table.locations.upstream_rq_time"));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.table.locations.upstream_rq_time_2xx"),
_));
EXPECT_CALL(stats_, deliverHistogramToSinks(
Property(&Stats::Metric::name,
"prefix.dynamodb.table.locations.upstream_rq_time_200"),
_));
EXPECT_CALL(
stats_,
deliverHistogramToSinks(
Property(&Stats::Metric::name, "prefix.dynamodb.table.locations.upstream_rq_time"), _));
EXPECT_CALL(
stats_,
counter("prefix.dynamodb.table.locations.capacity.BatchGetItem.__partition_id=ition_1"))
.Times(1);
EXPECT_CALL(
stats_,
counter("prefix.dynamodb.table.locations.capacity.BatchGetItem.__partition_id=ition_2"))
.Times(1);
Http::TestHeaderMapImpl response_headers{{":status", "200"}};
EXPECT_EQ(Http::FilterHeadersStatus::StopIteration,
filter_->encodeHeaders(response_headers, false));
Buffer::OwnedImpl empty_data;
Buffer::InstancePtr response_data(new Buffer::OwnedImpl());
std::string response_content = R"EOF(
{
"ConsumedCapacity": {
"Partitions": {
"partition_1" : 0.5,
"partition_2" : 3.0
}
}
}
)EOF";
response_data->add(response_content);
EXPECT_CALL(encoder_callbacks_, encodingBuffer()).WillOnce(Return(response_data.get()));
EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(empty_data, true));
}
} // namespace
} // namespace Dynamo
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
{std::array<float,2>{0.89678973f, 0.103728056f},
std::array<float,2>{0.18738313f, 0.686939657f},
std::array<float,2>{0.491404653f, 0.363231957f},
std::array<float,2>{0.529806197f, 0.790773034f},
std::array<float,2>{0.716216505f, 0.454463363f},
std::array<float,2>{0.317255616f, 0.950312376f},
std::array<float,2>{0.114851743f, 0.13660264f},
std::array<float,2>{0.766647279f, 0.55494225f},
std::array<float,2>{0.584992588f, 0.205627576f},
std::array<float,2>{0.419127911f, 0.577504098f},
std::array<float,2>{0.23595652f, 0.380042344f},
std::array<float,2>{0.996228516f, 0.937083185f},
std::array<float,2>{0.824100494f, 0.309196442f},
std::array<float,2>{0.0325064883f, 0.819546044f},
std::array<float,2>{0.282493949f, 0.0345288105f},
std::array<float,2>{0.662021875f, 0.73860687f},
std::array<float,2>{0.801289618f, 0.18416369f},
std::array<float,2>{0.0859847441f, 0.502742648f},
std::array<float,2>{0.358556151f, 0.480941117f},
std::array<float,2>{0.739625692f, 0.994580269f},
std::array<float,2>{0.531817138f, 0.341646105f},
std::array<float,2>{0.455636889f, 0.774138927f},
std::array<float,2>{0.134719133f, 0.062556468f},
std::array<float,2>{0.917150021f, 0.628957748f},
std::array<float,2>{0.648306191f, 0.000411768036f},
std::array<float,2>{0.253736556f, 0.691018283f},
std::array<float,2>{0.0179657284f, 0.25192371f},
std::array<float,2>{0.845172048f, 0.86259228f},
std::array<float,2>{0.939592063f, 0.418315053f},
std::array<float,2>{0.201687068f, 0.888645411f},
std::array<float,2>{0.401646763f, 0.235248178f},
std::array<float,2>{0.620336533f, 0.607907891f},
std::array<float,2>{0.861069083f, 0.0524597429f},
std::array<float,2>{0.000127122155f, 0.723944426f},
std::array<float,2>{0.273834705f, 0.281543106f},
std::array<float,2>{0.63067174f, 0.842316389f},
std::array<float,2>{0.596019089f, 0.400405765f},
std::array<float,2>{0.385059178f, 0.916155636f},
std::array<float,2>{0.209607676f, 0.191432685f},
std::array<float,2>{0.959789038f, 0.590507627f},
std::array<float,2>{0.72937423f, 0.146016985f},
std::array<float,2>{0.364547938f, 0.531578958f},
std::array<float,2>{0.0629986599f, 0.448637903f},
std::array<float,2>{0.795150459f, 0.959732294f},
std::array<float,2>{0.936387718f, 0.345781475f},
std::array<float,2>{0.152381569f, 0.800763071f},
std::array<float,2>{0.4402273f, 0.113065422f},
std::array<float,2>{0.551056564f, 0.658106387f},
std::array<float,2>{0.973562837f, 0.221967503f},
std::array<float,2>{0.220762208f, 0.613641918f},
std::array<float,2>{0.431510657f, 0.423083812f},
std::array<float,2>{0.576447129f, 0.903806686f},
std::array<float,2>{0.685358524f, 0.269461006f},
std::array<float,2>{0.308307201f, 0.859118104f},
std::array<float,2>{0.0512513109f, 0.0234747473f},
std::array<float,2>{0.835282147f, 0.71224308f},
std::array<float,2>{0.505094409f, 0.0846972391f},
std::array<float,2>{0.476558685f, 0.647063315f},
std::array<float,2>{0.156618655f, 0.317380667f},
std::array<float,2>{0.880461991f, 0.76315105f},
std::array<float,2>{0.763676345f, 0.495981991f},
std::array<float,2>{0.104959369f, 0.974722505f},
std::array<float,2>{0.328167498f, 0.161868095f},
std::array<float,2>{0.688450158f, 0.517846227f},
std::array<float,2>{0.961779892f, 0.0183473453f},
std::array<float,2>{0.217133954f, 0.708583653f},
std::array<float,2>{0.379748285f, 0.280533463f},
std::array<float,2>{0.603795826f, 0.849589169f},
std::array<float,2>{0.64033407f, 0.432748765f},
std::array<float,2>{0.269769847f, 0.895940304f},
std::array<float,2>{0.014673152f, 0.22783637f},
std::array<float,2>{0.870551586f, 0.617357194f},
std::array<float,2>{0.559175432f, 0.168120518f},
std::array<float,2>{0.451219559f, 0.526859522f},
std::array<float,2>{0.142890885f, 0.48709622f},
std::array<float,2>{0.925625026f, 0.978045821f},
std::array<float,2>{0.788132131f, 0.327174276f},
std::array<float,2>{0.0755526274f, 0.754933894f},
std::array<float,2>{0.371779084f, 0.0906743407f},
std::array<float,2>{0.723884106f, 0.655390203f},
std::array<float,2>{0.842775345f, 0.200169012f},
std::array<float,2>{0.056436833f, 0.585189164f},
std::array<float,2>{0.302236408f, 0.392256677f},
std::array<float,2>{0.673358321f, 0.908467591f},
std::array<float,2>{0.563254833f, 0.29320851f},
std::array<float,2>{0.424181789f, 0.828553796f},
std::array<float,2>{0.232736349f, 0.055224847f},
std::array<float,2>{0.983599126f, 0.731399834f},
std::array<float,2>{0.696421981f, 0.117783234f},
std::array<float,2>{0.33974722f, 0.668278635f},
std::array<float,2>{0.096807383f, 0.3592498f},
std::array<float,2>{0.755777001f, 0.810072899f},
std::array<float,2>{0.886676192f, 0.440644145f},
std::array<float,2>{0.166469768f, 0.96418649f},
std::array<float,2>{0.479554415f, 0.150166824f},
std::array<float,2>{0.514849722f, 0.540506065f},
std::array<float,2>{0.779894114f, 0.0758055001f},
std::array<float,2>{0.12395969f, 0.637348354f},
std::array<float,2>{0.320708007f, 0.330828637f},
std::array<float,2>{0.710510373f, 0.773068786f},
std::array<float,2>{0.520530224f, 0.476126313f},
std::array<float,2>{0.498820275f, 0.985026062f},
std::array<float,2>{0.178681001f, 0.175285861f},
std::array<float,2>{0.904566407f, 0.51413703f},
std::array<float,2>{0.668108404f, 0.244235367f},
std::array<float,2>{0.292864084f, 0.598858535f},
std::array<float,2>{0.0418198444f, 0.412865192f},
std::array<float,2>{0.81795013f, 0.880617142f},
std::array<float,2>{0.990172088f, 0.264678299f},
std::array<float,2>{0.248448715f, 0.867514133f},
std::array<float,2>{0.412654132f, 0.009304462f},
std::array<float,2>{0.58781743f, 0.699857533f},
std::array<float,2>{0.912226558f, 0.129226312f},
std::array<float,2>{0.1315272f, 0.548445702f},
std::array<float,2>{0.465922385f, 0.461655229f},
std::array<float,2>{0.541596472f, 0.944553494f},
std::array<float,2>{0.747938216f, 0.367369682f},
std::array<float,2>{0.348896801f, 0.781964719f},
std::array<float,2>{0.0791168064f, 0.0954991207f},
std::array<float,2>{0.807367682f, 0.679634392f},
std::array<float,2>{0.616023004f, 0.042565383f},
std::array<float,2>{0.397544175f, 0.745193243f},
std::array<float,2>{0.188683614f, 0.296975493f},
std::array<float,2>{0.952277958f, 0.826506913f},
std::array<float,2>{0.854417443f, 0.388938367f},
std::array<float,2>{0.0245322622f, 0.923835397f},
std::array<float,2>{0.258861989f, 0.216238543f},
std::array<float,2>{0.65239197f, 0.567354977f},
std::array<float,2>{0.927991927f, 0.035386093f},
std::array<float,2>{0.146802872f, 0.737357318f},
std::array<float,2>{0.446994573f, 0.307909399f},
std::array<float,2>{0.555030167f, 0.814604402f},
std::array<float,2>{0.719602227f, 0.376398563f},
std::array<float,2>{0.370036155f, 0.932875812f},
std::array<float,2>{0.0714596286f, 0.209407955f},
std::array<float,2>{0.781574428f, 0.574144006f},
std::array<float,2>{0.606672227f, 0.138842285f},
std::array<float,2>{0.376256078f, 0.559137642f},
std::array<float,2>{0.212909207f, 0.460505366f},
std::array<float,2>{0.968385696f, 0.947326541f},
std::array<float,2>{0.8733899f, 0.365239978f},
std::array<float,2>{0.00825852063f, 0.794328451f},
std::array<float,2>{0.265735745f, 0.107268967f},
std::array<float,2>{0.636003494f, 0.681770205f},
std::array<float,2>{0.753347754f, 0.240003541f},
std::array<float,2>{0.0995511264f, 0.604778588f},
std::array<float,2>{0.342498124f, 0.416857809f},
std::array<float,2>{0.701525509f, 0.884022117f},
std::array<float,2>{0.508943975f, 0.257458955f},
std::array<float,2>{0.481903076f, 0.864461422f},
std::array<float,2>{0.170622781f, 0.00459897052f},
std::array<float,2>{0.888924718f, 0.691916347f},
std::array<float,2>{0.677298844f, 0.0673437491f},
std::array<float,2>{0.300171345f, 0.62797147f},
std::array<float,2>{0.0597593039f, 0.338092804f},
std::array<float,2>{0.838519812f, 0.77813834f},
std::array<float,2>{0.976812422f, 0.477487117f},
std::array<float,2>{0.228331417f, 0.997996032f},
std::array<float,2>{0.427403063f, 0.18227008f},
std::array<float,2>{0.566931725f, 0.506699026f},
std::array<float,2>{0.815064192f, 0.116761655f},
std::array<float,2>{0.0459707901f, 0.662274063f},
std::array<float,2>{0.296165377f, 0.350655228f},
std::array<float,2>{0.665646255f, 0.801452994f},
std::array<float,2>{0.5924685f, 0.451900423f},
std::array<float,2>{0.409040093f, 0.955928683f},
std::array<float,2>{0.243121445f, 0.142885208f},
std::array<float,2>{0.986978531f, 0.535902798f},
std::array<float,2>{0.704044759f, 0.190222397f},
std::array<float,2>{0.327089906f, 0.587082326f},
std::array<float,2>{0.120069392f, 0.402466714f},
std::array<float,2>{0.776944518f, 0.919759035f},
std::array<float,2>{0.901760876f, 0.285396904f},
std::array<float,2>{0.172668979f, 0.838120818f},
std::array<float,2>{0.494813323f, 0.0488893464f},
std::array<float,2>{0.519274831f, 0.720236182f},
std::array<float,2>{0.947431326f, 0.156717435f},
std::array<float,2>{0.193131864f, 0.5212062f},
std::array<float,2>{0.394249469f, 0.49873215f},
std::array<float,2>{0.610601485f, 0.971157372f},
std::array<float,2>{0.652123153f, 0.314852238f},
std::array<float,2>{0.263744056f, 0.758512199f},
std::array<float,2>{0.0307869185f, 0.080204688f},
std::array<float,2>{0.85857439f, 0.641583562f},
std::array<float,2>{0.543729305f, 0.0296666268f},
std::array<float,2>{0.463791251f, 0.716618896f},
std::array<float,2>{0.128074735f, 0.270469159f},
std::array<float,2>{0.907661557f, 0.853864372f},
std::array<float,2>{0.811251581f, 0.426979184f},
std::array<float,2>{0.0825140551f, 0.901266575f},
std::array<float,2>{0.344947904f, 0.224250823f},
std::array<float,2>{0.74581629f, 0.611249685f},
std::array<float,2>{0.995175064f, 0.0897627696f},
std::array<float,2>{0.238915801f, 0.651140273f},
std::array<float,2>{0.417441756f, 0.320443809f},
std::array<float,2>{0.580883265f, 0.752165496f},
std::array<float,2>{0.658416331f, 0.488932908f},
std::array<float,2>{0.286768049f, 0.982759595f},
std::array<float,2>{0.0389905274f, 0.165488422f},
std::array<float,2>{0.825272322f, 0.530343115f},
std::array<float,2>{0.526864529f, 0.232306406f},
std::array<float,2>{0.486164778f, 0.623615086f},
std::array<float,2>{0.183203012f, 0.434101641f},
std::array<float,2>{0.892916024f, 0.89362216f},
std::array<float,2>{0.773352742f, 0.274267972f},
std::array<float,2>{0.11230547f, 0.846677065f},
std::array<float,2>{0.313102275f, 0.0225890577f},
std::array<float,2>{0.712811172f, 0.706157327f},
std::array<float,2>{0.847820401f, 0.155796677f},
std::array<float,2>{0.0207988992f, 0.545857191f},
std::array<float,2>{0.254959732f, 0.444690496f},
std::array<float,2>{0.642039001f, 0.968272388f},
std::array<float,2>{0.623475015f, 0.35241586f},
std::array<float,2>{0.402843893f, 0.808101296f},
std::array<float,2>{0.198336333f, 0.124721617f},
std::array<float,2>{0.944066226f, 0.665184259f},
std::array<float,2>{0.735736907f, 0.0613686293f},
std::array<float,2>{0.354944408f, 0.72665453f},
std::array<float,2>{0.0922528878f, 0.289859146f},
std::array<float,2>{0.799018085f, 0.833875239f},
std::array<float,2>{0.919582844f, 0.395502806f},
std::array<float,2>{0.139995322f, 0.910415947f},
std::array<float,2>{0.458157331f, 0.197533861f},
std::array<float,2>{0.53881067f, 0.580575705f},
std::array<float,2>{0.792719424f, 0.0144223645f},
std::array<float,2>{0.0687387064f, 0.696230233f},
std::array<float,2>{0.360527873f, 0.259280086f},
std::array<float,2>{0.731625974f, 0.872202098f},
std::array<float,2>{0.54905498f, 0.407153785f},
std::array<float,2>{0.444438547f, 0.877316356f},
std::array<float,2>{0.148718983f, 0.24794656f},
std::array<float,2>{0.930950463f, 0.596817374f},
std::array<float,2>{0.628753543f, 0.177568823f},
std::array<float,2>{0.27758944f, 0.510701954f},
std::array<float,2>{0.00707605667f, 0.470482618f},
std::array<float,2>{0.865256965f, 0.990525544f},
std::array<float,2>{0.954423249f, 0.332315624f},
std::array<float,2>{0.203511775f, 0.767731547f},
std::array<float,2>{0.390482962f, 0.0717047378f},
std::array<float,2>{0.598448873f, 0.634435534f},
std::array<float,2>{0.87719816f, 0.214454561f},
std::array<float,2>{0.163737655f, 0.563608527f},
std::array<float,2>{0.471359938f, 0.385886818f},
std::array<float,2>{0.50131917f, 0.927031517f},
std::array<float,2>{0.693904698f, 0.304627061f},
std::array<float,2>{0.333025068f, 0.820607364f},
std::array<float,2>{0.107372068f, 0.0432880931f},
std::array<float,2>{0.758450329f, 0.747973382f},
std::array<float,2>{0.573032439f, 0.1006817f},
std::array<float,2>{0.436104208f, 0.67466557f},
std::array<float,2>{0.224322781f, 0.373057574f},
std::array<float,2>{0.972064555f, 0.786370277f},
std::array<float,2>{0.831653118f, 0.467462122f},
std::array<float,2>{0.0491126962f, 0.938761234f},
std::array<float,2>{0.310991406f, 0.126910105f},
std::array<float,2>{0.683180332f, 0.551794231f},
std::array<float,2>{0.916009784f, 0.0657706782f},
std::array<float,2>{0.136208415f, 0.630876958f},
std::array<float,2>{0.454093844f, 0.34189868f},
std::array<float,2>{0.534484744f, 0.775678992f},
std::array<float,2>{0.740980148f, 0.482547998f},
std::array<float,2>{0.356105328f, 0.993964195f},
std::array<float,2>{0.0893711597f, 0.187082455f},
std::array<float,2>{0.803115845f, 0.501195014f},
std::array<float,2>{0.618693292f, 0.237296104f},
std::array<float,2>{0.400256515f, 0.605540693f},
std::array<float,2>{0.200628042f, 0.420265168f},
std::array<float,2>{0.939279377f, 0.888983607f},
std::array<float,2>{0.84654665f, 0.252443999f},
std::array<float,2>{0.0167777296f, 0.860922575f},
std::array<float,2>{0.251929164f, 0.00288367132f},
std::array<float,2>{0.644866407f, 0.687723339f},
std::array<float,2>{0.768215239f, 0.133320421f},
std::array<float,2>{0.115251906f, 0.557693839f},
std::array<float,2>{0.318392515f, 0.456506133f},
std::array<float,2>{0.718327105f, 0.951610565f},
std::array<float,2>{0.528354704f, 0.359638065f},
std::array<float,2>{0.488662243f, 0.79118973f},
std::array<float,2>{0.185079068f, 0.10194353f},
std::array<float,2>{0.895392776f, 0.683772326f},
std::array<float,2>{0.663310587f, 0.0330878794f},
std::array<float,2>{0.284194499f, 0.741992354f},
std::array<float,2>{0.0334021337f, 0.31127581f},
std::array<float,2>{0.821585119f, 0.818034768f},
std::array<float,2>{0.998497605f, 0.382283598f},
std::array<float,2>{0.23755528f, 0.93377763f},
std::array<float,2>{0.421321779f, 0.203275323f},
std::array<float,2>{0.582357287f, 0.57607311f},
std::array<float,2>{0.832102597f, 0.0272093061f},
std::array<float,2>{0.0545281842f, 0.71477735f},
std::array<float,2>{0.305385262f, 0.267521858f},
std::array<float,2>{0.686615825f, 0.857284427f},
std::array<float,2>{0.576056302f, 0.425282896f},
std::array<float,2>{0.432455987f, 0.905873954f},
std::array<float,2>{0.219007388f, 0.218873665f},
std::array<float,2>{0.976123691f, 0.61610347f},
std::array<float,2>{0.689844012f, 0.163187295f},
std::array<float,2>{0.331805319f, 0.515743375f},
std::array<float,2>{0.101693176f, 0.492777824f},
std::array<float,2>{0.761978567f, 0.973083913f},
std::array<float,2>{0.881507874f, 0.319255322f},
std::array<float,2>{0.158942908f, 0.764076889f},
std::array<float,2>{0.47357589f, 0.0825156569f},
std::array<float,2>{0.506561458f, 0.645588577f},
std::array<float,2>{0.958068192f, 0.194572017f},
std::array<float,2>{0.208517507f, 0.593181729f},
std::array<float,2>{0.384732902f, 0.399142206f},
std::array<float,2>{0.594373286f, 0.915998101f},
std::array<float,2>{0.631330907f, 0.283533841f},
std::array<float,2>{0.276449203f, 0.841085076f},
std::array<float,2>{0.00218689488f, 0.0534030795f},
std::array<float,2>{0.86142695f, 0.725818872f},
std::array<float,2>{0.553109884f, 0.110603951f},
std::array<float,2>{0.439171135f, 0.65904963f},
std::array<float,2>{0.154349536f, 0.344438344f},
std::array<float,2>{0.933772624f, 0.798176289f},
std::array<float,2>{0.793344498f, 0.446588695f},
std::array<float,2>{0.0656427965f, 0.958511472f},
std::array<float,2>{0.367030859f, 0.147355884f},
std::array<float,2>{0.727139652f, 0.534129024f},
std::array<float,2>{0.982186794f, 0.0584340021f},
std::array<float,2>{0.230762526f, 0.733066857f},
std::array<float,2>{0.423820913f, 0.29610762f},
std::array<float,2>{0.566020489f, 0.83014673f},
std::array<float,2>{0.674787879f, 0.393869996f},
std::array<float,2>{0.304308653f, 0.906670392f},
std::array<float,2>{0.0569864549f, 0.202721879f},
std::array<float,2>{0.840137064f, 0.582588255f},
std::array<float,2>{0.512876868f, 0.151442185f},
std::array<float,2>{0.476965278f, 0.541245401f},
std::array<float,2>{0.165786728f, 0.439304531f},
std::array<float,2>{0.882879674f, 0.961171508f},
std::array<float,2>{0.757162452f, 0.355918407f},
std::array<float,2>{0.0940705463f, 0.811477721f},
std::array<float,2>{0.3378025f, 0.119335771f},
std::array<float,2>{0.697644055f, 0.671256244f},
std::array<float,2>{0.868210852f, 0.229889572f},
std::array<float,2>{0.0125927813f, 0.621080458f},
std::array<float,2>{0.273143888f, 0.430456102f},
std::array<float,2>{0.637401044f, 0.897042096f},
std::array<float,2>{0.602171719f, 0.278797477f},
std::array<float,2>{0.382616162f, 0.851387382f},
std::array<float,2>{0.216027871f, 0.0170001071f},
std::array<float,2>{0.963547766f, 0.710313797f},
std::array<float,2>{0.725960255f, 0.0924905613f},
std::array<float,2>{0.374166816f, 0.652733386f},
std::array<float,2>{0.0772497728f, 0.325144738f},
std::array<float,2>{0.785946965f, 0.757791042f},
std::array<float,2>{0.923776686f, 0.48438859f},
std::array<float,2>{0.140985101f, 0.979648292f},
std::array<float,2>{0.449371904f, 0.17159757f},
std::array<float,2>{0.56176132f, 0.52446413f},
std::array<float,2>{0.805946767f, 0.0960887f},
std::array<float,2>{0.0811766237f, 0.676935971f},
std::array<float,2>{0.351028591f, 0.369357258f},
std::array<float,2>{0.749465406f, 0.784351587f},
std::array<float,2>{0.539952159f, 0.464821965f},
std::array<float,2>{0.467291653f, 0.942279875f},
std::array<float,2>{0.130845264f, 0.132635489f},
std::array<float,2>{0.911215603f, 0.548850179f},
std::array<float,2>{0.654971302f, 0.218268052f},
std::array<float,2>{0.260555387f, 0.570299864f},
std::array<float,2>{0.0260918476f, 0.386924028f},
std::array<float,2>{0.851642489f, 0.922703862f},
std::array<float,2>{0.949849069f, 0.299161553f},
std::array<float,2>{0.190187946f, 0.824437261f},
std::array<float,2>{0.395406753f, 0.0396614894f},
std::array<float,2>{0.614219129f, 0.743619263f},
std::array<float,2>{0.904087782f, 0.173657671f},
std::array<float,2>{0.177290961f, 0.512025714f},
std::array<float,2>{0.497037262f, 0.473913163f},
std::array<float,2>{0.521893024f, 0.988170624f},
std::array<float,2>{0.707756281f, 0.330049008f},
std::array<float,2>{0.322507441f, 0.770328701f},
std::array<float,2>{0.122114174f, 0.0762119144f},
std::array<float,2>{0.777946711f, 0.639226377f},
std::array<float,2>{0.589090645f, 0.00978536159f},
std::array<float,2>{0.410201848f, 0.703011513f},
std::array<float,2>{0.247178599f, 0.262157202f},
std::array<float,2>{0.990360379f, 0.870250762f},
std::array<float,2>{0.819674253f, 0.410882205f},
std::array<float,2>{0.0410146229f, 0.882453501f},
std::array<float,2>{0.290029556f, 0.243061289f},
std::array<float,2>{0.670831084f, 0.6011222f},
std::array<float,2>{0.887945533f, 0.00764565449f},
std::array<float,2>{0.168269649f, 0.693579793f},
std::array<float,2>{0.483620197f, 0.254965454f},
std::array<float,2>{0.510700345f, 0.866066754f},
std::array<float,2>{0.700622857f, 0.414846718f},
std::array<float,2>{0.33989203f, 0.88478756f},
std::array<float,2>{0.0999645516f, 0.240520403f},
std::array<float,2>{0.751823246f, 0.602025151f},
std::array<float,2>{0.569451988f, 0.180195689f},
std::array<float,2>{0.427757502f, 0.504282832f},
std::array<float,2>{0.229627639f, 0.480315238f},
std::array<float,2>{0.979902506f, 0.998463809f},
std::array<float,2>{0.837286651f, 0.335960329f},
std::array<float,2>{0.0621473305f, 0.780715406f},
std::array<float,2>{0.297750801f, 0.0694739968f},
std::array<float,2>{0.678445458f, 0.626508236f},
std::array<float,2>{0.78359133f, 0.208936349f},
std::array<float,2>{0.0729355887f, 0.572024584f},
std::array<float,2>{0.367264062f, 0.377405912f},
std::array<float,2>{0.721439064f, 0.931599736f},
std::array<float,2>{0.55706352f, 0.306158423f},
std::array<float,2>{0.448443025f, 0.813420713f},
std::array<float,2>{0.145168975f, 0.0383826867f},
std::array<float,2>{0.927492321f, 0.735697746f},
std::array<float,2>{0.633401513f, 0.107572064f},
std::array<float,2>{0.269492f, 0.68163681f},
std::array<float,2>{0.0116737131f, 0.363843858f},
std::array<float,2>{0.871816576f, 0.796653748f},
std::array<float,2>{0.965955913f, 0.458415836f},
std::array<float,2>{0.212625369f, 0.947143972f},
std::array<float,2>{0.377038985f, 0.13686572f},
std::array<float,2>{0.608714938f, 0.561830997f},
std::array<float,2>{0.857025862f, 0.0791367292f},
std::array<float,2>{0.0279751234f, 0.643056035f},
std::array<float,2>{0.262741834f, 0.314405382f},
std::array<float,2>{0.648991644f, 0.759924591f},
std::array<float,2>{0.612622917f, 0.496223986f},
std::array<float,2>{0.392543465f, 0.970032573f},
std::array<float,2>{0.193744123f, 0.158219799f},
std::array<float,2>{0.947217226f, 0.523115337f},
std::array<float,2>{0.74300772f, 0.225897446f},
std::array<float,2>{0.345805109f, 0.612992644f},
std::array<float,2>{0.0843196884f, 0.429510415f},
std::array<float,2>{0.80998987f, 0.899680376f},
std::array<float,2>{0.910002589f, 0.271912336f},
std::array<float,2>{0.126053467f, 0.853095412f},
std::array<float,2>{0.461414009f, 0.0284441672f},
std::array<float,2>{0.54648298f, 0.7184425f},
std::array<float,2>{0.984452784f, 0.140773997f},
std::array<float,2>{0.24419412f, 0.538856924f},
std::array<float,2>{0.407656819f, 0.450454116f},
std::array<float,2>{0.590863168f, 0.954914451f},
std::array<float,2>{0.667509258f, 0.349496484f},
std::array<float,2>{0.294764489f, 0.803213179f},
std::array<float,2>{0.0436802916f, 0.114447765f},
std::array<float,2>{0.813062429f, 0.661262155f},
std::array<float,2>{0.516165257f, 0.0470145158f},
std::array<float,2>{0.494011462f, 0.721142709f},
std::array<float,2>{0.174922764f, 0.287109882f},
std::array<float,2>{0.898526728f, 0.83676219f},
std::array<float,2>{0.774327815f, 0.405406862f},
std::array<float,2>{0.119134538f, 0.9210186f},
std::array<float,2>{0.32512185f, 0.188464448f},
std::array<float,2>{0.706141174f, 0.587920606f},
std::array<float,2>{0.941406906f, 0.122142032f},
std::array<float,2>{0.195714593f, 0.667025745f},
std::array<float,2>{0.405046523f, 0.355105788f},
std::array<float,2>{0.622588694f, 0.805969834f},
std::array<float,2>{0.644444764f, 0.443187267f},
std::array<float,2>{0.256293178f, 0.965514183f},
std::array<float,2>{0.0226824153f, 0.153154016f},
std::array<float,2>{0.849854827f, 0.544737041f},
std::array<float,2>{0.536546826f, 0.195722044f},
std::array<float,2>{0.460440248f, 0.579283535f},
std::array<float,2>{0.137214571f, 0.398403078f},
std::array<float,2>{0.920575261f, 0.913026333f},
std::array<float,2>{0.798295677f, 0.291904569f},
std::array<float,2>{0.0899819657f, 0.835802436f},
std::array<float,2>{0.352603734f, 0.0603490658f},
std::array<float,2>{0.7375651f, 0.729140162f},
std::array<float,2>{0.827975869f, 0.167611346f},
std::array<float,2>{0.0362863578f, 0.528979659f},
std::array<float,2>{0.288575411f, 0.491960794f},
std::array<float,2>{0.656709671f, 0.982318401f},
std::array<float,2>{0.58004421f, 0.323757917f},
std::array<float,2>{0.415023059f, 0.750609219f},
std::array<float,2>{0.24088417f, 0.0867191479f},
std::array<float,2>{0.993019402f, 0.649894238f},
std::array<float,2>{0.713659346f, 0.0197567884f},
std::array<float,2>{0.314511418f, 0.704011798f},
std::array<float,2>{0.110520422f, 0.276777625f},
std::array<float,2>{0.771033704f, 0.845668972f},
std::array<float,2>{0.892034531f, 0.436516702f},
std::array<float,2>{0.180658013f, 0.891892016f},
std::array<float,2>{0.486946374f, 0.2336317f},
std::array<float,2>{0.524961233f, 0.621559322f},
std::array<float,2>{0.759988844f, 0.0461412631f},
std::array<float,2>{0.10836038f, 0.748569608f},
std::array<float,2>{0.334647596f, 0.302697241f},
std::array<float,2>{0.691657901f, 0.822277963f},
std::array<float,2>{0.503338456f, 0.383963943f},
std::array<float,2>{0.470422715f, 0.929400623f},
std::array<float,2>{0.161307544f, 0.212003946f},
std::array<float,2>{0.875035882f, 0.56511277f},
std::array<float,2>{0.681379974f, 0.128606126f},
std::array<float,2>{0.309567481f, 0.553389251f},
std::array<float,2>{0.048320815f, 0.466220498f},
std::array<float,2>{0.828273594f, 0.941131055f},
std::array<float,2>{0.9694646f, 0.37209931f},
std::array<float,2>{0.22637862f, 0.787791908f},
std::array<float,2>{0.434751302f, 0.0983641893f},
std::array<float,2>{0.57062763f, 0.672477126f},
std::array<float,2>{0.932539582f, 0.249603465f},
std::array<float,2>{0.151856914f, 0.594569862f},
std::array<float,2>{0.442188442f, 0.408506513f},
std::array<float,2>{0.547288775f, 0.875502408f},
std::array<float,2>{0.734189868f, 0.2605533f},
std::array<float,2>{0.363049597f, 0.873259962f},
std::array<float,2>{0.0680805519f, 0.0132509926f},
std::array<float,2>{0.790739655f, 0.697518766f},
std::array<float,2>{0.599907637f, 0.0724974424f},
std::array<float,2>{0.387987852f, 0.636067033f},
std::array<float,2>{0.206788346f, 0.334400594f},
std::array<float,2>{0.955221236f, 0.765989959f},
std::array<float,2>{0.863862991f, 0.472284228f},
std::array<float,2>{0.00469182804f, 0.990171671f},
std::array<float,2>{0.279314995f, 0.178787217f},
std::array<float,2>{0.626815319f, 0.509594142f},
std::array<float,2>{0.879220426f, 0.0835826769f},
std::array<float,2>{0.157462358f, 0.644948959f},
std::array<float,2>{0.474810243f, 0.319738239f},
std::array<float,2>{0.504429638f, 0.765422583f},
std::array<float,2>{0.689288795f, 0.493477702f},
std::array<float,2>{0.329930276f, 0.97460562f},
std::array<float,2>{0.1036755f, 0.16239506f},
std::array<float,2>{0.764743805f, 0.517396986f},
std::array<float,2>{0.57795471f, 0.21977672f},
std::array<float,2>{0.430628747f, 0.616337061f},
std::array<float,2>{0.222512871f, 0.424441546f},
std::array<float,2>{0.974256277f, 0.904899836f},
std::array<float,2>{0.834623337f, 0.266532838f},
std::array<float,2>{0.0519672185f, 0.856185198f},
std::array<float,2>{0.307516038f, 0.0263131708f},
std::array<float,2>{0.684448242f, 0.712988019f},
std::array<float,2>{0.796774268f, 0.14812392f},
std::array<float,2>{0.0641390756f, 0.534382045f},
std::array<float,2>{0.364243031f, 0.445493549f},
std::array<float,2>{0.729601324f, 0.957704186f},
std::array<float,2>{0.552219868f, 0.345379382f},
std::array<float,2>{0.440538138f, 0.797073901f},
std::array<float,2>{0.153866246f, 0.109568208f},
std::array<float,2>{0.937449217f, 0.659535289f},
std::array<float,2>{0.629654169f, 0.0543398745f},
std::array<float,2>{0.274862081f, 0.724709153f},
std::array<float,2>{0.0010710964f, 0.284609407f},
std::array<float,2>{0.859823108f, 0.8400774f},
std::array<float,2>{0.960682213f, 0.399968714f},
std::array<float,2>{0.210863352f, 0.91476804f},
std::array<float,2>{0.385875493f, 0.193518132f},
std::array<float,2>{0.597557008f, 0.591930151f},
std::array<float,2>{0.844418347f, 0.00361787388f},
std::array<float,2>{0.0185757559f, 0.688599706f},
std::array<float,2>{0.252604961f, 0.253216684f},
std::array<float,2>{0.646613121f, 0.860323012f},
std::array<float,2>{0.620073199f, 0.421711296f},
std::array<float,2>{0.400871903f, 0.889896214f},
std::array<float,2>{0.202894703f, 0.238092482f},
std::array<float,2>{0.941376388f, 0.606914401f},
std::array<float,2>{0.738335669f, 0.186381519f},
std::array<float,2>{0.357496172f, 0.500671983f},
std::array<float,2>{0.0870166272f, 0.483652622f},
std::array<float,2>{0.80207175f, 0.992486179f},
std::array<float,2>{0.916351318f, 0.343061894f},
std::array<float,2>{0.133498222f, 0.776705801f},
std::array<float,2>{0.456826895f, 0.0650641322f},
std::array<float,2>{0.532341003f, 0.631934226f},
std::array<float,2>{0.997488618f, 0.204380199f},
std::array<float,2>{0.234412357f, 0.574788749f},
std::array<float,2>{0.418373495f, 0.381446809f},
std::array<float,2>{0.584656775f, 0.934645116f},
std::array<float,2>{0.660915673f, 0.312309951f},
std::array<float,2>{0.281986296f, 0.817131758f},
std::array<float,2>{0.0315553993f, 0.0318075232f},
std::array<float,2>{0.822889447f, 0.741097152f},
std::array<float,2>{0.530444026f, 0.103032805f},
std::array<float,2>{0.490936786f, 0.685235322f},
std::array<float,2>{0.186484396f, 0.361126631f},
std::array<float,2>{0.897595406f, 0.792224288f},
std::array<float,2>{0.766072273f, 0.455317974f},
std::array<float,2>{0.113295123f, 0.952623069f},
std::array<float,2>{0.317911565f, 0.134082049f},
std::array<float,2>{0.715267539f, 0.556696296f},
std::array<float,2>{0.95207119f, 0.0404166542f},
std::array<float,2>{0.187800527f, 0.743140697f},
std::array<float,2>{0.397336811f, 0.300354034f},
std::array<float,2>{0.616463959f, 0.826086521f},
std::array<float,2>{0.653755903f, 0.388186514f},
std::array<float,2>{0.258626372f, 0.923758507f},
std::array<float,2>{0.0239442047f, 0.21731402f},
std::array<float,2>{0.854544342f, 0.569123805f},
std::array<float,2>{0.542750001f, 0.131577924f},
std::array<float,2>{0.465019137f, 0.550477803f},
std::array<float,2>{0.132163957f, 0.462931186f},
std::array<float,2>{0.91331929f, 0.942609131f},
std::array<float,2>{0.807754815f, 0.370390654f},
std::array<float,2>{0.0785540864f, 0.783852458f},
std::array<float,2>{0.348496437f, 0.0974797159f},
std::array<float,2>{0.746551216f, 0.676168025f},
std::array<float,2>{0.816650331f, 0.243538409f},
std::array<float,2>{0.0420436226f, 0.600161254f},
std::array<float,2>{0.291909784f, 0.411438614f},
std::array<float,2>{0.669241488f, 0.881070733f},
std::array<float,2>{0.586399496f, 0.262829065f},
std::array<float,2>{0.413156927f, 0.869470477f},
std::array<float,2>{0.249265209f, 0.0109443842f},
std::array<float,2>{0.988946319f, 0.702023566f},
std::array<float,2>{0.709030449f, 0.0774294958f},
std::array<float,2>{0.321947664f, 0.640286505f},
std::array<float,2>{0.124991469f, 0.329084367f},
std::array<float,2>{0.781070828f, 0.771026552f},
std::array<float,2>{0.906004846f, 0.472729057f},
std::array<float,2>{0.179610014f, 0.987065494f},
std::array<float,2>{0.499705315f, 0.172690466f},
std::array<float,2>{0.520072997f, 0.513569534f},
std::array<float,2>{0.754060924f, 0.12016762f},
std::array<float,2>{0.0957096741f, 0.670336246f},
std::array<float,2>{0.338835597f, 0.357220232f},
std::array<float,2>{0.696178734f, 0.812216341f},
std::array<float,2>{0.514083803f, 0.437603772f},
std::array<float,2>{0.478715956f, 0.962660372f},
std::array<float,2>{0.167772934f, 0.15077351f},
std::array<float,2>{0.885302544f, 0.542178094f},
std::array<float,2>{0.672554612f, 0.201406658f},
std::array<float,2>{0.301600963f, 0.583159745f},
std::array<float,2>{0.0550035276f, 0.393482625f},
std::array<float,2>{0.842749953f, 0.907765746f},
std::array<float,2>{0.98335135f, 0.29540056f},
std::array<float,2>{0.234081119f, 0.8318097f},
std::array<float,2>{0.425734639f, 0.0567738973f},
std::array<float,2>{0.564287961f, 0.734124899f},
std::array<float,2>{0.924180448f, 0.170279354f},
std::array<float,2>{0.144110888f, 0.523465753f},
std::array<float,2>{0.452484161f, 0.485773861f},
std::array<float,2>{0.560456634f, 0.979236662f},
std::array<float,2>{0.723381817f, 0.325295627f},
std::array<float,2>{0.372106463f, 0.756476581f},
std::array<float,2>{0.0746419802f, 0.0931674913f},
std::array<float,2>{0.787384331f, 0.653702319f},
std::array<float,2>{0.605057538f, 0.0165420212f},
std::array<float,2>{0.380697161f, 0.709247231f},
std::array<float,2>{0.218066901f, 0.277979463f},
std::array<float,2>{0.962824285f, 0.850361824f},
std::array<float,2>{0.869210541f, 0.431557f},
std::array<float,2>{0.013881579f, 0.897570193f},
std::array<float,2>{0.270869464f, 0.228664324f},
std::array<float,2>{0.639244974f, 0.619369328f},
std::array<float,2>{0.906612635f, 0.0281069539f},
std::array<float,2>{0.12773864f, 0.716954887f},
std::array<float,2>{0.463877767f, 0.273244917f},
std::array<float,2>{0.544278085f, 0.852168858f},
std::array<float,2>{0.744736373f, 0.4280065f},
std::array<float,2>{0.344142497f, 0.899194956f},
std::array<float,2>{0.0838304609f, 0.22555761f},
std::array<float,2>{0.811896145f, 0.611613929f},
std::array<float,2>{0.610091388f, 0.159830838f},
std::array<float,2>{0.393134654f, 0.521890044f},
std::array<float,2>{0.191943973f, 0.497780889f},
std::array<float,2>{0.948272526f, 0.969419181f},
std::array<float,2>{0.857619464f, 0.313279092f},
std::array<float,2>{0.0300088562f, 0.760756612f},
std::array<float,2>{0.264667034f, 0.07855542f},
std::array<float,2>{0.650610328f, 0.644368768f},
std::array<float,2>{0.775488317f, 0.188652307f},
std::array<float,2>{0.120822847f, 0.589302421f},
std::array<float,2>{0.327707291f, 0.405087203f},
std::array<float,2>{0.705062091f, 0.920397043f},
std::array<float,2>{0.517635584f, 0.288833678f},
std::array<float,2>{0.495350748f, 0.837095618f},
std::array<float,2>{0.173241109f, 0.0481680632f},
std::array<float,2>{0.900825441f, 0.721741319f},
std::array<float,2>{0.664119244f, 0.113740548f},
std::array<float,2>{0.295240849f, 0.660830438f},
std::array<float,2>{0.0451725945f, 0.347987831f},
std::array<float,2>{0.815874636f, 0.803845942f},
std::array<float,2>{0.987619698f, 0.450193703f},
std::array<float,2>{0.243873417f, 0.953657329f},
std::array<float,2>{0.409499615f, 0.141972229f},
std::array<float,2>{0.593188643f, 0.537360311f},
std::array<float,2>{0.839801908f, 0.0692137927f},
std::array<float,2>{0.0591706373f, 0.625416994f},
std::array<float,2>{0.299336731f, 0.336971581f},
std::array<float,2>{0.6766482f, 0.779565513f},
std::array<float,2>{0.568253696f, 0.478781849f},
std::array<float,2>{0.426100612f, 0.999978542f},
std::array<float,2>{0.22719036f, 0.181284055f},
std::array<float,2>{0.977766454f, 0.505384028f},
std::array<float,2>{0.703065336f, 0.241999462f},
std::array<float,2>{0.343595356f, 0.603194773f},
std::array<float,2>{0.0983695313f, 0.415201545f},
std::array<float,2>{0.752004981f, 0.886550009f},
std::array<float,2>{0.890523195f, 0.254604697f},
std::array<float,2>{0.171751976f, 0.866505086f},
std::array<float,2>{0.481171221f, 0.00593347987f},
std::array<float,2>{0.508651912f, 0.694904625f},
std::array<float,2>{0.967755497f, 0.138524204f},
std::array<float,2>{0.214482725f, 0.56143105f},
std::array<float,2>{0.375656724f, 0.457442254f},
std::array<float,2>{0.606245697f, 0.945967257f},
std::array<float,2>{0.635220051f, 0.365009725f},
std::array<float,2>{0.266854197f, 0.795722723f},
std::array<float,2>{0.00971735641f, 0.108499095f},
std::array<float,2>{0.874333918f, 0.680159807f},
std::array<float,2>{0.556427419f, 0.0378119834f},
std::array<float,2>{0.446212292f, 0.735085726f},
std::array<float,2>{0.148064926f, 0.304698288f},
std::array<float,2>{0.929014921f, 0.813492715f},
std::array<float,2>{0.78307724f, 0.378863603f},
std::array<float,2>{0.0711290464f, 0.930249453f},
std::array<float,2>{0.37085703f, 0.207555383f},
std::array<float,2>{0.719842374f, 0.570360601f},
std::array<float,2>{0.971208811f, 0.0988058299f},
std::array<float,2>{0.223471045f, 0.673082411f},
std::array<float,2>{0.437452912f, 0.371732265f},
std::array<float,2>{0.57419163f, 0.788923025f},
std::array<float,2>{0.682339072f, 0.465737283f},
std::array<float,2>{0.311800152f, 0.94022733f},
std::array<float,2>{0.0500527695f, 0.127826974f},
std::array<float,2>{0.830244124f, 0.553821206f},
std::array<float,2>{0.500485837f, 0.211060151f},
std::array<float,2>{0.472083479f, 0.565567851f},
std::array<float,2>{0.162715375f, 0.382889926f},
std::array<float,2>{0.878020227f, 0.927775979f},
std::array<float,2>{0.759061635f, 0.300898552f},
std::array<float,2>{0.10548766f, 0.823964775f},
std::array<float,2>{0.332390904f, 0.0453206003f},
std::array<float,2>{0.695258081f, 0.749946475f},
std::array<float,2>{0.867022753f, 0.178167433f},
std::array<float,2>{0.0059521324f, 0.508726537f},
std::array<float,2>{0.279120535f, 0.470837593f},
std::array<float,2>{0.627575517f, 0.988487363f},
std::array<float,2>{0.599157214f, 0.335483193f},
std::array<float,2>{0.3894068f, 0.76700449f},
std::array<float,2>{0.204521969f, 0.0738860518f},
std::array<float,2>{0.953415573f, 0.635617316f},
std::array<float,2>{0.730488062f, 0.0117757777f},
std::array<float,2>{0.359983146f, 0.699090421f},
std::array<float,2>{0.0695099831f, 0.260820657f},
std::array<float,2>{0.79194504f, 0.874983668f},
std::array<float,2>{0.930294156f, 0.409184396f},
std::array<float,2>{0.14968124f, 0.876470625f},
std::array<float,2>{0.443987638f, 0.24822633f},
std::array<float,2>{0.549859107f, 0.595418394f},
std::array<float,2>{0.800162435f, 0.0590127409f},
std::array<float,2>{0.0933487043f, 0.729551315f},
std::array<float,2>{0.353725821f, 0.292485386f},
std::array<float,2>{0.734698534f, 0.834078431f},
std::array<float,2>{0.537633359f, 0.397220165f},
std::array<float,2>{0.457494408f, 0.913691878f},
std::array<float,2>{0.138783336f, 0.196811602f},
std::array<float,2>{0.918043017f, 0.578517795f},
std::array<float,2>{0.641040802f, 0.153992355f},
std::array<float,2>{0.254344016f, 0.543135107f},
std::array<float,2>{0.0197658204f, 0.442374378f},
std::array<float,2>{0.848645747f, 0.96670711f},
std::array<float,2>{0.944968402f, 0.354056865f},
std::array<float,2>{0.198049158f, 0.805147469f},
std::array<float,2>{0.403476864f, 0.121452957f},
std::array<float,2>{0.624431014f, 0.666813433f},
std::array<float,2>{0.893603742f, 0.232915372f},
std::array<float,2>{0.181914479f, 0.622243881f},
std::array<float,2>{0.485216469f, 0.437254101f},
std::array<float,2>{0.525607169f, 0.890817285f},
std::array<float,2>{0.711715639f, 0.275632143f},
std::array<float,2>{0.313900262f, 0.844199181f},
std::array<float,2>{0.111824982f, 0.020587841f},
std::array<float,2>{0.771668434f, 0.704903483f},
std::array<float,2>{0.581527293f, 0.0874739066f},
std::array<float,2>{0.416309774f, 0.64905411f},
std::array<float,2>{0.239566401f, 0.32278657f},
std::array<float,2>{0.994822919f, 0.751869678f},
std::array<float,2>{0.824693203f, 0.490624577f},
std::array<float,2>{0.0377707146f, 0.980829179f},
std::array<float,2>{0.28538692f, 0.166078851f},
std::array<float,2>{0.659381628f, 0.527452946f},
std::array<float,2>{0.934754193f, 0.11209739f},
std::array<float,2>{0.15612191f, 0.656394243f},
std::array<float,2>{0.437668413f, 0.347107142f},
std::array<float,2>{0.554175019f, 0.798854828f},
std::array<float,2>{0.727554262f, 0.448031098f},
std::array<float,2>{0.365956247f, 0.960184038f},
std::array<float,2>{0.0649998412f, 0.14475897f},
std::array<float,2>{0.794222653f, 0.532437325f},
std::array<float,2>{0.595181823f, 0.19275941f},
std::array<float,2>{0.383151382f, 0.591757417f},
std::array<float,2>{0.207507789f, 0.401649892f},
std::array<float,2>{0.95777005f, 0.917551517f},
std::array<float,2>{0.863273978f, 0.283094287f},
std::array<float,2>{0.0030525839f, 0.843682945f},
std::array<float,2>{0.27578643f, 0.0508163348f},
std::array<float,2>{0.632433951f, 0.723602891f},
std::array<float,2>{0.763007104f, 0.160696611f},
std::array<float,2>{0.103234485f, 0.518896043f},
std::array<float,2>{0.330557168f, 0.49457413f},
std::array<float,2>{0.691090524f, 0.97573173f},
std::array<float,2>{0.507804275f, 0.318333447f},
std::array<float,2>{0.474024445f, 0.761855364f},
std::array<float,2>{0.159415603f, 0.0853958428f},
std::array<float,2>{0.882385135f, 0.647774577f},
std::array<float,2>{0.685815156f, 0.0250892472f},
std::array<float,2>{0.306486845f, 0.711341739f},
std::array<float,2>{0.0536196716f, 0.267632335f},
std::array<float,2>{0.833504319f, 0.857534766f},
std::array<float,2>{0.975509167f, 0.422517568f},
std::array<float,2>{0.220315456f, 0.903199673f},
std::array<float,2>{0.433520913f, 0.221463442f},
std::array<float,2>{0.574571311f, 0.615048349f},
std::array<float,2>{0.82089591f, 0.034025874f},
std::array<float,2>{0.0342932716f, 0.740219533f},
std::array<float,2>{0.283752292f, 0.310296267f},
std::array<float,2>{0.662802041f, 0.818597853f},
std::array<float,2>{0.583934605f, 0.379090905f},
std::array<float,2>{0.420547962f, 0.936191499f},
std::array<float,2>{0.237137064f, 0.206575572f},
std::array<float,2>{0.999452829f, 0.577110708f},
std::array<float,2>{0.717676103f, 0.135420993f},
std::array<float,2>{0.319682658f, 0.556130409f},
std::array<float,2>{0.116308108f, 0.453585714f},
std::array<float,2>{0.769410253f, 0.949629962f},
std::array<float,2>{0.895633399f, 0.36229676f},
std::array<float,2>{0.184546575f, 0.789286077f},
std::array<float,2>{0.489367813f, 0.105179109f},
std::array<float,2>{0.527947068f, 0.686205089f},
std::array<float,2>{0.937687874f, 0.235472441f},
std::array<float,2>{0.199730128f, 0.608716011f},
std::array<float,2>{0.399280727f, 0.419842929f},
std::array<float,2>{0.618063092f, 0.887008369f},
std::array<float,2>{0.646066189f, 0.250494003f},
std::array<float,2>{0.250511676f, 0.861635327f},
std::array<float,2>{0.0161344074f, 0.00180002663f},
std::array<float,2>{0.847059906f, 0.690068245f},
std::array<float,2>{0.533811152f, 0.0639723092f},
std::array<float,2>{0.45499146f, 0.630112827f},
std::array<float,2>{0.134962097f, 0.340016991f},
std::array<float,2>{0.914619684f, 0.774429977f},
std::array<float,2>{0.804298162f, 0.48222506f},
std::array<float,2>{0.0880121961f, 0.995775759f},
std::array<float,2>{0.356930882f, 0.185317546f},
std::array<float,2>{0.741646469f, 0.503310144f},
std::array<float,2>{0.991625905f, 0.00821645744f},
std::array<float,2>{0.246304572f, 0.700206399f},
std::array<float,2>{0.411929101f, 0.263708085f},
std::array<float,2>{0.588062227f, 0.868809283f},
std::array<float,2>{0.671012104f, 0.413256615f},
std::array<float,2>{0.290181249f, 0.879310966f},
std::array<float,2>{0.039391391f, 0.245356664f},
std::array<float,2>{0.818889976f, 0.597896576f},
std::array<float,2>{0.522837937f, 0.174599662f},
std::array<float,2>{0.498033911f, 0.515008509f},
std::array<float,2>{0.176141039f, 0.474974215f},
std::array<float,2>{0.902772665f, 0.985895514f},
std::array<float,2>{0.778489769f, 0.33115533f},
std::array<float,2>{0.121817484f, 0.772282124f},
std::array<float,2>{0.323995948f, 0.0747133791f},
std::array<float,2>{0.708027959f, 0.638170779f},
std::array<float,2>{0.853268504f, 0.215024039f},
std::array<float,2>{0.0264576916f, 0.568015635f},
std::array<float,2>{0.261547744f, 0.38991192f},
std::array<float,2>{0.655778646f, 0.925266087f},
std::array<float,2>{0.615182161f, 0.298552781f},
std::array<float,2>{0.395797938f, 0.827177823f},
std::array<float,2>{0.191127867f, 0.0417580083f},
std::array<float,2>{0.950322807f, 0.744720697f},
std::array<float,2>{0.74817121f, 0.0937846303f},
std::array<float,2>{0.349781454f, 0.677885175f},
std::array<float,2>{0.080470264f, 0.369027495f},
std::array<float,2>{0.805569112f, 0.782990098f},
std::array<float,2>{0.910806715f, 0.462568492f},
std::array<float,2>{0.129053608f, 0.94355011f},
std::array<float,2>{0.468311906f, 0.130196944f},
std::array<float,2>{0.540974617f, 0.547571898f},
std::array<float,2>{0.787014544f, 0.0915849283f},
std::array<float,2>{0.0766126513f, 0.654446185f},
std::array<float,2>{0.373994678f, 0.326576054f},
std::array<float,2>{0.724890292f, 0.754731357f},
std::array<float,2>{0.561212003f, 0.487692714f},
std::array<float,2>{0.450739115f, 0.97714448f},
std::array<float,2>{0.142297253f, 0.169486359f},
std::array<float,2>{0.921897531f, 0.525969982f},
std::array<float,2>{0.638071418f, 0.226872772f},
std::array<float,2>{0.271645963f, 0.619105518f},
std::array<float,2>{0.0135123534f, 0.432107568f},
std::array<float,2>{0.867837965f, 0.894943237f},
std::array<float,2>{0.964109302f, 0.279993117f},
std::array<float,2>{0.215029866f, 0.848567009f},
std::array<float,2>{0.381175041f, 0.0194413718f},
std::array<float,2>{0.603052437f, 0.707709193f},
std::array<float,2>{0.884550452f, 0.148441732f},
std::array<float,2>{0.16437684f, 0.53963238f},
std::array<float,2>{0.478464335f, 0.439473242f},
std::array<float,2>{0.512251675f, 0.96360147f},
std::array<float,2>{0.698751688f, 0.357470244f},
std::array<float,2>{0.336029887f, 0.808651984f},
std::array<float,2>{0.0950931385f, 0.118165314f},
std::array<float,2>{0.756147802f, 0.66918689f},
std::array<float,2>{0.565030396f, 0.0557212383f},
std::array<float,2>{0.42204982f, 0.731553018f},
std::array<float,2>{0.231477201f, 0.29430148f},
std::array<float,2>{0.980735064f, 0.829121232f},
std::array<float,2>{0.841432989f, 0.390923411f},
std::array<float,2>{0.0581596121f, 0.909759879f},
std::array<float,2>{0.303455532f, 0.20067215f},
std::array<float,2>{0.675581455f, 0.584504664f},
std::array<float,2>{0.899804711f, 0.0507614613f},
std::array<float,2>{0.174150199f, 0.719654024f},
std::array<float,2>{0.492715925f, 0.286160022f},
std::array<float,2>{0.516788363f, 0.839784205f},
std::array<float,2>{0.705972075f, 0.404150814f},
std::array<float,2>{0.325859457f, 0.918595731f},
std::array<float,2>{0.11753691f, 0.191321418f},
std::array<float,2>{0.774585962f, 0.586070061f},
std::array<float,2>{0.589852214f, 0.143829316f},
std::array<float,2>{0.406401008f, 0.536591351f},
std::array<float,2>{0.24541162f, 0.452445984f},
std::array<float,2>{0.985493481f, 0.95692271f},
std::array<float,2>{0.813668311f, 0.350071609f},
std::array<float,2>{0.04476583f, 0.801944017f},
std::array<float,2>{0.293694496f, 0.11610914f},
std::array<float,2>{0.666662335f, 0.663896441f},
std::array<float,2>{0.809439301f, 0.222924322f},
std::array<float,2>{0.0854790732f, 0.609462142f},
std::array<float,2>{0.34673056f, 0.426436573f},
std::array<float,2>{0.743172705f, 0.901494622f},
std::array<float,2>{0.545344949f, 0.270737678f},
std::array<float,2>{0.462839425f, 0.855015576f},
std::array<float,2>{0.125447229f, 0.030376628f},
std::array<float,2>{0.908453107f, 0.715531111f},
std::array<float,2>{0.650232077f, 0.0819840729f},
std::array<float,2>{0.26247102f, 0.641603231f},
std::array<float,2>{0.0288346894f, 0.31579423f},
std::array<float,2>{0.855664909f, 0.759223461f},
std::array<float,2>{0.946037292f, 0.499515504f},
std::array<float,2>{0.194667891f, 0.972413838f},
std::array<float,2>{0.391174018f, 0.157854855f},
std::array<float,2>{0.611385882f, 0.519986689f},
std::array<float,2>{0.872169614f, 0.106331691f},
std::array<float,2>{0.0105271386f, 0.683258533f},
std::array<float,2>{0.267701983f, 0.366504103f},
std::array<float,2>{0.634117782f, 0.793313742f},
std::array<float,2>{0.607718945f, 0.459925771f},
std::array<float,2>{0.378042549f, 0.948268831f},
std::array<float,2>{0.211162299f, 0.140566349f},
std::array<float,2>{0.964981794f, 0.560210407f},
std::array<float,2>{0.721847057f, 0.210071117f},
std::array<float,2>{0.368885487f, 0.572745144f},
std::array<float,2>{0.0740903169f, 0.375647724f},
std::array<float,2>{0.784515381f, 0.932086825f},
std::array<float,2>{0.926603079f, 0.30672586f},
std::array<float,2>{0.145625517f, 0.815465569f},
std::array<float,2>{0.448085189f, 0.0369274318f},
std::array<float,2>{0.558227956f, 0.736419559f},
std::array<float,2>{0.978821278f, 0.18358539f},
std::array<float,2>{0.229361162f, 0.507762134f},
std::array<float,2>{0.428786844f, 0.478360921f},
std::array<float,2>{0.568845809f, 0.996312499f},
std::array<float,2>{0.679439783f, 0.339307398f},
std::array<float,2>{0.298551261f, 0.778365791f},
std::array<float,2>{0.0614836216f, 0.0683152154f},
std::array<float,2>{0.836489856f, 0.627410948f},
std::array<float,2>{0.511239052f, 0.00548729533f},
std::array<float,2>{0.482462347f, 0.693058133f},
std::array<float,2>{0.169803992f, 0.256289423f},
std::array<float,2>{0.887588263f, 0.863743067f},
std::array<float,2>{0.750845373f, 0.417410493f},
std::array<float,2>{0.101260237f, 0.882927835f},
std::array<float,2>{0.341273814f, 0.238774136f},
std::array<float,2>{0.699612141f, 0.603628397f},
std::array<float,2>{0.956466794f, 0.0711135119f},
std::array<float,2>{0.20542866f, 0.633774221f},
std::array<float,2>{0.387124866f, 0.333653569f},
std::array<float,2>{0.600701749f, 0.76924932f},
std::array<float,2>{0.625003278f, 0.468804985f},
std::array<float,2>{0.281074077f, 0.991492271f},
std::array<float,2>{0.00562580256f, 0.176648632f},
std::array<float,2>{0.864647925f, 0.511461318f},
std::array<float,2>{0.548008204f, 0.246625841f},
std::array<float,2>{0.442791581f, 0.595747888f},
std::array<float,2>{0.150639474f, 0.407509774f},
std::array<float,2>{0.932970881f, 0.878145695f},
std::array<float,2>{0.789583802f, 0.258649379f},
std::array<float,2>{0.0671946481f, 0.87118113f},
std::array<float,2>{0.361668617f, 0.0153034823f},
std::array<float,2>{0.732985437f, 0.697232783f},
std::array<float,2>{0.829896569f, 0.125823915f},
std::array<float,2>{0.047289107f, 0.55114013f},
std::array<float,2>{0.309901088f, 0.468608797f},
std::array<float,2>{0.680290043f, 0.937997401f},
std::array<float,2>{0.572210073f, 0.37465325f},
std::array<float,2>{0.433677733f, 0.785627663f},
std::array<float,2>{0.224890515f, 0.100044675f},
std::array<float,2>{0.970229328f, 0.675481677f},
std::array<float,2>{0.692610621f, 0.0443133824f},
std::array<float,2>{0.335553974f, 0.746599019f},
std::array<float,2>{0.108919479f, 0.303632855f},
std::array<float,2>{0.761557519f, 0.82131362f},
std::array<float,2>{0.876417518f, 0.384928256f},
std::array<float,2>{0.160709739f, 0.926187813f},
std::array<float,2>{0.469345599f, 0.213824257f},
std::array<float,2>{0.502215207f, 0.562720597f},
std::array<float,2>{0.770327151f, 0.0222770404f},
std::array<float,2>{0.109888934f, 0.705617845f},
std::array<float,2>{0.31590274f, 0.275299281f},
std::array<float,2>{0.713942885f, 0.846714497f},
std::array<float,2>{0.524362266f, 0.434733778f},
std::array<float,2>{0.487493217f, 0.892803788f},
std::array<float,2>{0.181421041f, 0.230571181f},
std::array<float,2>{0.891529322f, 0.624117553f},
std::array<float,2>{0.65737164f, 0.164144307f},
std::array<float,2>{0.287180394f, 0.529471278f},
std::array<float,2>{0.0356163681f, 0.489985228f},
std::array<float,2>{0.826265395f, 0.983487427f},
std::array<float,2>{0.994076312f, 0.321456105f},
std::array<float,2>{0.241737723f, 0.753163755f},
std::array<float,2>{0.415604621f, 0.087991029f},
std::array<float,2>{0.578273118f, 0.651888788f},
std::array<float,2>{0.921326399f, 0.198249966f},
std::array<float,2>{0.138604164f, 0.581114173f},
std::array<float,2>{0.459128052f, 0.395593107f},
std::array<float,2>{0.535897493f, 0.912066102f},
std::array<float,2>{0.736723244f, 0.290120274f},
std::array<float,2>{0.352390379f, 0.832843244f},
std::array<float,2>{0.0916657597f, 0.0624055862f},
std::array<float,2>{0.797688723f, 0.728075922f},
std::array<float,2>{0.622040808f, 0.123722032f},
std::array<float,2>{0.405977577f, 0.664332926f},
std::array<float,2>{0.196746022f, 0.353198349f},
std::array<float,2>{0.9432109f, 0.807290196f},
std::array<float,2>{0.851016939f, 0.444294542f},
std::array<float,2>{0.0221410971f, 0.967570484f},
std::array<float,2>{0.25733009f, 0.154434979f},
std::array<float,2>{0.643387318f, 0.546807647f},
std::array<float,2>{0.885035694f, 0.118762217f},
std::array<float,2>{0.167302951f, 0.669917941f},
std::array<float,2>{0.479176551f, 0.358091414f},
std::array<float,2>{0.514599502f, 0.80932796f},
std::array<float,2>{0.695694625f, 0.440150738f},
std::array<float,2>{0.338337421f, 0.962931633f},
std::array<float,2>{0.0965328515f, 0.149087697f},
std::array<float,2>{0.754640639f, 0.53931582f},
std::array<float,2>{0.563959062f, 0.200900063f},
std::array<float,2>{0.424890131f, 0.58446902f},
std::array<float,2>{0.233871207f, 0.391194701f},
std::array<float,2>{0.982568681f, 0.909209013f},
std::array<float,2>{0.842251182f, 0.294788361f},
std::array<float,2>{0.0554405302f, 0.829920232f},
std::array<float,2>{0.300787836f, 0.0565015711f},
std::array<float,2>{0.67208004f, 0.732394636f},
std::array<float,2>{0.788083434f, 0.169361293f},
std::array<float,2>{0.0747324228f, 0.52551198f},
std::array<float,2>{0.3727355f, 0.487941235f},
std::array<float,2>{0.723021626f, 0.976671338f},
std::array<float,2>{0.559607029f, 0.327083677f},
std::array<float,2>{0.452720493f, 0.754368663f},
std::array<float,2>{0.143671736f, 0.0911276639f},
std::array<float,2>{0.924585342f, 0.655130386f},
std::array<float,2>{0.638733685f, 0.018987488f},
std::array<float,2>{0.271264911f, 0.707518876f},
std::array<float,2>{0.0142757362f, 0.27946195f},
std::array<float,2>{0.870025337f, 0.848043621f},
std::array<float,2>{0.962145925f, 0.432510376f},
std::array<float,2>{0.218274087f, 0.895088196f},
std::array<float,2>{0.38034302f, 0.22712642f},
std::array<float,2>{0.604746699f, 0.618219912f},
std::array<float,2>{0.855330944f, 0.0411107391f},
std::array<float,2>{0.0234673694f, 0.744425595f},
std::array<float,2>{0.258155584f, 0.298136234f},
std::array<float,2>{0.654203832f, 0.827797711f},
std::array<float,2>{0.617137849f, 0.390424281f},
std::array<float,2>{0.396606892f, 0.925638378f},
std::array<float,2>{0.188390478f, 0.215552509f},
std::array<float,2>{0.951655328f, 0.567852199f},
std::array<float,2>{0.747023582f, 0.130400196f},
std::array<float,2>{0.348079652f, 0.547039628f},
std::array<float,2>{0.0786336884f, 0.46205321f},
std::array<float,2>{0.808429658f, 0.944145322f},
std::array<float,2>{0.913735747f, 0.36838311f},
std::array<float,2>{0.132783845f, 0.782511234f},
std::array<float,2>{0.46573931f, 0.0946219787f},
std::array<float,2>{0.542255819f, 0.67846638f},
std::array<float,2>{0.988327563f, 0.245949566f},
std::array<float,2>{0.249674737f, 0.598524153f},
std::array<float,2>{0.413820654f, 0.4138726f},
std::array<float,2>{0.586490095f, 0.879880965f},
std::array<float,2>{0.669702172f, 0.264206409f},
std::array<float,2>{0.291397095f, 0.868230164f},
std::array<float,2>{0.0427075028f, 0.00878336094f},
std::array<float,2>{0.817353904f, 0.700853527f},
std::array<float,2>{0.519579113f, 0.0744000077f},
std::array<float,2>{0.499420196f, 0.638531327f},
std::array<float,2>{0.178830788f, 0.331548899f},
std::array<float,2>{0.905400991f, 0.77185756f},
std::array<float,2>{0.780524969f, 0.475199968f},
std::array<float,2>{0.124213308f, 0.985473514f},
std::array<float,2>{0.321558744f, 0.173988789f},
std::array<float,2>{0.709584892f, 0.515570104f},
std::array<float,2>{0.940811038f, 0.00141319935f},
std::array<float,2>{0.20237349f, 0.689550996f},
std::array<float,2>{0.401047409f, 0.250063747f},
std::array<float,2>{0.619351268f, 0.862181723f},
std::array<float,2>{0.647176445f, 0.419003427f},
std::array<float,2>{0.252164423f, 0.887522638f},
std::array<float,2>{0.0191368181f, 0.236273631f},
std::array<float,2>{0.843887568f, 0.609271348f},
std::array<float,2>{0.533088982f, 0.184753612f},
std::array<float,2>{0.45644626f, 0.503485799f},
std::array<float,2>{0.132933721f, 0.481908709f},
std::array<float,2>{0.916722f, 0.995132029f},
std::array<float,2>{0.802402198f, 0.340501219f},
std::array<float,2>{0.0877417549f, 0.775227964f},
std::array<float,2>{0.358051032f, 0.0638455376f},
std::array<float,2>{0.739082158f, 0.630822122f},
std::array<float,2>{0.822379768f, 0.206465706f},
std::array<float,2>{0.0320002921f, 0.57618618f},
std::array<float,2>{0.281310648f, 0.379463404f},
std::array<float,2>{0.660310507f, 0.935705781f},
std::array<float,2>{0.584185004f, 0.309676111f},
std::array<float,2>{0.418667555f, 0.818848073f},
std::array<float,2>{0.235293999f, 0.0332143158f},
std::array<float,2>{0.997629046f, 0.739430368f},
std::array<float,2>{0.715654016f, 0.104694486f},
std::array<float,2>{0.317439646f, 0.685776949f},
std::array<float,2>{0.113943674f, 0.361427307f},
std::array<float,2>{0.766204f, 0.789924741f},
std::array<float,2>{0.898171246f, 0.4536888f},
std::array<float,2>{0.185982361f, 0.950193405f},
std::array<float,2>{0.490321815f, 0.135208845f},
std::array<float,2>{0.530899405f, 0.556499898f},
std::array<float,2>{0.765555203f, 0.085877113f},
std::array<float,2>{0.104130715f, 0.648344398f},
std::array<float,2>{0.329515755f, 0.317797661f},
std::array<float,2>{0.688717067f, 0.762248397f},
std::array<float,2>{0.504150212f, 0.494877487f},
std::array<float,2>{0.475554258f, 0.976215065f},
std::array<float,2>{0.15792425f, 0.160352185f},
std::array<float,2>{0.879818439f, 0.519170403f},
std::array<float,2>{0.683840036f, 0.221013948f},
std::array<float,2>{0.306941539f, 0.614505053f},
std::array<float,2>{0.0526874959f, 0.422339082f},
std::array<float,2>{0.834431112f, 0.902828336f},
std::array<float,2>{0.974117994f, 0.26808086f},
std::array<float,2>{0.222145259f, 0.858007669f},
std::array<float,2>{0.430168658f, 0.0246333126f},
std::array<float,2>{0.577258527f, 0.711707652f},
std::array<float,2>{0.936643183f, 0.145280451f},
std::array<float,2>{0.153587714f, 0.532963693f},
std::array<float,2>{0.44098565f, 0.447753608f},
std::array<float,2>{0.552274406f, 0.960484922f},
std::array<float,2>{0.730056942f, 0.347628534f},
std::array<float,2>{0.363517165f, 0.799791098f},
std::array<float,2>{0.0639514625f, 0.111677386f},
std::array<float,2>{0.795939624f, 0.657157958f},
std::array<float,2>{0.596799314f, 0.0516602211f},
std::array<float,2>{0.386495143f, 0.722705901f},
std::array<float,2>{0.21029672f, 0.2825782f},
std::array<float,2>{0.960101247f, 0.843129098f},
std::array<float,2>{0.860012114f, 0.401926607f},
std::array<float,2>{0.00154997583f, 0.917026103f},
std::array<float,2>{0.275257528f, 0.192901671f},
std::array<float,2>{0.628975809f, 0.591242731f},
std::array<float,2>{0.918601334f, 0.0617626607f},
std::array<float,2>{0.139227569f, 0.727751255f},
std::array<float,2>{0.457783371f, 0.290832639f},
std::array<float,2>{0.537512839f, 0.832041264f},
std::array<float,2>{0.735072076f, 0.396048069f},
std::array<float,2>{0.354440093f, 0.911137462f},
std::array<float,2>{0.0928220972f, 0.19897835f},
std::array<float,2>{0.800464809f, 0.581942081f},
std::array<float,2>{0.624965429f, 0.154961869f},
std::array<float,2>{0.404260933f, 0.545988858f},
std::array<float,2>{0.197572306f, 0.443725973f},
std::array<float,2>{0.944744468f, 0.967155099f},
std::array<float,2>{0.849203706f, 0.352660567f},
std::array<float,2>{0.0203828309f, 0.807023048f},
std::array<float,2>{0.254601538f, 0.123329975f},
std::array<float,2>{0.641190469f, 0.664737582f},
std::array<float,2>{0.771976829f, 0.230966553f},
std::array<float,2>{0.111730099f, 0.624982178f},
std::array<float,2>{0.314216524f, 0.435315877f},
std::array<float,2>{0.711317897f, 0.893420219f},
std::array<float,2>{0.525940359f, 0.274715215f},
std::array<float,2>{0.484661341f, 0.847299695f},
std::array<float,2>{0.182423428f, 0.0218596607f},
std::array<float,2>{0.894159853f, 0.705485284f},
std::array<float,2>{0.659677863f, 0.0885533988f},
std::array<float,2>{0.285960644f, 0.651494443f},
std::array<float,2>{0.0374245681f, 0.322074711f},
std::array<float,2>{0.825072706f, 0.753440022f},
std::array<float,2>{0.99424839f, 0.489396334f},
std::array<float,2>{0.240040079f, 0.984360278f},
std::array<float,2>{0.416985661f, 0.164830014f},
std::array<float,2>{0.581601262f, 0.530216753f},
std::array<float,2>{0.830608726f, 0.100237884f},
std::array<float,2>{0.0503326654f, 0.675082028f},
std::array<float,2>{0.312183499f, 0.37437737f},
std::array<float,2>{0.682113111f, 0.78589797f},
std::array<float,2>{0.573524117f, 0.468061954f},
std::array<float,2>{0.436977267f, 0.937879443f},
std::array<float,2>{0.222849667f, 0.125230595f},
std::array<float,2>{0.970903158f, 0.551712334f},
std::array<float,2>{0.694620132f, 0.21292609f},
std::array<float,2>{0.332639992f, 0.563471138f},
std::array<float,2>{0.106112152f, 0.385448635f},
std::array<float,2>{0.759361923f, 0.926616907f},
std::array<float,2>{0.878666222f, 0.303215981f},
std::array<float,2>{0.162554249f, 0.821824133f},
std::array<float,2>{0.472610086f, 0.044919163f},
std::array<float,2>{0.500948071f, 0.746111751f},
std::array<float,2>{0.953822732f, 0.176225156f},
std::array<float,2>{0.204658553f, 0.511041999f},
std::array<float,2>{0.388948768f, 0.469239295f},
std::array<float,2>{0.598865688f, 0.991823912f},
std::array<float,2>{0.627392113f, 0.333119094f},
std::array<float,2>{0.278735042f, 0.768884897f},
std::array<float,2>{0.00636872509f, 0.070592992f},
std::array<float,2>{0.866542637f, 0.633194685f},
std::array<float,2>{0.550415635f, 0.0149534931f},
std::array<float,2>{0.443767041f, 0.696389258f},
std::array<float,2>{0.150261998f, 0.257882208f},
std::array<float,2>{0.929791868f, 0.871936023f},
std::array<float,2>{0.791283786f, 0.407852888f},
std::array<float,2>{0.0698948354f, 0.878432989f},
std::array<float,2>{0.359625816f, 0.246437788f},
std::array<float,2>{0.731052041f, 0.596317172f},
std::array<float,2>{0.97803843f, 0.0674837157f},
std::array<float,2>{0.226942003f, 0.627626657f},
std::array<float,2>{0.426455855f, 0.339447469f},
std::array<float,2>{0.567826569f, 0.779007614f},
std::array<float,2>{0.675959289f, 0.477691531f},
std::array<float,2>{0.299214214f, 0.996842384f},
std::array<float,2>{0.0586912781f, 0.182887211f},
std::array<float,2>{0.839238703f, 0.50693655f},
std::array<float,2>{0.508116066f, 0.238380894f},
std::array<float,2>{0.480652094f, 0.604313016f},
std::array<float,2>{0.170993835f, 0.417616874f},
std::array<float,2>{0.88995856f, 0.883558869f},
std::array<float,2>{0.75252986f, 0.256358504f},
std::array<float,2>{0.0979681462f, 0.863937438f},
std::array<float,2>{0.343252212f, 0.00519187236f},
std::array<float,2>{0.702371895f, 0.692439675f},
std::array<float,2>{0.874756217f, 0.140060931f},
std::array<float,2>{0.00897688419f, 0.559979141f},
std::array<float,2>{0.267296404f, 0.459411234f},
std::array<float,2>{0.635350585f, 0.948879778f},
std::array<float,2>{0.605520248f, 0.367030114f},
std::array<float,2>{0.375329345f, 0.793755531f},
std::array<float,2>{0.213897511f, 0.105804354f},
std::array<float,2>{0.967199385f, 0.683066189f},
std::array<float,2>{0.720273733f, 0.0365596004f},
std::array<float,2>{0.370282173f, 0.737009406f},
std::array<float,2>{0.0706581473f, 0.307269931f},
std::array<float,2>{0.782385826f, 0.816048324f},
std::array<float,2>{0.929294169f, 0.375206828f},
std::array<float,2>{0.147713661f, 0.932294309f},
std::array<float,2>{0.445626438f, 0.210689366f},
std::array<float,2>{0.556086242f, 0.572809517f},
std::array<float,2>{0.812266171f, 0.0311970338f},
std::array<float,2>{0.0830788761f, 0.715306044f},
std::array<float,2>{0.34464103f, 0.271306753f},
std::array<float,2>{0.744570553f, 0.854497433f},
std::array<float,2>{0.544764578f, 0.426203817f},
std::array<float,2>{0.464501411f, 0.902105868f},
std::array<float,2>{0.127120703f, 0.223233789f},
std::array<float,2>{0.907160997f, 0.61005038f},
std::array<float,2>{0.651195824f, 0.157665148f},
std::array<float,2>{0.265471488f, 0.520445228f},
std::array<float,2>{0.0294154715f, 0.499071956f},
std::array<float,2>{0.857958078f, 0.971907079f},
std::array<float,2>{0.949176013f, 0.316168785f},
std::array<float,2>{0.191490665f, 0.75970763f},
std::array<float,2>{0.392914295f, 0.0812335387f},
std::array<float,2>{0.609429359f, 0.642161727f},
std::array<float,2>{0.901003182f, 0.19069694f},
std::array<float,2>{0.173472121f, 0.586478055f},
std::array<float,2>{0.495675951f, 0.403464496f},
std::array<float,2>{0.518359184f, 0.917976558f},
std::array<float,2>{0.704297721f, 0.286921799f},
std::array<float,2>{0.32724908f, 0.83892101f},
std::array<float,2>{0.120517477f, 0.0498507619f},
std::array<float,2>{0.775942802f, 0.71875304f},
std::array<float,2>{0.593414664f, 0.115515269f},
std::array<float,2>{0.409919679f, 0.66346997f},
std::array<float,2>{0.243305355f, 0.350556582f},
std::array<float,2>{0.988171995f, 0.802649319f},
std::array<float,2>{0.815979838f, 0.452776104f},
std::array<float,2>{0.0457927696f, 0.95607692f},
std::array<float,2>{0.295657516f, 0.144107252f},
std::array<float,2>{0.664778411f, 0.5367226f},
std::array<float,2>{0.922747076f, 0.0934273005f},
std::array<float,2>{0.141609624f, 0.654183805f},
std::array<float,2>{0.450364709f, 0.325814873f},
std::array<float,2>{0.560578585f, 0.756111741f},
std::array<float,2>{0.725584924f, 0.485951453f},
std::array<float,2>{0.373312771f, 0.978565216f},
std::array<float,2>{0.0766890571f, 0.170807138f},
std::array<float,2>{0.786410928f, 0.524258971f},
std::array<float,2>{0.602988303f, 0.229457483f},
std::array<float,2>{0.381566793f, 0.620108008f},
std::array<float,2>{0.215675324f, 0.430671781f},
std::array<float,2>{0.964390695f, 0.898077369f},
std::array<float,2>{0.867642403f, 0.277661055f},
std::array<float,2>{0.0129321441f, 0.8497082f},
std::array<float,2>{0.272426009f, 0.0158919673f},
std::array<float,2>{0.638287663f, 0.7095384f},
std::array<float,2>{0.756560504f, 0.151214227f},
std::array<float,2>{0.095621407f, 0.542559981f},
std::array<float,2>{0.336666644f, 0.43799305f},
std::array<float,2>{0.698419631f, 0.962076545f},
std::array<float,2>{0.51187408f, 0.356505424f},
std::array<float,2>{0.477679014f, 0.811801076f},
std::array<float,2>{0.164784059f, 0.120787486f},
std::array<float,2>{0.884158909f, 0.670422733f},
std::array<float,2>{0.675164998f, 0.057373438f},
std::array<float,2>{0.302793175f, 0.733708143f},
std::array<float,2>{0.0577032939f, 0.29556483f},
std::array<float,2>{0.841257036f, 0.831536293f},
std::array<float,2>{0.981291294f, 0.392730802f},
std::array<float,2>{0.232248306f, 0.907292843f},
std::array<float,2>{0.422637254f, 0.201829806f},
std::array<float,2>{0.564919889f, 0.583538592f},
std::array<float,2>{0.818635702f, 0.0114896642f},
std::array<float,2>{0.0396129489f, 0.701420546f},
std::array<float,2>{0.290772945f, 0.263488889f},
std::array<float,2>{0.671572328f, 0.869913161f},
std::array<float,2>{0.588609993f, 0.411633193f},
std::array<float,2>{0.411175996f, 0.881459057f},
std::array<float,2>{0.246744797f, 0.24401848f},
std::array<float,2>{0.991825581f, 0.599718392f},
std::array<float,2>{0.708634496f, 0.172293946f},
std::array<float,2>{0.323514193f, 0.512836874f},
std::array<float,2>{0.12111377f, 0.473308474f},
std::array<float,2>{0.778837979f, 0.986464143f},
std::array<float,2>{0.902846336f, 0.328498542f},
std::array<float,2>{0.176342919f, 0.77090174f},
std::array<float,2>{0.497089058f, 0.0776801929f},
std::array<float,2>{0.523124635f, 0.640024185f},
std::array<float,2>{0.951103091f, 0.21728006f},
std::array<float,2>{0.190448657f, 0.568674743f},
std::array<float,2>{0.396019012f, 0.387790412f},
std::array<float,2>{0.614657044f, 0.92300719f},
std::array<float,2>{0.655670464f, 0.300192088f},
std::array<float,2>{0.261044234f, 0.825354457f},
std::array<float,2>{0.0272591822f, 0.0409266166f},
std::array<float,2>{0.852590442f, 0.7425583f},
std::array<float,2>{0.540306687f, 0.0970025808f},
std::array<float,2>{0.468000829f, 0.676495731f},
std::array<float,2>{0.129459709f, 0.370775014f},
std::array<float,2>{0.910405278f, 0.783286452f},
std::array<float,2>{0.804786682f, 0.463721931f},
std::array<float,2>{0.0808077455f, 0.942953944f},
std::array<float,2>{0.350502849f, 0.131305709f},
std::array<float,2>{0.749022186f, 0.549840212f},
std::array<float,2>{0.999814212f, 0.0314215906f},
std::array<float,2>{0.236520424f, 0.740681887f},
std::array<float,2>{0.420334995f, 0.311890602f},
std::array<float,2>{0.583409011f, 0.816568494f},
std::array<float,2>{0.662216842f, 0.381262332f},
std::array<float,2>{0.283490717f, 0.935469568f},
std::array<float,2>{0.0348416008f, 0.204601973f},
std::array<float,2>{0.820347309f, 0.574531913f},
std::array<float,2>{0.527532041f, 0.134694204f},
std::array<float,2>{0.490157545f, 0.557350338f},
std::array<float,2>{0.183766648f, 0.456000745f},
std::array<float,2>{0.896181166f, 0.953056991f},
std::array<float,2>{0.768861949f, 0.360510856f},
std::array<float,2>{0.116797164f, 0.79296571f},
std::array<float,2>{0.320090711f, 0.102836668f},
std::array<float,2>{0.717074215f, 0.684585273f},
std::array<float,2>{0.847289383f, 0.237597078f},
std::array<float,2>{0.0157429874f, 0.606990039f},
std::array<float,2>{0.250465214f, 0.421384841f},
std::array<float,2>{0.645517945f, 0.890196145f},
std::array<float,2>{0.617298007f, 0.253591686f},
std::array<float,2>{0.398507565f, 0.859577894f},
std::array<float,2>{0.199632823f, 0.00315227523f},
std::array<float,2>{0.938346803f, 0.689138293f},
std::array<float,2>{0.74173224f, 0.0646011904f},
std::array<float,2>{0.357010454f, 0.632635951f},
std::array<float,2>{0.0884473845f, 0.343692154f},
std::array<float,2>{0.8039639f, 0.777280748f},
std::array<float,2>{0.914081931f, 0.483994246f},
std::array<float,2>{0.13548176f, 0.992771149f},
std::array<float,2>{0.454251289f, 0.185583979f},
std::array<float,2>{0.533358097f, 0.500465751f},
std::array<float,2>{0.794529915f, 0.110320896f},
std::array<float,2>{0.0648719743f, 0.659894466f},
std::array<float,2>{0.365686804f, 0.344744861f},
std::array<float,2>{0.728462517f, 0.797377169f},
std::array<float,2>{0.554493129f, 0.446257323f},
std::array<float,2>{0.438332736f, 0.957402527f},
std::array<float,2>{0.155616581f, 0.147582442f},
std::array<float,2>{0.935453653f, 0.534921825f},
std::array<float,2>{0.631960928f, 0.193916246f},
std::array<float,2>{0.276300848f, 0.59265095f},
std::array<float,2>{0.00355742197f, 0.399690896f},
std::array<float,2>{0.862495303f, 0.914298177f},
std::array<float,2>{0.957140207f, 0.284807533f},
std::array<float,2>{0.207638502f, 0.840398252f},
std::array<float,2>{0.383547425f, 0.0538176857f},
std::array<float,2>{0.595596373f, 0.725479901f},
std::array<float,2>{0.881914318f, 0.162622899f},
std::array<float,2>{0.159964144f, 0.516933918f},
std::array<float,2>{0.474206418f, 0.494083524f},
std::array<float,2>{0.507252336f, 0.973856628f},
std::array<float,2>{0.690674245f, 0.320307463f},
std::array<float,2>{0.330743343f, 0.764716387f},
std::array<float,2>{0.102583662f, 0.0830981508f},
std::array<float,2>{0.763596833f, 0.645391822f},
std::array<float,2>{0.575056314f, 0.0255848262f},
std::array<float,2>{0.432623714f, 0.713620603f},
std::array<float,2>{0.220139429f, 0.265706867f},
std::array<float,2>{0.974912226f, 0.855729103f},
std::array<float,2>{0.833097696f, 0.423926324f},
std::array<float,2>{0.0530895628f, 0.904585361f},
std::array<float,2>{0.305761904f, 0.220678076f},
std::array<float,2>{0.686494052f, 0.616872311f},
std::array<float,2>{0.891072035f, 0.021131305f},
std::array<float,2>{0.180683002f, 0.704272926f},
std::array<float,2>{0.487952083f, 0.276051968f},
std::array<float,2>{0.523660004f, 0.844643295f},
std::array<float,2>{0.714362502f, 0.436711878f},
std::array<float,2>{0.316080391f, 0.891484082f},
std::array<float,2>{0.109833039f, 0.232777625f},
std::array<float,2>{0.769921839f, 0.622747302f},
std::array<float,2>{0.5790115f, 0.166672751f},
std::array<float,2>{0.415299118f, 0.527921677f},
std::array<float,2>{0.241375446f, 0.490909547f},
std::array<float,2>{0.993562222f, 0.981421888f},
std::array<float,2>{0.82706207f, 0.322443604f},
std::array<float,2>{0.0360018015f, 0.751269162f},
std::array<float,2>{0.287752926f, 0.0870061517f},
std::array<float,2>{0.657907963f, 0.648483217f},
std::array<float,2>{0.797084153f, 0.196305364f},
std::array<float,2>{0.0911753848f, 0.579066038f},
std::array<float,2>{0.351792365f, 0.396890283f},
std::array<float,2>{0.737216055f, 0.913327992f},
std::array<float,2>{0.53532666f, 0.292163521f},
std::array<float,2>{0.459656358f, 0.83451581f},
std::array<float,2>{0.137927353f, 0.0595666319f},
std::array<float,2>{0.921401322f, 0.730158269f},
std::array<float,2>{0.643011272f, 0.12176121f},
std::array<float,2>{0.257053643f, 0.666238666f},
std::array<float,2>{0.0219069608f, 0.35400188f},
std::array<float,2>{0.851210296f, 0.805362344f},
std::array<float,2>{0.942665339f, 0.441661894f},
std::array<float,2>{0.196965784f, 0.965946317f},
std::array<float,2>{0.405467331f, 0.153529048f},
std::array<float,2>{0.621545792f, 0.54390645f},
std::array<float,2>{0.865162492f, 0.0732731819f},
std::array<float,2>{0.00510766031f, 0.635183871f},
std::array<float,2>{0.280551732f, 0.335105181f},
std::array<float,2>{0.625783503f, 0.767310977f},
std::array<float,2>{0.601379693f, 0.471552461f},
std::array<float,2>{0.387430042f, 0.988898814f},
std::array<float,2>{0.206023902f, 0.178538099f},
std::array<float,2>{0.956911564f, 0.508014858f},
std::array<float,2>{0.732781708f, 0.248902872f},
std::array<float,2>{0.362165719f, 0.594793797f},
std::array<float,2>{0.0665206164f, 0.409992605f},
std::array<float,2>{0.789232194f, 0.876019716f},
std::array<float,2>{0.933553517f, 0.261697024f},
std::array<float,2>{0.151218548f, 0.874469161f},
std::array<float,2>{0.443084776f, 0.0122928442f},
std::array<float,2>{0.548586369f, 0.69842875f},
std::array<float,2>{0.970144331f, 0.127209097f},
std::array<float,2>{0.225403279f, 0.554577291f},
std::array<float,2>{0.434535086f, 0.464949638f},
std::array<float,2>{0.5716905f, 0.939941168f},
std::array<float,2>{0.680122674f, 0.371478558f},
std::array<float,2>{0.310432822f, 0.788510263f},
std::array<float,2>{0.0478183106f, 0.0995679274f},
std::array<float,2>{0.829441488f, 0.673687458f},
std::array<float,2>{0.502765059f, 0.0458443835f},
std::array<float,2>{0.468897671f, 0.749426305f},
std::array<float,2>{0.160589382f, 0.301647365f},
std::array<float,2>{0.876723707f, 0.823689699f},
std::array<float,2>{0.761080146f, 0.383423895f},
std::array<float,2>{0.108734898f, 0.928396583f},
std::array<float,2>{0.335193127f, 0.211520538f},
std::array<float,2>{0.693112493f, 0.566349566f},
std::array<float,2>{0.965571463f, 0.108900905f},
std::array<float,2>{0.211606562f, 0.68028605f},
std::array<float,2>{0.378887534f, 0.364566594f},
std::array<float,2>{0.608160794f, 0.795399606f},
std::array<float,2>{0.634408891f, 0.457615882f},
std::array<float,2>{0.268281251f, 0.945631146f},
std::array<float,2>{0.010078771f, 0.138112679f},
std::array<float,2>{0.872793674f, 0.5606336f},
std::array<float,2>{0.557741344f, 0.207204491f},
std::array<float,2>{0.447701395f, 0.570874393f},
std::array<float,2>{0.146343425f, 0.378174782f},
std::array<float,2>{0.926099777f, 0.930148661f},
std::array<float,2>{0.784816504f, 0.305371135f},
std::array<float,2>{0.0737223476f, 0.814002097f},
std::array<float,2>{0.368231922f, 0.0374011584f},
std::array<float,2>{0.722239137f, 0.73480463f},
std::array<float,2>{0.836204886f, 0.180868f},
std::array<float,2>{0.0608249009f, 0.505105019f},
std::array<float,2>{0.298228592f, 0.479275554f},
std::array<float,2>{0.678805709f, 0.999222398f},
std::array<float,2>{0.569098532f, 0.337830573f},
std::array<float,2>{0.429297537f, 0.779869258f},
std::array<float,2>{0.228575334f, 0.0685778856f},
std::array<float,2>{0.979013026f, 0.625799298f},
std::array<float,2>{0.69996345f, 0.0066699395f},
std::array<float,2>{0.341648638f, 0.694695055f},
std::array<float,2>{0.100759111f, 0.254101694f},
std::array<float,2>{0.750268102f, 0.867086112f},
std::array<float,2>{0.8869766f, 0.4159289f},
std::array<float,2>{0.169195741f, 0.886128724f},
std::array<float,2>{0.483387947f, 0.241498932f},
std::array<float,2>{0.510932863f, 0.602758527f},
std::array<float,2>{0.775348067f, 0.0485057943f},
std::array<float,2>{0.117774256f, 0.722224832f},
std::array<float,2>{0.325373262f, 0.288211495f},
std::array<float,2>{0.705237985f, 0.837858856f},
std::array<float,2>{0.517199636f, 0.404306829f},
std::array<float,2>{0.492369205f, 0.920695126f},
std::array<float,2>{0.174446255f, 0.189145252f},
std::array<float,2>{0.900148332f, 0.589618146f},
std::array<float,2>{0.666377664f, 0.14219214f},
std::array<float,2>{0.293065995f, 0.538047791f},
std::array<float,2>{0.0440749191f, 0.449527591f},
std::array<float,2>{0.814226151f, 0.953547835f},
std::array<float,2>{0.986127019f, 0.348347455f},
std::array<float,2>{0.245712802f, 0.804244459f},
std::array<float,2>{0.406980604f, 0.113916598f},
std::array<float,2>{0.590786278f, 0.660419047f},
std::array<float,2>{0.908994555f, 0.224932656f},
std::array<float,2>{0.125596642f, 0.611968637f},
std::array<float,2>{0.462172061f, 0.428468406f},
std::array<float,2>{0.545758486f, 0.898639739f},
std::array<float,2>{0.743912041f, 0.27253598f},
std::array<float,2>{0.347170413f, 0.85194844f},
std::array<float,2>{0.0854366198f, 0.0277058743f},
std::array<float,2>{0.809009671f, 0.717683315f},
std::array<float,2>{0.612106979f, 0.0789187327f},
std::array<float,2>{0.390761226f, 0.643650591f},
std::array<float,2>{0.195280001f, 0.312847435f},
std::array<float,2>{0.945452929f, 0.761343539f},
std::array<float,2>{0.856387973f, 0.497219652f},
std::array<float,2>{0.0283927992f, 0.968998313f},
std::array<float,2>{0.26203391f, 0.159502774f},
std::array<float,2>{0.649753213f, 0.522127807f},
std::array<float,2>{0.905192912f, 0.0769752637f},
std::array<float,2>{0.177994445f, 0.638709664f},
std::array<float,2>{0.498259783f, 0.329537362f},
std::array<float,2>{0.521402717f, 0.769649088f},
std::array<float,2>{0.71039331f, 0.474427313f},
std::array<float,2>{0.320852995f, 0.987655938f},
std::array<float,2>{0.123257175f, 0.17319198f},
std::array<float,2>{0.779574156f, 0.512602806f},
std::array<float,2>{0.587256253f, 0.242466241f},
std::array<float,2>{0.412169069f, 0.600694835f},
std::array<float,2>{0.248711944f, 0.410497516f},
std::array<float,2>{0.989554465f, 0.882039726f},
std::array<float,2>{0.817494214f, 0.262368262f},
std::array<float,2>{0.0410508066f, 0.871083558f},
std::array<float,2>{0.292137742f, 0.0105899153f},
std::array<float,2>{0.668903172f, 0.702632248f},
std::array<float,2>{0.806900084f, 0.132011324f},
std::array<float,2>{0.0797464475f, 0.549801707f},
std::array<float,2>{0.349138618f, 0.464263201f},
std::array<float,2>{0.747286022f, 0.941451252f},
std::array<float,2>{0.54143101f, 0.370064139f},
std::array<float,2>{0.466781855f, 0.785112441f},
std::array<float,2>{0.131140068f, 0.0964280814f},
std::array<float,2>{0.912843168f, 0.677261889f},
std::array<float,2>{0.652933836f, 0.0392236449f},
std::array<float,2>{0.259410024f, 0.743708551f},
std::array<float,2>{0.0252046343f, 0.299566865f},
std::array<float,2>{0.853889465f, 0.824975491f},
std::array<float,2>{0.952906609f, 0.38727656f},
std::array<float,2>{0.189271644f, 0.922195315f},
std::array<float,2>{0.398388952f, 0.217875943f},
std::array<float,2>{0.615306735f, 0.569694996f},
std::array<float,2>{0.870684683f, 0.0174241997f},
std::array<float,2>{0.0154251894f, 0.710777879f},
std::array<float,2>{0.270092368f, 0.27922523f},
std::array<float,2>{0.64007175f, 0.85061723f},
std::array<float,2>{0.604239106f, 0.43001467f},
std::array<float,2>{0.379123777f, 0.896610379f},
std::array<float,2>{0.217765868f, 0.230148762f},
std::array<float,2>{0.961003006f, 0.620537758f},
std::array<float,2>{0.724321067f, 0.17122741f},
std::array<float,2>{0.371376663f, 0.524965763f},
std::array<float,2>{0.0760149285f, 0.485286981f},
std::array<float,2>{0.788700342f, 0.980449975f},
std::array<float,2>{0.925170183f, 0.324411273f},
std::array<float,2>{0.143226668f, 0.75710392f},
std::array<float,2>{0.45192641f, 0.0919757709f},
std::array<float,2>{0.558732569f, 0.652858317f},
std::array<float,2>{0.984098136f, 0.202544183f},
std::array<float,2>{0.233041003f, 0.582101762f},
std::array<float,2>{0.424345106f, 0.394183189f},
std::array<float,2>{0.56270498f, 0.907140017f},
std::array<float,2>{0.673190773f, 0.296617419f},
std::array<float,2>{0.302377641f, 0.8308267f},
std::array<float,2>{0.0559356585f, 0.0578134172f},
std::array<float,2>{0.843290389f, 0.73290801f},
std::array<float,2>{0.515162945f, 0.119950786f},
std::array<float,2>{0.480178237f, 0.671636641f},
std::array<float,2>{0.166577891f, 0.356152624f},
std::array<float,2>{0.886171043f, 0.810636818f},
std::array<float,2>{0.755262077f, 0.438923448f},
std::array<float,2>{0.0975632146f, 0.961856365f},
std::array<float,2>{0.339125425f, 0.151897803f},
std::array<float,2>{0.697075188f, 0.541876018f},
std::array<float,2>{0.959444642f, 0.0527736098f},
std::array<float,2>{0.209419176f, 0.726159811f},
std::array<float,2>{0.385633439f, 0.284044355f},
std::array<float,2>{0.596630931f, 0.841586232f},
std::array<float,2>{0.630264878f, 0.398870677f},
std::array<float,2>{0.274156481f, 0.915227711f},
std::array<float,2>{0.000790038379f, 0.195082873f},
std::array<float,2>{0.86035794f, 0.593390882f},
std::array<float,2>{0.551473379f, 0.146919683f},
std::array<float,2>{0.439786077f, 0.533308566f},
std::array<float,2>{0.153128639f, 0.447156608f},
std::array<float,2>{0.935815752f, 0.958036184f},
std::array<float,2>{0.795753479f, 0.344040632f},
std::array<float,2>{0.062738806f, 0.798643053f},
std::array<float,2>{0.364959121f, 0.1109019f},
std::array<float,2>{0.72853899f, 0.658287525f},
std::array<float,2>{0.835691214f, 0.219315574f},
std::array<float,2>{0.0514571667f, 0.615311623f},
std::array<float,2>{0.307924271f, 0.425333053f},
std::array<float,2>{0.684641421f, 0.905389249f},
std::array<float,2>{0.576942384f, 0.267046392f},
std::array<float,2>{0.430855811f, 0.856632054f},
std::array<float,2>{0.221637398f, 0.0264829788f},
std::array<float,2>{0.97279197f, 0.714087188f},
std::array<float,2>{0.687980294f, 0.0829862505f},
std::array<float,2>{0.328942001f, 0.646238744f},
std::array<float,2>{0.105323657f, 0.318783581f},
std::array<float,2>{0.764170885f, 0.76444006f},
std::array<float,2>{0.88000226f, 0.492437363f},
std::array<float,2>{0.156801268f, 0.973242402f},
std::array<float,2>{0.475792676f, 0.163736567f},
std::array<float,2>{0.505787909f, 0.516211092f},
std::array<float,2>{0.767121255f, 0.102464579f},
std::array<float,2>{0.114390664f, 0.684289575f},
std::array<float,2>{0.316784531f, 0.360027194f},
std::array<float,2>{0.716689467f, 0.791611969f},
std::array<float,2>{0.529408932f, 0.456739277f},
std::array<float,2>{0.491864711f, 0.951727986f},
std::array<float,2>{0.186697543f, 0.133109376f},
std::array<float,2>{0.897120953f, 0.55858165f},
std::array<float,2>{0.661158204f, 0.203956187f},
std::array<float,2>{0.282794714f, 0.575418413f},
std::array<float,2>{0.0327948704f, 0.382790267f},
std::array<float,2>{0.823544383f, 0.934410453f},
std::array<float,2>{0.996756315f, 0.310714841f},
std::array<float,2>{0.235374287f, 0.817723989f},
std::array<float,2>{0.419639111f, 0.0324353762f},
std::array<float,2>{0.585544109f, 0.741237581f},
std::array<float,2>{0.917754829f, 0.186865985f},
std::array<float,2>{0.133868337f, 0.501654506f},
std::array<float,2>{0.455132425f, 0.482972145f},
std::array<float,2>{0.531584144f, 0.993187904f},
std::array<float,2>{0.739908814f, 0.342559665f},
std::array<float,2>{0.359165728f, 0.77617979f},
std::array<float,2>{0.0865138173f, 0.0660208687f},
std::array<float,2>{0.800821424f, 0.631528676f},
std::array<float,2>{0.620843887f, 0.00229076855f},
std::array<float,2>{0.402249604f, 0.688439429f},
std::array<float,2>{0.201597288f, 0.251980901f},
std::array<float,2>{0.940271497f, 0.860578835f},
std::array<float,2>{0.845513642f, 0.420450896f},
std::array<float,2>{0.0181224309f, 0.889638782f},
std::array<float,2>{0.253196508f, 0.236772895f},
std::array<float,2>{0.647919118f, 0.605976641f},
std::array<float,2>{0.931507647f, 0.0130528677f},
std::array<float,2>{0.149368703f, 0.698035777f},
std::array<float,2>{0.444929212f, 0.26012519f},
std::array<float,2>{0.549400866f, 0.87355125f},
std::array<float,2>{0.732061267f, 0.408955157f},
std::array<float,2>{0.361102521f, 0.875315249f},
std::array<float,2>{0.0693179518f, 0.24930872f},
std::array<float,2>{0.792468429f, 0.593795717f},
std::array<float,2>{0.597931743f, 0.17942746f},
std::array<float,2>{0.389972121f, 0.509191275f},
std::array<float,2>{0.203961417f, 0.471810818f},
std::array<float,2>{0.95495218f, 0.989546895f},
std::array<float,2>{0.866113424f, 0.334647268f},
std::array<float,2>{0.00761148892f, 0.766275764f},
std::array<float,2>{0.27803719f, 0.0728590637f},
std::array<float,2>{0.628088176f, 0.636266649f},
std::array<float,2>{0.758091033f, 0.212653816f},
std::array<float,2>{0.106907152f, 0.564742923f},
std::array<float,2>{0.333837062f, 0.384486794f},
std::array<float,2>{0.693572223f, 0.928752601f},
std::array<float,2>{0.501662254f, 0.301888585f},
std::array<float,2>{0.470893949f, 0.82293874f},
std::array<float,2>{0.163278833f, 0.046420265f},
std::array<float,2>{0.877916455f, 0.748201013f},
std::array<float,2>{0.682880461f, 0.0979853794f},
std::array<float,2>{0.31144163f, 0.672240436f},
std::array<float,2>{0.0497907326f, 0.372961909f},
std::array<float,2>{0.831166029f, 0.78738302f},
std::array<float,2>{0.972344995f, 0.46673277f},
std::array<float,2>{0.223805368f, 0.940668821f},
std::array<float,2>{0.435733348f, 0.128268078f},
std::array<float,2>{0.572394133f, 0.553079069f},
std::array<float,2>{0.825957596f, 0.0860443115f},
std::array<float,2>{0.0384339094f, 0.650252938f},
std::array<float,2>{0.286297232f, 0.32330507f},
std::array<float,2>{0.658726037f, 0.750405729f},
std::array<float,2>{0.580288053f, 0.491508514f},
std::array<float,2>{0.417594433f, 0.981468022f},
std::array<float,2>{0.238333747f, 0.16709055f},
std::array<float,2>{0.995746613f, 0.528675079f},
std::array<float,2>{0.712393403f, 0.234216452f},
std::array<float,2>{0.312718242f, 0.621991336f},
std::array<float,2>{0.112943567f, 0.435838521f},
std::array<float,2>{0.772534132f, 0.892439127f},
std::array<float,2>{0.893355608f, 0.277008921f},
std::array<float,2>{0.182682648f, 0.845175505f},
std::array<float,2>{0.48558712f, 0.0200212561f},
std::array<float,2>{0.526647925f, 0.70320636f},
std::array<float,2>{0.943767428f, 0.152593762f},
std::array<float,2>{0.198898837f, 0.544414878f},
std::array<float,2>{0.402347863f, 0.442655981f},
std::array<float,2>{0.623539209f, 0.965139568f},
std::array<float,2>{0.642327428f, 0.354627341f},
std::array<float,2>{0.2554892f, 0.806195557f},
std::array<float,2>{0.0214648824f, 0.12261004f},
std::array<float,2>{0.848174036f, 0.667520761f},
std::array<float,2>{0.538433135f, 0.0598175041f},
std::array<float,2>{0.458708227f, 0.728563905f},
std::array<float,2>{0.140203863f, 0.291329622f},
std::array<float,2>{0.919151306f, 0.83503449f},
std::array<float,2>{0.799765885f, 0.397530526f},
std::array<float,2>{0.0926602036f, 0.91233325f},
std::array<float,2>{0.355106771f, 0.196044475f},
std::array<float,2>{0.736127675f, 0.580059588f},
std::array<float,2>{0.986357868f, 0.115208931f},
std::array<float,2>{0.242283225f, 0.662070394f},
std::array<float,2>{0.408485472f, 0.348870128f},
std::array<float,2>{0.592184484f, 0.803240478f},
std::array<float,2>{0.665101588f, 0.450830847f},
std::array<float,2>{0.296643317f, 0.954489052f},
std::array<float,2>{0.0468476564f, 0.141304851f},
std::array<float,2>{0.814894795f, 0.538481772f},
std::array<float,2>{0.51867497f, 0.187723592f},
std::array<float,2>{0.494498402f, 0.588819206f},
std::array<float,2>{0.172190458f, 0.405895919f},
std::array<float,2>{0.902215004f, 0.921423495f},
std::array<float,2>{0.776701152f, 0.287978917f},
std::array<float,2>{0.119500369f, 0.836306214f},
std::array<float,2>{0.326313078f, 0.0473931544f},
std::array<float,2>{0.703583479f, 0.721591234f},
std::array<float,2>{0.858899474f, 0.158928305f},
std::array<float,2>{0.0305084568f, 0.522570848f},
std::array<float,2>{0.264526933f, 0.496666431f},
std::array<float,2>{0.65147984f, 0.970355213f},
std::array<float,2>{0.611220002f, 0.313939273f},
std::array<float,2>{0.393808752f, 0.760685623f},
std::array<float,2>{0.192504212f, 0.0798598751f},
std::array<float,2>{0.94777596f, 0.643550277f},
std::array<float,2>{0.745276451f, 0.0289238188f},
std::array<float,2>{0.345445126f, 0.717880011f},
std::array<float,2>{0.0825950131f, 0.272323489f},
std::array<float,2>{0.810767353f, 0.852600515f},
std::array<float,2>{0.907947063f, 0.42881614f},
std::array<float,2>{0.128542304f, 0.900074244f},
std::array<float,2>{0.463216186f, 0.226270303f},
std::array<float,2>{0.543270528f, 0.612695992f},
std::array<float,2>{0.782036901f, 0.0386238135f},
std::array<float,2>{0.0721599534f, 0.735853553f},
std::array<float,2>{0.369349539f, 0.305697113f},
std::array<float,2>{0.719172657f, 0.812985361f},
std::array<float,2>{0.555631876f, 0.377633512f},
std::array<float,2>{0.446379602f, 0.930972755f},
std::array<float,2>{0.147258714f, 0.208067298f},
std::array<float,2>{0.928319871f, 0.571695328f},
std::array<float,2>{0.63642925f, 0.137457266f},
std::array<float,2>{0.266183496f, 0.562478185f},
std::array<float,2>{0.00837332383f, 0.458667606f},
std::array<float,2>{0.873768806f, 0.946338832f},
std::array<float,2>{0.967949092f, 0.363736123f},
std::array<float,2>{0.213708147f, 0.796025634f},
std::array<float,2>{0.376514584f, 0.108326949f},
std::array<float,2>{0.607026458f, 0.680703223f},
std::array<float,2>{0.889518261f, 0.241149768f},
std::array<float,2>{0.170310274f, 0.602239132f},
std::array<float,2>{0.482326299f, 0.414286733f},
std::array<float,2>{0.509411752f, 0.885715842f},
std::array<float,2>{0.702115238f, 0.255654514f},
std::array<float,2>{0.3420977f, 0.865554869f},
std::array<float,2>{0.0987571776f, 0.00691507244f},
std::array<float,2>{0.753458917f, 0.69414854f},
std::array<float,2>{0.566740155f, 0.0702460185f},
std::array<float,2>{0.426895201f, 0.626314461f},
std::array<float,2>{0.227939084f, 0.336547554f},
std::array<float,2>{0.977513254f, 0.780980229f},
std::array<float,2>{0.838280201f, 0.479680568f},
std::array<float,2>{0.0603250861f, 0.998941123f},
std::array<float,2>{0.300692081f, 0.17988044f},
std::array<float,2>{0.677119255f, 0.504734576f},
std::array<float,2>{0.912020922f, 0.0948879421f},
std::array<float,2>{0.130259603f, 0.679067254f},
std::array<float,2>{0.466866642f, 0.367750525f},
std::array<float,2>{0.539079368f, 0.781447172f},
std::array<float,2>{0.749727666f, 0.461073965f},
std::array<float,2>{0.351371557f, 0.94510287f},
std::array<float,2>{0.0817727447f, 0.129871085f},
std::array<float,2>{0.806314886f, 0.54806f},
std::array<float,2>{0.61355269f, 0.216389552f},
std::array<float,2>{0.394533813f, 0.566447318f},
std::array<float,2>{0.189508498f, 0.389187992f},
std::array<float,2>{0.949627399f, 0.924340546f},
std::array<float,2>{0.852434993f, 0.297517061f},
std::array<float,2>{0.0256577954f, 0.826878607f},
std::array<float,2>{0.260014981f, 0.0420025997f},
std::array<float,2>{0.654333055f, 0.745966017f},
std::array<float,2>{0.777402043f, 0.175413921f},
std::array<float,2>{0.122596644f, 0.514328659f},
std::array<float,2>{0.322870612f, 0.475951076f},
std::array<float,2>{0.707261801f, 0.984719157f},
std::array<float,2>{0.522212923f, 0.330480009f},
std::array<float,2>{0.496394902f, 0.772900105f},
std::array<float,2>{0.177029476f, 0.0754742101f},
std::array<float,2>{0.90332967f, 0.636990607f},
std::array<float,2>{0.670374215f, 0.00894840434f},
std::array<float,2>{0.28912887f, 0.699236691f},
std::array<float,2>{0.0404367261f, 0.265165806f},
std::array<float,2>{0.819968462f, 0.867916107f},
std::array<float,2>{0.991074622f, 0.412382841f},
std::array<float,2>{0.247594759f, 0.879939795f},
std::array<float,2>{0.411024123f, 0.244786873f},
std::array<float,2>{0.589371681f, 0.59916997f},
std::array<float,2>{0.840713859f, 0.0547958724f},
std::array<float,2>{0.0571294315f, 0.730633914f},
std::array<float,2>{0.303922564f, 0.293612033f},
std::array<float,2>{0.673920035f, 0.829000533f},
std::array<float,2>{0.565795541f, 0.391954809f},
std::array<float,2>{0.423250049f, 0.90906322f},
std::array<float,2>{0.231356651f, 0.199443281f},
std::array<float,2>{0.981497526f, 0.585695624f},
std::array<float,2>{0.697769701f, 0.149847761f},
std::array<float,2>{0.337110013f, 0.540815055f},
std::array<float,2>{0.0944041684f, 0.441380292f},
std::array<float,2>{0.757805407f, 0.964569628f},
std::array<float,2>{0.883499742f, 0.358426064f},
std::array<float,2>{0.165150031f, 0.809949577f},
std::array<float,2>{0.477105767f, 0.117415994f},
std::array<float,2>{0.513543606f, 0.668505669f},
std::array<float,2>{0.962997735f, 0.228418499f},
std::array<float,2>{0.216608211f, 0.617793679f},
std::array<float,2>{0.381937087f, 0.433472693f},
std::array<float,2>{0.601662695f, 0.896430433f},
std::array<float,2>{0.636841774f, 0.280875862f},
std::array<float,2>{0.272894084f, 0.84869194f},
std::array<float,2>{0.0121374568f, 0.0176895298f},
std::array<float,2>{0.868708849f, 0.708436549f},
std::array<float,2>{0.562127292f, 0.0902996063f},
std::array<float,2>{0.449796408f, 0.656216681f},
std::array<float,2>{0.141214713f, 0.327650756f},
std::array<float,2>{0.923106551f, 0.755662084f},
std::array<float,2>{0.7854442f, 0.486362159f},
std::array<float,2>{0.0780814216f, 0.977622211f},
std::array<float,2>{0.374728203f, 0.168812469f},
std::array<float,2>{0.726256728f, 0.526646256f},
std::array<float,2>{0.975599468f, 0.024142297f},
std::array<float,2>{0.219628036f, 0.712777376f},
std::array<float,2>{0.431929231f, 0.26883629f},
std::array<float,2>{0.575617135f, 0.858752847f},
std::array<float,2>{0.687161922f, 0.423706949f},
std::array<float,2>{0.304737151f, 0.903878331f},
std::array<float,2>{0.0541772284f, 0.222558647f},
std::array<float,2>{0.83284986f, 0.613832057f},
std::array<float,2>{0.506069005f, 0.161170155f},
std::array<float,2>{0.472722441f, 0.518406391f},
std::array<float,2>{0.158494562f, 0.495159954f},
std::array<float,2>{0.881150901f, 0.975372016f},
std::array<float,2>{0.762310147f, 0.316877782f},
std::array<float,2>{0.10246592f, 0.763549566f},
std::array<float,2>{0.331111342f, 0.0843228698f},
std::array<float,2>{0.690228343f, 0.646606207f},
std::array<float,2>{0.862238526f, 0.192210823f},
std::array<float,2>{0.00268511614f, 0.589956462f},
std::array<float,2>{0.277328908f, 0.401241571f},
std::array<float,2>{0.631459653f, 0.916607738f},
std::array<float,2>{0.593951404f, 0.282126188f},
std::array<float,2>{0.384255946f, 0.841857612f},
std::array<float,2>{0.208170742f, 0.0519064143f},
std::array<float,2>{0.958742201f, 0.724600494f},
std::array<float,2>{0.72703284f, 0.112726919f},
std::array<float,2>{0.366421223f, 0.657499671f},
std::array<float,2>{0.066303283f, 0.346294075f},
std::array<float,2>{0.793704808f, 0.799859643f},
std::array<float,2>{0.934376955f, 0.448843986f},
std::array<float,2>{0.155078337f, 0.959295869f},
std::array<float,2>{0.438578278f, 0.145785138f},
std::array<float,2>{0.55360949f, 0.531758606f},
std::array<float,2>{0.80326575f, 0.0629997328f},
std::array<float,2>{0.0893141925f, 0.629434645f},
std::array<float,2>{0.355926156f, 0.341271818f},
std::array<float,2>{0.740434945f, 0.773846209f},
std::array<float,2>{0.534786522f, 0.481143832f},
std::array<float,2>{0.453490674f, 0.994672f},
std::array<float,2>{0.136336327f, 0.183960184f},
std::array<float,2>{0.915190816f, 0.502082646f},
std::array<float,2>{0.645498157f, 0.234589994f},
std::array<float,2>{0.25124526f, 0.60796088f},
std::array<float,2>{0.0174511224f, 0.418540776f},
std::array<float,2>{0.846025944f, 0.888119817f},
std::array<float,2>{0.938903332f, 0.251060545f},
std::array<float,2>{0.200700819f, 0.862980306f},
std::array<float,2>{0.399625838f, 0.000851524586f},
std::array<float,2>{0.618248463f, 0.69067055f},
std::array<float,2>{0.894533932f, 0.136145383f},
std::array<float,2>{0.184652597f, 0.555408895f},
std::array<float,2>{0.488875538f, 0.454686254f},
std::array<float,2>{0.529121459f, 0.950740159f},
std::array<float,2>{0.718040228f, 0.362429291f},
std::array<float,2>{0.319273144f, 0.790455222f},
std::array<float,2>{0.116100773f, 0.104398549f},
std::array<float,2>{0.767592847f, 0.687278748f},
std::array<float,2>{0.582654238f, 0.0351326801f},
std::array<float,2>{0.42174986f, 0.739019871f},
std::array<float,2>{0.237953052f, 0.309023112f},
std::array<float,2>{0.99884516f, 0.820219159f},
std::array<float,2>{0.822059512f, 0.380665988f},
std::array<float,2>{0.0340924598f, 0.93662101f},
std::array<float,2>{0.285031408f, 0.205485389f},
std::array<float,2>{0.664006114f, 0.577834487f},
std::array<float,2>{0.87554878f, 0.0437908843f},
std::array<float,2>{0.161664352f, 0.74734658f},
std::array<float,2>{0.469869524f, 0.304175645f},
std::array<float,2>{0.503605187f, 0.821254373f},
std::array<float,2>{0.692228913f, 0.386535376f},
std::array<float,2>{0.334100246f, 0.927376449f},
std::array<float,2>{0.107804559f, 0.214250043f},
std::array<float,2>{0.760610878f, 0.56411922f},
std::array<float,2>{0.571267843f, 0.126367077f},
std::array<float,2>{0.435418606f, 0.552475095f},
std::array<float,2>{0.225781098f, 0.46716699f},
std::array<float,2>{0.968877137f, 0.939306617f},
std::array<float,2>{0.829023898f, 0.373880327f},
std::array<float,2>{0.0488028973f, 0.786841094f},
std::array<float,2>{0.308994442f, 0.101167433f},
std::array<float,2>{0.680844963f, 0.674034894f},
std::array<float,2>{0.790477991f, 0.247514516f},
std::array<float,2>{0.0676091313f, 0.597636342f},
std::array<float,2>{0.362491727f, 0.406546712f},
std::array<float,2>{0.733779788f, 0.8777951f},
std::array<float,2>{0.547844172f, 0.259054124f},
std::array<float,2>{0.441839397f, 0.87267679f},
std::array<float,2>{0.151686907f, 0.0139438109f},
std::array<float,2>{0.932080388f, 0.695551753f},
std::array<float,2>{0.626337647f, 0.071812965f},
std::array<float,2>{0.280253261f, 0.633870363f},
std::array<float,2>{0.00400952809f, 0.332897037f},
std::array<float,2>{0.863398314f, 0.76845026f},
std::array<float,2>{0.956054449f, 0.470207065f},
std::array<float,2>{0.206454948f, 0.99082756f},
std::array<float,2>{0.388214916f, 0.176858827f},
std::array<float,2>{0.600424588f, 0.510217845f},
std::array<float,2>{0.850485623f, 0.124383263f},
std::array<float,2>{0.023078369f, 0.665597379f},
std::array<float,2>{0.256374091f, 0.351779491f},
std::array<float,2>{0.6439327f, 0.808501005f},
std::array<float,2>{0.622367263f, 0.444921821f},
std::array<float,2>{0.404508054f, 0.968237042f},
std::array<float,2>{0.195877209f, 0.155544162f},
std::array<float,2>{0.942173064f, 0.545289874f},
std::array<float,2>{0.73818028f, 0.197818846f},
std::array<float,2>{0.353205204f, 0.580387175f},
std::array<float,2>{0.0906078294f, 0.394833982f},
std::array<float,2>{0.798720598f, 0.910832763f},
std::array<float,2>{0.920289755f, 0.289388955f},
std::array<float,2>{0.137124002f, 0.833318055f},
std::array<float,2>{0.460792303f, 0.0609021448f},
std::array<float,2>{0.53688693f, 0.727480233f},
std::array<float,2>{0.99232465f, 0.165718913f},
std::array<float,2>{0.240600646f, 0.531105876f},
std::array<float,2>{0.414339125f, 0.488680422f},
std::array<float,2>{0.579188704f, 0.983281791f},
std::array<float,2>{0.657051265f, 0.32084775f},
std::array<float,2>{0.288219184f, 0.752821028f},
std::array<float,2>{0.0366780013f, 0.0892549977f},
std::array<float,2>{0.827359974f, 0.650577962f},
std::array<float,2>{0.52464962f, 0.023347253f},
std::array<float,2>{0.486602336f, 0.706893504f},
std::array<float,2>{0.180137917f, 0.273583144f},
std::array<float,2>{0.892294407f, 0.84586668f},
std::array<float,2>{0.77052027f, 0.433731616f},
std::array<float,2>{0.111098848f, 0.894322455f},
std::array<float,2>{0.315409184f, 0.231827423f},
std::array<float,2>{0.713349521f, 0.623211026f},
std::array<float,2>{0.946525216f, 0.0809263065f},
std::array<float,2>{0.194179446f, 0.640664518f},
std::array<float,2>{0.391836703f, 0.315089643f},
std::array<float,2>{0.612886727f, 0.758154571f},
std::array<float,2>{0.648828685f, 0.498093903f},
std::array<float,2>{0.263267279f, 0.971390724f},
std::array<float,2>{0.0276673008f, 0.156921402f},
std::array<float,2>{0.856698453f, 0.52078867f},
std::array<float,2>{0.546037018f, 0.22380048f},
std::array<float,2>{0.461511314f, 0.610587358f},
std::array<float,2>{0.126926884f, 0.427411228f},
std::array<float,2>{0.909387529f, 0.900485396f},
std::array<float,2>{0.810220242f, 0.269759864f},
std::array<float,2>{0.0848835781f, 0.854405999f},
std::array<float,2>{0.346320122f, 0.0300936885f},
std::array<float,2>{0.742422819f, 0.715937853f},
std::array<float,2>{0.812791348f, 0.143443286f},
std::array<float,2>{0.0433394462f, 0.535528719f},
std::array<float,2>{0.294397265f, 0.451355696f},
std::array<float,2>{0.667069018f, 0.955543876f},
std::array<float,2>{0.591736257f, 0.351263285f},
std::array<float,2>{0.40809232f, 0.800840735f},
std::array<float,2>{0.244938403f, 0.116690196f},
std::array<float,2>{0.985166848f, 0.663029432f},
std::array<float,2>{0.706688166f, 0.0496422052f},
std::array<float,2>{0.32455343f, 0.719974875f},
std::array<float,2>{0.118304059f, 0.285696417f},
std::array<float,2>{0.773599327f, 0.838860452f},
std::array<float,2>{0.898963809f, 0.403097004f},
std::array<float,2>{0.175357059f, 0.919413328f},
std::array<float,2>{0.493337065f, 0.189474493f},
std::array<float,2>{0.516013443f, 0.587570548f},
std::array<float,2>{0.75146234f, 0.00438266108f},
std::array<float,2>{0.100233607f, 0.691545069f},
std::array<float,2>{0.340665638f, 0.257118881f},
std::array<float,2>{0.700889289f, 0.86475116f},
std::array<float,2>{0.509803116f, 0.416426867f},
std::array<float,2>{0.483922541f, 0.884635508f},
std::array<float,2>{0.16893214f, 0.239725754f},
std::array<float,2>{0.888539553f, 0.60542661f},
std::array<float,2>{0.677974403f, 0.182004899f},
std::array<float,2>{0.297088027f, 0.506103218f},
std::array<float,2>{0.0617520697f, 0.476790816f},
std::array<float,2>{0.837693632f, 0.9974069f},
std::array<float,2>{0.980399191f, 0.33859846f},
std::array<float,2>{0.230446845f, 0.777537823f},
std::array<float,2>{0.428339273f, 0.0668286085f},
std::array<float,2>{0.569833696f, 0.628840327f},
std::array<float,2>{0.926941156f, 0.209624812f},
std::array<float,2>{0.144990042f, 0.573502064f},
std::array<float,2>{0.448848814f, 0.376690239f},
std::array<float,2>{0.5573048f, 0.93341732f},
std::array<float,2>{0.720993519f, 0.308329046f},
std::array<float,2>{0.368055403f, 0.815048754f},
std::array<float,2>{0.072337538f, 0.0360069387f},
std::array<float,2>{0.78388381f, 0.737873554f},
std::array<float,2>{0.609257042f, 0.106602564f},
std::array<float,2>{0.377785504f, 0.68218869f},
std::array<float,2>{0.212105185f, 0.365812808f},
std::array<float,2>{0.96669364f, 0.794436395f},
std::array<float,2>{0.871356487f, 0.460127473f},
std::array<float,2>{0.0110787526f, 0.948239446f},
std::array<float,2>{0.268888861f, 0.139617473f},
std::array<float,2>{0.632823646f, 0.558878243f},
std::array<float,2>{0.878201962f, 0.101416409f},
std::array<float,2>{0.162884682f, 0.674132764f},
std::array<float,2>{0.471709043f, 0.373759329f},
std::array<float,2>{0.50001049f, 0.787088454f},
std::array<float,2>{0.695011616f, 0.466998816f},
std::array<float,2>{0.332268178f, 0.939142346f},
std::array<float,2>{0.105884887f, 0.126066282f},
std::array<float,2>{0.759002209f, 0.552620411f},
std::array<float,2>{0.573931634f, 0.213953868f},
std::array<float,2>{0.437062263f, 0.564243495f},
std::array<float,2>{0.223246455f, 0.386279553f},
std::array<float,2>{0.97167629f, 0.927723706f},
std::array<float,2>{0.830512941f, 0.303785384f},
std::array<float,2>{0.0499868616f, 0.820808768f},
std::array<float,2>{0.311658502f, 0.0434629843f},
std::array<float,2>{0.682489634f, 0.747239947f},
std::array<float,2>{0.791689992f, 0.177132219f},
std::array<float,2>{0.0696971491f, 0.509984255f},
std::array<float,2>{0.360253841f, 0.469870508f},
std::array<float,2>{0.730741918f, 0.991077065f},
std::array<float,2>{0.550052106f, 0.332661361f},
std::array<float,2>{0.444180101f, 0.768233597f},
std::array<float,2>{0.149655387f, 0.0721460134f},
std::array<float,2>{0.930519879f, 0.634173155f},
std::array<float,2>{0.627851009f, 0.0137690343f},
std::array<float,2>{0.278983504f, 0.695731759f},
std::array<float,2>{0.00634163944f, 0.258933723f},
std::array<float,2>{0.866732955f, 0.872823f},
std::array<float,2>{0.953183949f, 0.406470776f},
std::array<float,2>{0.204295471f, 0.877562642f},
std::array<float,2>{0.389366895f, 0.24719134f},
std::array<float,2>{0.599604666f, 0.597263098f},
std::array<float,2>{0.849050939f, 0.0605951324f},
std::array<float,2>{0.0199438576f, 0.727265179f},
std::array<float,2>{0.254080027f, 0.28921935f},
std::array<float,2>{0.640737414f, 0.833072722f},
std::array<float,2>{0.624134064f, 0.394747078f},
std::array<float,2>{0.403807461f, 0.910957456f},
std::array<float,2>{0.197963625f, 0.198175222f},
std::array<float,2>{0.945215881f, 0.580145121f},
std::array<float,2>{0.734505594f, 0.15535146f},
std::array<float,2>{0.35393855f, 0.544974089f},
std::array<float,2>{0.0937370211f, 0.445270866f},
std::array<float,2>{0.799973547f, 0.96778357f},
std::array<float,2>{0.918223023f, 0.351889133f},
std::array<float,2>{0.139097095f, 0.80832082f},
std::array<float,2>{0.45710361f, 0.124094643f},
std::array<float,2>{0.537952662f, 0.665972948f},
std::array<float,2>{0.995045841f, 0.231600121f},
std::array<float,2>{0.239349201f, 0.62335825f},
std::array<float,2>{0.416037917f, 0.433970243f},
std::array<float,2>{0.581060052f, 0.89409554f},
std::array<float,2>{0.659578204f, 0.273795158f},
std::array<float,2>{0.285514474f, 0.84607923f},
std::array<float,2>{0.0380740538f, 0.0230114497f},
std::array<float,2>{0.824432373f, 0.70670259f},
std::array<float,2>{0.525770307f, 0.0889607221f},
std::array<float,2>{0.485029638f, 0.650759459f},
std::array<float,2>{0.181705415f, 0.321073741f},
std::array<float,2>{0.893975854f, 0.752625287f},
std::array<float,2>{0.771831751f, 0.488433212f},
std::array<float,2>{0.112268463f, 0.983045936f},
std::array<float,2>{0.313552082f, 0.165949717f},
std::array<float,2>{0.711619794f, 0.530845344f},
std::array<float,2>{0.948553145f, 0.0299472231f},
std::array<float,2>{0.19214198f, 0.716228724f},
std::array<float,2>{0.393401325f, 0.26991716f},
std::array<float,2>{0.610335112f, 0.854233503f},
std::array<float,2>{0.650841832f, 0.427603692f},
std::array<float,2>{0.264911085f, 0.900816619f},
std::array<float,2>{0.030169148f, 0.223943949f},
std::array<float,2>{0.857849181f, 0.610687971f},
std::array<float,2>{0.54414618f, 0.157182992f},
std::array<float,2>{0.464274108f, 0.520733654f},
std::array<float,2>{0.127670169f, 0.498387903f},
std::array<float,2>{0.906368613f, 0.971563637f},
std::array<float,2>{0.811605573f, 0.315216422f},
std::array<float,2>{0.0835160166f, 0.757977426f},
std::array<float,2>{0.34392184f, 0.080628626f},
std::array<float,2>{0.744943261f, 0.641059697f},
std::array<float,2>{0.815642595f, 0.189898103f},
std::array<float,2>{0.0450178273f, 0.587808073f},
std::array<float,2>{0.295033336f, 0.402973235f},
std::array<float,2>{0.664404869f, 0.918957651f},
std::array<float,2>{0.592849612f, 0.28600961f},
std::array<float,2>{0.40931648f, 0.83855468f},
std::array<float,2>{0.24394387f, 0.0495083109f},
std::array<float,2>{0.987536013f, 0.719846308f},
std::array<float,2>{0.704644084f, 0.116249606f},
std::array<float,2>{0.327960193f, 0.662822843f},
std::array<float,2>{0.120982587f, 0.351493031f},
std::array<float,2>{0.775795877f, 0.801071942f},
std::array<float,2>{0.900463581f, 0.451520324f},
std::array<float,2>{0.173077151f, 0.955217838f},
std::array<float,2>{0.495604545f, 0.143239826f},
std::array<float,2>{0.518065512f, 0.535393834f},
std::array<float,2>{0.75239253f, 0.066411972f},
std::array<float,2>{0.0984899327f, 0.628456414f},
std::array<float,2>{0.343346924f, 0.33862552f},
std::array<float,2>{0.702772439f, 0.777602136f},
std::array<float,2>{0.508409858f, 0.476934612f},
std::array<float,2>{0.481440067f, 0.997114003f},
std::array<float,2>{0.171501666f, 0.181716248f},
std::array<float,2>{0.890205324f, 0.506228268f},
std::array<float,2>{0.676287651f, 0.239474803f},
std::array<float,2>{0.299649805f, 0.605184793f},
std::array<float,2>{0.0595139898f, 0.41616872f},
std::array<float,2>{0.839524567f, 0.884389937f},
std::array<float,2>{0.977798402f, 0.256968737f},
std::array<float,2>{0.227309465f, 0.865110397f},
std::array<float,2>{0.425827056f, 0.00391522748f},
std::array<float,2>{0.567912936f, 0.691793859f},
std::array<float,2>{0.928870201f, 0.139401317f},
std::array<float,2>{0.148208603f, 0.558737159f},
std::array<float,2>{0.445992023f, 0.460292459f},
std::array<float,2>{0.556279719f, 0.947819352f},
std::array<float,2>{0.719988406f, 0.366178006f},
std::array<float,2>{0.370796025f, 0.794703722f},
std::array<float,2>{0.0708539039f, 0.106717356f},
std::array<float,2>{0.782774031f, 0.682595253f},
std::array<float,2>{0.606078267f, 0.0357260667f},
std::array<float,2>{0.375904292f, 0.738252759f},
std::array<float,2>{0.214742631f, 0.30850932f},
std::array<float,2>{0.967311025f, 0.815286338f},
std::array<float,2>{0.874226332f, 0.376756489f},
std::array<float,2>{0.00949923322f, 0.933166504f},
std::array<float,2>{0.266662627f, 0.209840491f},
std::array<float,2>{0.634775758f, 0.573327541f},
std::array<float,2>{0.91352278f, 0.0422491208f},
std::array<float,2>{0.131857738f, 0.745723784f},
std::array<float,2>{0.465294868f, 0.297623277f},
std::array<float,2>{0.542549312f, 0.827034891f},
std::array<float,2>{0.746252298f, 0.389555037f},
std::array<float,2>{0.348203182f, 0.924660146f},
std::array<float,2>{0.078294687f, 0.216625541f},
std::array<float,2>{0.808051288f, 0.566664279f},
std::array<float,2>{0.616333365f, 0.129434571f},
std::array<float,2>{0.397029012f, 0.548296988f},
std::array<float,2>{0.187673569f, 0.461232036f},
std::array<float,2>{0.951769948f, 0.94493252f},
std::array<float,2>{0.854767919f, 0.368085057f},
std::array<float,2>{0.0242569372f, 0.78167671f},
std::array<float,2>{0.258305013f, 0.0951114297f},
std::array<float,2>{0.653413355f, 0.678826213f},
std::array<float,2>{0.780830324f, 0.244939148f},
std::array<float,2>{0.12460348f, 0.599444211f},
std::array<float,2>{0.322212368f, 0.412217766f},
std::array<float,2>{0.709376693f, 0.880167186f},
std::array<float,2>{0.520315111f, 0.265543282f},
std::array<float,2>{0.499923795f, 0.867954612f},
std::array<float,2>{0.179442242f, 0.00916494429f},
std::array<float,2>{0.906217277f, 0.699505746f},
std::array<float,2>{0.669139028f, 0.0752459094f},
std::array<float,2>{0.291672826f, 0.636873901f},
std::array<float,2>{0.0422831289f, 0.330119967f},
std::array<float,2>{0.81672287f, 0.772569716f},
std::array<float,2>{0.989152074f, 0.47570473f},
std::array<float,2>{0.24928382f, 0.984448135f},
std::array<float,2>{0.413462937f, 0.175772384f},
std::array<float,2>{0.586020827f, 0.514473379f},
std::array<float,2>{0.842308879f, 0.117602721f},
std::array<float,2>{0.054726705f, 0.66872102f},
std::array<float,2>{0.301442266f, 0.35883671f},
std::array<float,2>{0.672834814f, 0.809711158f},
std::array<float,2>{0.564181983f, 0.440956354f},
std::array<float,2>{0.425329417f, 0.964815497f},
std::array<float,2>{0.23416844f, 0.149516299f},
std::array<float,2>{0.982916296f, 0.540612221f},
std::array<float,2>{0.695904016f, 0.199513733f},
std::array<float,2>{0.338424027f, 0.585522115f},
std::array<float,2>{0.0961361304f, 0.391816705f},
std::array<float,2>{0.75434339f, 0.908781946f},
std::array<float,2>{0.885522246f, 0.293918937f},
std::array<float,2>{0.167678326f, 0.828653872f},
std::array<float,2>{0.478964657f, 0.0549823381f},
std::array<float,2>{0.513801992f, 0.730831027f},
std::array<float,2>{0.962604761f, 0.168628871f},
std::array<float,2>{0.218009368f, 0.526594162f},
std::array<float,2>{0.380417496f, 0.486773014f},
std::array<float,2>{0.605226636f, 0.977810979f},
std::array<float,2>{0.639527142f, 0.328105003f},
std::array<float,2>{0.270575285f, 0.755441427f},
std::array<float,2>{0.014145731f, 0.0898840353f},
std::array<float,2>{0.869529009f, 0.655881226f},
std::array<float,2>{0.560261488f, 0.0179402605f},
std::array<float,2>{0.452328026f, 0.708212912f},
std::array<float,2>{0.144473255f, 0.281211138f},
std::array<float,2>{0.923995614f, 0.848915339f},
std::array<float,2>{0.787250817f, 0.43311885f},
std::array<float,2>{0.0742484108f, 0.896013916f},
std::array<float,2>{0.372336f, 0.22816436f},
std::array<float,2>{0.723587096f, 0.617945552f},
std::array<float,2>{0.974425137f, 0.0842024237f},
std::array<float,2>{0.222368672f, 0.646787405f},
std::array<float,2>{0.430199653f, 0.316585422f},
std::array<float,2>{0.577870309f, 0.763292372f},
std::array<float,2>{0.684198201f, 0.495451599f},
std::array<float,2>{0.307216406f, 0.975288808f},
std::array<float,2>{0.0521813743f, 0.16143854f},
std::array<float,2>{0.834910035f, 0.518287241f},
std::array<float,2>{0.504868865f, 0.222395197f},
std::array<float,2>{0.474926203f, 0.614246726f},
std::array<float,2>{0.157531172f, 0.423398793f},
std::array<float,2>{0.879117429f, 0.904270351f},
std::array<float,2>{0.764958918f, 0.268690288f},
std::array<float,2>{0.103787966f, 0.858478069f},
std::array<float,2>{0.32982704f, 0.0241943393f},
std::array<float,2>{0.689193964f, 0.712515831f},
std::array<float,2>{0.859444201f, 0.145615295f},
std::array<float,2>{0.00124287431f, 0.532028437f},
std::array<float,2>{0.274530649f, 0.449155658f},
std::array<float,2>{0.629431844f, 0.959071577f},
std::array<float,2>{0.597362518f, 0.346515417f},
std::array<float,2>{0.386122555f, 0.800057232f},
std::array<float,2>{0.210473627f, 0.112391949f},
std::array<float,2>{0.96087867f, 0.657407105f},
std::array<float,2>{0.729777277f, 0.0520737916f},
std::array<float,2>{0.363855213f, 0.724252701f},
std::array<float,2>{0.064261198f, 0.281800687f},
std::array<float,2>{0.79651612f, 0.842056811f},
std::array<float,2>{0.937075615f, 0.40105927f},
std::array<float,2>{0.154285133f, 0.916768193f},
std::array<float,2>{0.440890521f, 0.192096859f},
std::array<float,2>{0.551917732f, 0.590206325f},
std::array<float,2>{0.801880121f, 0.000655945856f},
std::array<float,2>{0.0872617736f, 0.690755844f},
std::array<float,2>{0.357755035f, 0.251362741f},
std::array<float,2>{0.738728642f, 0.863063395f},
std::array<float,2>{0.532615721f, 0.418838114f},
std::array<float,2>{0.456681848f, 0.887904644f},
std::array<float,2>{0.133719578f, 0.234639883f},
std::array<float,2>{0.916196823f, 0.608347058f},
std::array<float,2>{0.64696753f, 0.183778837f},
std::array<float,2>{0.252735823f, 0.502223551f},
std::array<float,2>{0.018948935f, 0.481401712f},
std::array<float,2>{0.844498992f, 0.99502784f},
std::array<float,2>{0.941103399f, 0.340880781f},
std::array<float,2>{0.202738106f, 0.773538411f},
std::array<float,2>{0.400505394f, 0.0632947311f},
std::array<float,2>{0.619660497f, 0.629679084f},
std::array<float,2>{0.897839069f, 0.205212578f},
std::array<float,2>{0.186188787f, 0.577985466f},
std::array<float,2>{0.491157591f, 0.380381614f},
std::array<float,2>{0.530536294f, 0.936860979f},
std::array<float,2>{0.714915633f, 0.308645546f},
std::array<float,2>{0.318291456f, 0.819954932f},
std::array<float,2>{0.113526754f, 0.0348099172f},
std::array<float,2>{0.765715301f, 0.738847256f},
std::array<float,2>{0.584953785f, 0.104181729f},
std::array<float,2>{0.418117493f, 0.687208116f},
std::array<float,2>{0.234730527f, 0.362576962f},
std::array<float,2>{0.997167945f, 0.790065706f},
std::array<float,2>{0.823099256f, 0.454925627f},
std::array<float,2>{0.0314780585f, 0.951081872f},
std::array<float,2>{0.2817882f, 0.135747701f},
std::array<float,2>{0.660734594f, 0.555494547f},
std::array<float,2>{0.932709455f, 0.0731232688f},
std::array<float,2>{0.150420576f, 0.636601388f},
std::array<float,2>{0.442600399f, 0.334943086f},
std::array<float,2>{0.5481655f, 0.766545713f},
std::array<float,2>{0.733293533f, 0.471927136f},
std::array<float,2>{0.36142692f, 0.989498138f},
std::array<float,2>{0.0671301931f, 0.179685012f},
std::array<float,2>{0.789895475f, 0.508966744f},
std::array<float,2>{0.601001799f, 0.249078557f},
std::array<float,2>{0.386916846f, 0.594203472f},
std::array<float,2>{0.205213726f, 0.408736736f},
std::array<float,2>{0.95609796f, 0.875002861f},
std::array<float,2>{0.864444017f, 0.259869754f},
std::array<float,2>{0.00558678433f, 0.873792946f},
std::array<float,2>{0.280989647f, 0.0129258512f},
std::array<float,2>{0.625260055f, 0.697990417f},
std::array<float,2>{0.761374831f, 0.127931714f},
std::array<float,2>{0.109146342f, 0.55281502f},
std::array<float,2>{0.335786879f, 0.466530591f},
std::array<float,2>{0.69273454f, 0.940910041f},
std::array<float,2>{0.501979947f, 0.372629046f},
std::array<float,2>{0.46964401f, 0.787307739f},
std::array<float,2>{0.161069825f, 0.097691372f},
std::array<float,2>{0.876186967f, 0.671931982f},
std::array<float,2>{0.68051517f, 0.0468350537f},
std::array<float,2>{0.309622794f, 0.748534858f},
std::array<float,2>{0.046887368f, 0.302029639f},
std::array<float,2>{0.829672873f, 0.823195696f},
std::array<float,2>{0.970693707f, 0.384734243f},
std::array<float,2>{0.224801749f, 0.928960919f},
std::array<float,2>{0.433876425f, 0.212547079f},
std::array<float,2>{0.571789682f, 0.564615548f},
std::array<float,2>{0.826432467f, 0.0203507058f},
std::array<float,2>{0.035299696f, 0.703526258f},
std::array<float,2>{0.287582874f, 0.277131587f},
std::array<float,2>{0.657524168f, 0.844873548f},
std::array<float,2>{0.578530729f, 0.4356803f},
std::array<float,2>{0.415802211f, 0.892160654f},
std::array<float,2>{0.242059737f, 0.234056517f},
std::array<float,2>{0.993853033f, 0.621778309f},
std::array<float,2>{0.714197397f, 0.167423829f},
std::array<float,2>{0.315455705f, 0.528505623f},
std::array<float,2>{0.110278547f, 0.491317451f},
std::array<float,2>{0.770155668f, 0.981922626f},
std::array<float,2>{0.891184688f, 0.323617369f},
std::array<float,2>{0.181263566f, 0.750153661f},
std::array<float,2>{0.487673819f, 0.0863109604f},
std::array<float,2>{0.523992896f, 0.649994075f},
std::array<float,2>{0.943085492f, 0.196254656f},
std::array<float,2>{0.196297213f, 0.579737723f},
std::array<float,2>{0.406079054f, 0.397886068f},
std::array<float,2>{0.621626258f, 0.91251123f},
std::array<float,2>{0.643250227f, 0.291173935f},
std::array<float,2>{0.257649958f, 0.835211039f},
std::array<float,2>{0.0223292094f, 0.0597910695f},
std::array<float,2>{0.850586176f, 0.728892148f},
std::array<float,2>{0.535738051f, 0.122837402f},
std::array<float,2>{0.459392518f, 0.667749524f},
std::array<float,2>{0.1381993f, 0.354741782f},
std::array<float,2>{0.921092689f, 0.806614757f},
std::array<float,2>{0.797570407f, 0.442534328f},
std::array<float,2>{0.0915409103f, 0.965014338f},
std::array<float,2>{0.352226108f, 0.152511016f},
std::array<float,2>{0.73655504f, 0.544134319f},
std::array<float,2>{0.98566401f, 0.047807131f},
std::array<float,2>{0.245158955f, 0.721201599f},
std::array<float,2>{0.406571358f, 0.287747055f},
std::array<float,2>{0.590289772f, 0.836032569f},
std::array<float,2>{0.666933298f, 0.406105876f},
std::array<float,2>{0.293741614f, 0.921787679f},
std::array<float,2>{0.0445733294f, 0.187845394f},
std::array<float,2>{0.813754261f, 0.588398635f},
std::array<float,2>{0.516947925f, 0.141374648f},
std::array<float,2>{0.493136078f, 0.538250506f},
std::array<float,2>{0.174063623f, 0.451112658f},
std::array<float,2>{0.899650455f, 0.954200447f},
std::array<float,2>{0.774662018f, 0.349051267f},
std::array<float,2>{0.117322229f, 0.803560972f},
std::array<float,2>{0.326129168f, 0.114850834f},
std::array<float,2>{0.705611348f, 0.661853969f},
std::array<float,2>{0.855953097f, 0.226464868f},
std::array<float,2>{0.0291433372f, 0.612333298f},
std::array<float,2>{0.262443483f, 0.428967297f},
std::array<float,2>{0.650114357f, 0.900204837f},
std::array<float,2>{0.611734688f, 0.272142142f},
std::array<float,2>{0.391372234f, 0.853022993f},
std::array<float,2>{0.194421992f, 0.0291550793f},
std::array<float,2>{0.946084261f, 0.718066514f},
std::array<float,2>{0.743513107f, 0.079752028f},
std::array<float,2>{0.347003281f, 0.643239319f},
std::array<float,2>{0.0858746544f, 0.313488394f},
std::array<float,2>{0.80925113f, 0.760271907f},
std::array<float,2>{0.908219516f, 0.496995538f},
std::array<float,2>{0.125181735f, 0.970623434f},
std::array<float,2>{0.462414533f, 0.158963799f},
std::array<float,2>{0.545024276f, 0.522941947f},
std::array<float,2>{0.784263372f, 0.108085625f},
std::array<float,2>{0.0738398135f, 0.680966377f},
std::array<float,2>{0.368943304f, 0.363294631f},
std::array<float,2>{0.722049832f, 0.796287298f},
std::array<float,2>{0.558461547f, 0.458841443f},
std::array<float,2>{0.447853267f, 0.946553349f},
std::array<float,2>{0.145980597f, 0.137355119f},
std::array<float,2>{0.926424026f, 0.56217742f},
std::array<float,2>{0.633972526f, 0.208477706f},
std::array<float,2>{0.267982036f, 0.571425974f},
std::array<float,2>{0.0103473514f, 0.377848089f},
std::array<float,2>{0.872393727f, 0.930691421f},
std::array<float,2>{0.965322077f, 0.306063533f},
std::array<float,2>{0.211182579f, 0.812583625f},
std::array<float,2>{0.378298163f, 0.0389939882f},
std::array<float,2>{0.607554436f, 0.736218691f},
std::array<float,2>{0.887345612f, 0.180148691f},
std::array<float,2>{0.169490471f, 0.504580379f},
std::array<float,2>{0.482770443f, 0.47991094f},
std::array<float,2>{0.511538327f, 0.998547435f},
std::array<float,2>{0.699436069f, 0.336680949f},
std::array<float,2>{0.34084481f, 0.781215966f},
std::array<float,2>{0.101503879f, 0.0699962229f},
std::array<float,2>{0.750579536f, 0.626112819f},
std::array<float,2>{0.568540156f, 0.00723877409f},
std::array<float,2>{0.428958684f, 0.694012523f},
std::array<float,2>{0.229110852f, 0.255600065f},
std::array<float,2>{0.978641033f, 0.865331411f},
std::array<float,2>{0.836769402f, 0.414540321f},
std::array<float,2>{0.0611612462f, 0.885445774f},
std::array<float,2>{0.298773408f, 0.240789115f},
std::array<float,2>{0.679603815f, 0.602519989f},
std::array<float,2>{0.90244168f, 0.0104629686f},
std::array<float,2>{0.175984576f, 0.702351511f},
std::array<float,2>{0.497709662f, 0.262681127f},
std::array<float,2>{0.522578597f, 0.870642185f},
std::array<float,2>{0.708431065f, 0.41020003f},
std::array<float,2>{0.323972344f, 0.882167637f},
std::array<float,2>{0.122057565f, 0.242199928f},
std::array<float,2>{0.778577387f, 0.601036131f},
std::array<float,2>{0.588136971f, 0.172883123f},
std::array<float,2>{0.411719233f, 0.512217462f},
std::array<float,2>{0.246527538f, 0.474143833f},
std::array<float,2>{0.991300404f, 0.987493396f},
std::array<float,2>{0.819225669f, 0.329288065f},
std::array<float,2>{0.0391322002f, 0.769878149f},
std::array<float,2>{0.290329963f, 0.076867044f},
std::array<float,2>{0.671366096f, 0.639114678f},
std::array<float,2>{0.805333257f, 0.21819821f},
std::array<float,2>{0.0803182498f, 0.569548428f},
std::array<float,2>{0.349892944f, 0.387589484f},
std::array<float,2>{0.748295486f, 0.921953619f},
std::array<float,2>{0.540544689f, 0.299515367f},
std::array<float,2>{0.468719929f, 0.824822426f},
std::array<float,2>{0.129312888f, 0.0393322632f},
std::array<float,2>{0.911045372f, 0.743918955f},
std::array<float,2>{0.656205654f, 0.0964721963f},
std::array<float,2>{0.261385471f, 0.677681983f},
std::array<float,2>{0.0268461369f, 0.369784594f},
std::array<float,2>{0.853356957f, 0.784703255f},
std::array<float,2>{0.950665236f, 0.463884205f},
std::array<float,2>{0.191348925f, 0.941684186f},
std::array<float,2>{0.395535052f, 0.132234827f},
std::array<float,2>{0.614791453f, 0.549440384f},
std::array<float,2>{0.868148685f, 0.0920607969f},
std::array<float,2>{0.0133042978f, 0.653158128f},
std::array<float,2>{0.271854162f, 0.324508488f},
std::array<float,2>{0.637776315f, 0.757056534f},
std::array<float,2>{0.603506148f, 0.485078901f},
std::array<float,2>{0.380910695f, 0.980002165f},
std::array<float,2>{0.215174779f, 0.170944378f},
std::array<float,2>{0.964266539f, 0.525275946f},
std::array<float,2>{0.724616528f, 0.230462804f},
std::array<float,2>{0.373580217f, 0.620331883f},
std::array<float,2>{0.0761894062f, 0.429896921f},
std::array<float,2>{0.786676526f, 0.896788001f},
std::array<float,2>{0.922227204f, 0.278939903f},
std::array<float,2>{0.142481402f, 0.851005316f},
std::array<float,2>{0.45117116f, 0.0171974618f},
std::array<float,2>{0.561413884f, 0.710560262f},
std::array<float,2>{0.98065418f, 0.152260885f},
std::array<float,2>{0.23186627f, 0.541680336f},
std::array<float,2>{0.422331572f, 0.438611835f},
std::array<float,2>{0.56533277f, 0.961614013f},
std::array<float,2>{0.675519466f, 0.356252611f},
std::array<float,2>{0.303625464f, 0.811011732f},
std::array<float,2>{0.0585701577f, 0.119860388f},
std::array<float,2>{0.84166348f, 0.671416461f},
std::array<float,2>{0.512502193f, 0.0579658151f},
std::array<float,2>{0.478089839f, 0.732552588f},
std::array<float,2>{0.164218768f, 0.296839386f},
std::array<float,2>{0.884500504f, 0.830803394f},
std::array<float,2>{0.756100833f, 0.394352168f},
std::array<float,2>{0.0949019045f, 0.906754315f},
std::array<float,2>{0.336311579f, 0.202349707f},
std::array<float,2>{0.69911772f, 0.582360625f},
std::array<float,2>{0.957547307f, 0.111215882f},
std::array<float,2>{0.207250595f, 0.658686459f},
std::array<float,2>{0.382988364f, 0.343796045f},
std::array<float,2>{0.594964564f, 0.79837954f},
std::array<float,2>{0.63272661f, 0.446872085f},
std::array<float,2>{0.275573432f, 0.95839262f},
std::array<float,2>{0.0033315511f, 0.146541119f},
std::array<float,2>{0.862957656f, 0.533665717f},
std::array<float,2>{0.553869009f, 0.194976643f},
std::array<float,2>{0.437808156f, 0.593694448f},
std::array<float,2>{0.155884147f, 0.398638308f},
std::array<float,2>{0.93485105f, 0.915439069f},
std::array<float,2>{0.794125676f, 0.283827037f},
std::array<float,2>{0.065357469f, 0.841549456f},
std::array<float,2>{0.366153032f, 0.0531780161f},
std::array<float,2>{0.727874696f, 0.726516843f},
std::array<float,2>{0.833975315f, 0.163961887f},
std::array<float,2>{0.0533354543f, 0.51657337f},
std::array<float,2>{0.306224227f, 0.492288589f},
std::array<float,2>{0.685708404f, 0.973531723f},
std::array<float,2>{0.574454308f, 0.31855318f},
std::array<float,2>{0.433298886f, 0.764356613f},
std::array<float,2>{0.220507309f, 0.0826773867f},
std::array<float,2>{0.975331187f, 0.646285594f},
std::array<float,2>{0.691262245f, 0.0266967025f},
std::array<float,2>{0.330108613f, 0.714176714f},
std::array<float,2>{0.103305921f, 0.266745597f},
std::array<float,2>{0.762924314f, 0.856721878f},
std::array<float,2>{0.882613778f, 0.425658196f},
std::array<float,2>{0.159618393f, 0.905661821f},
std::array<float,2>{0.473849237f, 0.219548076f},
std::array<float,2>{0.507525086f, 0.615506351f},
std::array<float,2>{0.769110203f, 0.0326690003f},
std::array<float,2>{0.116467491f, 0.74154973f},
std::array<float,2>{0.319343001f, 0.310897917f},
std::array<float,2>{0.71728617f, 0.817507386f},
std::array<float,2>{0.528268158f, 0.38238126f},
std::array<float,2>{0.489598304f, 0.934265673f},
std::array<float,2>{0.184111536f, 0.203846768f},
std::array<float,2>{0.895838439f, 0.575485885f},
std::array<float,2>{0.662857652f, 0.132846117f},
std::array<float,2>{0.284068823f, 0.558184922f},
std::array<float,2>{0.0344659239f, 0.456879109f},
std::array<float,2>{0.821056545f, 0.952118695f},
std::array<float,2>{0.999067247f, 0.360303909f},
std::array<float,2>{0.236924157f, 0.791815937f},
std::array<float,2>{0.420842022f, 0.102062434f},
std::array<float,2>{0.583585739f, 0.684485078f},
std::array<float,2>{0.915035665f, 0.236526713f},
std::array<float,2>{0.135074943f, 0.606215835f},
std::array<float,2>{0.454722017f, 0.420877278f},
std::array<float,2>{0.534004033f, 0.889230311f},
std::array<float,2>{0.741398811f, 0.25238511f},
std::array<float,2>{0.356476277f, 0.860707998f},
std::array<float,2>{0.0882571489f, 0.00204699952f},
std::array<float,2>{0.804565609f, 0.688227236f},
std::array<float,2>{0.617732048f, 0.0663908347f},
std::array<float,2>{0.398964256f, 0.631815255f},
std::array<float,2>{0.200058296f, 0.342351019f},
std::array<float,2>{0.937754631f, 0.775998831f},
std::array<float,2>{0.846809208f, 0.483186185f},
std::array<float,2>{0.0164334327f, 0.993581057f},
std::array<float,2>{0.250852764f, 0.186533988f},
std::array<float,2>{0.646345377f, 0.501830637f},
std::array<float,2>{0.892727733f, 0.0871966928f},
std::array<float,2>{0.183484897f, 0.648777366f},
std::array<float,2>{0.48588565f, 0.322675496f},
std::array<float,2>{0.52729851f, 0.751066148f},
std::array<float,2>{0.712481797f, 0.49107188f},
std::array<float,2>{0.313282728f, 0.981091738f},
std::array<float,2>{0.112668127f, 0.166828766f},
std::array<float,2>{0.772985697f, 0.528148234f},
std::array<float,2>{0.580656528f, 0.232653901f},
std::array<float,2>{0.417046249f, 0.623034716f},
std::array<float,2>{0.239187941f, 0.436871797f},
std::array<float,2>{0.995505452f, 0.891339421f},
std::array<float,2>{0.82559371f, 0.276162416f},
std::array<float,2>{0.0386319868f, 0.844347179f},
std::array<float,2>{0.286985785f, 0.0212423354f},
std::array<float,2>{0.658536077f, 0.704440832f},
std::array<float,2>{0.799131155f, 0.153583363f},
std::array<float,2>{0.0919761956f, 0.543683112f},
std::array<float,2>{0.354548782f, 0.441588968f},
std::array<float,2>{0.735403597f, 0.966122568f},
std::array<float,2>{0.53904742f, 0.3537471f},
std::array<float,2>{0.458492786f, 0.805537045f},
std::array<float,2>{0.139714912f, 0.121946864f},
std::array<float,2>{0.919839501f, 0.666280687f},
std::array<float,2>{0.641835928f, 0.0592981465f},
std::array<float,2>{0.255164951f, 0.730397105f},
std::array<float,2>{0.0206573997f, 0.292309582f},
std::array<float,2>{0.848060846f, 0.834721744f},
std::array<float,2>{0.94421792f, 0.396607637f},
std::array<float,2>{0.198686138f, 0.913458824f},
std::array<float,2>{0.403276652f, 0.196582675f},
std::array<float,2>{0.62323761f, 0.57863766f},
std::array<float,2>{0.865622342f, 0.0125922151f},
std::array<float,2>{0.00710400706f, 0.698696911f},
std::array<float,2>{0.27752611f, 0.261304498f},
std::array<float,2>{0.628455162f, 0.874219716f},
std::array<float,2>{0.598256826f, 0.409875304f},
std::array<float,2>{0.390190423f, 0.876315951f},
std::array<float,2>{0.203191489f, 0.248740166f},
std::array<float,2>{0.954129994f, 0.595056713f},
std::array<float,2>{0.731851161f, 0.178403258f},
std::array<float,2>{0.360626638f, 0.508117974f},
std::array<float,2>{0.068523176f, 0.471424788f},
std::array<float,2>{0.792947292f, 0.989225805f},
std::array<float,2>{0.930871189f, 0.335333675f},
std::array<float,2>{0.148488685f, 0.767547429f},
std::array<float,2>{0.44467479f, 0.0736921728f},
std::array<float,2>{0.54925704f, 0.634818673f},
std::array<float,2>{0.971766591f, 0.211713865f},
std::array<float,2>{0.22441794f, 0.566011071f},
std::array<float,2>{0.436427832f, 0.383551121f},
std::array<float,2>{0.57284379f, 0.92849654f},
std::array<float,2>{0.6833722f, 0.301494539f},
std::array<float,2>{0.310713887f, 0.823264599f},
std::array<float,2>{0.0489739738f, 0.0456300713f},
std::array<float,2>{0.831836581f, 0.749055624f},
std::array<float,2>{0.501106501f, 0.0991271958f},
std::array<float,2>{0.471469015f, 0.673361182f},
std::array<float,2>{0.163949385f, 0.371305913f},
std::array<float,2>{0.877078772f, 0.788099885f},
std::array<float,2>{0.758659899f, 0.465095341f},
std::array<float,2>{0.107131205f, 0.93969357f},
std::array<float,2>{0.333318651f, 0.127040282f},
std::array<float,2>{0.694122195f, 0.554427862f},
std::array<float,2>{0.968522131f, 0.0372089855f},
std::array<float,2>{0.213225707f, 0.734562337f},
std::array<float,2>{0.376206607f, 0.305601716f},
std::array<float,2>{0.60685885f, 0.814273953f},
std::array<float,2>{0.635849416f, 0.378115863f},
std::array<float,2>{0.265993208f, 0.929812074f},
std::array<float,2>{0.00788791198f, 0.207315817f},
std::array<float,2>{0.873085618f, 0.57118392f},
std::array<float,2>{0.554882348f, 0.1377175f},
std::array<float,2>{0.447067052f, 0.560996056f},
std::array<float,2>{0.146550983f, 0.457810163f},
std::array<float,2>{0.927829623f, 0.945315003f},
std::array<float,2>{0.781489432f, 0.364381105f},
std::array<float,2>{0.0717642531f, 0.795100808f},
std::array<float,2>{0.369770676f, 0.109328322f},
std::array<float,2>{0.719362795f, 0.680464268f},
std::array<float,2>{0.838776767f, 0.241339162f},
std::array<float,2>{0.0599623658f, 0.602804184f},
std::array<float,2>{0.300017804f, 0.415552437f},
std::array<float,2>{0.67761606f, 0.885860443f},
std::array<float,2>{0.567150176f, 0.254213274f},
std::array<float,2>{0.427519441f, 0.866768599f},
std::array<float,2>{0.228212163f, 0.00651143445f},
std::array<float,2>{0.976567626f, 0.694483399f},
std::array<float,2>{0.701374114f, 0.0687957853f},
std::array<float,2>{0.342733353f, 0.625500679f},
std::array<float,2>{0.099231042f, 0.337496698f},
std::array<float,2>{0.753094554f, 0.780153275f},
std::array<float,2>{0.888760567f, 0.479101032f},
std::array<float,2>{0.170784369f, 0.999494076f},
std::array<float,2>{0.481639326f, 0.181094125f},
std::array<float,2>{0.509149492f, 0.505209386f},
std::array<float,2>{0.777238727f, 0.114029117f},
std::array<float,2>{0.119808406f, 0.660190165f},
std::array<float,2>{0.326666743f, 0.348587185f},
std::array<float,2>{0.703624904f, 0.804498494f},
std::array<float,2>{0.519385099f, 0.44939515f},
std::array<float,2>{0.494873255f, 0.953231215f},
std::array<float,2>{0.172497973f, 0.14238508f},
std::array<float,2>{0.901556551f, 0.537605643f},
std::array<float,2>{0.665790439f, 0.189305872f},
std::array<float,2>{0.296002418f, 0.589425325f},
std::array<float,2>{0.0462700352f, 0.404607981f},
std::array<float,2>{0.815420806f, 0.920448601f},
std::array<float,2>{0.987198412f, 0.288463056f},
std::array<float,2>{0.242716178f, 0.837491274f},
std::array<float,2>{0.408842981f, 0.0487236194f},
std::array<float,2>{0.592677176f, 0.722461104f},
std::array<float,2>{0.907348037f, 0.159289628f},
std::array<float,2>{0.128324956f, 0.522263885f},
std::array<float,2>{0.46361652f, 0.497315049f},
std::array<float,2>{0.543552637f, 0.968916118f},
std::array<float,2>{0.746006608f, 0.312505722f},
std::array<float,2>{0.345179379f, 0.761707783f},
std::array<float,2>{0.082201913f, 0.078741096f},
std::array<float,2>{0.811376035f, 0.643847525f},
std::array<float,2>{0.610464633f, 0.0273669045f},
std::array<float,2>{0.39435932f, 0.717492819f},
std::array<float,2>{0.193059236f, 0.272942364f},
std::array<float,2>{0.947721422f, 0.851683617f},
std::array<float,2>{0.85883683f, 0.428400397f},
std::array<float,2>{0.0311147217f, 0.898878992f},
std::array<float,2>{0.264135957f, 0.22472173f},
std::array<float,2>{0.651985705f, 0.612205267f},
std::array<float,2>{0.925488114f, 0.0157424249f},
std::array<float,2>{0.142610848f, 0.709799111f},
std::array<float,2>{0.451457351f, 0.277520418f},
std::array<float,2>{0.559402883f, 0.850036442f},
std::array<float,2>{0.723782539f, 0.431014419f},
std::array<float,2>{0.371992648f, 0.898364484f},
std::array<float,2>{0.0754350796f, 0.229112849f},
std::array<float,2>{0.788521409f, 0.619732916f},
std::array<float,2>{0.603611171f, 0.170594841f},
std::array<float,2>{0.379483104f, 0.523991108f},
std::array<float,2>{0.216948658f, 0.486237735f},
std::array<float,2>{0.961548924f, 0.97892189f},
std::array<float,2>{0.870343506f, 0.326125056f},
std::array<float,2>{0.01494925f, 0.755943775f},
std::array<float,2>{0.269808799f, 0.0937348679f},
std::array<float,2>{0.640540123f, 0.654042423f},
std::array<float,2>{0.755471408f, 0.201945558f},
std::array<float,2>{0.0969927236f, 0.583820462f},
std::array<float,2>{0.339524835f, 0.393032819f},
std::array<float,2>{0.696775198f, 0.907661855f},
std::array<float,2>{0.515126348f, 0.295699328f},
std::array<float,2>{0.479966849f, 0.831289947f},
std::array<float,2>{0.166067973f, 0.0571467057f},
std::array<float,2>{0.886383653f, 0.733589768f},
std::array<float,2>{0.673677623f, 0.120923318f},
std::array<float,2>{0.301767558f, 0.670676529f},
std::array<float,2>{0.0563241132f, 0.356689543f},
std::array<float,2>{0.843027353f, 0.811672032f},
std::array<float,2>{0.983759999f, 0.438467771f},
std::array<float,2>{0.232566282f, 0.962242842f},
std::array<float,2>{0.423909217f, 0.151025072f},
std::array<float,2>{0.563056231f, 0.542778254f},
std::array<float,2>{0.818314552f, 0.0780987367f},
std::array<float,2>{0.0416507833f, 0.639725685f},
std::array<float,2>{0.292545944f, 0.328143001f},
std::array<float,2>{0.66834712f, 0.770561039f},
std::array<float,2>{0.587407231f, 0.47347641f},
std::array<float,2>{0.412876427f, 0.986766517f},
std::array<float,2>{0.248246148f, 0.171892226f},
std::array<float,2>{0.989779294f, 0.512978494f},
std::array<float,2>{0.710698962f, 0.243821129f},
std::array<float,2>{0.320546478f, 0.599876225f},
std::array<float,2>{0.123742417f, 0.411995828f},
std::array<float,2>{0.78027153f, 0.881748915f},
std::array<float,2>{0.904300034f, 0.263233632f},
std::array<float,2>{0.178356916f, 0.869870901f},
std::array<float,2>{0.498619229f, 0.0113670742f},
std::array<float,2>{0.520795286f, 0.701185405f},
std::array<float,2>{0.95261687f, 0.130932376f},
std::array<float,2>{0.188788697f, 0.550158501f},
std::array<float,2>{0.397846371f, 0.46353516f},
std::array<float,2>{0.615840793f, 0.943305373f},
std::array<float,2>{0.652819335f, 0.370899826f},
std::array<float,2>{0.259152323f, 0.783598006f},
std::array<float,2>{0.0248354394f, 0.0968059823f},
std::array<float,2>{0.854074419f, 0.676707327f},
std::array<float,2>{0.541938066f, 0.0407378748f},
std::array<float,2>{0.46620205f, 0.742400587f},
std::array<float,2>{0.131702632f, 0.299865484f},
std::array<float,2>{0.912569284f, 0.825496078f},
std::array<float,2>{0.807580769f, 0.388022602f},
std::array<float,2>{0.0795459375f, 0.923106611f},
std::array<float,2>{0.348771244f, 0.216842636f},
std::array<float,2>{0.747677743f, 0.568517029f},
std::array<float,2>{0.996403039f, 0.102632537f},
std::array<float,2>{0.236217454f, 0.684854567f},
std::array<float,2>{0.41942066f, 0.360676765f},
std::array<float,2>{0.585218012f, 0.792563736f},
std::array<float,2>{0.661805034f, 0.455593139f},
std::array<float,2>{0.282287031f, 0.952832818f},
std::array<float,2>{0.032299716f, 0.134334773f},
std::array<float,2>{0.823838592f, 0.557503998f},
std::array<float,2>{0.530238986f, 0.205036432f},
std::array<float,2>{0.491667092f, 0.57430923f},
std::array<float,2>{0.187032923f, 0.380995929f},
std::array<float,2>{0.896639705f, 0.935266852f},
std::array<float,2>{0.767080426f, 0.311766684f},
std::array<float,2>{0.115047753f, 0.816746354f},
std::array<float,2>{0.31692332f, 0.0315014273f},
std::array<float,2>{0.715984881f, 0.74033004f},
std::array<float,2>{0.844965994f, 0.186025307f},
std::array<float,2>{0.0177661907f, 0.500186205f},
std::array<float,2>{0.253425628f, 0.484303981f},
std::array<float,2>{0.647982597f, 0.992934763f},
std::array<float,2>{0.620425165f, 0.343381226f},
std::array<float,2>{0.401564747f, 0.777087033f},
std::array<float,2>{0.201922521f, 0.0647125989f},
std::array<float,2>{0.939828396f, 0.632471085f},
std::array<float,2>{0.73937273f, 0.00341373915f},
std::array<float,2>{0.358740181f, 0.689240336f},
std::array<float,2>{0.0863475502f, 0.25379318f},
std::array<float,2>{0.801648736f, 0.859720588f},
std::array<float,2>{0.917367518f, 0.420944422f},
std::array<float,2>{0.134437382f, 0.890543163f},
std::array<float,2>{0.45603922f, 0.237306952f},
std::array<float,2>{0.532152534f, 0.607377648f},
std::array<float,2>{0.795200884f, 0.054165218f},
std::array<float,2>{0.0634158626f, 0.7252478f},
std::array<float,2>{0.364309937f, 0.284962237f},
std::array<float,2>{0.729177892f, 0.840758979f},
std::array<float,2>{0.550915241f, 0.399587452f},
std::array<float,2>{0.439996481f, 0.914483249f},
std::array<float,2>{0.152615666f, 0.194231004f},
std::array<float,2>{0.936067283f, 0.592308164f},
std::array<float,2>{0.630573273f, 0.147793919f},
std::array<float,2>{0.273582399f, 0.534911156f},
std::array<float,2>{0.00042013629f, 0.445998609f},
std::array<float,2>{0.861245453f, 0.957098305f},
std::array<float,2>{0.959662437f, 0.345188588f},
std::array<float,2>{0.209939867f, 0.797760487f},
std::array<float,2>{0.384806037f, 0.109962583f},
std::array<float,2>{0.595888138f, 0.660012603f},
std::array<float,2>{0.880792081f, 0.220265061f},
std::array<float,2>{0.156379297f, 0.616960406f},
std::array<float,2>{0.476193726f, 0.42424047f},
std::array<float,2>{0.505214572f, 0.904359221f},
std::array<float,2>{0.688138843f, 0.266074568f},
std::array<float,2>{0.328454882f, 0.855520785f},
std::array<float,2>{0.104543664f, 0.0257718507f},
std::array<float,2>{0.764029086f, 0.71383512f},
std::array<float,2>{0.576354504f, 0.083330363f},
std::array<float,2>{0.431324601f, 0.645231724f},
std::array<float,2>{0.221146852f, 0.319876492f},
std::array<float,2>{0.973311484f, 0.765122175f},
std::array<float,2>{0.834965765f, 0.493679613f},
std::array<float,2>{0.050935261f, 0.974054217f},
std::array<float,2>{0.308551103f, 0.163011611f},
std::array<float,2>{0.685296178f, 0.516636908f},
std::array<float,2>{0.920736432f, 0.123148829f},
std::array<float,2>{0.137596965f, 0.664923906f},
std::array<float,2>{0.460092574f, 0.352831841f},
std::array<float,2>{0.53624326f, 0.80686599f},
std::array<float,2>{0.737365842f, 0.443527609f},
std::array<float,2>{0.352920651f, 0.967004001f},
std::array<float,2>{0.0902327299f, 0.155061111f},
std::array<float,2>{0.797881305f, 0.546344936f},
std::array<float,2>{0.622872531f, 0.198866814f},
std::array<float,2>{0.404982388f, 0.581751883f},
std::array<float,2>{0.195494086f, 0.396382838f},
std::array<float,2>{0.94185394f, 0.91158396f},
std::array<float,2>{0.84965843f, 0.290561944f},
std::array<float,2>{0.0228185393f, 0.832494974f},
std::array<float,2>{0.255874157f, 0.061993055f},
std::array<float,2>{0.644132555f, 0.72779566f},
std::array<float,2>{0.77146244f, 0.164668024f},
std::array<float,2>{0.110783294f, 0.530015767f},
std::array<float,2>{0.314838231f, 0.4896065f},
std::array<float,2>{0.713552296f, 0.984114587f},
std::array<float,2>{0.525163293f, 0.321825206f},
std::array<float,2>{0.487137645f, 0.753900051f},
std::array<float,2>{0.180375069f, 0.0886414722f},
std::array<float,2>{0.891692638f, 0.651666582f},
std::array<float,2>{0.65635103f, 0.0216656663f},
std::array<float,2>{0.289049774f, 0.705160677f},
std::array<float,2>{0.0364366397f, 0.274542481f},
std::array<float,2>{0.827866375f, 0.847483456f},
std::array<float,2>{0.992827475f, 0.43529886f},
std::array<float,2>{0.241046131f, 0.893166959f},
std::array<float,2>{0.414626479f, 0.231413499f},
std::array<float,2>{0.579658508f, 0.62461853f},
std::array<float,2>{0.828554094f, 0.0445528999f},
std::array<float,2>{0.0479913838f, 0.74645102f},
std::array<float,2>{0.309111565f, 0.302742153f},
std::array<float,2>{0.681627631f, 0.82224983f},
std::array<float,2>{0.570390403f, 0.385571718f},
std::array<float,2>{0.434822112f, 0.926335752f},
std::array<float,2>{0.226200864f, 0.213321522f},
std::array<float,2>{0.969519913f, 0.56303817f},
std::array<float,2>{0.691537619f, 0.125468731f},
std::array<float,2>{0.334822208f, 0.551386654f},
std::array<float,2>{0.108040936f, 0.46797061f},
std::array<float,2>{0.760243297f, 0.937578857f},
std::array<float,2>{0.875384688f, 0.374031454f},
std::array<float,2>{0.16139634f, 0.785805702f},
std::array<float,2>{0.470471948f, 0.100376233f},
std::array<float,2>{0.502959907f, 0.674981952f},
std::array<float,2>{0.955374956f, 0.246199206f},
std::array<float,2>{0.206590787f, 0.59655571f},
std::array<float,2>{0.387845427f, 0.408043742f},
std::array<float,2>{0.599841893f, 0.878831565f},
std::array<float,2>{0.62657088f, 0.258090138f},
std::array<float,2>{0.279584587f, 0.87173301f},
std::array<float,2>{0.00447510416f, 0.0148738958f},
std::array<float,2>{0.864213288f, 0.6966694f},
std::array<float,2>{0.547048092f, 0.0703649819f},
std::array<float,2>{0.442053169f, 0.632928491f},
std::array<float,2>{0.15222463f, 0.333388716f},
std::array<float,2>{0.932242334f, 0.768783689f},
std::array<float,2>{0.790827513f, 0.469523728f},
std::array<float,2>{0.0681577623f, 0.992056012f},
std::array<float,2>{0.362952888f, 0.175875291f},
std::array<float,2>{0.733997762f, 0.510894537f},
std::array<float,2>{0.979733109f, 0.00506810797f},
std::array<float,2>{0.229940712f, 0.692654192f},
std::array<float,2>{0.428140908f, 0.256742716f},
std::array<float,2>{0.569586754f, 0.864236772f},
std::array<float,2>{0.678686857f, 0.417924523f},
std::array<float,2>{0.297588706f, 0.883441806f},
std::array<float,2>{0.0623856448f, 0.238577232f},
std::array<float,2>{0.837124527f, 0.604241729f},
std::array<float,2>{0.510295689f, 0.182686418f},
std::array<float,2>{0.483807892f, 0.507255733f},
std::array<float,2>{0.168198198f, 0.477891475f},
std::array<float,2>{0.887912035f, 0.996615112f},
std::array<float,2>{0.75168252f, 0.33971718f},
std::array<float,2>{0.0996734723f, 0.779241264f},
std::array<float,2>{0.340242714f, 0.0678067505f},
std::array<float,2>{0.700355411f, 0.627846777f},
std::array<float,2>{0.871901572f, 0.210697383f},
std::array<float,2>{0.011422406f, 0.573011041f},
std::array<float,2>{0.26911363f, 0.375258148f},
std::array<float,2>{0.633553088f, 0.93257767f},
std::array<float,2>{0.608449519f, 0.307524681f},
std::array<float,2>{0.377199501f, 0.816221595f},
std::array<float,2>{0.21281983f, 0.0362881646f},
std::array<float,2>{0.966209114f, 0.737215877f},
std::array<float,2>{0.721283674f, 0.105557628f},
std::array<float,2>{0.367483526f, 0.682764292f},
std::array<float,2>{0.0731097087f, 0.366763264f},
std::array<float,2>{0.783355474f, 0.793685377f},
std::array<float,2>{0.927469969f, 0.459081352f},
std::array<float,2>{0.145312548f, 0.949215233f},
std::array<float,2>{0.448695362f, 0.139659584f},
std::array<float,2>{0.556750774f, 0.559718311f},
std::array<float,2>{0.809574664f, 0.0813734233f},
std::array<float,2>{0.084110342f, 0.642401814f},
std::array<float,2>{0.346021503f, 0.31608662f},
std::array<float,2>{0.742823184f, 0.759384036f},
std::array<float,2>{0.546666324f, 0.499498844f},
std::array<float,2>{0.461135536f, 0.972116888f},
std::array<float,2>{0.126329273f, 0.157297045f},
std::array<float,2>{0.909834802f, 0.520260692f},
std::array<float,2>{0.649394691f, 0.223546162f},
std::array<float,2>{0.26293987f, 0.610191584f},
std::array<float,2>{0.0281501673f, 0.425834835f},
std::array<float,2>{0.857370019f, 0.901943922f},
std::array<float,2>{0.946831584f, 0.27102828f},
std::array<float,2>{0.193387806f, 0.854952514f},
std::array<float,2>{0.392281651f, 0.0308059938f},
std::array<float,2>{0.612503111f, 0.714990437f},
std::array<float,2>{0.898888648f, 0.144513771f},
std::array<float,2>{0.175186127f, 0.536995411f},
std::array<float,2>{0.493887186f, 0.452934265f},
std::array<float,2>{0.516572952f, 0.956406891f},
std::array<float,2>{0.706348777f, 0.350156099f},
std::array<float,2>{0.32483241f, 0.80240041f},
std::array<float,2>{0.118723504f, 0.115360811f},
std::array<float,2>{0.773929775f, 0.663159788f},
std::array<float,2>{0.591214836f, 0.0501427911f},
std::array<float,2>{0.407301813f, 0.719037831f},
std::array<float,2>{0.244523406f, 0.286743999f},
std::array<float,2>{0.984624982f, 0.839144766f},
std::array<float,2>{0.813441694f, 0.403751194f},
std::array<float,2>{0.0438632257f, 0.918278515f},
std::array<float,2>{0.294566721f, 0.190582544f},
std::array<float,2>{0.667742252f, 0.586725712f},
std::array<float,2>{0.883185625f, 0.0563088097f},
std::array<float,2>{0.165698975f, 0.732094646f},
std::array<float,2>{0.47672984f, 0.294466764f},
std::array<float,2>{0.513084233f, 0.829731762f},
std::array<float,2>{0.69732362f, 0.391522855f},
std::array<float,2>{0.337510735f, 0.909520686f},
std::array<float,2>{0.0937591791f, 0.20109278f},
std::array<float,2>{0.756947756f, 0.583989084f},
std::array<float,2>{0.566223264f, 0.149402618f},
std::array<float,2>{0.423448712f, 0.539090872f},
std::array<float,2>{0.230593875f, 0.44020167f},
std::array<float,2>{0.981973588f, 0.963196635f},
std::array<float,2>{0.839912295f, 0.358262748f},
std::array<float,2>{0.0567920282f, 0.809194565f},
std::array<float,2>{0.304655045f, 0.119078189f},
std::array<float,2>{0.674319208f, 0.669497848f},
std::array<float,2>{0.785669923f, 0.227538094f},
std::array<float,2>{0.0775000006f, 0.618518829f},
std::array<float,2>{0.374442577f, 0.432329714f},
std::array<float,2>{0.725783706f, 0.895430326f},
std::array<float,2>{0.561960697f, 0.279598892f},
std::array<float,2>{0.449546367f, 0.847721815f},
std::array<float,2>{0.140657246f, 0.0186081044f},
std::array<float,2>{0.923443973f, 0.707050622f},
std::array<float,2>{0.637494922f, 0.0909686163f},
std::array<float,2>{0.273238063f, 0.654904544f},
std::array<float,2>{0.0123577435f, 0.326801866f},
std::array<float,2>{0.868623257f, 0.754092515f},
std::array<float,2>{0.963740528f, 0.488132685f},
std::array<float,2>{0.216156885f, 0.976853192f},
std::array<float,2>{0.38235864f, 0.169175968f},
std::array<float,2>{0.602321208f, 0.525794744f},
std::array<float,2>{0.851889014f, 0.0942985937f},
std::array<float,2>{0.0263252668f, 0.678667367f},
std::array<float,2>{0.260287613f, 0.368504733f},
std::array<float,2>{0.655229509f, 0.78230083f},
std::array<float,2>{0.613986254f, 0.462194294f},
std::array<float,2>{0.395108223f, 0.943896472f},
std::array<float,2>{0.189993277f, 0.130722567f},
std::array<float,2>{0.95002526f, 0.547144592f},
std::array<float,2>{0.749063253f, 0.215586707f},
std::array<float,2>{0.350727558f, 0.567602634f},
std::array<float,2>{0.0815220401f, 0.390336782f},
std::array<float,2>{0.80575943f, 0.925530493f},
std::array<float,2>{0.911536813f, 0.298060179f},
std::array<float,2>{0.130521104f, 0.827954352f},
std::array<float,2>{0.467559755f, 0.0413134657f},
std::array<float,2>{0.539660513f, 0.744179368f},
std::array<float,2>{0.990662634f, 0.174263671f},
std::array<float,2>{0.247490689f, 0.515181363f},
std::array<float,2>{0.410488725f, 0.475547731f},
std::array<float,2>{0.589229226f, 0.985699713f},
std::array<float,2>{0.670621574f, 0.331861019f},
std::array<float,2>{0.289702564f, 0.771582365f},
std::array<float,2>{0.0407282338f, 0.0746560395f},
std::array<float,2>{0.819440663f, 0.638266146f},
std::array<float,2>{0.521594763f, 0.00847848412f},
std::array<float,2>{0.496662289f, 0.701032698f},
std::array<float,2>{0.177710131f, 0.26454711f},
std::array<float,2>{0.903915703f, 0.86842984f},
std::array<float,2>{0.778187871f, 0.413767874f},
std::array<float,2>{0.122487888f, 0.879630983f},
std::array<float,2>{0.322541535f, 0.245644644f},
std::array<float,2>{0.707993984f, 0.59832716f},
std::array<float,2>{0.939148366f, 0.0635097772f},
std::array<float,2>{0.200355217f, 0.630384505f},
std::array<float,2>{0.400116056f, 0.340584457f},
std::array<float,2>{0.619022191f, 0.775099993f},
std::array<float,2>{0.644635797f, 0.481648594f},
std::array<float,2>{0.251493782f, 0.995380044f},
std::array<float,2>{0.0169414319f, 0.18499577f},
std::array<float,2>{0.846350014f, 0.503814816f},
std::array<float,2>{0.534349501f, 0.235970736f},
std::array<float,2>{0.45377484f, 0.609006226f},
std::array<float,2>{0.135954127f, 0.419225991f},
std::array<float,2>{0.915679038f, 0.887211978f},
std::array<float,2>{0.802950323f, 0.250435382f},
std::array<float,2>{0.0896798f, 0.86190486f},
std::array<float,2>{0.35639599f, 0.00104722427f},
std::array<float,2>{0.740873277f, 0.689737797f},
std::array<float,2>{0.821421802f, 0.13484697f},
std::array<float,2>{0.0335162692f, 0.556226373f},
std::array<float,2>{0.284608275f, 0.454090595f},
std::array<float,2>{0.663425624f, 0.949925721f},
std::array<float,2>{0.58217895f, 0.361588776f},
std::array<float,2>{0.420909882f, 0.789719999f},
std::array<float,2>{0.237514198f, 0.104835346f},
std::array<float,2>{0.998214543f, 0.685913205f},
std::array<float,2>{0.718599916f, 0.0335440263f},
std::array<float,2>{0.318632126f, 0.739530206f},
std::array<float,2>{0.115628749f, 0.309818059f},
std::array<float,2>{0.76844883f, 0.819162011f},
std::array<float,2>{0.895234644f, 0.379651964f},
std::array<float,2>{0.185304239f, 0.935872018f},
std::array<float,2>{0.488460988f, 0.206185535f},
std::array<float,2>{0.528770089f, 0.576572478f},
std::array<float,2>{0.76179415f, 0.0248039458f},
std::array<float,2>{0.101811089f, 0.711572587f},
std::array<float,2>{0.331771076f, 0.268529385f},
std::array<float,2>{0.689652324f, 0.858259797f},
std::array<float,2>{0.506796539f, 0.422076911f},
std::array<float,2>{0.473176658f, 0.902578771f},
std::array<float,2>{0.158813253f, 0.220902964f},
std::array<float,2>{0.881795108f, 0.614501715f},
std::array<float,2>{0.686867714f, 0.160416603f},
std::array<float,2>{0.30543676f, 0.519353688f},
std::array<float,2>{0.0543760695f, 0.494795054f},
std::array<float,2>{0.832421243f, 0.97649616f},
std::array<float,2>{0.976466358f, 0.317404926f},
std::array<float,2>{0.218843654f, 0.76255554f},
std::array<float,2>{0.432216913f, 0.0856421515f},
std::array<float,2>{0.575908542f, 0.64795804f},
std::array<float,2>{0.933876872f, 0.193220317f},
std::array<float,2>{0.154598787f, 0.590898991f},
std::array<float,2>{0.439290345f, 0.402232438f},
std::array<float,2>{0.552881479f, 0.917373359f},
std::array<float,2>{0.727438748f, 0.282317638f},
std::array<float,2>{0.36694172f, 0.842805982f},
std::array<float,2>{0.065775305f, 0.0514811762f},
std::array<float,2>{0.793078184f, 0.72305119f},
std::array<float,2>{0.594661295f, 0.11143411f},
std::array<float,2>{0.384507954f, 0.656838596f},
std::array<float,2>{0.208813056f, 0.347213149f},
std::array<float,2>{0.958344996f, 0.799535453f},
std::array<float,2>{0.861724913f, 0.447402865f},
std::array<float,2>{0.00224922458f, 0.96076262f},
std::array<float,2>{0.276720375f, 0.145105943f},
std::array<float,2>{0.630987287f, 0.532937407f},
std::array<float,2>{0.901903749f, 0.115793526f},
std::array<float,2>{0.172114074f, 0.663613558f},
std::array<float,2>{0.494295835f, 0.349804133f},
std::array<float,2>{0.51899761f, 0.802101731f},
std::array<float,2>{0.70327723f, 0.452240229f},
std::array<float,2>{0.326621026f, 0.956773698f},
std::array<float,2>{0.119199693f, 0.14370124f},
std::array<float,2>{0.776414931f, 0.536267459f},
std::array<float,2>{0.59194237f, 0.190935507f},
std::array<float,2>{0.408348739f, 0.586188912f},
std::array<float,2>{0.242522821f, 0.404024839f},
std::array<float,2>{0.98671633f, 0.91888541f},
std::array<float,2>{0.814661682f, 0.286414295f},
std::array<float,2>{0.0466276817f, 0.839597344f},
std::array<float,2>{0.29648608f, 0.0503742211f},
std::array<float,2>{0.665456235f, 0.719336987f},
std::array<float,2>{0.81085515f, 0.158201993f},
std::array<float,2>{0.0828194395f, 0.519560039f},
std::array<float,2>{0.345459521f, 0.499786794f},
std::array<float,2>{0.745461464f, 0.972179294f},
std::array<float,2>{0.543134809f, 0.315568894f},
std::array<float,2>{0.46305126f, 0.758814156f},
std::array<float,2>{0.12869896f, 0.0817182139f},
std::array<float,2>{0.908020735f, 0.641946554f},
std::array<float,2>{0.651833355f, 0.0306739658f},
std::array<float,2>{0.264300585f, 0.715778291f},
std::array<float,2>{0.0307487492f, 0.270880133f},
std::array<float,2>{0.859225273f, 0.855246067f},
std::array<float,2>{0.94808352f, 0.42672053f},
std::array<float,2>{0.19285275f, 0.901844382f},
std::array<float,2>{0.39363718f, 0.222807363f},
std::array<float,2>{0.611082494f, 0.60966903f},
std::array<float,2>{0.873793662f, 0.0367101133f},
std::array<float,2>{0.00870742183f, 0.736787081f},
std::array<float,2>{0.266403258f, 0.307002664f},
std::array<float,2>{0.636651635f, 0.815712273f},
std::array<float,2>{0.607233346f, 0.375957429f},
std::array<float,2>{0.376933515f, 0.931816101f},
std::array<float,2>{0.21341224f, 0.210213572f},
std::array<float,2>{0.968034625f, 0.572286367f},
std::array<float,2>{0.718828499f, 0.140371725f},
std::array<float,2>{0.36944443f, 0.56054461f},
std::array<float,2>{0.0719259083f, 0.459679723f},
std::array<float,2>{0.781840861f, 0.94858849f},
std::array<float,2>{0.928676724f, 0.366324872f},
std::array<float,2>{0.14718768f, 0.793024302f},
std::array<float,2>{0.446593195f, 0.106200382f},
std::array<float,2>{0.555284262f, 0.683433235f},
std::array<float,2>{0.977223754f, 0.239130333f},
std::array<float,2>{0.227743953f, 0.603957117f},
std::array<float,2>{0.427011728f, 0.416998059f},
std::array<float,2>{0.566538215f, 0.883148849f},
std::array<float,2>{0.676860869f, 0.256069183f},
std::array<float,2>{0.300442517f, 0.863519788f},
std::array<float,2>{0.0602606311f, 0.00569365546f},
std::array<float,2>{0.838124394f, 0.693312228f},
std::array<float,2>{0.509666741f, 0.0678877905f},
std::array<float,2>{0.482015729f, 0.627162874f},
std::array<float,2>{0.170115933f, 0.339067549f},
std::array<float,2>{0.889376342f, 0.778654337f},
std::array<float,2>{0.753731608f, 0.478074849f},
std::array<float,2>{0.0989765599f, 0.996420681f},
std::array<float,2>{0.342023283f, 0.183160096f},
std::array<float,2>{0.701757431f, 0.507487237f},
std::array<float,2>{0.954624832f, 0.0155508649f},
std::array<float,2>{0.203620553f, 0.69693923f},
std::array<float,2>{0.38977167f, 0.258506685f},
std::array<float,2>{0.597662985f, 0.871352255f},
std::array<float,2>{0.628272414f, 0.407335788f},
std::array<float,2>{0.278190315f, 0.878399551f},
std::array<float,2>{0.00737846224f, 0.247050866f},
std::array<float,2>{0.86578232f, 0.596087873f},
std::array<float,2>{0.549645305f, 0.176511571f},
std::array<float,2>{0.445180267f, 0.511650264f},
std::array<float,2>{0.149116769f, 0.469041526f},
std::array<float,2>{0.931365073f, 0.991448998f},
std::array<float,2>{0.792174041f, 0.333814234f},
std::array<float,2>{0.0689825714f, 0.769420803f},
std::array<float,2>{0.360901594f, 0.0709862709f},
std::array<float,2>{0.732239783f, 0.633457363f},
std::array<float,2>{0.831346035f, 0.213612378f},
std::array<float,2>{0.0495505817f, 0.562982798f},
std::array<float,2>{0.311125636f, 0.385240942f},
std::array<float,2>{0.682819903f, 0.92594707f},
std::array<float,2>{0.57266885f, 0.303417623f},
std::array<float,2>{0.4359712f, 0.821662426f},
std::array<float,2>{0.223956659f, 0.0440149605f},
std::array<float,2>{0.972550154f, 0.747044206f},
std::array<float,2>{0.693641543f, 0.0996416509f},
std::array<float,2>{0.333673954f, 0.675634682f},
std::array<float,2>{0.10647165f, 0.374845654f},
std::array<float,2>{0.757838607f, 0.785344362f},
std::array<float,2>{0.877454519f, 0.468289703f},
std::array<float,2>{0.163549528f, 0.938427687f},
std::array<float,2>{0.470974207f, 0.125732362f},
std::array<float,2>{0.501742184f, 0.550781429f},
std::array<float,2>{0.77278465f, 0.088285543f},
std::array<float,2>{0.113258563f, 0.652100682f},
std::array<float,2>{0.312750876f, 0.32170409f},
std::array<float,2>{0.712065101f, 0.753196299f},
std::array<float,2>{0.526440442f, 0.490103096f},
std::array<float,2>{0.485794902f, 0.983677447f},
std::array<float,2>{0.182967409f, 0.164379582f},
std::array<float,2>{0.893292487f, 0.529737175f},
std::array<float,2>{0.659062922f, 0.230934292f},
std::array<float,2>{0.286525279f, 0.624377251f},
std::array<float,2>{0.0381150097f, 0.434905201f},
std::array<float,2>{0.825821221f, 0.893043935f},
std::array<float,2>{0.996065736f, 0.275022656f},
std::array<float,2>{0.238713652f, 0.847046018f},
std::array<float,2>{0.417963713f, 0.0221518539f},
std::array<float,2>{0.580329657f, 0.705965698f},
std::array<float,2>{0.91932857f, 0.1545638f},
std::array<float,2>{0.140425891f, 0.546449363f},
std::array<float,2>{0.458780587f, 0.443864614f},
std::array<float,2>{0.538217366f, 0.967472792f},
std::array<float,2>{0.73586899f, 0.353391171f},
std::array<float,2>{0.355350167f, 0.807609618f},
std::array<float,2>{0.092447713f, 0.123837098f},
std::array<float,2>{0.799486995f, 0.664071321f},
std::array<float,2>{0.623829186f, 0.0620319918f},
std::array<float,2>{0.402796179f, 0.728500605f},
std::array<float,2>{0.199036032f, 0.290414661f},
std::array<float,2>{0.943580329f, 0.832763433f},
std::array<float,2>{0.848417997f, 0.395805508f},
std::array<float,2>{0.0211858843f, 0.911639035f},
std::array<float,2>{0.255627334f, 0.198674679f},
std::array<float,2>{0.642455697f, 0.581376433f},
std::array<float,2>{0.935593367f, 0.0511955842f},
std::array<float,2>{0.153028175f, 0.723272741f},
std::array<float,2>{0.439523995f, 0.28282851f},
std::array<float,2>{0.55164212f, 0.843432486f},
std::array<float,2>{0.728948116f, 0.401392519f},
std::array<float,2>{0.36506021f, 0.917739391f},
std::array<float,2>{0.0628383458f, 0.192400515f},
std::array<float,2>{0.795566618f, 0.591547251f},
std::array<float,2>{0.596240163f, 0.144971773f},
std::array<float,2>{0.385377705f, 0.532707512f},
std::array<float,2>{0.209096655f, 0.447819114f},
std::array<float,2>{0.959144413f, 0.960208416f},
std::array<float,2>{0.860627115f, 0.346719652f},
std::array<float,2>{0.000491321669f, 0.799286783f},
std::array<float,2>{0.274412692f, 0.111954227f},
std::array<float,2>{0.629899025f, 0.65666765f},
std::array<float,2>{0.764539123f, 0.221360803f},
std::array<float,2>{0.105062589f, 0.614780724f},
std::array<float,2>{0.328805834f, 0.422635883f},
std::array<float,2>{0.687735021f, 0.90285337f},
std::array<float,2>{0.505565941f, 0.267869234f},
std::array<float,2>{0.475952834f, 0.85766691f},
std::array<float,2>{0.157082066f, 0.0253753141f},
std::array<float,2>{0.880295038f, 0.711004615f},
std::array<float,2>{0.685015738f, 0.0849694908f},
std::array<float,2>{0.307810187f, 0.647496462f},
std::array<float,2>{0.0516946875f, 0.317952186f},
std::array<float,2>{0.835933626f, 0.762180507f},
std::array<float,2>{0.973013818f, 0.494341344f},
std::array<float,2>{0.221350521f, 0.975917995f},
std::array<float,2>{0.4309946f, 0.161086887f},
std::array<float,2>{0.576693594f, 0.518712699f},
std::array<float,2>{0.823460698f, 0.105248079f},
std::array<float,2>{0.0330114812f, 0.686368942f},
std::array<float,2>{0.283147544f, 0.361900181f},
std::array<float,2>{0.661409259f, 0.789344847f},
std::array<float,2>{0.585766137f, 0.453207165f},
std::array<float,2>{0.419896483f, 0.949236572f},
std::array<float,2>{0.235767305f, 0.135555923f},
std::array<float,2>{0.996851742f, 0.555878997f},
std::array<float,2>{0.716422796f, 0.206791118f},
std::array<float,2>{0.316500515f, 0.576682627f},
std::array<float,2>{0.114603996f, 0.37925297f},
std::array<float,2>{0.767360091f, 0.936402977f},
std::array<float,2>{0.897250831f, 0.310420692f},
std::array<float,2>{0.18690896f, 0.818733037f},
std::array<float,2>{0.492136955f, 0.0338214114f},
std::array<float,2>{0.529653311f, 0.73978287f},
std::array<float,2>{0.939986169f, 0.185176805f},
std::array<float,2>{0.201383218f, 0.502941072f},
std::array<float,2>{0.401983202f, 0.481983364f},
std::array<float,2>{0.620975137f, 0.996031165f},
std::array<float,2>{0.647605956f, 0.340111166f},
std::array<float,2>{0.252983749f, 0.77467531f},
std::array<float,2>{0.0183576252f, 0.0643279329f},
std::array<float,2>{0.845404267f, 0.630272448f},
std::array<float,2>{0.531466782f, 0.00152240507f},
std::array<float,2>{0.455361068f, 0.69040674f},
std::array<float,2>{0.134228706f, 0.250973493f},
std::array<float,2>{0.917684555f, 0.86152941f},
std::array<float,2>{0.801174819f, 0.419669449f},
std::array<float,2>{0.0868858472f, 0.886865795f},
std::array<float,2>{0.358987421f, 0.235611558f},
std::array<float,2>{0.740052283f, 0.608456969f},
std::array<float,2>{0.98938638f, 0.0750945583f},
std::array<float,2>{0.248781234f, 0.63784492f},
std::array<float,2>{0.412487328f, 0.33144331f},
std::array<float,2>{0.587117612f, 0.772076488f},
std::array<float,2>{0.668696702f, 0.47481671f},
std::array<float,2>{0.292349517f, 0.986219585f},
std::array<float,2>{0.0413559154f, 0.174416959f},
std::array<float,2>{0.81762892f, 0.514761746f},
std::array<float,2>{0.521085262f, 0.245407209f},
std::array<float,2>{0.498372078f, 0.598054945f},
std::array<float,2>{0.177969605f, 0.413519293f},
std::array<float,2>{0.904962659f, 0.879025042f},
std::array<float,2>{0.779300213f, 0.264121264f},
std::array<float,2>{0.123514898f, 0.869132519f},
std::array<float,2>{0.321217507f, 0.00790066831f},
std::array<float,2>{0.710146427f, 0.700556099f},
std::array<float,2>{0.853716075f, 0.130046472f},
std::array<float,2>{0.0250500906f, 0.547849178f},
std::array<float,2>{0.259561241f, 0.462764829f},
std::array<float,2>{0.653120756f, 0.943769455f},
std::array<float,2>{0.615644455f, 0.368798196f},
std::array<float,2>{0.397988647f, 0.782865584f},
std::array<float,2>{0.189042881f, 0.0941124931f},
std::array<float,2>{0.952704012f, 0.678141534f},
std::array<float,2>{0.747341156f, 0.0417011455f},
std::array<float,2>{0.349568218f, 0.744877398f},
std::array<float,2>{0.0799398422f, 0.298585236f},
std::array<float,2>{0.806640923f, 0.827624142f},
std::array<float,2>{0.912791491f, 0.389770508f},
std::array<float,2>{0.130915925f, 0.925019324f},
std::array<float,2>{0.466399819f, 0.215102881f},
std::array<float,2>{0.541229725f, 0.568255126f},
std::array<float,2>{0.788973987f, 0.0190765373f},
std::array<float,2>{0.0758339167f, 0.707893968f},
std::array<float,2>{0.371302843f, 0.280089617f},
std::array<float,2>{0.724410236f, 0.84836024f},
std::array<float,2>{0.558895767f, 0.431702018f},
std::array<float,2>{0.451675475f, 0.894687533f},
std::array<float,2>{0.143507004f, 0.226605266f},
std::array<float,2>{0.925027192f, 0.618784606f},
std::array<float,2>{0.639849782f, 0.169740424f},
std::array<float,2>{0.270286441f, 0.526131749f},
std::array<float,2>{0.0151867736f, 0.487490118f},
std::array<float,2>{0.871054649f, 0.9773646f},
std::array<float,2>{0.961329103f, 0.326357543f},
std::array<float,2>{0.217431918f, 0.75451535f},
std::array<float,2>{0.379367709f, 0.0914883241f},
std::array<float,2>{0.604316652f, 0.65472132f},
std::array<float,2>{0.885855615f, 0.200226471f},
std::array<float,2>{0.166799992f, 0.584925413f},
std::array<float,2>{0.480430603f, 0.390766054f},
std::array<float,2>{0.515539467f, 0.910047352f},
std::array<float,2>{0.696861446f, 0.294095457f},
std::array<float,2>{0.339040935f, 0.829515994f},
std::array<float,2>{0.097370699f, 0.0560968891f},
std::array<float,2>{0.754938126f, 0.731791019f},
std::array<float,2>{0.562880337f, 0.118597664f},
std::array<float,2>{0.424602419f, 0.669352353f},
std::array<float,2>{0.233272806f, 0.357857823f},
std::array<float,2>{0.98418808f, 0.809081197f},
std::array<float,2>{0.843551874f, 0.43983829f},
std::array<float,2>{0.0557270907f, 0.963803053f},
std::array<float,2>{0.302637398f, 0.148701191f},
std::array<float,2>{0.67300266f, 0.539803207f},
std::array<float,2>{0.909566522f, 0.0782143995f},
std::array<float,2>{0.126585096f, 0.644160986f},
std::array<float,2>{0.461847603f, 0.313008636f},
std::array<float,2>{0.546344697f, 0.761129975f},
std::array<float,2>{0.742564619f, 0.497938126f},
std::array<float,2>{0.346634865f, 0.969653189f},
std::array<float,2>{0.0846594796f, 0.16000393f},
std::array<float,2>{0.810523868f, 0.521684289f},
std::array<float,2>{0.613063872f, 0.225164309f},
std::array<float,2>{0.3920829f, 0.611363888f},
std::array<float,2>{0.193975314f, 0.427801013f},
std::array<float,2>{0.946735382f, 0.899016261f},
std::array<float,2>{0.85653758f, 0.273007154f},
std::array<float,2>{0.0274807326f, 0.852438807f},
std::array<float,2>{0.26344052f, 0.027872676f},
std::array<float,2>{0.648563266f, 0.717076361f},
std::array<float,2>{0.773771524f, 0.141671598f},
std::array<float,2>{0.118531063f, 0.537163377f},
std::array<float,2>{0.324243248f, 0.449827969f},
std::array<float,2>{0.707024992f, 0.954092264f},
std::array<float,2>{0.515763521f, 0.347856998f},
std::array<float,2>{0.493557483f, 0.804013789f},
std::array<float,2>{0.17571421f, 0.113516532f},
std::array<float,2>{0.899392426f, 0.661099553f},
std::array<float,2>{0.66736269f, 0.0479695797f},
std::array<float,2>{0.294170916f, 0.72210902f},
std::array<float,2>{0.0430439636f, 0.288774997f},
std::array<float,2>{0.81263119f, 0.837397873f},
std::array<float,2>{0.985043705f, 0.40496397f},
std::array<float,2>{0.244871095f, 0.920020819f},
std::array<float,2>{0.407886446f, 0.188729942f},
std::array<float,2>{0.591393471f, 0.589096963f},
std::array<float,2>{0.837402403f, 0.00614751875f},
std::array<float,2>{0.061893221f, 0.695262909f},
std::array<float,2>{0.297278225f, 0.254793614f},
std::array<float,2>{0.677998483f, 0.866268218f},
std::array<float,2>{0.570073903f, 0.415485919f},
std::array<float,2>{0.428689748f, 0.886464834f},
std::array<float,2>{0.230130255f, 0.241824314f},
std::array<float,2>{0.980139315f, 0.603438556f},
std::array<float,2>{0.701104343f, 0.181615919f},
std::array<float,2>{0.340480626f, 0.505663633f},
std::array<float,2>{0.100438803f, 0.478529215f},
std::array<float,2>{0.751219571f, 0.999693573f},
std::array<float,2>{0.888297975f, 0.337269187f},
std::array<float,2>{0.168526337f, 0.779486358f},
std::array<float,2>{0.484237581f, 0.0690049082f},
std::array<float,2>{0.510154545f, 0.6250664f},
std::array<float,2>{0.96634078f, 0.207859889f},
std::array<float,2>{0.212371752f, 0.570766807f},
std::array<float,2>{0.377614558f, 0.378556281f},
std::array<float,2>{0.6089046f, 0.930578887f},
std::array<float,2>{0.633092344f, 0.305033773f},
std::array<float,2>{0.268590629f, 0.813896418f},
std::array<float,2>{0.0109537393f, 0.0379996337f},
std::array<float,2>{0.871309042f, 0.735323071f},
std::array<float,2>{0.557614625f, 0.108768292f},
std::array<float,2>{0.449213594f, 0.679850459f},
std::array<float,2>{0.144594371f, 0.364905804f},
std::array<float,2>{0.927230299f, 0.795466542f},
std::array<float,2>{0.783999026f, 0.457218111f},
std::array<float,2>{0.0726393387f, 0.946083128f},
std::array<float,2>{0.367704809f, 0.138215378f},
std::array<float,2>{0.720716059f, 0.561090231f},
std::array<float,2>{0.969124377f, 0.045017451f},
std::array<float,2>{0.225910947f, 0.749540389f},
std::array<float,2>{0.435247093f, 0.301243842f},
std::array<float,2>{0.570989907f, 0.82420826f},
std::array<float,2>{0.680986285f, 0.383266419f},
std::array<float,2>{0.308826506f, 0.928220093f},
std::array<float,2>{0.0485495552f, 0.211404741f},
std::array<float,2>{0.828761935f, 0.565801024f},
std::array<float,2>{0.503813267f, 0.127489224f},
std::array<float,2>{0.470064878f, 0.554183185f},
std::array<float,2>{0.162082046f, 0.465425462f},
std::array<float,2>{0.875814557f, 0.939971328f},
std::array<float,2>{0.760366678f, 0.371853828f},
std::array<float,2>{0.107479446f, 0.788745105f},
std::array<float,2>{0.334272087f, 0.0990206748f},
std::array<float,2>{0.692049503f, 0.673112094f},
std::array<float,2>{0.863736987f, 0.248437524f},
std::array<float,2>{0.00418436201f, 0.595503926f},
std::array<float,2>{0.279802293f, 0.409488082f},
std::array<float,2>{0.626067519f, 0.876880467f},
std::array<float,2>{0.600203276f, 0.261092246f},
std::array<float,2>{0.388504595f, 0.874600351f},
std::array<float,2>{0.206186801f, 0.0120737692f},
std::array<float,2>{0.955583334f, 0.69888097f},
std::array<float,2>{0.733566642f, 0.074162744f},
std::array<float,2>{0.362597555f, 0.635419548f},
std::array<float,2>{0.0678692907f, 0.335798115f},
std::array<float,2>{0.790230274f, 0.766637266f},
std::array<float,2>{0.931803465f, 0.471098453f},
std::array<float,2>{0.151456803f, 0.988696396f},
std::array<float,2>{0.44144699f, 0.177837253f},
std::array<float,2>{0.547497869f, 0.508377254f},
std::array<float,2>{0.798483968f, 0.121199414f},
std::array<float,2>{0.0904233828f, 0.666741192f},
std::array<float,2>{0.353301108f, 0.354402333f},
std::array<float,2>{0.738029718f, 0.804841042f},
std::array<float,2>{0.536752701f, 0.441931456f},
std::array<float,2>{0.46068868f, 0.96636343f},
std::array<float,2>{0.136852831f, 0.154117525f},
std::array<float,2>{0.920093954f, 0.54343003f},
std::array<float,2>{0.643672407f, 0.19710283f},
std::array<float,2>{0.256694824f, 0.578341126f},
std::array<float,2>{0.0232678354f, 0.396980435f},
std::array<float,2>{0.850172818f, 0.913957596f},
std::array<float,2>{0.94201535f, 0.292744845f},
std::array<float,2>{0.196145356f, 0.834288597f},
std::array<float,2>{0.40472272f, 0.0586957298f},
std::array<float,2>{0.622236013f, 0.72984159f},
std::array<float,2>{0.892344415f, 0.166453838f},
std::array<float,2>{0.179724455f, 0.527645886f},
std::array<float,2>{0.486360788f, 0.490265638f},
std::array<float,2>{0.524873078f, 0.980600476f},
std::array<float,2>{0.712990582f, 0.323010415f},
std::array<float,2>{0.314992666f, 0.751673937f},
std::array<float,2>{0.110893965f, 0.0878809243f},
std::array<float,2>{0.770795882f, 0.649194479f},
std::array<float,2>{0.579459965f, 0.0208352171f},
std::array<float,2>{0.414097339f, 0.704678118f},
std::array<float,2>{0.24039799f, 0.275688291f},
std::array<float,2>{0.992476881f, 0.843793273f},
std::array<float,2>{0.827537596f, 0.437283486f},
std::array<float,2>{0.0370731056f, 0.890920281f},
std::array<float,2>{0.288555801f, 0.233194187f},
std::array<float,2>{0.656969547f, 0.622447073f},
std::array<float,2>{0.88103354f, 0.025942944f},
std::array<float,2>{0.158278018f, 0.713165462f},
std::array<float,2>{0.473078191f, 0.266178787f},
std::array<float,2>{0.506147325f, 0.856342733f},
std::array<float,2>{0.690017939f, 0.424692065f},
std::array<float,2>{0.331530124f, 0.905053377f},
std::array<float,2>{0.102083802f, 0.220013008f},
std::array<float,2>{0.762512505f, 0.61662966f},
std::array<float,2>{0.575196803f, 0.162166819f},
std::array<float,2>{0.431801051f, 0.517196894f},
std::array<float,2>{0.219262138f, 0.493394852f},
std::array<float,2>{0.975830138f, 0.974262118f},
std::array<float,2>{0.832658708f, 0.319351166f},
std::array<float,2>{0.053720396f, 0.765168965f},
std::array<float,2>{0.304996014f, 0.0839081854f},
std::array<float,2>{0.687289894f, 0.644662619f},
std::array<float,2>{0.793521047f, 0.193841785f},
std::array<float,2>{0.0660539418f, 0.592267275f},
std::array<float,2>{0.366501659f, 0.400263608f},
std::array<float,2>{0.726582706f, 0.915018976f},
std::array<float,2>{0.55340904f, 0.28438136f},
std::array<float,2>{0.438743144f, 0.840272069f},
std::array<float,2>{0.155017883f, 0.0544804744f},
std::array<float,2>{0.934091389f, 0.724900305f},
std::array<float,2>{0.631764293f, 0.109649926f},
std::array<float,2>{0.276895821f, 0.659223437f},
std::array<float,2>{0.00279017794f, 0.345518321f},
std::array<float,2>{0.861962497f, 0.797281444f},
std::array<float,2>{0.958548307f, 0.445620656f},
std::array<float,2>{0.208386883f, 0.957878649f},
std::array<float,2>{0.383960932f, 0.148338601f},
std::array<float,2>{0.594047308f, 0.534623921f},
std::array<float,2>{0.845925212f, 0.0653484166f},
std::array<float,2>{0.017140476f, 0.632215738f},
std::array<float,2>{0.25113067f, 0.343004704f},
std::array<float,2>{0.645256162f, 0.776571572f},
std::array<float,2>{0.618610919f, 0.483560681f},
std::array<float,2>{0.399739414f, 0.992413759f},
std::array<float,2>{0.200949818f, 0.18626231f},
std::array<float,2>{0.938676238f, 0.500895083f},
std::array<float,2>{0.740656018f, 0.237859756f},
std::array<float,2>{0.355475068f, 0.606589735f},
std::array<float,2>{0.0890389234f, 0.421407342f},
std::array<float,2>{0.803507566f, 0.889881909f},
std::array<float,2>{0.915303051f, 0.253044665f},
std::array<float,2>{0.136589497f, 0.859946549f},
std::array<float,2>{0.453345269f, 0.00370265404f},
std::array<float,2>{0.534993112f, 0.688921034f},
std::array<float,2>{0.998599231f, 0.133980632f},
std::array<float,2>{0.238222033f, 0.55698806f},
std::array<float,2>{0.421572894f, 0.455392659f},
std::array<float,2>{0.582959056f, 0.952358782f},
std::array<float,2>{0.663658857f, 0.360931367f},
std::array<float,2>{0.284694999f, 0.792256117f},
std::array<float,2>{0.0337844305f, 0.103275329f},
std::array<float,2>{0.821906924f, 0.685438573f},
std::array<float,2>{0.529034495f, 0.0320766047f},
std::array<float,2>{0.489151418f, 0.740722775f},
std::array<float,2>{0.18500635f, 0.312076479f},
std::array<float,2>{0.894872785f, 0.817289591f},
std::array<float,2>{0.768046677f, 0.381729633f},
std::array<float,2>{0.115832672f, 0.934819818f},
std::array<float,2>{0.31901902f, 0.204107612f},
std::array<float,2>{0.717796206f, 0.575142562f},
std::array<float,2>{0.949253201f, 0.0972827896f},
std::array<float,2>{0.189777136f, 0.676008284f},
std::array<float,2>{0.394990563f, 0.370344579f},
std::array<float,2>{0.613403022f, 0.78402108f},
std::array<float,2>{0.654649258f, 0.463243365f},
std::array<float,2>{0.259849697f, 0.942706347f},
std::array<float,2>{0.0256021153f, 0.131826252f},
std::array<float,2>{0.852230191f, 0.550564885f},
std::array<float,2>{0.539363444f, 0.217573181f},
std::array<float,2>{0.467041075f, 0.569045663f},
std::array<float,2>{0.130089238f, 0.388513058f},
std::array<float,2>{0.911842406f, 0.923575997f},
std::array<float,2>{0.806450069f, 0.300618231f},
std::array<float,2>{0.0819216222f, 0.825798631f},
std::array<float,2>{0.351212859f, 0.0401843376f},
std::array<float,2>{0.749796271f, 0.742746472f},
std::array<float,2>{0.820123911f, 0.172369778f},
std::array<float,2>{0.0402540416f, 0.513349354f},
std::array<float,2>{0.289473504f, 0.473141104f},
std::array<float,2>{0.670024931f, 0.98690933f},
std::array<float,2>{0.589692116f, 0.328622907f},
std::array<float,2>{0.410688937f, 0.77135241f},
std::array<float,2>{0.247877583f, 0.0772338808f},
std::array<float,2>{0.99090898f, 0.64061147f},
std::array<float,2>{0.707339108f, 0.0109876078f},
std::array<float,2>{0.3231062f, 0.701798558f},
std::array<float,2>{0.122928686f, 0.263059497f},
std::array<float,2>{0.777620435f, 0.869145632f},
std::array<float,2>{0.903804004f, 0.411260009f},
std::array<float,2>{0.176914543f, 0.88128835f},
std::array<float,2>{0.496306181f, 0.243221924f},
std::array<float,2>{0.522301316f, 0.600574553f},
std::array<float,2>{0.757515907f, 0.0570299849f},
std::array<float,2>{0.0946454182f, 0.73427707f},
std::array<float,2>{0.337365061f, 0.295081854f},
std::array<float,2>{0.698200464f, 0.831677914f},
std::array<float,2>{0.513260424f, 0.393093377f},
std::array<float,2>{0.477332622f, 0.908027709f},
std::array<float,2>{0.165481433f, 0.201516435f},
std::array<float,2>{0.883721054f, 0.583394587f},
std::array<float,2>{0.674263835f, 0.150586709f},
std::array<float,2>{0.303971827f, 0.542258978f},
std::array<float,2>{0.0575554445f, 0.437806666f},
std::array<float,2>{0.840431988f, 0.962462783f},
std::array<float,2>{0.981764913f, 0.356936336f},
std::array<float,2>{0.230974972f, 0.81236726f},
std::array<float,2>{0.422984064f, 0.120472647f},
std::array<float,2>{0.565563023f, 0.670135617f},
std::array<float,2>{0.923018217f, 0.228844807f},
std::array<float,2>{0.141588837f, 0.619582534f},
std::array<float,2>{0.450155914f, 0.431224734f},
std::array<float,2>{0.562291622f, 0.897815287f},
std::array<float,2>{0.726545393f, 0.27814126f},
std::array<float,2>{0.37491712f, 0.850335956f},
std::array<float,2>{0.0776460841f, 0.0163306985f},
std::array<float,2>{0.78523773f, 0.709211469f},
std::array<float,2>{0.601808488f, 0.0928847417f},
std::array<float,2>{0.38210085f, 0.653497577f},
std::array<float,2>{0.216498941f, 0.325616419f},
std::array<float,2>{0.963298202f, 0.756627738f},
std::array<float,2>{0.869132936f, 0.485494405f},
std::array<float,2>{0.0118267257f, 0.979444861f},
std::array<float,2>{0.272591263f, 0.169935033f},
std::array<float,2>{0.637111008f, 0.523711681f},
std::array<float,2>{0.889693379f, 0.0697142407f},
std::array<float,2>{0.17115289f, 0.626876414f},
std::array<float,2>{0.480909795f, 0.336319804f},
std::array<float,2>{0.507949471f, 0.780351043f},
std::array<float,2>{0.702565849f, 0.479983628f},
std::array<float,2>{0.342948169f, 0.998217046f},
std::array<float,2>{0.0978462026f, 0.18052873f},
std::array<float,2>{0.752888858f, 0.504073858f},
std::array<float,2>{0.567578971f, 0.240298003f},
std::array<float,2>{0.426669985f, 0.601563692f},
std::array<float,2>{0.226596341f, 0.414620101f},
std::array<float,2>{0.978467345f, 0.885160148f},
std::array<float,2>{0.838972807f, 0.255197763f},
std::array<float,2>{0.0589022301f, 0.865911663f},
std::array<float,2>{0.298909724f, 0.00748486398f},
std::array<float,2>{0.676205039f, 0.693701863f},
std::array<float,2>{0.782506227f, 0.137005314f},
std::array<float,2>{0.0703605339f, 0.561666369f},
std::array<float,2>{0.370453209f, 0.458078563f},
std::array<float,2>{0.720689297f, 0.946864247f},
std::array<float,2>{0.555759728f, 0.364210576f},
std::array<float,2>{0.445381224f, 0.796419322f},
std::array<float,2>{0.147568405f, 0.107750669f},
std::array<float,2>{0.929571629f, 0.681260049f},
std::array<float,2>{0.635522842f, 0.0381272398f},
std::array<float,2>{0.267566383f, 0.735461116f},
std::array<float,2>{0.00916757155f, 0.306515694f},
std::array<float,2>{0.874610066f, 0.813049257f},
std::array<float,2>{0.966894627f, 0.377149761f},
std::array<float,2>{0.214145035f, 0.931291699f},
std::array<float,2>{0.375122756f, 0.208595559f},
std::array<float,2>{0.605776608f, 0.57187593f},
std::array<float,2>{0.858314991f, 0.0286156777f},
std::array<float,2>{0.0295722112f, 0.718654811f},
std::array<float,2>{0.265195936f, 0.271636307f},
std::array<float,2>{0.650929868f, 0.853425503f},
std::array<float,2>{0.609855175f, 0.429316372f},
std::array<float,2>{0.392592281f, 0.899636984f},
std::array<float,2>{0.191717282f, 0.225704759f},
std::array<float,2>{0.948944569f, 0.613155782f},
std::array<float,2>{0.74432385f, 0.158593208f},
std::array<float,2>{0.34425354f, 0.523293912f},
std::array<float,2>{0.0834067464f, 0.496563971f},
std::array<float,2>{0.812163472f, 0.969921708f},
std::array<float,2>{0.906873107f, 0.313975632f},
std::array<float,2>{0.127386719f, 0.760102093f},
std::array<float,2>{0.464843512f, 0.0795321688f},
std::array<float,2>{0.544443786f, 0.642695427f},
std::array<float,2>{0.987853229f, 0.188214079f},
std::array<float,2>{0.243572325f, 0.588152707f},
std::array<float,2>{0.409778893f, 0.405677706f},
std::array<float,2>{0.593597233f, 0.921346605f},
std::array<float,2>{0.664838016f, 0.287450314f},
std::array<float,2>{0.29564485f, 0.83650738f},
std::array<float,2>{0.0454866439f, 0.0473368689f},
std::array<float,2>{0.816388249f, 0.720924914f},
std::array<float,2>{0.518096387f, 0.114611037f},
std::array<float,2>{0.496045798f, 0.661482751f},
std::array<float,2>{0.173667684f, 0.349165797f},
std::array<float,2>{0.901141703f, 0.802734375f},
std::array<float,2>{0.776159108f, 0.450426042f},
std::array<float,2>{0.120124832f, 0.954832435f},
std::array<float,2>{0.327604383f, 0.141061172f},
std::array<float,2>{0.704483211f, 0.538718581f},
std::array<float,2>{0.944413841f, 0.0601933263f},
std::array<float,2>{0.197493926f, 0.729327559f},
std::array<float,2>{0.403948933f, 0.291726798f},
std::array<float,2>{0.624611497f, 0.835672915f},
std::array<float,2>{0.641510248f, 0.398071051f},
std::array<float,2>{0.254871279f, 0.912708819f},
std::array<float,2>{0.0202555917f, 0.195527062f},
std::array<float,2>{0.849474967f, 0.579553485f},
std::array<float,2>{0.537333608f, 0.152978897f},
std::array<float,2>{0.457727134f, 0.544633031f},
std::array<float,2>{0.139600635f, 0.443000108f},
std::array<float,2>{0.918890297f, 0.965600193f},
std::array<float,2>{0.800546646f, 0.355354846f},
std::array<float,2>{0.0932168737f, 0.80578351f},
std::array<float,2>{0.354213625f, 0.122454539f},
std::array<float,2>{0.735295773f, 0.667404175f},
std::array<float,2>{0.824728906f, 0.233713046f},
std::array<float,2>{0.0371420011f, 0.621221006f},
std::array<float,2>{0.285882831f, 0.436170816f},
std::array<float,2>{0.659932196f, 0.891773582f},
std::array<float,2>{0.581991494f, 0.276497304f},
std::array<float,2>{0.416575372f, 0.845315456f},
std::array<float,2>{0.239852548f, 0.0199066792f},
std::array<float,2>{0.994424045f, 0.703713655f},
std::array<float,2>{0.711098969f, 0.0865289122f},
std::array<float,2>{0.3141056f, 0.649497688f},
std::array<float,2>{0.111559935f, 0.323997259f},
std::array<float,2>{0.772260785f, 0.750971854f},
std::array<float,2>{0.894326508f, 0.491912752f},
std::array<float,2>{0.182372943f, 0.982012093f},
std::array<float,2>{0.484440416f, 0.16794607f},
std::array<float,2>{0.526193142f, 0.529082358f},
std::array<float,2>{0.75959456f, 0.098544918f},
std::array<float,2>{0.106250823f, 0.672732472f},
std::array<float,2>{0.332955033f, 0.372558504f},
std::array<float,2>{0.694504321f, 0.787940085f},
std::array<float,2>{0.500508606f, 0.466020763f},
std::array<float,2>{0.472336501f, 0.941162348f},
std::array<float,2>{0.162249148f, 0.128700361f},
std::array<float,2>{0.878524125f, 0.553556561f},
std::array<float,2>{0.681736171f, 0.21231994f},
std::array<float,2>{0.312408328f, 0.565255523f},
std::array<float,2>{0.0505493693f, 0.384171903f},
std::array<float,2>{0.831006289f, 0.92946893f},
std::array<float,2>{0.971167326f, 0.302349508f},
std::array<float,2>{0.223071799f, 0.822640181f},
std::array<float,2>{0.436660439f, 0.0462560765f},
std::array<float,2>{0.573367417f, 0.748833179f},
std::array<float,2>{0.930094004f, 0.179073229f},
std::array<float,2>{0.149963543f, 0.509361148f},
std::array<float,2>{0.443552732f, 0.472642124f},
std::array<float,2>{0.550759196f, 0.989757538f},
std::array<float,2>{0.731438458f, 0.334102303f},
std::array<float,2>{0.359579891f, 0.765867591f},
std::array<float,2>{0.070107758f, 0.0725783184f},
std::array<float,2>{0.791052163f, 0.635863066f},
std::array<float,2>{0.598980129f, 0.0134337237f},
std::array<float,2>{0.388715446f, 0.697316825f},
std::array<float,2>{0.204969004f, 0.260334283f},
std::array<float,2>{0.953966737f, 0.873396993f},
std::array<float,2>{0.866353691f, 0.408259124f},
std::array<float,2>{0.00668676617f, 0.875854313f},
std::array<float,2>{0.27834785f, 0.249970973f},
std::array<float,2>{0.627134502f, 0.594346642f},
std::array<float,2>{0.91695416f, 0.00261283643f},
std::array<float,2>{0.133232236f, 0.687796235f},
std::array<float,2>{0.456201762f, 0.252770096f},
std::array<float,2>{0.53281188f, 0.861201108f},
std::array<float,2>{0.738851309f, 0.420066416f},
std::array<float,2>{0.358249515f, 0.88876909f},
std::array<float,2>{0.0874351412f, 0.236841708f},
std::array<float,2>{0.802702188f, 0.605825067f},
std::array<float,2>{0.61952579f, 0.187405959f},
std::array<float,2>{0.401344776f, 0.5013026f},
std::array<float,2>{0.202541485f, 0.482778788f},
std::array<float,2>{0.940547347f, 0.99365449f},
std::array<float,2>{0.844197571f, 0.342186213f},
std::array<float,2>{0.0195190124f, 0.775623798f},
std::array<float,2>{0.252218097f, 0.0655199215f},
std::array<float,2>{0.647364497f, 0.631323457f},
std::array<float,2>{0.766447961f, 0.203562841f},
std::array<float,2>{0.114155918f, 0.575879633f},
std::array<float,2>{0.317822576f, 0.38197872f},
std::array<float,2>{0.715474665f, 0.934075296f},
std::array<float,2>{0.531059206f, 0.311432898f},
std::array<float,2>{0.490539283f, 0.818158925f},
std::array<float,2>{0.185615376f, 0.0328596905f},
std::array<float,2>{0.898321629f, 0.741913319f},
std::array<float,2>{0.660513282f, 0.101669438f},
std::array<float,2>{0.281594485f, 0.683876693f},
std::array<float,2>{0.0318645872f, 0.359449506f},
std::array<float,2>{0.822555244f, 0.791493475f},
std::array<float,2>{0.997829735f, 0.456113636f},
std::array<float,2>{0.235107303f, 0.951245487f},
std::array<float,2>{0.41875121f, 0.133591011f},
std::array<float,2>{0.584423661f, 0.55798918f},
std::array<float,2>{0.834170878f, 0.0821211711f},
std::array<float,2>{0.0523380786f, 0.645826221f},
std::array<float,2>{0.306783408f, 0.318916619f},
std::array<float,2>{0.683597207f, 0.763707519f},
std::array<float,2>{0.577446043f, 0.493120074f},
std::array<float,2>{0.429825366f, 0.972832382f},
std::array<float,2>{0.221901983f, 0.163335904f},
std::array<float,2>{0.973770857f, 0.516016662f},
std::array<float,2>{0.68878603f, 0.219137207f},
std::array<float,2>{0.329297274f, 0.615850866f},
std::array<float,2>{0.104355551f, 0.424992621f},
std::array<float,2>{0.765262663f, 0.906138182f},
std::array<float,2>{0.879569411f, 0.267309666f},
std::array<float,2>{0.158091843f, 0.857010782f},
std::array<float,2>{0.475153208f, 0.0270790122f},
std::array<float,2>{0.504159689f, 0.714480996f},
std::array<float,2>{0.960418582f, 0.147216201f},
std::array<float,2>{0.210121721f, 0.533786356f},
std::array<float,2>{0.386417359f, 0.446380824f},
std::array<float,2>{0.597081602f, 0.958811462f},
std::array<float,2>{0.629341841f, 0.3446787f},
std::array<float,2>{0.274986714f, 0.797885299f},
std::array<float,2>{0.00171807013f, 0.110433795f},
std::array<float,2>{0.86018461f, 0.658794165f},
std::array<float,2>{0.552514076f, 0.0534775481f},
std::array<float,2>{0.44130224f, 0.725853503f},
std::array<float,2>{0.153363898f, 0.283272237f},
std::array<float,2>{0.937011302f, 0.841043413f},
std::array<float,2>{0.796214521f, 0.399410576f},
std::array<float,2>{0.0634933859f, 0.915683687f},
std::array<float,2>{0.363656729f, 0.194698989f},
std::array<float,2>{0.730292857f, 0.592846513f},
std::array<float,2>{0.982772648f, 0.119573429f},
std::array<float,2>{0.233469114f, 0.67093569f},
std::array<float,2>{0.425271869f, 0.355655283f},
std::array<float,2>{0.563692868f, 0.811072171f},
std::array<float,2>{0.672209561f, 0.439077199f},
std::array<float,2>{0.301241636f, 0.961373866f},
std::array<float,2>{0.0553477257f, 0.151768386f},
std::array<float,2>{0.841889977f, 0.541488707f},
std::array<float,2>{0.514328837f, 0.203072712f},
std::array<float,2>{0.479418814f, 0.582907379f},
std::array<float,2>{0.167065203f, 0.393731177f},
std::array<float,2>{0.884780347f, 0.906400383f},
std::array<float,2>{0.754618645f, 0.296367943f},
std::array<float,2>{0.0962739736f, 0.830461681f},
std::array<float,2>{0.338105589f, 0.0582302809f},
std::array<float,2>{0.695414126f, 0.733262956f},
std::array<float,2>{0.869820774f, 0.171788231f},
std::array<float,2>{0.0145571874f, 0.524700522f},
std::array<float,2>{0.271158099f, 0.484730721f},
std::array<float,2>{0.639125466f, 0.979812086f},
std::array<float,2>{0.604567528f, 0.324950278f},
std::array<float,2>{0.37990427f, 0.757386744f},
std::array<float,2>{0.218747795f, 0.0926264152f},
std::array<float,2>{0.962375164f, 0.652585566f},
std::array<float,2>{0.722697079f, 0.0167736989f},
std::array<float,2>{0.373033106f, 0.709970057f},
std::array<float,2>{0.0749969557f, 0.278543442f},
std::array<float,2>{0.787830651f, 0.851223469f},
std::array<float,2>{0.924412131f, 0.430331022f},
std::array<float,2>{0.143848136f, 0.897381604f},
std::array<float,2>{0.453058362f, 0.2295582f},
std::array<float,2>{0.559912801f, 0.620615959f},
std::array<float,2>{0.808278441f, 0.0398768149f},
std::array<float,2>{0.0788886324f, 0.743343651f},
std::array<float,2>{0.347863615f, 0.298980862f},
std::array<float,2>{0.746696472f, 0.824472427f},
std::array<float,2>{0.542166412f, 0.387143254f},
std::array<float,2>{0.465429217f, 0.922461867f},
std::array<float,2>{0.13252078f, 0.218625113f},
std::array<float,2>{0.913840711f, 0.569932103f},
std::array<float,2>{0.65385443f, 0.132463232f},
std::array<float,2>{0.257944733f, 0.549203873f},
std::array<float,2>{0.023812877f, 0.46439594f},
std::array<float,2>{0.855187237f, 0.941978276f},
std::array<float,2>{0.951380968f, 0.369425952f},
std::array<float,2>{0.188138798f, 0.784598172f},
std::array<float,2>{0.396822721f, 0.0958296731f},
std::array<float,2>{0.616916537f, 0.677234769f},
std::array<float,2>{0.90561074f, 0.242828906f},
std::array<float,2>{0.179181725f, 0.601368189f},
std::array<float,2>{0.499112427f, 0.410891712f},
std::array<float,2>{0.519792557f, 0.882789552f},
std::array<float,2>{0.709803641f, 0.261725157f},
std::array<float,2>{0.321431518f, 0.870544791f},
std::array<float,2>{0.124376014f, 0.0102248909f},
std::array<float,2>{0.780507445f, 0.702658892f},
std::array<float,2>{0.586722016f, 0.0766038895f},
std::array<float,2>{0.413618088f, 0.639620602f},
std::array<float,2>{0.249767438f, 0.329680264f},
std::array<float,2>{0.988624156f, 0.770054698f},
std::array<float,2>{0.816969275f, 0.47374481f},
std::array<float,2>{0.0428245068f, 0.987830222f},
std::array<float,2>{0.291050404f, 0.173558459f},
std::array<float,2>{0.669595063f, 0.511838377f},
std::array<float,2>{0.92585212f, 0.106971368f},
std::array<float,2>{0.145997375f, 0.681943595f},
std::array<float,2>{0.447291017f, 0.365557045f},
std::array<float,2>{0.557895243f, 0.794052541f},
std::array<float,2>{0.722432494f, 0.460930407f},
std::array<float,2>{0.368445307f, 0.947717428f},
std::array<float,2>{0.073332347f, 0.139128402f},
std::array<float,2>{0.785145581f, 0.55936861f},
std::array<float,2>{0.60814023f, 0.209065527f},
std::array<float,2>{0.378458351f, 0.573966563f},
std::array<float,2>{0.211787581f, 0.376022607f},
std::array<float,2>{0.965632975f, 0.932657957f},
std::array<float,2>{0.872873545f, 0.307634294f},
std::array<float,2>{0.00978072453f, 0.814701736f},
std::array<float,2>{0.268511266f, 0.0355921276f},
std::array<float,2>{0.634649456f, 0.737597704f},
std::array<float,2>{0.750056684f, 0.182511628f},
std::array<float,2>{0.100924395f, 0.506421506f},
std::array<float,2>{0.34134376f, 0.477064282f},
std::array<float,2>{0.699948311f, 0.997652352f},
std::array<float,2>{0.511011004f, 0.338149965f},
std::array<float,2>{0.483109325f, 0.778050244f},
std::array<float,2>{0.169140473f, 0.0670973733f},
std::array<float,2>{0.886781275f, 0.62818563f},
std::array<float,2>{0.679127216f, 0.00465779379f},
std::array<float,2>{0.298083663f, 0.692308009f},
std::array<float,2>{0.0607648417f, 0.25778988f},
std::array<float,2>{0.836128414f, 0.86470443f},
std::array<float,2>{0.979469001f, 0.416575611f},
std::array<float,2>{0.228832737f, 0.884078681f},
std::array<float,2>{0.429647774f, 0.23985301f},
std::array<float,2>{0.569043279f, 0.604512632f},
std::array<float,2>{0.814167976f, 0.0492475927f},
std::array<float,2>{0.0443177372f, 0.720621586f},
std::array<float,2>{0.293250769f, 0.285405487f},
std::array<float,2>{0.666034639f, 0.83829987f},
std::array<float,2>{0.590515852f, 0.40274024f},
std::array<float,2>{0.407132804f, 0.919627249f},
std::array<float,2>{0.245952174f, 0.190182596f},
std::array<float,2>{0.986036777f, 0.58726126f},
std::array<float,2>{0.705335915f, 0.142687067f},
std::array<float,2>{0.325577021f, 0.535674274f},
std::array<float,2>{0.118139438f, 0.452044994f},
std::array<float,2>{0.774923146f, 0.955631971f},
std::array<float,2>{0.900099754f, 0.350967467f},
std::array<float,2>{0.17462717f, 0.801540971f},
std::array<float,2>{0.492447376f, 0.11715088f},
std::array<float,2>{0.517453611f, 0.662507176f},
std::array<float,2>{0.945585668f, 0.224582344f},
std::array<float,2>{0.194907337f, 0.610864282f},
std::array<float,2>{0.390881389f, 0.427027285f},
std::array<float,2>{0.611839414f, 0.901084065f},
std::array<float,2>{0.649439633f, 0.270240366f},
std::array<float,2>{0.261757642f, 0.853637457f},
std::array<float,2>{0.0286062658f, 0.0294390023f},
std::array<float,2>{0.856038809f, 0.716501474f},
std::array<float,2>{0.545462072f, 0.0803696066f},
std::array<float,2>{0.462084472f, 0.641165674f},
std::array<float,2>{0.12589854f, 0.314672887f},
std::array<float,2>{0.908886075f, 0.758607328f},
std::array<float,2>{0.808622897f, 0.49885118f},
std::array<float,2>{0.0850032866f, 0.970864892f},
std::array<float,2>{0.34757939f, 0.156364605f},
std::array<float,2>{0.743781924f, 0.521437109f},
std::array<float,2>{0.993370891f, 0.0229181126f},
std::array<float,2>{0.241635695f, 0.706372261f},
std::array<float,2>{0.415114731f, 0.274040133f},
std::array<float,2>{0.578722537f, 0.846394777f},
std::array<float,2>{0.658162713f, 0.434338719f},
std::array<float,2>{0.288012356f, 0.893860996f},
std::array<float,2>{0.035704039f, 0.232139796f},
std::array<float,2>{0.826824427f, 0.623921812f},
std::array<float,2>{0.523729622f, 0.16508688f},
std::array<float,2>{0.488124311f, 0.530536354f},
std::array<float,2>{0.181089595f, 0.489030421f},
std::array<float,2>{0.890762448f, 0.982563317f},
std::array<float,2>{0.769705713f, 0.320781142f},
std::array<float,2>{0.109491982f, 0.752352536f},
std::array<float,2>{0.316244006f, 0.0893760696f},
std::array<float,2>{0.714799702f, 0.65099287f},
std::array<float,2>{0.851520598f, 0.197357118f},
std::array<float,2>{0.021524854f, 0.580972672f},
std::array<float,2>{0.257231325f, 0.395246595f},
std::array<float,2>{0.64264679f, 0.910272419f},
std::array<float,2>{0.621117592f, 0.289721549f},
std::array<float,2>{0.405713856f, 0.833688974f},
std::array<float,2>{0.197180584f, 0.0611415319f},
std::array<float,2>{0.9424299f, 0.726843953f},
std::array<float,2>{0.736922801f, 0.124780029f},
std::array<float,2>{0.352050692f, 0.665404975f},
std::array<float,2>{0.0909000188f, 0.352139324f},
std::array<float,2>{0.797230065f, 0.807764232f},
std::array<float,2>{0.921794415f, 0.444538295f},
std::array<float,2>{0.138183042f, 0.968565047f},
std::array<float,2>{0.459856361f, 0.15611662f},
std::array<float,2>{0.535488904f, 0.545628905f},
std::array<float,2>{0.789333165f, 0.0715299696f},
std::array<float,2>{0.0666813776f, 0.634712398f},
std::array<float,2>{0.361921757f, 0.332032442f},
std::array<float,2>{0.732555389f, 0.76798141f},
std::array<float,2>{0.548505962f, 0.470349222f},
std::array<float,2>{0.443256497f, 0.990355253f},
std::array<float,2>{0.150956199f, 0.177300304f},
std::array<float,2>{0.933228672f, 0.510312498f},
std::array<float,2>{0.625548065f, 0.247607872f},
std::array<float,2>{0.280442536f, 0.597036183f},
std::array<float,2>{0.00534636108f, 0.406817108f},
std::array<float,2>{0.86476469f, 0.876975298f},
std::array<float,2>{0.956735849f, 0.259738922f},
std::array<float,2>{0.205606073f, 0.872542024f},
std::array<float,2>{0.387512505f, 0.014265582f},
std::array<float,2>{0.601241648f, 0.695852578f},
std::array<float,2>{0.8764835f, 0.126486599f},
std::array<float,2>{0.160368398f, 0.552146614f},
std::array<float,2>{0.469163686f, 0.467756093f},
std::array<float,2>{0.502487004f, 0.938587606f},
std::array<float,2>{0.693241537f, 0.373519301f},
std::array<float,2>{0.33535257f, 0.786526918f},
std::array<float,2>{0.108612873f, 0.100904383f},
std::array<float,2>{0.760764956f, 0.674403071f},
std::array<float,2>{0.57133013f, 0.0430630706f},
std::array<float,2>{0.434260637f, 0.747705102f},
std::array<float,2>{0.225124776f, 0.304258913f},
std::array<float,2>{0.969830513f, 0.820541084f},
std::array<float,2>{0.829191625f, 0.386034995f},
std::array<float,2>{0.0473699309f, 0.926872313f},
std::array<float,2>{0.310217977f, 0.214735746f},
std::array<float,2>{0.679737508f, 0.563947141f},
std::array<float,2>{0.896286786f, 0.0344032347f},
std::array<float,2>{0.184024557f, 0.73841691f},
std::array<float,2>{0.489906192f, 0.309474885f},
std::array<float,2>{0.527825117f, 0.81958437f},
std::array<float,2>{0.716993153f, 0.380218059f},
std::array<float,2>{0.319883525f, 0.937357962f},
std::array<float,2>{0.117144428f, 0.206015989f},
std::array<float,2>{0.768641829f, 0.577219665f},
std::array<float,2>{0.583201408f, 0.136436999f},
std::array<float,2>{0.42013824f, 0.554873288f},
std::array<float,2>{0.236791432f, 0.454106688f},
std::array<float,2>{0.999675095f, 0.950527191f},
std::array<float,2>{0.82076174f, 0.363004476f},
std::array<float,2>{0.0350144692f, 0.790654063f},
std::array<float,2>{0.283243239f, 0.103822432f},
std::array<float,2>{0.662547708f, 0.686686873f},
std::array<float,2>{0.803746879f, 0.234985739f},
std::array<float,2>{0.0887839794f, 0.607636154f},
std::array<float,2>{0.357349545f, 0.417978108f},
std::array<float,2>{0.742056787f, 0.888356626f},
std::array<float,2>{0.533468008f, 0.251697749f},
std::array<float,2>{0.454510778f, 0.862542093f},
std::array<float,2>{0.135639578f, 0.000240550042f},
std::array<float,2>{0.914441466f, 0.69132036f},
std::array<float,2>{0.645857155f, 0.0629379749f},
std::array<float,2>{0.250141948f, 0.62920475f},
std::array<float,2>{0.01601048f, 0.341524035f},
std::array<float,2>{0.847576618f, 0.774366915f},
std::array<float,2>{0.938068986f, 0.480568081f},
std::array<float,2>{0.199241981f, 0.994260669f},
std::array<float,2>{0.398845971f, 0.184367627f},
std::array<float,2>{0.617663443f, 0.50266099f},
std::array<float,2>{0.862620771f, 0.112859502f},
std::array<float,2>{0.00384281226f, 0.657864034f},
std::array<float,2>{0.2760593f, 0.346074522f},
std::array<float,2>{0.632191122f, 0.800361812f},
std::array<float,2>{0.595378876f, 0.448282599f},
std::array<float,2>{0.383343905f, 0.959644675f},
std::array<float,2>{0.207886443f, 0.146396324f},
std::array<float,2>{0.957502902f, 0.531313717f},
std::array<float,2>{0.728186667f, 0.191685483f},
std::array<float,2>{0.365397871f, 0.590767562f},
std::array<float,2>{0.064529486f, 0.400753111f},
std::array<float,2>{0.794696927f, 0.916277111f},
std::array<float,2>{0.935089111f, 0.281253368f},
std::array<float,2>{0.155325189f, 0.842703819f},
std::array<float,2>{0.438136756f, 0.0526595674f},
std::array<float,2>{0.554285944f, 0.723858476f},
std::array<float,2>{0.974707723f, 0.161761165f},
std::array<float,2>{0.21977222f, 0.517775834f},
std::array<float,2>{0.432903409f, 0.495847166f},
std::array<float,2>{0.574899554f, 0.975062788f},
std::array<float,2>{0.686262727f, 0.316926837f},
std::array<float,2>{0.306141496f, 0.762787461f},
std::array<float,2>{0.0527818911f, 0.0848023668f},
std::array<float,2>{0.833261132f, 0.647350252f},
std::array<float,2>{0.506991386f, 0.0238833446f},
std::array<float,2>{0.474520206f, 0.71207583f},
std::array<float,2>{0.159861535f, 0.269210428f},
std::array<float,2>{0.882134616f, 0.859167874f},
std::array<float,2>{0.763203263f, 0.423192501f},
std::array<float,2>{0.102975912f, 0.903551936f},
std::array<float,2>{0.330898881f, 0.221684024f},
std::array<float,2>{0.690633416f, 0.613361657f},
std::array<float,2>{0.964687169f, 0.0904382244f},
std::array<float,2>{0.215493947f, 0.65571171f},
std::array<float,2>{0.381631911f, 0.327602118f},
std::array<float,2>{0.602718532f, 0.755145013f},
std::array<float,2>{0.63846463f, 0.48704198f},
std::array<float,2>{0.27207008f, 0.97831893f},
std::array<float,2>{0.0130176852f, 0.168224528f},
std::array<float,2>{0.867293835f, 0.527147353f},
std::array<float,2>{0.560977936f, 0.227699667f},
std::array<float,2>{0.450459063f, 0.617479503f},
std::array<float,2>{0.141990826f, 0.433053434f},
std::array<float,2>{0.922492981f, 0.895721614f},
std::array<float,2>{0.786346793f, 0.280453712f},
std::array<float,2>{0.0769664869f, 0.849200308f},
std::array<float,2>{0.373066068f, 0.0181006398f},
std::array<float,2>{0.725303948f, 0.708931863f},
std::array<float,2>{0.840941131f, 0.150062606f},
std::array<float,2>{0.0580269843f, 0.540168047f},
std::array<float,2>{0.302994221f, 0.440829456f},
std::array<float,2>{0.674919903f, 0.964052677f},
std::array<float,2>{0.564558029f, 0.358965605f},
std::array<float,2>{0.422443628f, 0.810368419f},
std::array<float,2>{0.232025102f, 0.118077941f},
std::array<float,2>{0.980967045f, 0.668165803f},
std::array<float,2>{0.698634207f, 0.0554607175f},
std::array<float,2>{0.336882293f, 0.731196046f},
std::array<float,2>{0.0954351947f, 0.293428063f},
std::array<float,2>{0.756686985f, 0.828269601f},
std::array<float,2>{0.883976698f, 0.392473727f},
std::array<float,2>{0.164950684f, 0.908215523f},
std::array<float,2>{0.477904528f, 0.199947998f},
std::array<float,2>{0.512114167f, 0.585256219f},
std::array<float,2>{0.779087186f, 0.00966777932f},
std::array<float,2>{0.121575087f, 0.700181186f},
std::array<float,2>{0.323430419f, 0.264932156f},
std::array<float,2>{0.708746016f, 0.867286205f},
std::array<float,2>{0.523224115f, 0.412643403f},
std::array<float,2>{0.497402996f, 0.880371869f},
std::array<float,2>{0.176581889f, 0.244560733f},
std::array<float,2>{0.90321672f, 0.598895609f},
std::array<float,2>{0.671777308f, 0.174943328f},
std::array<float,2>{0.290757895f, 0.513771713f},
std::array<float,2>{0.0400135517f, 0.476366788f},
std::array<float,2>{0.818515301f, 0.985151947f},
std::array<float,2>{0.991945446f, 0.330807f},
std::array<float,2>{0.2469071f, 0.77328229f},
std::array<float,2>{0.411467403f, 0.0761607066f},
std::array<float,2>{0.588860333f, 0.637481868f},
std::array<float,2>{0.910327733f, 0.215936914f},
std::array<float,2>{0.129847541f, 0.566936314f},
std::array<float,2>{0.468060404f, 0.388704807f},
std::array<float,2>{0.540179431f, 0.924257755f},
std::array<float,2>{0.74872607f, 0.297248632f},
std::array<float,2>{0.350152671f, 0.826409996f},
std::array<float,2>{0.080959335f, 0.0429640003f},
std::array<float,2>{0.804934561f, 0.74549526f},
std::array<float,2>{0.614265323f, 0.0954501331f},
std::array<float,2>{0.396290451f, 0.679316521f},
std::array<float,2>{0.190842688f, 0.367567629f},
std::array<float,2>{0.950855076f, 0.782133579f},
std::array<float,2>{0.852927983f, 0.461737752f},
std::array<float,2>{0.0268940032f, 0.944772184f},
std::array<float,2>{0.260948181f, 0.129128665f},
std::array<float,2>{0.655494452f, 0.548665166f}}
|
/* internaltest.cc: test of the Xapian internals
*
* Copyright 1999,2000,2001 BrightStation PLC
* Copyright 2002 Ananova Ltd
* Copyright 2002,2003,2006,2007,2008,2009,2010 Olly Betts
* Copyright 2006 Lemur Consulting Ltd
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include <config.h>
#include <xapian.h>
#include <cfloat>
#include "safeerrno.h"
#include <iostream>
#include <string>
using namespace std;
#include "autoptr.h"
#include "testsuite.h"
#include "testutils.h"
#include "omassert.h"
#include "omqueryinternal.h"
#include "pack.h"
#include "serialise.h"
#include "serialise-double.h"
#include "str.h"
static bool test_except1()
{
try {
throw 1;
} catch (int) {
}
return true;
}
class Test_Exception {
public:
int value;
Test_Exception(int value_) : value(value_) {}
};
// test that nested exceptions work correctly.
static bool test_exception1()
{
try {
try {
throw Test_Exception(1);
} catch (...) {
try {
throw Test_Exception(2);
} catch (...) {
}
throw;
}
} catch (const Test_Exception & e) {
TEST_EQUAL(e.value, 1);
return true;
}
return false;
}
// ###########################################
// # Tests of the reference counted pointers #
// ###########################################
class test_refcnt : public Xapian::Internal::RefCntBase {
private:
bool &deleted;
public:
test_refcnt(bool &deleted_) : deleted(deleted_) {
tout << "constructor\n";
}
Xapian::Internal::RefCntPtr<const test_refcnt> test() {
return Xapian::Internal::RefCntPtr<const test_refcnt>(this);
}
~test_refcnt() {
deleted = true;
tout << "destructor\n";
}
};
static bool test_refcnt1()
{
bool deleted = false;
test_refcnt *p = new test_refcnt(deleted);
TEST_EQUAL(p->ref_count, 0);
{
Xapian::Internal::RefCntPtr<test_refcnt> rcp(p);
TEST_EQUAL(rcp->ref_count, 1);
{
Xapian::Internal::RefCntPtr<test_refcnt> rcp2;
rcp2 = rcp;
TEST_EQUAL(rcp->ref_count, 2);
// rcp2 goes out of scope here
}
TEST_AND_EXPLAIN(!deleted, "Object prematurely deleted!");
TEST_EQUAL(rcp->ref_count, 1);
// rcp goes out of scope here
}
TEST_AND_EXPLAIN(deleted, "Object not properly deleted");
return true;
}
// This is a regression test - a RefCntPtr used to delete the object pointed
// to if you assigned it to itself and the reference count was 1.
static bool test_refcnt2()
{
bool deleted = false;
test_refcnt *p = new test_refcnt(deleted);
Xapian::Internal::RefCntPtr<test_refcnt> rcp(p);
rcp = rcp;
TEST_AND_EXPLAIN(!deleted, "Object deleted by self-assignment");
return true;
}
// Class for testing AutoPtr<>.
class test_autoptr {
bool &deleted;
public:
test_autoptr(bool &deleted_) : deleted(deleted_) {
tout << "test_autoptr constructor\n";
}
~test_autoptr() {
deleted = true;
tout << "test_autoptr destructor\n";
}
};
// Test autoptr self-assignment.
static bool test_autoptr1()
{
bool deleted = false;
test_autoptr * raw_ptr = new test_autoptr(deleted);
{
AutoPtr<test_autoptr> ptr(raw_ptr);
TEST_EQUAL(ptr.get(), raw_ptr);
TEST(!deleted);
ptr = ptr;
TEST_EQUAL(ptr.get(), raw_ptr);
TEST(!deleted);
}
TEST(deleted);
return true;
}
// test string comparisons
static bool test_stringcomp1()
{
bool success = true;
string s1;
string s2;
s1 = "foo";
s2 = "foo";
if ((s1 != s2) || (s1 > s2)) {
success = false;
tout << "String comparisons BADLY wrong" << endl;
}
s1 += '\0';
if ((s1 == s2) || (s1 < s2)) {
success = false;
tout << "String comparisons don't cope with extra nulls" << endl;
}
s2 += '\0';
s1 += 'a';
s2 += 'z';
if ((s1.length() != 5) || (s2.length() != 5)) {
success = false;
tout << "Lengths with added nulls wrong" << endl;
}
if ((s1 == s2) || !(s1 < s2)) {
success = false;
tout << "Characters after a null ignored in comparisons" << endl;
}
return success;
}
static bool test_tostring1()
{
TEST_EQUAL(str(0), "0");
TEST_EQUAL(str(10), "10");
TEST_EQUAL(str(10u), "10");
TEST_EQUAL(str(-10), "-10");
TEST_EQUAL(str(0xffffffff), "4294967295");
TEST_EQUAL(str(0x7fffffff), "2147483647");
TEST_EQUAL(str(0x7fffffffu), "2147483647");
TEST_EQUAL(str(-0x7fffffff), "-2147483647");
#ifdef __WIN32__
/* Test the 64 bit integer conversion to string.
* (Currently only exists for windows.)
*/
TEST_EQUAL(str(10ll), "10");
TEST_EQUAL(str(-10ll), "-10");
TEST_EQUAL(str(0x200000000ll), "8589934592");
// We don't currently have an "unsigned long long" version since it's not required
// anywhere in the library.
// TEST_EQUAL(str(0x200000000ull), "8589934592");
#endif
return true;
}
#ifdef XAPIAN_HAS_REMOTE_BACKEND
// Check serialisation of lengths.
static bool test_serialiselength1()
{
size_t n = 0;
while (n < 0xff000000) {
string s = encode_length(n);
const char *p = s.data();
const char *p_end = p + s.size();
size_t decoded_n = decode_length(&p, p_end, false);
if (n != decoded_n || p != p_end) tout << "[" << s << "]" << endl;
TEST_EQUAL(n, decoded_n);
TEST_EQUAL(p_end - p, 0);
if (n < 5000) {
++n;
} else {
n += 53643;
}
}
return true;
}
// Regression test: vetting the remaining buffer length
static bool test_serialiselength2()
{
// Special case tests for 0
{
string s = encode_length(0);
{
const char *p = s.data();
const char *p_end = p + s.size();
TEST(decode_length(&p, p_end, true) == 0);
TEST(p == p_end);
}
s += 'x';
{
const char *p = s.data();
const char *p_end = p + s.size();
TEST(decode_length(&p, p_end, true) == 0);
TEST_EQUAL(p_end - p, 1);
}
}
// Special case tests for 1
{
string s = encode_length(1);
TEST_EXCEPTION(Xapian::NetworkError,
const char *p = s.data();
const char *p_end = p + s.size();
TEST(decode_length(&p, p_end, true) == 1);
);
s += 'x';
{
const char *p = s.data();
const char *p_end = p + s.size();
TEST(decode_length(&p, p_end, true) == 1);
TEST_EQUAL(p_end - p, 1);
}
s += 'x';
{
const char *p = s.data();
const char *p_end = p + s.size();
TEST(decode_length(&p, p_end, true) == 1);
TEST_EQUAL(p_end - p, 2);
}
}
// Nothing magic here, just test a range of odd and even values.
for (size_t n = 2; n < 1000; n = (n + 1) * 2 + (n >> 1)) {
string s = encode_length(n);
TEST_EXCEPTION(Xapian::NetworkError,
const char *p = s.data();
const char *p_end = p + s.size();
TEST(decode_length(&p, p_end, true) == n);
);
s.append(n-1, 'x');
TEST_EXCEPTION(Xapian::NetworkError,
const char *p = s.data();
const char *p_end = p + s.size();
TEST(decode_length(&p, p_end, true) == n);
);
s += 'x';
{
const char *p = s.data();
const char *p_end = p + s.size();
TEST(decode_length(&p, p_end, true) == n);
TEST_EQUAL(size_t(p_end - p), n);
}
s += 'x';
{
const char *p = s.data();
const char *p_end = p + s.size();
TEST(decode_length(&p, p_end, true) == n);
TEST_EQUAL(size_t(p_end - p), n + 1);
}
}
return true;
}
#endif
static void check_double_serialisation(double u)
{
string encoded = serialise_double(u);
const char * ptr = encoded.data();
const char * end = ptr + encoded.size();
double v = unserialise_double(&ptr, end);
if (ptr != end || u != v) {
tout << u << " -> " << v << ", difference = " << v - u << endl;
tout << "FLT_RADIX = " << FLT_RADIX << endl;
tout << "DBL_MAX_EXP = " << DBL_MAX_EXP << endl;
}
TEST(ptr == end);
TEST_EQUAL(u, v);
}
// Check serialisation of doubles.
static bool test_serialisedouble1()
{
static const double test_values[] = {
3.14159265,
1e57,
123.1,
257.12,
1234.567e123,
255.5,
256.125,
257.03125,
};
check_double_serialisation(0.0);
check_double_serialisation(1.0);
check_double_serialisation(-1.0);
check_double_serialisation(DBL_MAX);
check_double_serialisation(-DBL_MAX);
check_double_serialisation(DBL_MIN);
check_double_serialisation(-DBL_MIN);
const double *p;
for (p = test_values; p < test_values + sizeof(test_values) / sizeof(double); ++p) {
double val = *p;
check_double_serialisation(val);
check_double_serialisation(-val);
check_double_serialisation(1.0 / val);
check_double_serialisation(-1.0 / val);
}
return true;
}
#ifdef XAPIAN_HAS_REMOTE_BACKEND
// Check serialisation of documents.
static bool test_serialisedoc1()
{
Xapian::Document doc;
string s;
s = serialise_document(doc);
TEST(serialise_document(unserialise_document(s)) == s);
doc.set_data("helllooooo");
doc.add_term("term");
doc.add_value(1, "foo");
s = serialise_document(doc);
TEST(serialise_document(unserialise_document(s)) == s);
return true;
}
static void
serialisequery1_helper(const Xapian::Query & query)
{
string before = query.internal->serialise();
Xapian::Registry reg;
Xapian::Query::Internal * qint;
qint = Xapian::Query::Internal::unserialise(before, reg);
string after = qint->serialise();
delete qint;
TEST(before == after);
}
// Check serialisation of queries.
static bool test_serialisequery1()
{
string s;
serialisequery1_helper(Xapian::Query("foo"));
// Regression test for bug in 0.9.10 and earlier.
serialisequery1_helper(Xapian::Query("foo", 1, 1));
serialisequery1_helper(Xapian::Query(Xapian::Query::OP_OR,
Xapian::Query("foo", 1, 1),
Xapian::Query("bar", 1, 1)));
static const char * words[] = { "paragraph", "word" };
serialisequery1_helper(Xapian::Query(Xapian::Query::OP_OR, words, words + 2));
static const char * words2[] = { "milk", "on", "fridge" };
serialisequery1_helper(
Xapian::Query(Xapian::Query::OP_SCALE_WEIGHT,
Xapian::Query(Xapian::Query::OP_OR,
Xapian::Query("leave"),
Xapian::Query(Xapian::Query::OP_PHRASE, words2, words2 + 3)
),
2.5)
);
return true;
}
// Check serialisation of Xapian::Error.
static bool test_serialiseerror1()
{
string enoent_msg(strerror(ENOENT));
Xapian::DatabaseOpeningError e("Failed to open database", ENOENT);
// Regression test for bug in 1.0.0 - it didn't convert errno values for
// get_description() if they hadn't already been converted.
TEST_STRINGS_EQUAL(e.get_description(), "DatabaseOpeningError: Failed to open database (" + enoent_msg + ")");
TEST_STRINGS_EQUAL(e.get_error_string(), enoent_msg);
string serialisation = serialise_error(e);
// Test if unserialise_error() throws with a flag to avoid the possibility
// of an "unreachable code" warning when we get around to marking
// unserialise_error() as "noreturn".
bool threw = false;
try {
// unserialise_error throws an exception.
unserialise_error(serialisation, "", "");
} catch (const Xapian::Error & ecaught) {
TEST_STRINGS_EQUAL(ecaught.get_error_string(), enoent_msg);
threw = true;
}
TEST(threw);
// Check that the original is still OK.
TEST_STRINGS_EQUAL(e.get_error_string(), enoent_msg);
// Regression test - in 1.0.0, copying used to duplicate the error_string
// pointer, resulting in double calls to free().
Xapian::DatabaseOpeningError ecopy(e);
TEST_STRINGS_EQUAL(ecopy.get_error_string(), enoent_msg);
return true;
}
#endif
// By default Sun's C++ compiler doesn't call the destructor on a
// temporary object until the end of the block (contrary to what
// ISO C++ requires). This is done in the name of "compatibility".
// Passing -features=tmplife to CC fixes this. This check ensures
// that this actually works for Sun's C++ and any other compilers
// that might have this problem.
struct TempDtorTest {
static int count;
static TempDtorTest factory() { return TempDtorTest(); }
TempDtorTest() { ++count; }
~TempDtorTest() { --count; }
};
int TempDtorTest::count = 0;
static bool test_temporarydtor1()
{
TEST_EQUAL(TempDtorTest::count, 0);
TempDtorTest::factory();
TEST_EQUAL(TempDtorTest::count, 0);
return true;
}
static bool test_static_assert1()
{
STATIC_ASSERT(true);
STATIC_ASSERT(1);
STATIC_ASSERT(-1);
STATIC_ASSERT(42);
STATIC_ASSERT(sizeof(char) == 1);
// FIXME: We should test cases which should fail, but these are hard to
// check with our current test framework.
STATIC_ASSERT_UNSIGNED_TYPE(bool);
STATIC_ASSERT_UNSIGNED_TYPE(unsigned char);
STATIC_ASSERT_UNSIGNED_TYPE(unsigned short);
STATIC_ASSERT_UNSIGNED_TYPE(unsigned int);
STATIC_ASSERT_UNSIGNED_TYPE(unsigned long);
// FIXME: We should test cases which should fail, but these are hard to
// check with our current test framework.
STATIC_ASSERT_TYPE_DOMINATES(unsigned long, unsigned long);
STATIC_ASSERT_TYPE_DOMINATES(unsigned int, unsigned int);
STATIC_ASSERT_TYPE_DOMINATES(unsigned short, unsigned short);
STATIC_ASSERT_TYPE_DOMINATES(unsigned char, unsigned char);
STATIC_ASSERT_TYPE_DOMINATES(long, long);
STATIC_ASSERT_TYPE_DOMINATES(int, int);
STATIC_ASSERT_TYPE_DOMINATES(short, short);
STATIC_ASSERT_TYPE_DOMINATES(signed char, signed char);
STATIC_ASSERT_TYPE_DOMINATES(char, char);
STATIC_ASSERT_TYPE_DOMINATES(unsigned long, unsigned int);
STATIC_ASSERT_TYPE_DOMINATES(unsigned int, unsigned short);
STATIC_ASSERT_TYPE_DOMINATES(unsigned short, unsigned char);
STATIC_ASSERT_TYPE_DOMINATES(long, int);
STATIC_ASSERT_TYPE_DOMINATES(int, short);
STATIC_ASSERT_TYPE_DOMINATES(short, signed char);
STATIC_ASSERT_TYPE_DOMINATES(long, unsigned char);
STATIC_ASSERT_TYPE_DOMINATES(int, unsigned char);
STATIC_ASSERT_TYPE_DOMINATES(short, unsigned char);
// FIXME: We should test cases which should fail, but these are hard to
// check with our current test framework.
return true;
}
/// Regression test for bug fixed in 1.1.1.
static bool test_strbool1()
{
TEST_EQUAL(str(true), "1");
TEST_EQUAL(str(false), "0");
return true;
}
/// Test pack_uint_preserving_sort()
static bool test_pack_uint_preserving_sort1()
{
string prev_packed;
for (unsigned int i = 0; i != 1000; ++i) {
string packed;
pack_uint_preserving_sort(packed, i);
const char * ptr = packed.data();
const char * end = ptr + packed.size();
unsigned int result;
TEST(unpack_uint_preserving_sort(&ptr, end, &result));
TEST_EQUAL(result, i);
TEST(ptr == end);
TEST_REL(prev_packed, <, packed);
swap(prev_packed, packed);
}
return true;
}
// ##################################################################
// # End of actual tests #
// ##################################################################
/// The lists of tests to perform
static const test_desc tests[] = {
{"except1", test_except1},
{"exception1", test_exception1},
{"refcnt1", test_refcnt1},
{"refcnt2", test_refcnt2},
{"autoptr1", test_autoptr1},
{"stringcomp1", test_stringcomp1},
{"temporarydtor1", test_temporarydtor1},
{"tostring1", test_tostring1},
{"serialisedouble1", test_serialisedouble1},
#ifdef XAPIAN_HAS_REMOTE_BACKEND
{"serialiselength1", test_serialiselength1},
{"serialiselength2", test_serialiselength2},
{"serialisedoc1", test_serialisedoc1},
{"serialisequery1", test_serialisequery1},
{"serialiseerror1", test_serialiseerror1},
#endif
{"static_assert1", test_static_assert1},
{"strbool1", test_strbool1},
{"pack1", test_pack_uint_preserving_sort1},
{0, 0}
};
int main(int argc, char **argv)
try {
test_driver::parse_command_line(argc, argv);
return test_driver::run(tests);
} catch (const char * e) {
cout << e << endl;
return 1;
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2018 The Bulwark developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/skyrocket-config.h"
#endif
#include "addressbookpage.h"
#include "ui_addressbookpage.h"
#include "addresstablemodel.h"
#include "bitcoingui.h"
#include "csvmodelwriter.h"
#include "editaddressdialog.h"
#include "guiutil.h"
#include <QIcon>
#include <QMenu>
#include <QMessageBox>
#include <QSortFilterProxyModel>
AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget* parent) : QDialog(parent),
ui(new Ui::AddressBookPage),
model(0),
mode(mode),
tab(tab)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->newAddress->setIcon(QIcon());
ui->copyAddress->setIcon(QIcon());
ui->deleteAddress->setIcon(QIcon());
ui->exportButton->setIcon(QIcon());
#endif
switch (mode) {
case ForSelection:
switch (tab) {
case SendingTab:
setWindowTitle(tr("Choose the address to send coins to"));
break;
case ReceivingTab:
setWindowTitle(tr("Choose the address to receive coins with"));
break;
}
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setFocus();
ui->closeButton->setText(tr("C&hoose"));
ui->exportButton->hide();
break;
case ForEditing:
switch (tab) {
case SendingTab:
setWindowTitle(tr("Sending addresses"));
break;
case ReceivingTab:
setWindowTitle(tr("Receiving addresses"));
break;
}
break;
}
switch (tab) {
case SendingTab:
ui->labelExplanation->setText(tr("These are your Skyrocket addresses for sending payments. Always check the amount and the receiving address before sending coins."));
ui->deleteAddress->setVisible(true);
break;
case ReceivingTab:
ui->labelExplanation->setText(tr("These are your Skyrocket addresses for receiving payments. It is recommended to use a new receiving address for each transaction."));
ui->deleteAddress->setVisible(false);
break;
}
// Context menu actions
QAction* copyAddressAction = new QAction(tr("&Copy Address"), this);
QAction* copyLabelAction = new QAction(tr("Copy &Label"), this);
QAction* editAction = new QAction(tr("&Edit"), this);
deleteAction = new QAction(ui->deleteAddress->text(), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(editAction);
if (tab == SendingTab)
contextMenu->addAction(deleteAction);
contextMenu->addSeparator();
// Connect signals for context menu actions
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));
connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept()));
}
AddressBookPage::~AddressBookPage()
{
delete ui;
}
void AddressBookPage::setModel(AddressTableModel* model)
{
this->model = model;
if (!model)
return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
switch (tab) {
case ReceivingTab:
// Receive filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Receive);
break;
case SendingTab:
// Send filter
proxyModel->setFilterRole(AddressTableModel::TypeRole);
proxyModel->setFilterFixedString(AddressTableModel::Send);
break;
}
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
#if QT_VERSION < 0x050000
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
#else
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
#endif
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created address
connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(selectNewAddress(QModelIndex, int, int)));
selectionChanged();
}
void AddressBookPage::on_copyAddress_clicked()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address);
}
void AddressBookPage::onCopyLabelAction()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label);
}
void AddressBookPage::onEditAction()
{
if (!model)
return;
if (!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if (indexes.isEmpty())
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress,
this);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void AddressBookPage::on_newAddress_clicked()
{
if (!model)
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::NewSendingAddress :
EditAddressDialog::NewReceivingAddress,
this);
dlg.setModel(model);
if (dlg.exec()) {
newAddressToSelect = dlg.getAddress();
}
}
void AddressBookPage::on_deleteAddress_clicked()
{
QTableView* table = ui->tableView;
if (!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if (!indexes.isEmpty()) {
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView* table = ui->tableView;
if (!table->selectionModel())
return;
if (table->selectionModel()->hasSelection()) {
switch (tab) {
case SendingTab:
// In sending tab, allow deletion of selection
ui->deleteAddress->setEnabled(true);
ui->deleteAddress->setVisible(true);
deleteAction->setEnabled(true);
break;
case ReceivingTab:
// Deleting receiving addresses, however, is not allowed
ui->deleteAddress->setEnabled(false);
ui->deleteAddress->setVisible(false);
deleteAction->setEnabled(false);
break;
}
ui->copyAddress->setEnabled(true);
} else {
ui->deleteAddress->setEnabled(false);
ui->copyAddress->setEnabled(false);
}
}
void AddressBookPage::done(int retval)
{
QTableView* table = ui->tableView;
if (!table->selectionModel() || !table->model())
return;
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
foreach (QModelIndex index, indexes) {
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if (returnValue.isEmpty()) {
// If no address entry selected, return rejected
retval = Rejected;
}
QDialog::done(retval);
}
void AddressBookPage::on_exportButton_clicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(this,
tr("Export Address List"), QString(),
tr("Comma separated file (*.csv)"), NULL);
if (filename.isNull())
return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole);
writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole);
if (!writer.write()) {
QMessageBox::critical(this, tr("Exporting Failed"),
tr("There was an error trying to save the address list to %1. Please try again.").arg(filename));
}
}
void AddressBookPage::contextualMenu(const QPoint& point)
{
QModelIndex index = ui->tableView->indexAt(point);
if (index.isValid()) {
contextMenu->exec(QCursor::pos());
}
}
void AddressBookPage::selectNewAddress(const QModelIndex& parent, int begin, int /*end*/)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent));
if (idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) {
// Select row of newly created address, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newAddressToSelect.clear();
}
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Sunplatform developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "noui.h"
#include "ui_interface.h"
#include "util.h"
#include <cstdio>
#include <stdint.h>
#include <string>
static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
bool fSecure = style & CClientUIInterface::SECURE;
style &= ~CClientUIInterface::SECURE;
std::string strCaption;
// Check for usage of predefined caption
switch (style) {
case CClientUIInterface::MSG_ERROR:
strCaption += _("Error");
break;
case CClientUIInterface::MSG_WARNING:
strCaption += _("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
strCaption += _("Information");
break;
default:
strCaption += caption; // Use supplied caption (can be empty)
}
if (!fSecure)
LogPrintf("%s: %s\n", strCaption, message);
fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str());
return false;
}
static void noui_InitMessage(const std::string& message)
{
LogPrintf("init message: %s\n", message);
}
void noui_connect()
{
// Connect sunplatformd signal handlers
uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox);
uiInterface.InitMessage.connect(noui_InitMessage);
}
|
/*
* Authors:
* Christian Schulte <schulte@gecode.org>
*
* Copyright:
* Christian Schulte, 2008-2012
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this 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 <gecode/int.hh>
using namespace Gecode;
class Equal : public BinaryPropagator<Int::IntView,Int::PC_INT_DOM> {
public:
Equal(Home home, Int::IntView x0, Int::IntView x1)
: BinaryPropagator<Int::IntView,Int::PC_INT_DOM>(home,x0,x1) {}
static ExecStatus post(Home home,
Int::IntView x0, Int::IntView x1) {
if (!same(x0,x1))
(void) new (home) Equal(home,x0,x1);
return ES_OK;
}
Equal(Space& home, bool share, Equal& p)
: BinaryPropagator<Int::IntView,Int::PC_INT_DOM>(home,share,p) {}
virtual Propagator* copy(Space& home, bool share) {
return new (home) Equal(home,share,*this);
}
virtual PropCost cost(const Space&, const ModEventDelta&) const {
return PropCost::binary(PropCost::HI);
}
virtual ExecStatus propagate(Space& home, const ModEventDelta&) {
Int::ViewRanges<Int::IntView> r0(x0);
GECODE_ME_CHECK(x1.inter_r(home,r0,false));
Int::ViewRanges<Int::IntView> r1(x1);
GECODE_ME_CHECK(x0.narrow_r(home,r1,false));
if (x0.assigned() && x1.assigned())
return home.ES_SUBSUMED(*this);
else
return ES_FIX;
}
};
void equal(Home home, IntVar x0, IntVar x1) {
if (home.failed()) return;
GECODE_ES_FAIL(Equal::post(home,x0,x1));
}
|
/*
* Copyright (c) 2013-2014,2018-2020 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cpu/minor/execute.hh"
#include <functional>
#include "cpu/minor/cpu.hh"
#include "cpu/minor/exec_context.hh"
#include "cpu/minor/fetch1.hh"
#include "cpu/minor/lsq.hh"
#include "cpu/op_class.hh"
#include "debug/Activity.hh"
#include "debug/Branch.hh"
#include "debug/Drain.hh"
#include "debug/ExecFaulting.hh"
#include "debug/MinorExecute.hh"
#include "debug/MinorInterrupt.hh"
#include "debug/MinorMem.hh"
#include "debug/MinorTrace.hh"
#include "debug/PCEvent.hh"
namespace gem5
{
GEM5_DEPRECATED_NAMESPACE(Minor, minor);
namespace minor
{
Execute::Execute(const std::string &name_,
MinorCPU &cpu_,
const BaseMinorCPUParams ¶ms,
Latch<ForwardInstData>::Output inp_,
Latch<BranchData>::Input out_) :
Named(name_),
inp(inp_),
out(out_),
cpu(cpu_),
zeroReg(cpu.threads[0]->getIsaPtr()->regClasses().
at(IntRegClass).zeroReg()),
issueLimit(params.executeIssueLimit),
memoryIssueLimit(params.executeMemoryIssueLimit),
commitLimit(params.executeCommitLimit),
memoryCommitLimit(params.executeMemoryCommitLimit),
processMoreThanOneInput(params.executeCycleInput),
fuDescriptions(*params.executeFuncUnits),
numFuncUnits(fuDescriptions.funcUnits.size()),
setTraceTimeOnCommit(params.executeSetTraceTimeOnCommit),
setTraceTimeOnIssue(params.executeSetTraceTimeOnIssue),
allowEarlyMemIssue(params.executeAllowEarlyMemoryIssue),
noCostFUIndex(fuDescriptions.funcUnits.size() + 1),
lsq(name_ + ".lsq", name_ + ".dcache_port",
cpu_, *this,
params.executeMaxAccessesInMemory,
params.executeMemoryWidth,
params.executeLSQRequestsQueueSize,
params.executeLSQTransfersQueueSize,
params.executeLSQStoreBufferSize,
params.executeLSQMaxStoreBufferStoresPerCycle,
zeroReg),
executeInfo(params.numThreads,
ExecuteThreadInfo(params.executeCommitLimit)),
interruptPriority(0),
issuePriority(0),
commitPriority(0)
{
if (commitLimit < 1) {
fatal("%s: executeCommitLimit must be >= 1 (%d)\n", name_,
commitLimit);
}
if (issueLimit < 1) {
fatal("%s: executeCommitLimit must be >= 1 (%d)\n", name_,
issueLimit);
}
if (memoryIssueLimit < 1) {
fatal("%s: executeMemoryIssueLimit must be >= 1 (%d)\n", name_,
memoryIssueLimit);
}
if (memoryCommitLimit > commitLimit) {
fatal("%s: executeMemoryCommitLimit (%d) must be <="
" executeCommitLimit (%d)\n",
name_, memoryCommitLimit, commitLimit);
}
if (params.executeInputBufferSize < 1) {
fatal("%s: executeInputBufferSize must be >= 1 (%d)\n", name_,
params.executeInputBufferSize);
}
if (params.executeInputBufferSize < 1) {
fatal("%s: executeInputBufferSize must be >= 1 (%d)\n", name_,
params.executeInputBufferSize);
}
/* This should be large enough to count all the in-FU instructions
* which need to be accounted for in the inFlightInsts
* queue */
unsigned int total_slots = 0;
/* Make FUPipelines for each MinorFU */
for (unsigned int i = 0; i < numFuncUnits; i++) {
std::ostringstream fu_name;
MinorFU *fu_description = fuDescriptions.funcUnits[i];
/* Note the total number of instruction slots (for sizing
* the inFlightInst queue) and the maximum latency of any FU
* (for sizing the activity recorder) */
total_slots += fu_description->opLat;
fu_name << name_ << ".fu." << i;
FUPipeline *fu = new FUPipeline(fu_name.str(), *fu_description, cpu);
funcUnits.push_back(fu);
}
/** Check that there is a functional unit for all operation classes */
for (int op_class = No_OpClass + 1; op_class < Num_OpClasses; op_class++) {
bool found_fu = false;
unsigned int fu_index = 0;
while (fu_index < numFuncUnits && !found_fu)
{
if (funcUnits[fu_index]->provides(
static_cast<OpClass>(op_class)))
{
found_fu = true;
}
fu_index++;
}
if (!found_fu) {
warn("No functional unit for OpClass %s\n",
enums::OpClassStrings[op_class]);
}
}
/* Per-thread structures */
for (ThreadID tid = 0; tid < params.numThreads; tid++) {
std::string tid_str = std::to_string(tid);
/* Input Buffers */
inputBuffer.push_back(
InputBuffer<ForwardInstData>(
name_ + ".inputBuffer" + tid_str, "insts",
params.executeInputBufferSize));
const auto ®Classes = cpu.threads[tid]->getIsaPtr()->regClasses();
/* Scoreboards */
scoreboard.emplace_back(name_ + ".scoreboard" + tid_str, regClasses);
/* In-flight instruction records */
executeInfo[tid].inFlightInsts = new Queue<QueuedInst,
ReportTraitsAdaptor<QueuedInst> >(
name_ + ".inFlightInsts" + tid_str, "insts", total_slots);
executeInfo[tid].inFUMemInsts = new Queue<QueuedInst,
ReportTraitsAdaptor<QueuedInst> >(
name_ + ".inFUMemInsts" + tid_str, "insts", total_slots);
}
}
const ForwardInstData *
Execute::getInput(ThreadID tid)
{
/* Get a line from the inputBuffer to work with */
if (!inputBuffer[tid].empty()) {
const ForwardInstData &head = inputBuffer[tid].front();
return (head.isBubble() ? NULL : &(inputBuffer[tid].front()));
} else {
return NULL;
}
}
void
Execute::popInput(ThreadID tid)
{
if (!inputBuffer[tid].empty())
inputBuffer[tid].pop();
executeInfo[tid].inputIndex = 0;
}
void
Execute::tryToBranch(MinorDynInstPtr inst, Fault fault, BranchData &branch)
{
ThreadContext *thread = cpu.getContext(inst->id.threadId);
const std::unique_ptr<PCStateBase> pc_before(inst->pc->clone());
std::unique_ptr<PCStateBase> target(thread->pcState().clone());
/* Force a branch for SerializeAfter/SquashAfter instructions
* at the end of micro-op sequence when we're not suspended */
bool force_branch = thread->status() != ThreadContext::Suspended &&
!inst->isFault() &&
inst->isLastOpInInst() &&
(inst->staticInst->isSerializeAfter() ||
inst->staticInst->isSquashAfter());
DPRINTF(Branch, "tryToBranch before: %s after: %s%s\n",
*pc_before, *target, (force_branch ? " (forcing)" : ""));
/* Will we change the PC to something other than the next instruction? */
bool must_branch = *pc_before != *target ||
fault != NoFault ||
force_branch;
/* The reason for the branch data we're about to generate, set below */
BranchData::Reason reason = BranchData::NoBranch;
if (fault == NoFault) {
inst->staticInst->advancePC(*target);
thread->pcState(*target);
DPRINTF(Branch, "Advancing current PC from: %s to: %s\n",
*pc_before, *target);
}
if (inst->predictedTaken && !force_branch) {
/* Predicted to branch */
if (!must_branch) {
/* No branch was taken, change stream to get us back to the
* intended PC value */
DPRINTF(Branch, "Predicted a branch from 0x%x to 0x%x but"
" none happened inst: %s\n",
inst->pc->instAddr(), inst->predictedTarget->instAddr(),
*inst);
reason = BranchData::BadlyPredictedBranch;
} else if (*inst->predictedTarget == *target) {
/* Branch prediction got the right target, kill the branch and
* carry on.
* Note that this information to the branch predictor might get
* overwritten by a "real" branch during this cycle */
DPRINTF(Branch, "Predicted a branch from 0x%x to 0x%x correctly"
" inst: %s\n",
inst->pc->instAddr(), inst->predictedTarget->instAddr(),
*inst);
reason = BranchData::CorrectlyPredictedBranch;
} else {
/* Branch prediction got the wrong target */
DPRINTF(Branch, "Predicted a branch from 0x%x to 0x%x"
" but got the wrong target (actual: 0x%x) inst: %s\n",
inst->pc->instAddr(), inst->predictedTarget->instAddr(),
target->instAddr(), *inst);
reason = BranchData::BadlyPredictedBranchTarget;
}
} else if (must_branch) {
/* Unpredicted branch */
DPRINTF(Branch, "Unpredicted branch from 0x%x to 0x%x inst: %s\n",
inst->pc->instAddr(), target->instAddr(), *inst);
reason = BranchData::UnpredictedBranch;
} else {
/* No branch at all */
reason = BranchData::NoBranch;
}
updateBranchData(inst->id.threadId, reason, inst, *target, branch);
}
void
Execute::updateBranchData(
ThreadID tid,
BranchData::Reason reason,
MinorDynInstPtr inst, const PCStateBase &target,
BranchData &branch)
{
if (reason != BranchData::NoBranch) {
/* Bump up the stream sequence number on a real branch*/
if (BranchData::isStreamChange(reason))
executeInfo[tid].streamSeqNum++;
/* Branches (even mis-predictions) don't change the predictionSeqNum,
* just the streamSeqNum */
branch = BranchData(reason, tid,
executeInfo[tid].streamSeqNum,
/* Maintaining predictionSeqNum if there's no inst is just a
* courtesy and looks better on minorview */
(inst->isBubble() ? executeInfo[tid].lastPredictionSeqNum
: inst->id.predictionSeqNum),
target, inst);
DPRINTF(Branch, "Branch data signalled: %s\n", branch);
}
}
void
Execute::handleMemResponse(MinorDynInstPtr inst,
LSQ::LSQRequestPtr response, BranchData &branch, Fault &fault)
{
ThreadID thread_id = inst->id.threadId;
ThreadContext *thread = cpu.getContext(thread_id);
ExecContext context(cpu, *cpu.threads[thread_id], *this, inst, zeroReg);
PacketPtr packet = response->packet;
bool is_load = inst->staticInst->isLoad();
bool is_store = inst->staticInst->isStore();
bool is_atomic = inst->staticInst->isAtomic();
bool is_prefetch = inst->staticInst->isDataPrefetch();
/* If true, the trace's predicate value will be taken from the exec
* context predicate, otherwise, it will be set to false */
bool use_context_predicate = true;
if (inst->translationFault != NoFault) {
/* Invoke memory faults. */
DPRINTF(MinorMem, "Completing fault from DTLB access: %s\n",
inst->translationFault->name());
if (inst->staticInst->isPrefetch()) {
DPRINTF(MinorMem, "Not taking fault on prefetch: %s\n",
inst->translationFault->name());
/* Don't assign to fault */
} else {
/* Take the fault raised during the TLB/memory access */
fault = inst->translationFault;
fault->invoke(thread, inst->staticInst);
}
} else if (!packet) {
DPRINTF(MinorMem, "Completing failed request inst: %s\n",
*inst);
use_context_predicate = false;
if (!context.readMemAccPredicate())
inst->staticInst->completeAcc(nullptr, &context, inst->traceData);
} else if (packet->isError()) {
DPRINTF(MinorMem, "Trying to commit error response: %s\n",
*inst);
fatal("Received error response packet for inst: %s\n", *inst);
} else if (is_store || is_load || is_prefetch || is_atomic) {
assert(packet);
DPRINTF(MinorMem, "Memory response inst: %s addr: 0x%x size: %d\n",
*inst, packet->getAddr(), packet->getSize());
if (is_load && packet->getSize() > 0) {
DPRINTF(MinorMem, "Memory data[0]: 0x%x\n",
static_cast<unsigned int>(packet->getConstPtr<uint8_t>()[0]));
}
/* Complete the memory access instruction */
fault = inst->staticInst->completeAcc(packet, &context,
inst->traceData);
if (fault != NoFault) {
/* Invoke fault created by instruction completion */
DPRINTF(MinorMem, "Fault in memory completeAcc: %s\n",
fault->name());
fault->invoke(thread, inst->staticInst);
} else {
/* Stores need to be pushed into the store buffer to finish
* them off */
if (response->needsToBeSentToStoreBuffer())
lsq.sendStoreToStoreBuffer(response);
}
} else {
fatal("There should only ever be reads, "
"writes or faults at this point\n");
}
lsq.popResponse(response);
if (inst->traceData) {
inst->traceData->setPredicate((use_context_predicate ?
context.readPredicate() : false));
}
doInstCommitAccounting(inst);
/* Generate output to account for branches */
tryToBranch(inst, fault, branch);
}
bool
Execute::isInterrupted(ThreadID thread_id) const
{
return cpu.checkInterrupts(thread_id);
}
bool
Execute::takeInterrupt(ThreadID thread_id, BranchData &branch)
{
DPRINTF(MinorInterrupt, "Considering interrupt status from PC: %s\n",
cpu.getContext(thread_id)->pcState());
Fault interrupt = cpu.getInterruptController(thread_id)->getInterrupt();
if (interrupt != NoFault) {
/* The interrupt *must* set pcState */
cpu.getInterruptController(thread_id)->updateIntrInfo();
interrupt->invoke(cpu.getContext(thread_id));
assert(!lsq.accessesInFlight());
DPRINTF(MinorInterrupt, "Invoking interrupt: %s to PC: %s\n",
interrupt->name(), cpu.getContext(thread_id)->pcState());
/* Assume that an interrupt *must* cause a branch. Assert this? */
updateBranchData(thread_id, BranchData::Interrupt,
MinorDynInst::bubble(), cpu.getContext(thread_id)->pcState(),
branch);
}
return interrupt != NoFault;
}
bool
Execute::executeMemRefInst(MinorDynInstPtr inst, BranchData &branch,
bool &passed_predicate, Fault &fault)
{
bool issued = false;
/* Set to true if the mem op. is issued and sent to the mem system */
passed_predicate = false;
if (!lsq.canRequest()) {
/* Not acting on instruction yet as the memory
* queues are full */
issued = false;
} else {
ThreadContext *thread = cpu.getContext(inst->id.threadId);
std::unique_ptr<PCStateBase> old_pc(thread->pcState().clone());
ExecContext context(cpu, *cpu.threads[inst->id.threadId],
*this, inst, zeroReg);
DPRINTF(MinorExecute, "Initiating memRef inst: %s\n", *inst);
Fault init_fault = inst->staticInst->initiateAcc(&context,
inst->traceData);
if (inst->inLSQ) {
if (init_fault != NoFault) {
assert(inst->translationFault != NoFault);
// Translation faults are dealt with in handleMemResponse()
init_fault = NoFault;
} else {
// If we have a translation fault then it got suppressed by
// initateAcc()
inst->translationFault = NoFault;
}
}
if (init_fault != NoFault) {
DPRINTF(MinorExecute, "Fault on memory inst: %s"
" initiateAcc: %s\n", *inst, init_fault->name());
fault = init_fault;
} else {
/* Only set this if the instruction passed its
* predicate */
if (!context.readMemAccPredicate()) {
DPRINTF(MinorMem, "No memory access for inst: %s\n", *inst);
assert(context.readPredicate());
}
passed_predicate = context.readPredicate();
/* Set predicate in tracing */
if (inst->traceData)
inst->traceData->setPredicate(passed_predicate);
/* If the instruction didn't pass its predicate
* or it is a predicated vector instruction and the
* associated predicate register is all-false (and so will not
* progress from here) Try to branch to correct and branch
* mis-prediction. */
if (!inst->inLSQ) {
/* Leave it up to commit to handle the fault */
lsq.pushFailedRequest(inst);
inst->inLSQ = true;
}
}
/* Restore thread PC */
thread->pcState(*old_pc);
issued = true;
}
return issued;
}
/** Increment a cyclic buffer index for indices [0, cycle_size-1] */
inline unsigned int
cyclicIndexInc(unsigned int index, unsigned int cycle_size)
{
unsigned int ret = index + 1;
if (ret == cycle_size)
ret = 0;
return ret;
}
/** Decrement a cyclic buffer index for indices [0, cycle_size-1] */
inline unsigned int
cyclicIndexDec(unsigned int index, unsigned int cycle_size)
{
int ret = index - 1;
if (ret < 0)
ret = cycle_size - 1;
return ret;
}
unsigned int
Execute::issue(ThreadID thread_id)
{
const ForwardInstData *insts_in = getInput(thread_id);
ExecuteThreadInfo &thread = executeInfo[thread_id];
/* Early termination if we have no instructions */
if (!insts_in)
return 0;
/* Start from the first FU */
unsigned int fu_index = 0;
/* Remains true while instructions are still being issued. If any
* instruction fails to issue, this is set to false and we exit issue.
* This strictly enforces in-order issue. For other issue behaviours,
* a more complicated test in the outer while loop below is needed. */
bool issued = true;
/* Number of insts issues this cycle to check for issueLimit */
unsigned num_insts_issued = 0;
/* Number of memory ops issues this cycle to check for memoryIssueLimit */
unsigned num_mem_insts_issued = 0;
/* Number of instructions discarded this cycle in order to enforce a
* discardLimit. @todo, add that parameter? */
unsigned num_insts_discarded = 0;
do {
MinorDynInstPtr inst = insts_in->insts[thread.inputIndex];
Fault fault = inst->fault;
bool discarded = false;
bool issued_mem_ref = false;
if (inst->isBubble()) {
/* Skip */
issued = true;
} else if (cpu.getContext(thread_id)->status() ==
ThreadContext::Suspended)
{
DPRINTF(MinorExecute, "Discarding inst: %s from suspended"
" thread\n", *inst);
issued = true;
discarded = true;
} else if (inst->id.streamSeqNum != thread.streamSeqNum) {
DPRINTF(MinorExecute, "Discarding inst: %s as its stream"
" state was unexpected, expected: %d\n",
*inst, thread.streamSeqNum);
issued = true;
discarded = true;
} else {
/* Try and issue an instruction into an FU, assume we didn't and
* fix that in the loop */
issued = false;
/* Try FU from 0 each instruction */
fu_index = 0;
/* Try and issue a single instruction stepping through the
* available FUs */
do {
FUPipeline *fu = funcUnits[fu_index];
DPRINTF(MinorExecute, "Trying to issue inst: %s to FU: %d\n",
*inst, fu_index);
/* Does the examined fu have the OpClass-related capability
* needed to execute this instruction? Faults can always
* issue to any FU but probably should just 'live' in the
* inFlightInsts queue rather than having an FU. */
bool fu_is_capable = (!inst->isFault() ?
fu->provides(inst->staticInst->opClass()) : true);
if (inst->isNoCostInst()) {
/* Issue free insts. to a fake numbered FU */
fu_index = noCostFUIndex;
/* And start the countdown on activity to allow
* this instruction to get to the end of its FU */
cpu.activityRecorder->activity();
/* Mark the destinations for this instruction as
* busy */
scoreboard[thread_id].markupInstDests(inst, cpu.curCycle() +
Cycles(0), cpu.getContext(thread_id), false);
DPRINTF(MinorExecute, "Issuing %s to %d\n", inst->id, noCostFUIndex);
inst->fuIndex = noCostFUIndex;
inst->extraCommitDelay = Cycles(0);
inst->extraCommitDelayExpr = NULL;
/* Push the instruction onto the inFlight queue so
* it can be committed in order */
QueuedInst fu_inst(inst);
thread.inFlightInsts->push(fu_inst);
issued = true;
} else if (!fu_is_capable || fu->alreadyPushed()) {
/* Skip */
if (!fu_is_capable) {
DPRINTF(MinorExecute, "Can't issue as FU: %d isn't"
" capable\n", fu_index);
} else {
DPRINTF(MinorExecute, "Can't issue as FU: %d is"
" already busy\n", fu_index);
}
} else if (fu->stalled) {
DPRINTF(MinorExecute, "Can't issue inst: %s into FU: %d,"
" it's stalled\n",
*inst, fu_index);
} else if (!fu->canInsert()) {
DPRINTF(MinorExecute, "Can't issue inst: %s to busy FU"
" for another: %d cycles\n",
*inst, fu->cyclesBeforeInsert());
} else {
MinorFUTiming *timing = (!inst->isFault() ?
fu->findTiming(inst->staticInst) : NULL);
const std::vector<Cycles> *src_latencies =
(timing ? &(timing->srcRegsRelativeLats)
: NULL);
const std::vector<bool> *cant_forward_from_fu_indices =
&(fu->cantForwardFromFUIndices);
if (timing && timing->suppress) {
DPRINTF(MinorExecute, "Can't issue inst: %s as extra"
" decoding is suppressing it\n",
*inst);
} else if (!scoreboard[thread_id].canInstIssue(inst,
src_latencies, cant_forward_from_fu_indices,
cpu.curCycle(), cpu.getContext(thread_id)))
{
DPRINTF(MinorExecute, "Can't issue inst: %s yet\n",
*inst);
} else {
/* Can insert the instruction into this FU */
DPRINTF(MinorExecute, "Issuing inst: %s"
" into FU %d\n", *inst,
fu_index);
Cycles extra_dest_retire_lat = Cycles(0);
TimingExpr *extra_dest_retire_lat_expr = NULL;
Cycles extra_assumed_lat = Cycles(0);
/* Add the extraCommitDelay and extraAssumeLat to
* the FU pipeline timings */
if (timing) {
extra_dest_retire_lat =
timing->extraCommitLat;
extra_dest_retire_lat_expr =
timing->extraCommitLatExpr;
extra_assumed_lat =
timing->extraAssumedLat;
}
issued_mem_ref = inst->isMemRef();
QueuedInst fu_inst(inst);
/* Decorate the inst with FU details */
inst->fuIndex = fu_index;
inst->extraCommitDelay = extra_dest_retire_lat;
inst->extraCommitDelayExpr =
extra_dest_retire_lat_expr;
if (issued_mem_ref) {
/* Remember which instruction this memory op
* depends on so that initiateAcc can be called
* early */
if (allowEarlyMemIssue) {
inst->instToWaitFor =
scoreboard[thread_id].execSeqNumToWaitFor(inst,
cpu.getContext(thread_id));
if (lsq.getLastMemBarrier(thread_id) >
inst->instToWaitFor)
{
DPRINTF(MinorExecute, "A barrier will"
" cause a delay in mem ref issue of"
" inst: %s until after inst"
" %d(exec)\n", *inst,
lsq.getLastMemBarrier(thread_id));
inst->instToWaitFor =
lsq.getLastMemBarrier(thread_id);
} else {
DPRINTF(MinorExecute, "Memory ref inst:"
" %s must wait for inst %d(exec)"
" before issuing\n",
*inst, inst->instToWaitFor);
}
inst->canEarlyIssue = true;
}
/* Also queue this instruction in the memory ref
* queue to ensure in-order issue to the LSQ */
DPRINTF(MinorExecute, "Pushing mem inst: %s\n",
*inst);
thread.inFUMemInsts->push(fu_inst);
}
/* Issue to FU */
fu->push(fu_inst);
/* And start the countdown on activity to allow
* this instruction to get to the end of its FU */
cpu.activityRecorder->activity();
/* Mark the destinations for this instruction as
* busy */
scoreboard[thread_id].markupInstDests(inst, cpu.curCycle() +
fu->description.opLat +
extra_dest_retire_lat +
extra_assumed_lat,
cpu.getContext(thread_id),
issued_mem_ref && extra_assumed_lat == Cycles(0));
/* Push the instruction onto the inFlight queue so
* it can be committed in order */
thread.inFlightInsts->push(fu_inst);
issued = true;
}
}
fu_index++;
} while (fu_index != numFuncUnits && !issued);
if (!issued)
DPRINTF(MinorExecute, "Didn't issue inst: %s\n", *inst);
}
if (issued) {
/* Generate MinorTrace's MinorInst lines. Do this at commit
* to allow better instruction annotation? */
if (debug::MinorTrace && !inst->isBubble()) {
inst->minorTraceInst(*this,
cpu.threads[0]->getIsaPtr()->regClasses());
}
/* Mark up barriers in the LSQ */
if (!discarded && inst->isInst() &&
inst->staticInst->isFullMemBarrier())
{
DPRINTF(MinorMem, "Issuing memory barrier inst: %s\n", *inst);
lsq.issuedMemBarrierInst(inst);
}
if (inst->traceData && setTraceTimeOnIssue) {
inst->traceData->setWhen(curTick());
}
if (issued_mem_ref)
num_mem_insts_issued++;
if (discarded) {
num_insts_discarded++;
} else if (!inst->isBubble()) {
num_insts_issued++;
if (num_insts_issued == issueLimit)
DPRINTF(MinorExecute, "Reached inst issue limit\n");
}
thread.inputIndex++;
DPRINTF(MinorExecute, "Stepping to next inst inputIndex: %d\n",
thread.inputIndex);
}
/* Got to the end of a line */
if (thread.inputIndex == insts_in->width()) {
popInput(thread_id);
/* Set insts_in to null to force us to leave the surrounding
* loop */
insts_in = NULL;
if (processMoreThanOneInput) {
DPRINTF(MinorExecute, "Wrapping\n");
insts_in = getInput(thread_id);
}
}
} while (insts_in && thread.inputIndex < insts_in->width() &&
/* We still have instructions */
fu_index != numFuncUnits && /* Not visited all FUs */
issued && /* We've not yet failed to issue an instruction */
num_insts_issued != issueLimit && /* Still allowed to issue */
num_mem_insts_issued != memoryIssueLimit);
return num_insts_issued;
}
bool
Execute::tryPCEvents(ThreadID thread_id)
{
ThreadContext *thread = cpu.getContext(thread_id);
unsigned int num_pc_event_checks = 0;
/* Handle PC events on instructions */
Addr oldPC;
do {
oldPC = thread->pcState().instAddr();
cpu.threads[thread_id]->pcEventQueue.service(oldPC, thread);
num_pc_event_checks++;
} while (oldPC != thread->pcState().instAddr());
if (num_pc_event_checks > 1) {
DPRINTF(PCEvent, "Acting on PC Event to PC: %s\n",
thread->pcState());
}
return num_pc_event_checks > 1;
}
void
Execute::doInstCommitAccounting(MinorDynInstPtr inst)
{
assert(!inst->isFault());
MinorThread *thread = cpu.threads[inst->id.threadId];
/* Increment the many and various inst and op counts in the
* thread and system */
if (!inst->staticInst->isMicroop() || inst->staticInst->isLastMicroop())
{
thread->numInst++;
thread->threadStats.numInsts++;
cpu.stats.numInsts++;
/* Act on events related to instruction counts */
thread->comInstEventQueue.serviceEvents(thread->numInst);
}
thread->numOp++;
thread->threadStats.numOps++;
cpu.stats.numOps++;
cpu.stats.committedInstType[inst->id.threadId]
[inst->staticInst->opClass()]++;
/* Set the CP SeqNum to the numOps commit number */
if (inst->traceData)
inst->traceData->setCPSeq(thread->numOp);
cpu.probeInstCommit(inst->staticInst, inst->pc->instAddr());
}
bool
Execute::commitInst(MinorDynInstPtr inst, bool early_memory_issue,
BranchData &branch, Fault &fault, bool &committed,
bool &completed_mem_issue)
{
ThreadID thread_id = inst->id.threadId;
ThreadContext *thread = cpu.getContext(thread_id);
bool completed_inst = true;
fault = NoFault;
/* Is the thread for this instruction suspended? In that case, just
* stall as long as there are no pending interrupts */
if (thread->status() == ThreadContext::Suspended &&
!isInterrupted(thread_id))
{
panic("We should never hit the case where we try to commit from a "
"suspended thread as the streamSeqNum should not match");
} else if (inst->isFault()) {
ExecContext context(cpu, *cpu.threads[thread_id], *this,
inst, zeroReg);
DPRINTF(MinorExecute, "Fault inst reached Execute: %s\n",
inst->fault->name());
fault = inst->fault;
inst->fault->invoke(thread, NULL);
tryToBranch(inst, fault, branch);
} else if (inst->staticInst->isMemRef()) {
/* Memory accesses are executed in two parts:
* executeMemRefInst -- calculates the EA and issues the access
* to memory. This is done here.
* handleMemResponse -- handles the response packet, done by
* Execute::commit
*
* While the memory access is in its FU, the EA is being
* calculated. At the end of the FU, when it is ready to
* 'commit' (in this function), the access is presented to the
* memory queues. When a response comes back from memory,
* Execute::commit will commit it.
*/
bool predicate_passed = false;
bool completed_mem_inst = executeMemRefInst(inst, branch,
predicate_passed, fault);
if (completed_mem_inst && fault != NoFault) {
if (early_memory_issue) {
DPRINTF(MinorExecute, "Fault in early executing inst: %s\n",
fault->name());
/* Don't execute the fault, just stall the instruction
* until it gets to the head of inFlightInsts */
inst->canEarlyIssue = false;
/* Not completed as we'll come here again to pick up
* the fault when we get to the end of the FU */
completed_inst = false;
} else {
DPRINTF(MinorExecute, "Fault in execute: %s\n",
fault->name());
fault->invoke(thread, NULL);
tryToBranch(inst, fault, branch);
completed_inst = true;
}
} else {
completed_inst = completed_mem_inst;
}
completed_mem_issue = completed_inst;
} else if (inst->isInst() && inst->staticInst->isFullMemBarrier() &&
!lsq.canPushIntoStoreBuffer())
{
DPRINTF(MinorExecute, "Can't commit data barrier inst: %s yet as"
" there isn't space in the store buffer\n", *inst);
completed_inst = false;
} else if (inst->isInst() && inst->staticInst->isQuiesce()
&& !branch.isBubble()){
/* This instruction can suspend, need to be able to communicate
* backwards, so no other branches may evaluate this cycle*/
completed_inst = false;
} else {
ExecContext context(cpu, *cpu.threads[thread_id], *this,
inst, zeroReg);
DPRINTF(MinorExecute, "Committing inst: %s\n", *inst);
fault = inst->staticInst->execute(&context,
inst->traceData);
/* Set the predicate for tracing and dump */
if (inst->traceData)
inst->traceData->setPredicate(context.readPredicate());
committed = true;
if (fault != NoFault) {
if (inst->traceData) {
if (debug::ExecFaulting) {
inst->traceData->setFaulting(true);
} else {
delete inst->traceData;
inst->traceData = NULL;
}
}
DPRINTF(MinorExecute, "Fault in execute of inst: %s fault: %s\n",
*inst, fault->name());
fault->invoke(thread, inst->staticInst);
}
doInstCommitAccounting(inst);
tryToBranch(inst, fault, branch);
}
if (completed_inst) {
/* Keep a copy of this instruction's predictionSeqNum just in case
* we need to issue a branch without an instruction (such as an
* interrupt) */
executeInfo[thread_id].lastPredictionSeqNum = inst->id.predictionSeqNum;
/* Check to see if this instruction suspended the current thread. */
if (!inst->isFault() &&
thread->status() == ThreadContext::Suspended &&
branch.isBubble() && /* It didn't branch too */
!isInterrupted(thread_id)) /* Don't suspend if we have
interrupts */
{
auto &resume_pc = cpu.getContext(thread_id)->pcState();
assert(resume_pc.microPC() == 0);
DPRINTF(MinorInterrupt, "Suspending thread: %d from Execute"
" inst: %s\n", thread_id, *inst);
cpu.stats.numFetchSuspends++;
updateBranchData(thread_id, BranchData::SuspendThread, inst,
resume_pc, branch);
}
}
return completed_inst;
}
void
Execute::commit(ThreadID thread_id, bool only_commit_microops, bool discard,
BranchData &branch)
{
Fault fault = NoFault;
Cycles now = cpu.curCycle();
ExecuteThreadInfo &ex_info = executeInfo[thread_id];
/**
* Try and execute as many instructions from the end of FU pipelines as
* possible. This *doesn't* include actually advancing the pipelines.
*
* We do this by looping on the front of the inFlightInsts queue for as
* long as we can find the desired instruction at the end of the
* functional unit it was issued to without seeing a branch or a fault.
* In this function, these terms are used:
* complete -- The instruction has finished its passage through
* its functional unit and its fate has been decided
* (committed, discarded, issued to the memory system)
* commit -- The instruction is complete(d), not discarded and has
* its effects applied to the CPU state
* discard(ed) -- The instruction is complete but not committed
* as its streamSeqNum disagrees with the current
* Execute::streamSeqNum
*
* Commits are also possible from two other places:
*
* 1) Responses returning from the LSQ
* 2) Mem ops issued to the LSQ ('committed' from the FUs) earlier
* than their position in the inFlightInsts queue, but after all
* their dependencies are resolved.
*/
/* Has an instruction been completed? Once this becomes false, we stop
* trying to complete instructions. */
bool completed_inst = true;
/* Number of insts committed this cycle to check against commitLimit */
unsigned int num_insts_committed = 0;
/* Number of memory access instructions committed to check against
* memCommitLimit */
unsigned int num_mem_refs_committed = 0;
if (only_commit_microops && !ex_info.inFlightInsts->empty()) {
DPRINTF(MinorInterrupt, "Only commit microops %s %d\n",
*(ex_info.inFlightInsts->front().inst),
ex_info.lastCommitWasEndOfMacroop);
}
while (!ex_info.inFlightInsts->empty() && /* Some more instructions to process */
!branch.isStreamChange() && /* No real branch */
fault == NoFault && /* No faults */
completed_inst && /* Still finding instructions to execute */
num_insts_committed != commitLimit /* Not reached commit limit */
)
{
if (only_commit_microops) {
DPRINTF(MinorInterrupt, "Committing tail of insts before"
" interrupt: %s\n",
*(ex_info.inFlightInsts->front().inst));
}
QueuedInst *head_inflight_inst = &(ex_info.inFlightInsts->front());
InstSeqNum head_exec_seq_num =
head_inflight_inst->inst->id.execSeqNum;
/* The instruction we actually process if completed_inst
* remains true to the end of the loop body.
* Start by considering the the head of the in flight insts queue */
MinorDynInstPtr inst = head_inflight_inst->inst;
bool committed_inst = false;
bool discard_inst = false;
bool completed_mem_ref = false;
bool issued_mem_ref = false;
bool early_memory_issue = false;
/* Must set this again to go around the loop */
completed_inst = false;
/* If we're just completing a macroop before an interrupt or drain,
* can we stil commit another microop (rather than a memory response)
* without crosing into the next full instruction? */
bool can_commit_insts = !ex_info.inFlightInsts->empty() &&
!(only_commit_microops && ex_info.lastCommitWasEndOfMacroop);
/* Can we find a mem response for this inst */
LSQ::LSQRequestPtr mem_response =
(inst->inLSQ ? lsq.findResponse(inst) : NULL);
DPRINTF(MinorExecute, "Trying to commit canCommitInsts: %d\n",
can_commit_insts);
/* Test for PC events after every instruction */
if (isInbetweenInsts(thread_id) && tryPCEvents(thread_id)) {
ThreadContext *thread = cpu.getContext(thread_id);
/* Branch as there was a change in PC */
updateBranchData(thread_id, BranchData::UnpredictedBranch,
MinorDynInst::bubble(), thread->pcState(), branch);
} else if (mem_response &&
num_mem_refs_committed < memoryCommitLimit)
{
/* Try to commit from the memory responses next */
discard_inst = inst->id.streamSeqNum !=
ex_info.streamSeqNum || discard;
DPRINTF(MinorExecute, "Trying to commit mem response: %s\n",
*inst);
/* Complete or discard the response */
if (discard_inst) {
DPRINTF(MinorExecute, "Discarding mem inst: %s as its"
" stream state was unexpected, expected: %d\n",
*inst, ex_info.streamSeqNum);
lsq.popResponse(mem_response);
} else {
handleMemResponse(inst, mem_response, branch, fault);
committed_inst = true;
}
completed_mem_ref = true;
completed_inst = true;
} else if (can_commit_insts) {
/* If true, this instruction will, subject to timing tweaks,
* be considered for completion. try_to_commit flattens
* the `if' tree a bit and allows other tests for inst
* commit to be inserted here. */
bool try_to_commit = false;
/* Try and issue memory ops early if they:
* - Can push a request into the LSQ
* - Have reached the end of their FUs
* - Have had all their dependencies satisfied
* - Are from the right stream
*
* For any other case, leave it to the normal instruction
* issue below to handle them.
*/
if (!ex_info.inFUMemInsts->empty() && lsq.canRequest()) {
DPRINTF(MinorExecute, "Trying to commit from mem FUs\n");
const MinorDynInstPtr head_mem_ref_inst =
ex_info.inFUMemInsts->front().inst;
FUPipeline *fu = funcUnits[head_mem_ref_inst->fuIndex];
const MinorDynInstPtr &fu_inst = fu->front().inst;
/* Use this, possibly out of order, inst as the one
* to 'commit'/send to the LSQ */
if (!fu_inst->isBubble() &&
!fu_inst->inLSQ &&
fu_inst->canEarlyIssue &&
ex_info.streamSeqNum == fu_inst->id.streamSeqNum &&
head_exec_seq_num > fu_inst->instToWaitFor)
{
DPRINTF(MinorExecute, "Issuing mem ref early"
" inst: %s instToWaitFor: %d\n",
*(fu_inst), fu_inst->instToWaitFor);
inst = fu_inst;
try_to_commit = true;
early_memory_issue = true;
completed_inst = true;
}
}
/* Try and commit FU-less insts */
if (!completed_inst && inst->isNoCostInst()) {
DPRINTF(MinorExecute, "Committing no cost inst: %s", *inst);
try_to_commit = true;
completed_inst = true;
}
/* Try to issue from the ends of FUs and the inFlightInsts
* queue */
if (!completed_inst && !inst->inLSQ) {
DPRINTF(MinorExecute, "Trying to commit from FUs\n");
/* Try to commit from a functional unit */
/* Is the head inst of the expected inst's FU actually the
* expected inst? */
QueuedInst &fu_inst =
funcUnits[inst->fuIndex]->front();
InstSeqNum fu_inst_seq_num = fu_inst.inst->id.execSeqNum;
if (fu_inst.inst->isBubble()) {
/* No instruction ready */
completed_inst = false;
} else if (fu_inst_seq_num != head_exec_seq_num) {
/* Past instruction: we must have already executed it
* in the same cycle and so the head inst isn't
* actually at the end of its pipeline
* Future instruction: handled above and only for
* mem refs on their way to the LSQ */
} else if (fu_inst.inst->id == inst->id) {
/* All instructions can be committed if they have the
* right execSeqNum and there are no in-flight
* mem insts before us */
try_to_commit = true;
completed_inst = true;
}
}
if (try_to_commit) {
discard_inst = inst->id.streamSeqNum !=
ex_info.streamSeqNum || discard;
/* Is this instruction discardable as its streamSeqNum
* doesn't match? */
if (!discard_inst) {
/* Try to commit or discard a non-memory instruction.
* Memory ops are actually 'committed' from this FUs
* and 'issued' into the memory system so we need to
* account for them later (commit_was_mem_issue gets
* set) */
if (inst->extraCommitDelayExpr) {
DPRINTF(MinorExecute, "Evaluating expression for"
" extra commit delay inst: %s\n", *inst);
ThreadContext *thread = cpu.getContext(thread_id);
TimingExprEvalContext context(inst->staticInst,
thread, NULL);
uint64_t extra_delay = inst->extraCommitDelayExpr->
eval(context);
DPRINTF(MinorExecute, "Extra commit delay expr"
" result: %d\n", extra_delay);
if (extra_delay < 128) {
inst->extraCommitDelay += Cycles(extra_delay);
} else {
DPRINTF(MinorExecute, "Extra commit delay was"
" very long: %d\n", extra_delay);
}
inst->extraCommitDelayExpr = NULL;
}
/* Move the extraCommitDelay from the instruction
* into the minimumCommitCycle */
if (inst->extraCommitDelay != Cycles(0)) {
inst->minimumCommitCycle = cpu.curCycle() +
inst->extraCommitDelay;
inst->extraCommitDelay = Cycles(0);
}
/* @todo Think about making lastMemBarrier be
* MAX_UINT_64 to avoid using 0 as a marker value */
if (!inst->isFault() && inst->isMemRef() &&
lsq.getLastMemBarrier(thread_id) <
inst->id.execSeqNum &&
lsq.getLastMemBarrier(thread_id) != 0)
{
DPRINTF(MinorExecute, "Not committing inst: %s yet"
" as there are incomplete barriers in flight\n",
*inst);
completed_inst = false;
} else if (inst->minimumCommitCycle > now) {
DPRINTF(MinorExecute, "Not committing inst: %s yet"
" as it wants to be stalled for %d more cycles\n",
*inst, inst->minimumCommitCycle - now);
completed_inst = false;
} else {
completed_inst = commitInst(inst,
early_memory_issue, branch, fault,
committed_inst, issued_mem_ref);
}
} else {
/* Discard instruction */
completed_inst = true;
}
if (completed_inst) {
/* Allow the pipeline to advance. If the FU head
* instruction wasn't the inFlightInsts head
* but had already been committed, it would have
* unstalled the pipeline before here */
if (inst->fuIndex != noCostFUIndex) {
DPRINTF(MinorExecute, "Unstalling %d for inst %s\n", inst->fuIndex, inst->id);
funcUnits[inst->fuIndex]->stalled = false;
}
}
}
} else {
DPRINTF(MinorExecute, "No instructions to commit\n");
completed_inst = false;
}
/* All discardable instructions must also be 'completed' by now */
assert(!(discard_inst && !completed_inst));
/* Instruction committed but was discarded due to streamSeqNum
* mismatch */
if (discard_inst) {
DPRINTF(MinorExecute, "Discarding inst: %s as its stream"
" state was unexpected, expected: %d\n",
*inst, ex_info.streamSeqNum);
if (fault == NoFault)
cpu.stats.numDiscardedOps++;
}
/* Mark the mem inst as being in the LSQ */
if (issued_mem_ref) {
inst->fuIndex = 0;
inst->inLSQ = true;
}
/* Pop issued (to LSQ) and discarded mem refs from the inFUMemInsts
* as they've *definitely* exited the FUs */
if (completed_inst && inst->isMemRef()) {
/* The MemRef could have been discarded from the FU or the memory
* queue, so just check an FU instruction */
if (!ex_info.inFUMemInsts->empty() &&
ex_info.inFUMemInsts->front().inst == inst)
{
ex_info.inFUMemInsts->pop();
}
}
if (completed_inst && !(issued_mem_ref && fault == NoFault)) {
/* Note that this includes discarded insts */
DPRINTF(MinorExecute, "Completed inst: %s\n", *inst);
/* Got to the end of a full instruction? */
ex_info.lastCommitWasEndOfMacroop = inst->isFault() ||
inst->isLastOpInInst();
/* lastPredictionSeqNum is kept as a convenience to prevent its
* value from changing too much on the minorview display */
ex_info.lastPredictionSeqNum = inst->id.predictionSeqNum;
/* Finished with the inst, remove it from the inst queue and
* clear its dependencies */
ex_info.inFlightInsts->pop();
/* Complete barriers in the LSQ/move to store buffer */
if (inst->isInst() && inst->staticInst->isFullMemBarrier()) {
DPRINTF(MinorMem, "Completing memory barrier"
" inst: %s committed: %d\n", *inst, committed_inst);
lsq.completeMemBarrierInst(inst, committed_inst);
}
scoreboard[thread_id].clearInstDests(inst, inst->isMemRef());
}
/* Handle per-cycle instruction counting */
if (committed_inst) {
bool is_no_cost_inst = inst->isNoCostInst();
/* Don't show no cost instructions as having taken a commit
* slot */
if (debug::MinorTrace && !is_no_cost_inst)
ex_info.instsBeingCommitted.insts[num_insts_committed] = inst;
if (!is_no_cost_inst)
num_insts_committed++;
if (num_insts_committed == commitLimit)
DPRINTF(MinorExecute, "Reached inst commit limit\n");
/* Re-set the time of the instruction if that's required for
* tracing */
if (inst->traceData) {
if (setTraceTimeOnCommit)
inst->traceData->setWhen(curTick());
inst->traceData->dump();
}
if (completed_mem_ref)
num_mem_refs_committed++;
if (num_mem_refs_committed == memoryCommitLimit)
DPRINTF(MinorExecute, "Reached mem ref commit limit\n");
}
}
}
bool
Execute::isInbetweenInsts(ThreadID thread_id) const
{
return executeInfo[thread_id].lastCommitWasEndOfMacroop &&
!lsq.accessesInFlight();
}
void
Execute::evaluate()
{
if (!inp.outputWire->isBubble())
inputBuffer[inp.outputWire->threadId].setTail(*inp.outputWire);
BranchData &branch = *out.inputWire;
unsigned int num_issued = 0;
/* Do all the cycle-wise activities for dcachePort here to potentially
* free up input spaces in the LSQ's requests queue */
lsq.step();
/* Check interrupts first. Will halt commit if interrupt found */
bool interrupted = false;
ThreadID interrupt_tid = checkInterrupts(branch, interrupted);
if (interrupt_tid != InvalidThreadID) {
/* Signalling an interrupt this cycle, not issuing/committing from
* any other threads */
} else if (!branch.isBubble()) {
/* It's important that this is here to carry Fetch1 wakeups to Fetch1
* without overwriting them */
DPRINTF(MinorInterrupt, "Execute skipping a cycle to allow old"
" branch to complete\n");
} else {
ThreadID commit_tid = getCommittingThread();
if (commit_tid != InvalidThreadID) {
ExecuteThreadInfo& commit_info = executeInfo[commit_tid];
DPRINTF(MinorExecute, "Attempting to commit [tid:%d]\n",
commit_tid);
/* commit can set stalled flags observable to issue and so *must* be
* called first */
if (commit_info.drainState != NotDraining) {
if (commit_info.drainState == DrainCurrentInst) {
/* Commit only micro-ops, don't kill anything else */
commit(commit_tid, true, false, branch);
if (isInbetweenInsts(commit_tid))
setDrainState(commit_tid, DrainHaltFetch);
/* Discard any generated branch */
branch = BranchData::bubble();
} else if (commit_info.drainState == DrainAllInsts) {
/* Kill all instructions */
while (getInput(commit_tid))
popInput(commit_tid);
commit(commit_tid, false, true, branch);
}
} else {
/* Commit micro-ops only if interrupted. Otherwise, commit
* anything you like */
DPRINTF(MinorExecute, "Committing micro-ops for interrupt[tid:%d]\n",
commit_tid);
bool only_commit_microops = interrupted &&
hasInterrupt(commit_tid);
commit(commit_tid, only_commit_microops, false, branch);
}
/* Halt fetch, but don't do it until we have the current instruction in
* the bag */
if (commit_info.drainState == DrainHaltFetch) {
updateBranchData(commit_tid, BranchData::HaltFetch,
MinorDynInst::bubble(),
cpu.getContext(commit_tid)->pcState(), branch);
cpu.wakeupOnEvent(Pipeline::ExecuteStageId);
setDrainState(commit_tid, DrainAllInsts);
}
}
ThreadID issue_tid = getIssuingThread();
/* This will issue merrily even when interrupted in the sure and
* certain knowledge that the interrupt with change the stream */
if (issue_tid != InvalidThreadID) {
DPRINTF(MinorExecute, "Attempting to issue [tid:%d]\n",
issue_tid);
num_issued = issue(issue_tid);
}
}
/* Run logic to step functional units + decide if we are active on the next
* clock cycle */
std::vector<MinorDynInstPtr> next_issuable_insts;
bool can_issue_next = false;
for (ThreadID tid = 0; tid < cpu.numThreads; tid++) {
/* Find the next issuable instruction for each thread and see if it can
be issued */
if (getInput(tid)) {
unsigned int input_index = executeInfo[tid].inputIndex;
MinorDynInstPtr inst = getInput(tid)->insts[input_index];
if (inst->isFault()) {
can_issue_next = true;
} else if (!inst->isBubble()) {
next_issuable_insts.push_back(inst);
}
}
}
bool becoming_stalled = true;
/* Advance the pipelines and note whether they still need to be
* advanced */
for (unsigned int i = 0; i < numFuncUnits; i++) {
FUPipeline *fu = funcUnits[i];
fu->advance();
/* If we need to tick again, the pipeline will have been left or set
* to be unstalled */
if (fu->occupancy !=0 && !fu->stalled)
becoming_stalled = false;
/* Could we possibly issue the next instruction from any thread?
* This is quite an expensive test and is only used to determine
* if the CPU should remain active, only run it if we aren't sure
* we are active next cycle yet */
for (auto inst : next_issuable_insts) {
if (!fu->stalled && fu->provides(inst->staticInst->opClass()) &&
scoreboard[inst->id.threadId].canInstIssue(inst,
NULL, NULL, cpu.curCycle() + Cycles(1),
cpu.getContext(inst->id.threadId))) {
can_issue_next = true;
break;
}
}
}
bool head_inst_might_commit = false;
/* Could the head in flight insts be committed */
for (auto const &info : executeInfo) {
if (!info.inFlightInsts->empty()) {
const QueuedInst &head_inst = info.inFlightInsts->front();
if (head_inst.inst->isNoCostInst()) {
head_inst_might_commit = true;
} else {
FUPipeline *fu = funcUnits[head_inst.inst->fuIndex];
if ((fu->stalled &&
fu->front().inst->id == head_inst.inst->id) ||
lsq.findResponse(head_inst.inst))
{
head_inst_might_commit = true;
break;
}
}
}
}
DPRINTF(Activity, "Need to tick num issued insts: %s%s%s%s%s%s\n",
(num_issued != 0 ? " (issued some insts)" : ""),
(becoming_stalled ? "(becoming stalled)" : "(not becoming stalled)"),
(can_issue_next ? " (can issued next inst)" : ""),
(head_inst_might_commit ? "(head inst might commit)" : ""),
(lsq.needsToTick() ? " (LSQ needs to tick)" : ""),
(interrupted ? " (interrupted)" : ""));
bool need_to_tick =
num_issued != 0 || /* Issued some insts this cycle */
!becoming_stalled || /* Some FU pipelines can still move */
can_issue_next || /* Can still issue a new inst */
head_inst_might_commit || /* Could possible commit the next inst */
lsq.needsToTick() || /* Must step the dcache port */
interrupted; /* There are pending interrupts */
if (!need_to_tick) {
DPRINTF(Activity, "The next cycle might be skippable as there are no"
" advanceable FUs\n");
}
/* Wake up if we need to tick again */
if (need_to_tick)
cpu.wakeupOnEvent(Pipeline::ExecuteStageId);
/* Note activity of following buffer */
if (!branch.isBubble())
cpu.activityRecorder->activity();
/* Make sure the input (if any left) is pushed */
if (!inp.outputWire->isBubble())
inputBuffer[inp.outputWire->threadId].pushTail();
}
ThreadID
Execute::checkInterrupts(BranchData& branch, bool& interrupted)
{
ThreadID tid = interruptPriority;
/* Evaluate interrupts in round-robin based upon service */
do {
/* Has an interrupt been signalled? This may not be acted on
* straighaway so this is different from took_interrupt */
bool thread_interrupted = false;
if (FullSystem && cpu.getInterruptController(tid)) {
/* This is here because it seems that after drainResume the
* interrupt controller isn't always set */
thread_interrupted = executeInfo[tid].drainState == NotDraining &&
isInterrupted(tid);
interrupted = interrupted || thread_interrupted;
} else {
DPRINTF(MinorInterrupt, "No interrupt controller\n");
}
DPRINTF(MinorInterrupt, "[tid:%d] thread_interrupted?=%d isInbetweenInsts?=%d\n",
tid, thread_interrupted, isInbetweenInsts(tid));
/* Act on interrupts */
if (thread_interrupted && isInbetweenInsts(tid)) {
if (takeInterrupt(tid, branch)) {
interruptPriority = tid;
return tid;
}
} else {
tid = (tid + 1) % cpu.numThreads;
}
} while (tid != interruptPriority);
return InvalidThreadID;
}
bool
Execute::hasInterrupt(ThreadID thread_id)
{
if (FullSystem && cpu.getInterruptController(thread_id)) {
return executeInfo[thread_id].drainState == NotDraining &&
isInterrupted(thread_id);
}
return false;
}
void
Execute::minorTrace() const
{
std::ostringstream insts;
std::ostringstream stalled;
executeInfo[0].instsBeingCommitted.reportData(insts);
lsq.minorTrace();
inputBuffer[0].minorTrace();
scoreboard[0].minorTrace();
/* Report functional unit stalling in one string */
unsigned int i = 0;
while (i < numFuncUnits)
{
stalled << (funcUnits[i]->stalled ? '1' : 'E');
i++;
if (i != numFuncUnits)
stalled << ',';
}
minor::minorTrace("insts=%s inputIndex=%d streamSeqNum=%d"
" stalled=%s drainState=%d isInbetweenInsts=%d\n",
insts.str(), executeInfo[0].inputIndex, executeInfo[0].streamSeqNum,
stalled.str(), executeInfo[0].drainState, isInbetweenInsts(0));
std::for_each(funcUnits.begin(), funcUnits.end(),
std::mem_fn(&FUPipeline::minorTrace));
executeInfo[0].inFlightInsts->minorTrace();
executeInfo[0].inFUMemInsts->minorTrace();
}
inline ThreadID
Execute::getCommittingThread()
{
std::vector<ThreadID> priority_list;
switch (cpu.threadPolicy) {
case enums::SingleThreaded:
return 0;
case enums::RoundRobin:
priority_list = cpu.roundRobinPriority(commitPriority);
break;
case enums::Random:
priority_list = cpu.randomPriority();
break;
default:
panic("Invalid thread policy");
}
for (auto tid : priority_list) {
ExecuteThreadInfo &ex_info = executeInfo[tid];
bool can_commit_insts = !ex_info.inFlightInsts->empty();
if (can_commit_insts) {
QueuedInst *head_inflight_inst = &(ex_info.inFlightInsts->front());
MinorDynInstPtr inst = head_inflight_inst->inst;
can_commit_insts = can_commit_insts &&
(!inst->inLSQ || (lsq.findResponse(inst) != NULL));
if (!inst->inLSQ) {
bool can_transfer_mem_inst = false;
if (!ex_info.inFUMemInsts->empty() && lsq.canRequest()) {
const MinorDynInstPtr head_mem_ref_inst =
ex_info.inFUMemInsts->front().inst;
FUPipeline *fu = funcUnits[head_mem_ref_inst->fuIndex];
const MinorDynInstPtr &fu_inst = fu->front().inst;
can_transfer_mem_inst =
!fu_inst->isBubble() &&
fu_inst->id.threadId == tid &&
!fu_inst->inLSQ &&
fu_inst->canEarlyIssue &&
inst->id.execSeqNum > fu_inst->instToWaitFor;
}
bool can_execute_fu_inst = inst->fuIndex == noCostFUIndex;
if (can_commit_insts && !can_transfer_mem_inst &&
inst->fuIndex != noCostFUIndex)
{
QueuedInst& fu_inst = funcUnits[inst->fuIndex]->front();
can_execute_fu_inst = !fu_inst.inst->isBubble() &&
fu_inst.inst->id == inst->id;
}
can_commit_insts = can_commit_insts &&
(can_transfer_mem_inst || can_execute_fu_inst);
}
}
if (can_commit_insts) {
commitPriority = tid;
return tid;
}
}
return InvalidThreadID;
}
inline ThreadID
Execute::getIssuingThread()
{
std::vector<ThreadID> priority_list;
switch (cpu.threadPolicy) {
case enums::SingleThreaded:
return 0;
case enums::RoundRobin:
priority_list = cpu.roundRobinPriority(issuePriority);
break;
case enums::Random:
priority_list = cpu.randomPriority();
break;
default:
panic("Invalid thread scheduling policy.");
}
for (auto tid : priority_list) {
if (getInput(tid)) {
issuePriority = tid;
return tid;
}
}
return InvalidThreadID;
}
void
Execute::drainResume()
{
DPRINTF(Drain, "MinorExecute drainResume\n");
for (ThreadID tid = 0; tid < cpu.numThreads; tid++) {
setDrainState(tid, NotDraining);
}
cpu.wakeupOnEvent(Pipeline::ExecuteStageId);
}
std::ostream &operator <<(std::ostream &os, Execute::DrainState state)
{
switch (state)
{
case Execute::NotDraining:
os << "NotDraining";
break;
case Execute::DrainCurrentInst:
os << "DrainCurrentInst";
break;
case Execute::DrainHaltFetch:
os << "DrainHaltFetch";
break;
case Execute::DrainAllInsts:
os << "DrainAllInsts";
break;
default:
os << "Drain-" << static_cast<int>(state);
break;
}
return os;
}
void
Execute::setDrainState(ThreadID thread_id, DrainState state)
{
DPRINTF(Drain, "setDrainState[%d]: %s\n", thread_id, state);
executeInfo[thread_id].drainState = state;
}
unsigned int
Execute::drain()
{
DPRINTF(Drain, "MinorExecute drain\n");
for (ThreadID tid = 0; tid < cpu.numThreads; tid++) {
if (executeInfo[tid].drainState == NotDraining) {
cpu.wakeupOnEvent(Pipeline::ExecuteStageId);
/* Go to DrainCurrentInst if we're between microops
* or waiting on an unbufferable memory operation.
* Otherwise we can go straight to DrainHaltFetch
*/
if (isInbetweenInsts(tid))
setDrainState(tid, DrainHaltFetch);
else
setDrainState(tid, DrainCurrentInst);
}
}
return (isDrained() ? 0 : 1);
}
bool
Execute::isDrained()
{
if (!lsq.isDrained())
return false;
for (ThreadID tid = 0; tid < cpu.numThreads; tid++) {
if (!inputBuffer[tid].empty() ||
!executeInfo[tid].inFlightInsts->empty()) {
return false;
}
}
return true;
}
Execute::~Execute()
{
for (unsigned int i = 0; i < numFuncUnits; i++)
delete funcUnits[i];
for (ThreadID tid = 0; tid < cpu.numThreads; tid++)
delete executeInfo[tid].inFlightInsts;
}
bool
Execute::instIsRightStream(MinorDynInstPtr inst)
{
return inst->id.streamSeqNum == executeInfo[inst->id.threadId].streamSeqNum;
}
bool
Execute::instIsHeadInst(MinorDynInstPtr inst)
{
bool ret = false;
if (!executeInfo[inst->id.threadId].inFlightInsts->empty())
ret = executeInfo[inst->id.threadId].inFlightInsts->front().inst->id == inst->id;
return ret;
}
MinorCPU::MinorCPUPort &
Execute::getDcachePort()
{
return lsq.getDcachePort();
}
} // namespace minor
} // namespace gem5
|
#pragma once
#include "BWAPI.h"
#ifdef BWAPI4
#include <chrono>
#elif BWAPI3
#include <boost/chrono.hpp>
#endif
#include <fstream>
#ifdef BWAPI4
enum struct WinReason { Eliminated, Crash };
enum struct Winner { Self, Enemy };
#define WR WinReason::
#define Wn Winner::
#define _NOEXCEPT noexcept
using SteadyClock = std::chrono::steady_clock;
using TimePoint = std::chrono::time_point<SteadyClock>;
using Duration = std::chrono::duration<float, std::milli>;
using BWAPIPlayer = BWAPI::Player;
using TournamentAction = BWAPI::Tournament::ActionID;
#elif BWAPI3
typedef enum { Eliminated, Crash } WinReason;
typedef enum { Self, Enemy } Winner;
#define WR
#define Wn
#define _NOEXCEPT
typedef boost::chrono::steady_clock SteadyClock;
typedef boost::chrono::time_point<SteadyClock> TimePoint;
typedef boost::chrono::duration<float, boost::milli> Duration;
typedef BWAPI::Player *BWAPIPlayer;
typedef int TournamentAction;
#endif
struct TournamentModuleManager;
extern TournamentModuleManager tm;
#ifdef WIN32
#include "Windows.h"
// Assumes no unicode, ASCII only
inline std::string Envvar(const char *var) {
const unsigned long bufSize = (1 << 15) - 1;
char buf[bufSize];
const unsigned ignore = GetEnvironmentVariableA(var, buf, bufSize);
return std::string(buf);
}
#endif
inline const char *BoolName(const bool b) { return b ? "true" : "false"; }
template <typename T>
void PrintVar(std::ofstream &os, const char *name, const T &var, const char *postfix = "");
template <>
inline void PrintVar<std::string>(std::ofstream &os, const char *name, const std::string &var, const char *postfix) {
os << "\t\"" << name << "\": \"" << var << "\"" << postfix << "\n";
}
template <typename T>
void PrintVar(std::ofstream &os, const char *name, const T &var, const char *postfix) {
os << "\t\"" << name << "\": " << var << postfix << "\n";
}
const std::string log_results_file = Envvar("TM_LOG_RESULTS");
const std::string log_frametimes_file = Envvar("TM_LOG_FRAMETIMES");
const bool allow_user_input = (Envvar("TM_ALLOW_USER_INPUT").compare("1") == 0);
const int speed_override = std::atoi(Envvar("TM_SPEED_OVERRIDE").c_str());
struct TournamentModuleManager {
TournamentModuleManager() : win_reason(WR Crash), winner(Wn Enemy), num_actions(0), minerals_gathered(0), minerals_spent(0), gas_gathered(0), gas_spent(0) {
}
~TournamentModuleManager() _NOEXCEPT {
try {
writeResults();
}
catch (...) {
}
}
void onReset() {
TournamentModuleManager();
frametimes.open(log_frametimes_file.c_str());
frametimes << "frame_count,frame_time_max,frame_time_avg,num_actions,minerals_gathered,minerals_spent,gas_gathered,gas_spent,supply_used,supply_total\n";
BWAPI::Broodwar->setLocalSpeed(speed_override);
lastFrameTimePoint = SteadyClock::now();
}
template <typename Action>
static bool onAction(Action action, void *parameter) {
switch (action) {
case BWAPI::Tournament::EnableFlag:
switch (*static_cast<int *>(parameter)) {
case BWAPI::Flag::CompleteMapInformation:
return false;
case BWAPI::Flag::UserInput:
return allow_user_input;
default:
return true;
}
case BWAPI::Tournament::LeaveGame:
case BWAPI::Tournament::SetLatCom:
case BWAPI::Tournament::SetTextSize:
case BWAPI::Tournament::SendText:
case BWAPI::Tournament::Printf:
case BWAPI::Tournament::SetCommandOptimizationLevel:
return true;
default:
return false;
}
}
void writeResults() const {
std::ofstream of(log_results_file.c_str());
if (of.is_open()) {
of << "{\n";
PrintVar(of, "is_winner", BoolName(winner == Wn Self), ",");
PrintVar(of, "is_crashed", BoolName(win_reason == WR Crash), ",");
PrintVar(of, "building_score", building_score, ",");
PrintVar(of, "kill_score", kill_score, ",");
PrintVar(of, "razing_score", razing_score, ",");
PrintVar(of, "unit_score", unit_score);
of << "}";
}
}
void onEnd(bool didWin) {
win_reason = WR Eliminated;
winner = didWin ? Wn Self : Wn Enemy;
}
void onFrame() {
BWAPIPlayer const self = BWAPI::Broodwar->self();
building_score = self->getBuildingScore();
kill_score = self->getKillScore();
razing_score = self->getRazingScore();
unit_score = self->getUnitScore();
const TimePoint now = SteadyClock::now();
const float lastFrameDuration = Duration(now - lastFrameTimePoint).count();
lastFrameTimePoint = now;
if (lastFrameDuration > maxFrameTime) {
maxFrameTime = lastFrameDuration;
}
frameTimeSum += lastFrameDuration;
// Check executed actions
for(BWAPI::Unitset::iterator it = BWAPI::Broodwar->self()->getUnits().begin(); it != BWAPI::Broodwar->self()->getUnits().end(); ++ it) {
int id = (*it)->getID();
std::map<int, BWAPI::Position>::const_iterator it2 = lastCommandPosition.find(id);
if (it2 != lastCommandPosition.end()) {
if (lastCommandType[id] != (*it)->getOrder().getID() || (*it)->getTargetPosition() != (*it2).second || ((*it)->getTarget() && (*it)->getTarget()->getID() != lastCommandTarget[id])) {
++num_actions;
}
}
lastCommandPosition[id] = (*it)->getTargetPosition();
if((*it)->getTarget())
lastCommandTarget[id] = (*it)->getTarget()->getID();
lastCommandType[id] = (*it)->getOrder().getID();
}
if (BWAPI::Broodwar->getFrameCount() % 20 == 19) {
// Write game data to file
frametimes
<< BWAPI::Broodwar->getFrameCount() + 1 << ","
<< maxFrameTime << ","
<< frameTimeSum / 20.f << ","
<< num_actions << ","
<< BWAPI::Broodwar->self()->gatheredMinerals() - minerals_gathered << ","
<< BWAPI::Broodwar->self()->spentMinerals() - minerals_spent << ","
<< BWAPI::Broodwar->self()->gatheredGas() - gas_gathered << ","
<< BWAPI::Broodwar->self()->spentGas() - gas_spent << ","
<< BWAPI::Broodwar->self()->supplyUsed() << ","
<< BWAPI::Broodwar->self()->supplyTotal()
<< "\n" << std::flush;
// Reset variables
frameTimeSum = .0f, maxFrameTime = .0f;
num_actions = 0;
minerals_gathered = BWAPI::Broodwar->self()->gatheredMinerals();
minerals_spent = BWAPI::Broodwar->self()->spentMinerals();
gas_gathered = BWAPI::Broodwar->self()->gatheredGas();
gas_spent = BWAPI::Broodwar->self()->spentGas();
}
}
WinReason win_reason;
Winner winner;
int building_score;
int kill_score;
int razing_score;
int unit_score;
std::ofstream frametimes;
TimePoint lastFrameTimePoint;
float maxFrameTime;
float frameTimeSum;
int num_actions;
int minerals_gathered;
int minerals_spent;
int gas_gathered;
int gas_spent;
std::map<int, BWAPI::Position> lastCommandPosition;
std::map<int, int> lastCommandTarget;
std::map<int, int> lastCommandType;
struct TournamentModule : BWAPI::TournamentModule {
bool onAction(TournamentAction action, void *parameter) override {
return tm.onAction(action, parameter);
}
void onFirstAdvertisement() override {}
};
TournamentModule *mod;
struct TournamentBot : BWAPI::AIModule {
void onStart() override { tm.onReset(); }
void onFrame() override { tm.onFrame(); }
void onEnd(bool didWin) override { tm.onEnd(didWin); }
};
TournamentBot *bot;
};
|
/*
This source file is part of GIMPACT Library.
For the latest info, see http://gimpact.sourceforge.net/
Copyright (c) 2007 Francisco Leon Najera. C.C. 80087371.
email: projectileman@yahoo.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "btGImpactConvexDecompositionShape.h"
#include "BulletCollision/CollisionShapes/btConvexHullShape.h"
#include "ConvexBuilder.h"
class GIM_ConvexDecomposition : public ConvexDecomposition::ConvexDecompInterface
{
protected:
btGImpactConvexDecompositionShape * m_compoundShape;
btAlignedObjectArray<btCollisionShape*> m_convexShapes;
public:
int mBaseCount;
int mHullCount;
bool m_transformSubShapes;
GIM_ConvexDecomposition(btGImpactConvexDecompositionShape * compoundShape,bool transformSubShapes)
{
mBaseCount = 0;
mHullCount = 0;
m_compoundShape = compoundShape;
m_transformSubShapes = transformSubShapes;
}
virtual ~GIM_ConvexDecomposition()
{
int i;
for (i=0;i<m_convexShapes.size();i++)
{
btCollisionShape* shape = m_convexShapes[i];
delete shape;
}
}
virtual void ConvexDecompResult(ConvexDecomposition::ConvexResult &result)
{
//calc centroid, to shift vertices around center of mass
btVector3 centroid(0,0,0);
btAlignedObjectArray<btVector3> vertices;
if(m_transformSubShapes)
{
//const unsigned int *src = result.mHullIndices;
for (unsigned int i=0; i<result.mHullVcount; i++)
{
btVector3 vertex(result.mHullVertices[i*3],result.mHullVertices[i*3+1],result.mHullVertices[i*3+2]);
centroid += vertex;
}
centroid *= 1.f/(float(result.mHullVcount) );
}
// collect vertices
for (unsigned int i=0; i<result.mHullVcount; i++)
{
btVector3 vertex(result.mHullVertices[i*3],result.mHullVertices[i*3+1],result.mHullVertices[i*3+2]);
if(m_transformSubShapes)
{
vertex -= centroid ;
}
vertices.push_back(vertex);
}
// build convex shape
btCollisionShape* convexShape = new btConvexHullShape(
&(vertices[0].getX()),vertices.size(),sizeof(btVector3));
m_convexShapes.push_back(convexShape);
convexShape->setMargin(m_compoundShape->getMargin());
if(m_transformSubShapes)
{
btTransform trans;
trans.setIdentity();
trans.setOrigin(centroid);
// add convex shape
m_compoundShape->addChildShape(trans,convexShape);
}
else
{
btTransform trans;
trans.setIdentity();
//trans.setOrigin(centroid);
// add convex shape
m_compoundShape->addChildShape(trans,convexShape);
//m_compoundShape->addChildShape(convexShape);
}
}
void processDecomposition(int part)
{
btGImpactMeshShapePart::TrimeshPrimitiveManager * trimeshInterface =
m_compoundShape->getTrimeshInterface(part);
trimeshInterface->lock();
//collect vertices
btAlignedObjectArray<float> vertices;
vertices.reserve(trimeshInterface->get_vertex_count()*3);
for(int vi = 0;vi<trimeshInterface->get_vertex_count();vi++)
{
btVector3 vec;
trimeshInterface->get_vertex(vi,vec);
vertices.push_back(vec[0]);
vertices.push_back(vec[1]);
vertices.push_back(vec[2]);
}
//collect indices
btAlignedObjectArray<unsigned int> indices;
indices.reserve(trimeshInterface->get_primitive_count()*3);
for(int i = 0;i<trimeshInterface->get_primitive_count();i++)
{
int i0, i1,i2;
trimeshInterface->get_indices(i,i0,i1,i2);
indices.push_back(i0);
indices.push_back(i1);
indices.push_back(i2);
}
trimeshInterface->unlock();
unsigned int depth = 5;
float cpercent = 5;
float ppercent = 15;
unsigned int maxv = 16;
float skinWidth = 0.0f;
ConvexDecomposition::DecompDesc desc;
desc.mVcount = trimeshInterface->get_vertex_count();
desc.mVertices = &vertices[0];
desc.mTcount = trimeshInterface->get_primitive_count();
desc.mIndices = &indices[0];
desc.mDepth = depth;
desc.mCpercent = cpercent;
desc.mPpercent = ppercent;
desc.mMaxVertices = maxv;
desc.mSkinWidth = skinWidth;
desc.mCallback = this;
//convexDecomposition.performConvexDecomposition(desc);
ConvexBuilder cb(desc.mCallback);
cb.process(desc);
}
};
void btGImpactConvexDecompositionShape::buildConvexDecomposition(bool transformSubShapes)
{
m_decomposition = new GIM_ConvexDecomposition(this,transformSubShapes);
int part_count = m_trimeshInterfaces.size();
for (int i = 0;i<part_count ;i++ )
{
m_decomposition->processDecomposition(i);
}
postUpdate();
}
btGImpactConvexDecompositionShape::~btGImpactConvexDecompositionShape()
{
delete m_decomposition;
}
void btGImpactConvexDecompositionShape::processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const
{
int part_count = m_trimeshInterfaces.size();
for (int part = 0;part<part_count ;part++ )
{
void * ptr = (void * )&m_trimeshInterfaces[part];
btGImpactMeshShapePart::TrimeshPrimitiveManager * trimeshInterface =
static_cast<btGImpactMeshShapePart::TrimeshPrimitiveManager *>(ptr);
trimeshInterface->lock();
btPrimitiveTriangle triangle;
int i = trimeshInterface->get_primitive_count();
while(i--)
{
trimeshInterface->get_primitive_triangle(i,triangle);
callback->processTriangle(triangle.m_vertices,part,i);
}
trimeshInterface->unlock();
}
}
|
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include <luabind/luabind.hpp>
#include <luabind/class.hpp>
#include <luabind/function.hpp>
#include <luabind/object.hpp>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
struct glut_constants {};
struct gl_constants {};
using luabind::object;
namespace glut_bindings
{
object displayfunc;
void displayfunc_callback()
{
displayfunc();
}
void set_displayfunc(object const& fun)
{
glutDisplayFunc(&displayfunc_callback);
displayfunc = fun;
}
object idlefunc;
void idlefunc_callback()
{
idlefunc();
}
void set_idlefunc(object const& fun)
{
glutIdleFunc(&idlefunc_callback);
idlefunc = fun;
}
object reshapefunc;
void reshapefunc_callback(int w, int h)
{
reshapefunc(w, h);
}
void set_reshapefunc(object const& fun)
{
reshapefunc = fun;
}
object keyboardfunc;
void keyboardfunc_callback(unsigned char key, int x, int y)
{
keyboardfunc(key, x, y);
}
void set_keyboardfunc(object const& fun)
{
glutKeyboardFunc(&keyboardfunc_callback);
keyboardfunc = fun;
}
object mousefunc;
void mousefunc_callback(int button, int state, int x, int y)
{
mousefunc(button, state, x, y);
}
void set_mousefunc(object const& fun)
{
mousefunc = fun;
}
}
void bind_glut(lua_State* L)
{
using namespace luabind;
using namespace glut_bindings;
open(L);
module(L)
[
def("glutInitWindowSize", &glutInitWindowSize),
def("glutInitWindowPosition", &glutInitWindowPosition),
def("glutInitDisplayMode", &glutInitDisplayMode),
class_<glut_constants>("glut")
.enum_("constants")
[
value("RGB", GLUT_RGB),
value("RGBA", GLUT_RGBA),
value("INDEX", GLUT_INDEX),
value("SINGLE", GLUT_SINGLE),
value("DOUBLE", GLUT_DOUBLE),
value("DEPTH", GLUT_DEPTH),
value("STENCIL", GLUT_STENCIL),
value("LEFT_BUTTON", GLUT_LEFT_BUTTON),
value("MIDDLE_BUTTON", GLUT_MIDDLE_BUTTON),
value("RIGHT_BUTTON", GLUT_RIGHT_BUTTON),
value("UP", GLUT_UP),
value("DOWN", GLUT_DOWN),
value("ELAPSED_TIME", GLUT_ELAPSED_TIME)
],
def("glutCreateWindow", &glutCreateWindow),
def("glutDestroyWindow", &glutDestroyWindow),
def("glutFullScreen", &glutFullScreen),
def("glutDisplayFunc", &set_displayfunc),
def("glutKeyboardFunc", &set_keyboardfunc),
def("glutReshapeFunc", &set_reshapefunc),
def("glutIdleFunc", &set_idlefunc),
def("glutMainLoop", &glutMainLoop),
def("glutSwapBuffers", &glutSwapBuffers),
def("glutGet", &glutGet),
def("glutSolidSphere", &glutSolidSphere),
def("glutWireSphere", &glutWireSphere),
def("glutWireTeapot", &glutWireTeapot),
def("glutSolidTeapot", &glutSolidTeapot),
// -- opengl
class_<gl_constants>("gl")
.enum_("constants")
[
value("COLOR_BUFFER_BIT", GL_COLOR_BUFFER_BIT),
value("DEPTH_BUFFER_BIT", GL_DEPTH_BUFFER_BIT),
value("TRIANGLES", GL_TRIANGLES),
value("MODELVIEW", GL_MODELVIEW),
value("PROJECTION", GL_PROJECTION)
],
def("glBegin", &glBegin),
def("glVertex3", &glVertex3f),
def("glEnd", &glEnd),
def("glClear", &glClear),
def("glPushMatrix", &glPushMatrix),
def("glPopMatrix", &glPopMatrix),
def("glRotate", &glRotatef),
def("glColor3", &glColor3f),
def("glColor4", &glColor4f),
def("glMatrixMode", &glMatrixMode),
def("glLoadIdentity", &glLoadIdentity),
def("glViewport", &glViewport),
def("glTranslate", &glTranslatef),
// -- glu
def("gluPerspective", &gluPerspective)
];
}
int main(int argc, char* argv[])
{
lua_State* L = lua_open();
lua_baselibopen(L);
lua_mathlibopen(L);
bind_glut(L);
glutInit (&argc, argv);
lua_dofile(L, "glut_bindings.lua");
lua_close(L);
return 0;
}
|
// Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2018-2020 The DAPS Project developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "addrman.h"
#include "masternode.h"
#include "masternodeconfig.h"
#include "masternodeman.h"
#include "protocol.h"
//
// Bootup the Masternode, look for a 1000000 DAPS input and register on the network
//
void CActiveMasternode::ManageStatus()
{
std::string errorMessage;
if (!fMasterNode) return;
if (fDebug) LogPrint("masternode", "CActiveMasternode::ManageStatus() - Begin\n");
//need correct blocks to send ping
if (Params().NetworkID() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {
status = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;
LogPrint("masternode", "CActiveMasternode::ManageStatus() - %s\n", GetStatus());
return;
}
if (status == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) status = ACTIVE_MASTERNODE_INITIAL;
if (status == ACTIVE_MASTERNODE_INITIAL) {
CMasternode* pmn;
pmn = mnodeman.Find(pubKeyMasternode);
if (pmn != NULL) {
pmn->Check();
if (pmn->IsEnabled() && pmn->protocolVersion == PROTOCOL_VERSION) EnableHotColdMasterNode(pmn->vin, pmn->addr);
}
}
if (status != ACTIVE_MASTERNODE_STARTED) {
// Set defaults
status = ACTIVE_MASTERNODE_NOT_CAPABLE;
notCapableReason = "";
if (pwalletMain->IsLocked()) {
notCapableReason = "Wallet is locked.";
LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
return;
}
if (pwalletMain->GetBalance() == 0) {
notCapableReason = "Hot node, waiting for remote activation.";
LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
return;
}
if (strMasterNodeAddr.empty()) {
if (!GetLocal(service)) {
notCapableReason = "Can't detect external address. Please use the masternodeaddr configuration option.";
LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
return;
}
} else {
service = CService(strMasterNodeAddr);
}
// The service needs the correct default port to work properly
if(!CMasternodeBroadcast::CheckDefaultPort(strMasterNodeAddr, errorMessage, "CActiveMasternode::ManageStatus()"))
return;
LogPrintf("CActiveMasternode::ManageStatus() - Checking inbound connection to '%s'\n", service.ToString());
CNode* pnode = ConnectNode((CAddress)service, NULL, false);
if (!pnode) {
notCapableReason = "Could not connect to " + service.ToString();
LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
return;
}
pnode->Release();
// Choose coins to use
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
if (GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress)) {
if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) {
status = ACTIVE_MASTERNODE_INPUT_TOO_NEW;
notCapableReason = strprintf("%s - %d confirmations", GetStatus(), GetInputAge(vin));
LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason);
return;
}
LOCK(pwalletMain->cs_wallet);
pwalletMain->LockCoin(vin.prevout);
// send to all nodes
CPubKey pubKeyMasternode;
CKey keyMasternode;
if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) {
notCapableReason = "Error upon calling SetKey: " + errorMessage;
LogPrintf("Register::ManageStatus() - %s\n", notCapableReason);
return;
}
CMasternodeBroadcast mnb;
if (!CreateBroadcast(vin, service, keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage, mnb)) {
notCapableReason = "Error on Register: " + errorMessage;
LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason);
return;
}
//send to all peers
LogPrintf("CActiveMasternode::ManageStatus() - Relay broadcast vin = %s\n", vin.ToString());
mnb.Relay();
LogPrintf("CActiveMasternode::ManageStatus() - Is capable master node!\n");
status = ACTIVE_MASTERNODE_STARTED;
return;
} else {
notCapableReason = "Could not find suitable coins!";
LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason);
return;
}
}
//send to all peers
if (!SendMasternodePing(errorMessage)) {
LogPrintf("CActiveMasternode::ManageStatus() - Error on Ping: %s\n", errorMessage);
}
}
std::string CActiveMasternode::GetStatus()
{
switch (status) {
case ACTIVE_MASTERNODE_INITIAL:
return "Node just started, not yet activated";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS:
return "Sync in progress. Must wait until sync is complete to start Masternode";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW:
return strprintf("Masternode input must have at least %d confirmations", MASTERNODE_MIN_CONFIRMATIONS);
case ACTIVE_MASTERNODE_NOT_CAPABLE:
return "Not capable masternode: " + notCapableReason;
case ACTIVE_MASTERNODE_STARTED:
return "Masternode successfully started";
default:
return "unknown";
}
}
bool CActiveMasternode::SendMasternodePing(std::string& errorMessage)
{
if (status != ACTIVE_MASTERNODE_STARTED) {
errorMessage = "Masternode is not in a running status";
return false;
}
CPubKey pubKeyMasternode;
CKey keyMasternode;
if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) {
errorMessage = strprintf("Error upon calling SetKey: %s\n", errorMessage);
return false;
}
std::string stl(vin.masternodeStealthAddress.begin(), vin.masternodeStealthAddress.end());
CMasternodePing mnp(vin);
if (!mnp.Sign(keyMasternode, pubKeyMasternode)) {
errorMessage = "Couldn't sign Masternode Ping";
return false;
}
// Update lastPing for our masternode in Masternode list
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL) {
if (pmn->IsPingedWithin(MASTERNODE_PING_SECONDS, mnp.sigTime)) {
errorMessage = "Too early to send Masternode Ping";
return false;
}
pmn->lastPing = mnp;
mnodeman.mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp));
//mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it
CMasternodeBroadcast mnb(*pmn);
uint256 hash = mnb.GetHash();
if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = mnp;
mnp.Relay();
// for migration purposes ping our node on old masternodes network too
std::string retErrorMessage;
std::vector<unsigned char> vchMasterNodeSignature;
int64_t masterNodeSignatureTime = GetAdjustedTime();
std::string ss = service.ToString();
bool val = false;
CDataStream ser(SER_NETWORK, PROTOCOL_VERSION);
ser << ss << masterNodeSignatureTime << val;
std::string strMessage = HexStr(ser.begin(), ser.end());
if (!obfuScationSigner.SignMessage(strMessage, retErrorMessage, vchMasterNodeSignature, keyMasternode)) {
errorMessage = "dseep sign message failed: " + retErrorMessage;
return false;
}
if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchMasterNodeSignature, strMessage, retErrorMessage)) {
errorMessage = "dseep verify message failed: " + retErrorMessage;
return false;
}
LogPrint("masternode", "dseep - relaying from active mn, %s \n", vin.ToString().c_str());
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
pnode->PushMessage("dseep", vin, vchMasterNodeSignature, masterNodeSignatureTime, false);
/*
* END OF "REMOVE"
*/
return true;
} else {
// Seems like we are trying to send a ping while the Masternode is not registered in the network
errorMessage = "Obfuscation Masternode List doesn't include our Masternode, shutting down Masternode pinging service! " + vin.ToString();
status = ACTIVE_MASTERNODE_NOT_CAPABLE;
notCapableReason = errorMessage;
return false;
}
}
bool CActiveMasternode::CreateBroadcast(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& errorMessage, CMasternodeBroadcast &mnb, bool fOffline)
{
CTxIn vin;
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
CPubKey pubKeyMasternode;
CKey keyMasternode;
//need correct blocks to send ping
if (!fOffline && !masternodeSync.IsBlockchainSynced()) {
errorMessage = "Sync in progress. Must wait until sync is complete to start Masternode";
LogPrintf("CActiveMasternode::CreateBroadcast() - %s\n", errorMessage);
return false;
}
if (!obfuScationSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) {
errorMessage = strprintf("Can't find keys for masternode %s - %s", strService, errorMessage);
LogPrintf("CActiveMasternode::CreateBroadcast() - %s\n", errorMessage);
return false;
}
if (!GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress, strTxHash, strOutputIndex)) {
errorMessage = strprintf("Could not allocate vin %s:%s for masternode %s", strTxHash, strOutputIndex, strService);
LogPrintf("CActiveMasternode::CreateBroadcast() - %s\n", errorMessage);
return false;
}
CService service = CService(strService);
// The service needs the correct default port to work properly
if(!CMasternodeBroadcast::CheckDefaultPort(strService, errorMessage, "CActiveMasternode::CreateBroadcast()"))
return false;
addrman.Add(CAddress(service), CNetAddr("127.0.0.1"), 2 * 60 * 60);
return CreateBroadcast(vin, CService(strService), keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage, mnb);
}
bool CActiveMasternode::CreateBroadcast(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyMasternode, CPubKey pubKeyMasternode, std::string& errorMessage, CMasternodeBroadcast &mnb)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
CMasternodePing mnp(vin);
if (!mnp.Sign(keyMasternode, pubKeyMasternode)) {
errorMessage = strprintf("Failed to sign ping, vin: %s", vin.ToString());
LogPrintf("CActiveMasternode::CreateBroadcast() - %s\n", errorMessage);
mnb = CMasternodeBroadcast();
return false;
}
mnb = CMasternodeBroadcast(service, vin, pubKeyCollateralAddress, pubKeyMasternode, PROTOCOL_VERSION);
mnb.lastPing = mnp;
if (!mnb.Sign(keyCollateralAddress)) {
errorMessage = strprintf("Failed to sign broadcast, vin: %s", vin.ToString());
LogPrintf("CActiveMasternode::CreateBroadcast() - %s\n", errorMessage);
mnb = CMasternodeBroadcast();
return false;
}
// for migration purposes inject our node in old masternodes' list too
std::string retErrorMessage;
std::vector<unsigned char> vchMasterNodeSignature;
int64_t masterNodeSignatureTime = GetAdjustedTime();
std::string donationAddress = "";
int donationPercantage = 0;
std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end());
std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end());
std::string ss = service.ToString();
CDataStream ser(SER_NETWORK, PROTOCOL_VERSION);
ser << ss << masterNodeSignatureTime << pubKeyCollateralAddress << pubKeyMasternode << PROTOCOL_VERSION;
/*uint256 h = Hash(BEGIN(ss), END(ss),
BEGIN(masterNodeSignatureTime), END(masterNodeSignatureTime),
pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end(),
pubKeyMasternode.begin(), pubKeyMasternode.end(),
BEGIN(PROTOCOL_VERSION), END(PROTOCOL_VERSION));*/
std::string strMessage = HexStr(ser.begin(), ser.end());
if (!obfuScationSigner.SignMessage(strMessage, retErrorMessage, vchMasterNodeSignature, keyCollateralAddress)) {
errorMessage = "dsee sign message failed: " + retErrorMessage;
LogPrintf("CActiveMasternode::Register() - Error: %s\n", errorMessage.c_str());
return false;
}
if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, vchMasterNodeSignature, strMessage, retErrorMessage)) {
errorMessage = "dsee verify message failed: " + retErrorMessage;
LogPrintf("CActiveMasternode::Register() - Error: %s\n", errorMessage.c_str());
return false;
}
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
pnode->PushMessage("dsee", vin, service, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyMasternode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION, donationAddress, donationPercantage);
return true;
}
bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey)
{
return GetMasterNodeVin(vin, pubkey, secretKey, "", "");
}
bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
// Find possible candidates
TRY_LOCK(pwalletMain->cs_wallet, fWallet);
if (!fWallet) return false;
std::vector<COutput> possibleCoins = SelectCoinsMasternode();
COutput* selectedOutput;
// Find the vin
if (!strTxHash.empty()) {
// Let's find it
uint256 txHash(strTxHash);
int outputIndex;
try {
outputIndex = std::stoi(strOutputIndex.c_str());
} catch (const std::exception& e) {
LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what());
return false;
}
bool found = false;
for (COutput& out : possibleCoins) {
if (out.tx->GetHash() == txHash && out.i == outputIndex) {
selectedOutput = &out;
found = true;
break;
}
}
if (!found) {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate valid vin\n");
return false;
}
} else {
// No output specified, Select the first one
if (possibleCoins.size() > 0) {
selectedOutput = &possibleCoins[0];
} else {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate specified vin from possible list\n");
return false;
}
}
// At this point we have a selected output, retrieve the associated info
return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey);
}
// Extract Masternode vin information from output
bool CActiveMasternode::GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
CScript pubScript;
vin = CTxIn(out.tx->GetHash(), out.i);
pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
pwalletMain->findCorrespondingPrivateKey(out.tx->vout[out.i], secretKey);
CTxDestination address1;
ExtractDestination(pubScript, address1);
CBitcoinAddress address2(address1);
CPubKey sharedSec;
pwalletMain->computeSharedSec(*out.tx, out.tx->vout[out.i], sharedSec);
vin.encryptionKey.clear();
std::copy(sharedSec.begin(), sharedSec.end(), std::back_inserter(vin.encryptionKey));
CKeyID keyID;
if (!address2.GetKeyID(keyID)) {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Address does not refer to a key\n");
return false;
}
if (!pwalletMain->GetKey(keyID, secretKey)) {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Private key for address is not known\n");
return false;
}
pubkey = secretKey.GetPubKey();
std::string msa;
pwalletMain->ComputeStealthPublicAddress("masteraccount", msa);
std::copy(msa.begin(), msa.end(), std::back_inserter(vin.masternodeStealthAddress));
if (!pwalletMain->generateKeyImage(out.tx->vout[out.i].scriptPubKey, vin.keyImage)) {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Failed to generate key image\n");
return false;
}
if (!pwalletMain->MakeShnorrSignatureTxIn(vin, GetTxInSignatureHash(vin))) {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Failed to make Shnorr signature\n");
return false;
}
//test verification masternode broadcast
if (!VerifyShnorrKeyImageTxIn(vin, GetTxInSignatureHash(vin))) {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Failed to verify Shnorr signature\n");
return false;
}
//Test the commitment and decoded value, if everything goes right, other nodes can verify it as well
COutPoint prevout = vin.prevout;
CTransaction prev;
uint256 bh;
if (!GetTransaction(prevout.hash, prev, bh, true)) {
LogPrint("masternode","dsee - failed to read transaction hash %s\n", vin.prevout.hash.ToString());
return false;
}
CTxOut txout = prev.vout[prevout.n];
CPubKey sharedSec1(vin.encryptionKey.begin(), vin.encryptionKey.end());
CKey mask;
CAmount amount;
ECDHInfo::Decode(txout.maskValue.mask.begin(), txout.maskValue.amount.begin(), sharedSec1, mask, amount);
std::vector<unsigned char> commitment;
CWallet::CreateCommitment(mask.begin(), amount, commitment);
if (commitment != txout.commitment) {
LogPrintf("dsee - decoded masternode collateralization not match %s\n", vin.prevout.hash.ToString());
return false;
}
if (amount != 1000000 * COIN) {
LogPrintf("dsee - masternode collateralization not equal to 1M %s\n", vin.prevout.hash.ToString());
return false;
}
return true;
}
// get all possible outputs for running Masternode
vector<COutput> CActiveMasternode::SelectCoinsMasternode()
{
std::vector<COutput> vCoins;
std::vector<COutput> filteredCoins;
std::vector<COutPoint> confLockedCoins;
// Temporary unlock MN coins from masternode.conf
if (GetBoolArg("-mnconflock", true)) {
uint256 mnTxHash;
{
LOCK2(cs_main, pwalletMain->cs_wallet);
for (CMasternodeConfig::CMasternodeEntry mne : masternodeConfig.getEntries()) {
mnTxHash.SetHex(mne.getTxHash());
int nIndex;
if(!mne.castOutputIndex(nIndex))
continue;
COutPoint outpoint = COutPoint(mnTxHash, nIndex);
confLockedCoins.push_back(outpoint);
pwalletMain->UnlockCoin(outpoint);
}
}
}
// Retrieve all possible outputs
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->AvailableCoins(vCoins, true, NULL, false, AvailableCoinsType::ONLY_1000000);
// Lock MN coins from masternode.conf back if they where temporary unlocked
if (!confLockedCoins.empty()) {
for (COutPoint outpoint : confLockedCoins)
pwalletMain->LockCoin(outpoint);
}
// Filter
for (const COutput& out : vCoins) {
if (pwalletMain->getCTxOutValue(*out.tx, out.tx->vout[out.i]) == 1000000 * COIN) { //exactly
filteredCoins.push_back(out);
}
}
}
return filteredCoins;
}
// when starting a Masternode, this can enable to run as a hot wallet with no funds
bool CActiveMasternode::EnableHotColdMasterNode(CTxIn& newVin, CService& newService)
{
if (!fMasterNode) return false;
status = ACTIVE_MASTERNODE_STARTED;
//The values below are needed for signing mnping messages going forward
vin = newVin;
service = newService;
LogPrintf("CActiveMasternode::EnableHotColdMasterNode() - Enabled! You may shut down the cold daemon.\n");
return true;
}
|
#include "AliAnalysisTaskSE.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliAODEvent.h"
#include "AliStack.h"
#include "AliPID.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliAODTracklets.h"
#include "AliAODTrack.h"
#include "AliESDtrack.h"
#include "AliESDVertex.h"
#include <AliAODMCParticle.h>
#include <TSystem.h>
#include <TTree.h>
#include <TTree.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TChain.h>
#include "AliPIDResponse.h"
#include "AliAnalysisTaskCheckAODTracks.h"
/**************************************************************************
* Copyright(c) 1998-2012, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//*************************************************************************
// Implementation of class AliAnalysisTaskCheckAODTracks
// AliAnalysisTaskSE to extract QA and performance histos for tracks
//
//
// Authors:
// F. Prino, prino@to.infn.it
//
//*************************************************************************
ClassImp(AliAnalysisTaskCheckAODTracks)
//______________________________________________________________________________
AliAnalysisTaskCheckAODTracks::AliAnalysisTaskCheckAODTracks() :
AliAnalysisTaskSE("ITSsa resolution"),
fOutput{nullptr},
fHistNEvents{nullptr},
fHistNTracks{nullptr},
fHistNTracksVsTPCclusters{nullptr},
fHistNTracksVsITSclusters{nullptr},
fHistITSclustersVsTPCclusters{nullptr},
fHistNTracksFB4VsTPCclusters{nullptr},
fHistNTracksFB4VsITSclusters{nullptr},
fHistFilterBits{nullptr},
fHistITSnClusTPCsel{nullptr},
fHistITSnClusITSsa{nullptr},
fHistITSnClusITSPureSA{nullptr},
fHistITSCluInLayTPCsel{nullptr},
fHistITSCluInLayITSsa{nullptr},
fHistITSCluInLayITSPureSA{nullptr},
fHistNtracksFb4VsV0befEvSel{nullptr},
fHistNtracksFb5VsV0befEvSel{nullptr},
fHistNtracksFb4VsV0aftEvSel{nullptr},
fHistNtracksFb5VsV0aftEvSel{nullptr},
fHistEtaPhiPtTPCsel{nullptr},
fHistEtaPhiPtTPCselITSref{nullptr},
fHistEtaPhiPtTPCselSPDany{nullptr},
fHistEtaPhiPtPosChargeTPCsel{nullptr},
fHistEtaPhiPtPosChargeTPCselITSref{nullptr},
fHistEtaPhiPtPosChargeTPCselSPDany{nullptr},
fHistEtaPhiPtNegChargeTPCsel{nullptr},
fHistEtaPhiPtNegChargeTPCselITSref{nullptr},
fHistEtaPhiPtNegChargeTPCselSPDany{nullptr},
fHistEtaPhiPtTPCselTOFbc{nullptr},
fHistEtaPhiPtTPCselITSrefTOFbc{nullptr},
fHistEtaPhiPtTPCselSPDanyTOFbc{nullptr},
fHistEtaPhiPtTPCselSPDanyTOFpid{nullptr},
fHistTPCchi2PerClusPhiPtTPCsel{nullptr},
fHistTPCchi2PerClusPhiPtTPCselITSref{nullptr},
fHistTPCchi2PerClusPhiPtTPCselSPDany{nullptr},
fHistImpParXYPtMulPionTPCselSPDany{nullptr},
fHistImpParXYPtMulKaonTPCselSPDany{nullptr},
fHistImpParXYPtMulProtonTPCselSPDany{nullptr},
fHistPtResidVsPtTPCselAll{nullptr},
fHistPtResidVsPtTPCselITSrefAll{nullptr},
fHistPtResidVsPtTPCsel{nullptr},
fHistPtResidVsPtTPCselITSref{nullptr},
fHistOneOverPtResidVsPtTPCselAll{nullptr},
fHistOneOverPtResidVsPtTPCselITSrefAll{nullptr},
fHistOneOverPtResidVsPtTPCsel{nullptr},
fHistOneOverPtResidVsPtTPCselITSref{nullptr},
fHistEtaPhiPtTPCselITSrefGood{nullptr},
fHistEtaPhiPtTPCselITSrefFake{nullptr},
fHistImpParXYPtMulTPCselSPDanyGood{nullptr},
fHistImpParXYPtMulTPCselSPDanyFake{nullptr},
fHistImpParXYPtMulTPCselSPDanyPrim{nullptr},
fHistImpParXYPtMulTPCselSPDanySecDec{nullptr},
fHistImpParXYPtMulTPCselSPDanySecMat{nullptr},
fHistInvMassK0s{nullptr},
fHistInvMassLambda{nullptr},
fHistInvMassAntiLambda{nullptr},
fFillTree(kFALSE),
fTrackTree{nullptr},
fTreeVarFloat{nullptr},
fTreeVarInt{nullptr},
fTrCutsTPC{nullptr},
fMinNumOfTPCPIDclu(0),
fUsePhysSel(kTRUE),
fTriggerMask(AliVEvent::kAnyINT),
fNEtaBins(10),
fNPhiBins(144),
fNPtBins(100),
fMinPt(0.),
fMaxPt(25.),
fMaxMult(500.),
fReadMC{kFALSE},
fUseMCId{kFALSE}
{
//
fTrCutsTPC = new AliESDtrackCuts("esdtrackCutsTPC");
fTrCutsTPC->SetMinNCrossedRowsTPC(50);
fTrCutsTPC->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
fTrCutsTPC->SetEtaRange(-0.8,0.8);
// fTrCutsTPC->SetCutGeoNcrNcl(2., 130., 1.5, 0.0, 0.0);
// fTrCutsTPC->SetCutOutDistortedRegionsTPC(kTRUE);
fTrCutsTPC->SetMaxChi2PerClusterTPC(4);
fTrCutsTPC->SetAcceptKinkDaughters(kFALSE);
fTrCutsTPC->SetRequireTPCRefit(kTRUE);
fTrCutsTPC->SetDCAToVertex2D(kFALSE);
fTrCutsTPC->SetRequireSigmaToVertex(kFALSE);
// fTrCutsTPC->SetMaxChi2TPCConstrainedGlobal(36);
// fTrCutsTPC->SetMaxChi2PerClusterITS(36);
fTrCutsTPC->SetMaxDCAToVertexXY(2.);
fTrCutsTPC->SetMaxDCAToVertexZ(3.);
for(Int_t jb=0; jb<kNumOfFilterBits; jb++){
fHistImpParXYPtMulFiltBit[jb]=0x0;
fHistEtaPhiPtFiltBit[jb]=0x0;
fHistITScluPtFiltBit[jb]=0x0;
fHistSPDcluPtFiltBit[jb]=0x0;
fHistTPCcluPtFiltBit[jb]=0x0;
fHistTPCcrrowsPtFiltBit[jb]=0x0;
fHistTPCCrowOverFindPtFiltBit[jb]=0x0;
fHistTPCChi2ndfPtFiltBit[jb]=0x0;
fHistChi2TPCConstrVsGlobPtFiltBit[jb]=0x0;
}
DefineInput(0, TChain::Class());
DefineOutput(1, TList::Class());
DefineOutput(2, TTree::Class());
}
//___________________________________________________________________________
AliAnalysisTaskCheckAODTracks::~AliAnalysisTaskCheckAODTracks(){
//
if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) return;
if(fOutput && !fOutput->IsOwner()){
delete fHistNEvents;
delete fHistNTracks;
delete fHistNTracksVsTPCclusters;
delete fHistNTracksVsITSclusters;
delete fHistITSclustersVsTPCclusters;
delete fHistNTracksFB4VsTPCclusters;
delete fHistNTracksFB4VsITSclusters;
delete fHistFilterBits;
delete fHistITSnClusTPCsel;
delete fHistITSnClusITSsa;
delete fHistITSnClusITSPureSA;
delete fHistITSCluInLayTPCsel;
delete fHistITSCluInLayITSsa;
delete fHistITSCluInLayITSPureSA;
delete fHistNtracksFb4VsV0befEvSel;
delete fHistNtracksFb5VsV0befEvSel;
delete fHistNtracksFb4VsV0aftEvSel;
delete fHistNtracksFb5VsV0aftEvSel;
delete fHistEtaPhiPtTPCsel;
delete fHistEtaPhiPtTPCselITSref;
delete fHistEtaPhiPtTPCselSPDany;
delete fHistEtaPhiPtPosChargeTPCsel;
delete fHistEtaPhiPtPosChargeTPCselITSref;
delete fHistEtaPhiPtPosChargeTPCselSPDany;
delete fHistEtaPhiPtNegChargeTPCsel;
delete fHistEtaPhiPtNegChargeTPCselITSref;
delete fHistEtaPhiPtNegChargeTPCselSPDany;
delete fHistEtaPhiPtTPCselTOFbc;
delete fHistEtaPhiPtTPCselITSrefTOFbc;
delete fHistEtaPhiPtTPCselSPDanyTOFbc;
delete fHistEtaPhiPtTPCselSPDanyTOFpid;
delete fHistTPCchi2PerClusPhiPtTPCsel;
delete fHistTPCchi2PerClusPhiPtTPCselITSref;
delete fHistTPCchi2PerClusPhiPtTPCselSPDany;
delete fHistImpParXYPtMulPionTPCselSPDany;
delete fHistImpParXYPtMulKaonTPCselSPDany;
delete fHistImpParXYPtMulProtonTPCselSPDany;
delete fHistPtResidVsPtTPCselAll;
delete fHistPtResidVsPtTPCselITSrefAll;
delete fHistOneOverPtResidVsPtTPCselAll;
delete fHistOneOverPtResidVsPtTPCselITSrefAll;
for (int iS = 0; iS < AliPID::kSPECIESC;++iS) {
delete fHistPtResidVsPtTPCsel[iS];
delete fHistPtResidVsPtTPCselITSref[iS];
delete fHistOneOverPtResidVsPtTPCsel[iS];
delete fHistOneOverPtResidVsPtTPCselITSref[iS];
}
delete fHistEtaPhiPtTPCselITSrefGood;
delete fHistEtaPhiPtTPCselITSrefFake;
delete fHistImpParXYPtMulTPCselSPDanyGood;
delete fHistImpParXYPtMulTPCselSPDanyFake;
delete fHistImpParXYPtMulTPCselSPDanyPrim;
delete fHistImpParXYPtMulTPCselSPDanySecDec;
delete fHistImpParXYPtMulTPCselSPDanySecMat;
delete fHistInvMassK0s;
delete fHistInvMassLambda;
delete fHistInvMassAntiLambda;
for(Int_t jb=0; jb<kNumOfFilterBits; jb++){
delete fHistImpParXYPtMulFiltBit[jb];
delete fHistEtaPhiPtFiltBit[jb];
delete fHistITScluPtFiltBit[jb];
delete fHistSPDcluPtFiltBit[jb];
delete fHistTPCcluPtFiltBit[jb];
delete fHistTPCcrrowsPtFiltBit[jb];
delete fHistTPCCrowOverFindPtFiltBit[jb];
delete fHistTPCChi2ndfPtFiltBit[jb];
delete fHistChi2TPCConstrVsGlobPtFiltBit[jb];
}
delete fTrackTree;
}
delete fOutput;
delete fTrCutsTPC;
delete [] fTreeVarFloat;
delete [] fTreeVarInt;
}
//___________________________________________________________________________
void AliAnalysisTaskCheckAODTracks::UserCreateOutputObjects() {
// create output histos
fOutput = new TList();
fOutput->SetOwner();
fOutput->SetName("OutputHistos");
fTrackTree = new TTree("trackTree", "Tree for analysis");
TString floatVarName[kNumOfFloatVar];
fTreeVarFloat = new Float_t[kNumOfFloatVar];
floatVarName[0]="xvert";
floatVarName[1]="yvert";
floatVarName[2]="zvert";
floatVarName[3]="px";
floatVarName[4]="py";
floatVarName[5]="pz";
floatVarName[6]="pt";
floatVarName[7]="p";
floatVarName[8]="eta";
floatVarName[9]="phi";
floatVarName[10]="d0xy";
floatVarName[11]="d0z";
floatVarName[12]="chi2clustpc";
floatVarName[13]="chi2tpcconstglob";
floatVarName[14]="croverfind";
floatVarName[15]="dedxTPC";
floatVarName[16]="nsigel";
floatVarName[17]="nsigpi";
floatVarName[18]="nsigk";
floatVarName[19]="nsigp";
floatVarName[20]="pxgen";
floatVarName[21]="pygen";
floatVarName[22]="pzgen";
floatVarName[23]="ptgen";
floatVarName[24]="pgen";
floatVarName[25]="etagen";
floatVarName[26]="phigen";
Int_t usedVar=kNumOfFloatVar-7;
if(fReadMC) usedVar=kNumOfFloatVar;
for(Int_t ivar=0; ivar<usedVar; ivar++){
fTrackTree->Branch(floatVarName[ivar].Data(),&fTreeVarFloat[ivar],Form("%s/F",floatVarName[ivar].Data()));
}
TString intVarName[kNumOfIntVar];
fTreeVarInt = new Int_t[kNumOfIntVar];
intVarName[0]="ntrack";
intVarName[1]="ntracklets";
intVarName[2]="trackcharge";
intVarName[3]="ITSrefit";
intVarName[4]="ITSclumap";
intVarName[5]="nTPCclu";
intVarName[6]="TOFbc";
intVarName[7]="filbits";
intVarName[8]="particlecharge";
intVarName[9]="label";
intVarName[10]="truePID";
intVarName[11]="isPhysPrim";
usedVar=kNumOfIntVar-4;
if(fReadMC) usedVar=kNumOfIntVar;
for(Int_t ivar=0; ivar<usedVar; ivar++){
fTrackTree->Branch(intVarName[ivar].Data(),&fTreeVarInt[ivar],Form("%s/I",intVarName[ivar].Data()));
}
fHistNEvents = new TH1F("hNEvents", "Number of processed events",15,-0.5,14.5);
//fHistNEvents->Sumw2();
fHistNEvents->SetMinimum(0);
fHistNEvents->GetXaxis()->SetBinLabel(1,"All events");
fHistNEvents->GetXaxis()->SetBinLabel(2,"PhysSel");
fHistNEvents->GetXaxis()->SetBinLabel(3,"Good vertex");
fHistNEvents->GetXaxis()->SetBinLabel(4,"Pass zSPD-zTrk vert sel");
fHistNEvents->GetXaxis()->SetBinLabel(5,"|zvert|<10");
fOutput->Add(fHistNEvents);
fHistNTracks = new TH1F("hNTracks", "Number of tracks in AOD events ; N_{tracks}",(Int_t)(fMaxMult+1.00001),-0.5,fMaxMult+0.5);
fOutput->Add(fHistNTracks);
fHistNTracksVsTPCclusters = new TH2F("hNTracksVsTPCclusters"," ; N_{TPCclusters} ; N_{tracks}",100,0.,300.*fMaxMult,100,0.,fMaxMult);
fHistNTracksVsITSclusters = new TH2F("hNTracksVsITSclusters"," ; N_{ITSclusters} ; N_{tracks}",100,0.,10*fMaxMult,100,0.,fMaxMult);
fHistITSclustersVsTPCclusters = new TH2F("hITSclustersVsTPCclusters"," ; N_{ITSclusters} ; N_{TPCclusters}",100,0.,300.*fMaxMult,100,0.,10*fMaxMult);
fHistNTracksFB4VsTPCclusters = new TH2F("hNTracksFB4VsTPCclusters"," ; N_{TPCclusters} ; N_{tracks,FB4}",100,0.,300.*fMaxMult,100,0.,fMaxMult);
fHistNTracksFB4VsITSclusters = new TH2F("hNTracksFB4VsITSclusters"," ; N_{ITSclusters} ; N_{tracks,FB4}",100,0.,10*fMaxMult,100,0.,fMaxMult);
fOutput->Add(fHistNTracksVsTPCclusters);
fOutput->Add(fHistNTracksVsITSclusters);
fOutput->Add(fHistITSclustersVsTPCclusters);
fOutput->Add(fHistNTracksFB4VsTPCclusters);
fOutput->Add(fHistNTracksFB4VsITSclusters);
fHistFilterBits = new TH2D("hFilterBits", " ; Filter Bit ; Id ; N_{tracks}",kNumOfFilterBits,-0.5,kNumOfFilterBits-0.5,2,-1,1);
fHistFilterBits->GetYaxis()->SetBinLabel(1,"Neg. ID");
fHistFilterBits->GetYaxis()->SetBinLabel(2,"Pos. ID");
fOutput->Add(fHistFilterBits);
fHistITSnClusTPCsel=new TH1F("hITSnClusTPCsel","N ITS clusters (TPC+ITS)",7,-0.5,6.5);
fHistITSnClusITSsa=new TH1F("hITSnClusITSsa","N ITS clusters (TPC+ITS)",7,-0.5,6.5);
fHistITSnClusITSPureSA=new TH1F("hITSnClusITSPureSA","N ITS clusters (TPC+ITS)",7,-0.5,6.5);
fOutput->Add(fHistITSnClusTPCsel);
fOutput->Add(fHistITSnClusITSsa);
fOutput->Add(fHistITSnClusITSPureSA);
fHistITSCluInLayTPCsel = new TH1F("hITSCluInLayTPCsel", "N tracks with point on Layer (TPC+ITS); Layer; N tracks",6, -0.5, 5.5);
fHistITSCluInLayITSsa = new TH1F("hITSCluInLayITSsa", "N tracks with point on Layer (ITSsa); Layer; N tracks",6, -0.5, 5.5);
fHistITSCluInLayITSPureSA = new TH1F("hITSCluInLayITSPureSA", "N tracks with point on Layer (ITSsa); Layer; N tracks",6, -0.5, 5.5);
fOutput->Add(fHistITSCluInLayTPCsel);
fOutput->Add(fHistITSCluInLayITSsa);
fOutput->Add(fHistITSCluInLayITSPureSA);
fHistNtracksFb4VsV0befEvSel=new TH2F("hNtracksFb4VsV0befEvSel"," ; V0 signal ; N_{tracks,FilBit4}",250,0.,15000.,250,0.,5000.);
fHistNtracksFb5VsV0befEvSel=new TH2F("hNtracksFb5VsV0befEvSel"," ; V0 signal ; N_{tracks,FilBit5}",250,0.,15000.,250,0.,5000.);
fHistNtracksFb4VsV0aftEvSel=new TH2F("hNtracksFb4VsV0aftEvSel"," ; V0 signal ; N_{tracks,FilBit4}",250,0.,15000.,250,0.,5000.);
fHistNtracksFb5VsV0aftEvSel=new TH2F("hNtracksFb5VsV0aftEvSel"," ; V0 signal ; N_{tracks,FilBit5}",250,0.,15000.,250,0.,5000.);
fOutput->Add(fHistNtracksFb4VsV0befEvSel);
fOutput->Add(fHistNtracksFb5VsV0befEvSel);
fOutput->Add(fHistNtracksFb4VsV0aftEvSel);
fOutput->Add(fHistNtracksFb5VsV0aftEvSel);
fHistEtaPhiPtTPCsel = new TH3F("hEtaPhiPtTPCsel"," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtTPCselITSref = new TH3F("hEtaPhiPtTPCselITSref"," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtTPCselSPDany = new TH3F("hEtaPhiPtTPCselSPDany"," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fOutput->Add(fHistEtaPhiPtTPCsel);
fOutput->Add(fHistEtaPhiPtTPCselITSref);
fOutput->Add(fHistEtaPhiPtTPCselSPDany);
fHistEtaPhiPtPosChargeTPCsel = new TH3F("hEtaPhiPtPosChargeTPCsel"," Positive charged tracks ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtPosChargeTPCselITSref = new TH3F("hEtaPhiPtPosChargeTPCselITSref"," Positive charged tracks ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtPosChargeTPCselSPDany = new TH3F("hEtaPhiPtPosChargeTPCselSPDany"," Positive charged tracks ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fOutput->Add(fHistEtaPhiPtPosChargeTPCsel);
fOutput->Add(fHistEtaPhiPtPosChargeTPCselITSref);
fOutput->Add(fHistEtaPhiPtPosChargeTPCselSPDany);
fHistEtaPhiPtNegChargeTPCsel = new TH3F("hEtaPhiPtNegChargeTPCsel"," Negative charged tracks ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtNegChargeTPCselITSref = new TH3F("hEtaPhiPtNegChargeTPCselITSref"," Negative charged tracks ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtNegChargeTPCselSPDany = new TH3F("hEtaPhiPtNegChargeTPCselSPDany"," Negative charged tracks ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fOutput->Add(fHistEtaPhiPtNegChargeTPCsel);
fOutput->Add(fHistEtaPhiPtNegChargeTPCselITSref);
fOutput->Add(fHistEtaPhiPtNegChargeTPCselSPDany);
fHistEtaPhiPtTPCselTOFbc = new TH3F("hEtaPhiPtTPCselTOFbc"," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtTPCselITSrefTOFbc = new TH3F("hEtaPhiPtTPCselITSrefTOFbc"," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtTPCselSPDanyTOFbc = new TH3F("hEtaPhiPtTPCselSPDanyTOFbc"," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtTPCselSPDanyTOFpid = new TH3F("hEtaPhiPtTPCselSPDanyTOFpid"," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fOutput->Add(fHistEtaPhiPtTPCselTOFbc);
fOutput->Add(fHistEtaPhiPtTPCselITSrefTOFbc);
fOutput->Add(fHistEtaPhiPtTPCselSPDanyTOFbc);
fOutput->Add(fHistEtaPhiPtTPCselSPDanyTOFpid);
fHistTPCchi2PerClusPhiPtTPCsel = new TH3F("hTPCchi2PerClusPhiPtTPCsel"," ; TPC #chi^{2}/nClusters; p_{T} (GeV/c) ; #varphi",100, 0, 10, 100, 0, 10, 72, 0, 2*TMath::Pi());
fHistTPCchi2PerClusPhiPtTPCselITSref = new TH3F("hTPCchi2PerClusPhiPtTPCselITSref"," ; TPC #chi^{2}/nClusters; p_{T} (GeV/c) ; #varphi",100, 0, 10, 100, 0, 10, 72, 0, 2*TMath::Pi());
fHistTPCchi2PerClusPhiPtTPCselSPDany = new TH3F("hTPCchi2PerClusPhiPtTPCselSPDany"," ; TPC #chi^{2}/nClusters; p_{T} (GeV/c) ; #varphi",100, 0, 10, 100, 0, 10, 72, 0, 2*TMath::Pi());
fOutput->Add(fHistTPCchi2PerClusPhiPtTPCsel);
fOutput->Add(fHistTPCchi2PerClusPhiPtTPCselITSref);
fOutput->Add(fHistTPCchi2PerClusPhiPtTPCselSPDany);
const Int_t nPtBins4ip=90;
Double_t ptBins4ip[nPtBins4ip+1];
for(Int_t jjj=0; jjj<=50; jjj++) ptBins4ip[jjj]=0.020*jjj;
for(Int_t jjj=51; jjj<=70; jjj++) ptBins4ip[jjj]=ptBins4ip[50]+0.050*(jjj-50);
for(Int_t jjj=71; jjj<=80; jjj++) ptBins4ip[jjj]=ptBins4ip[70]+0.1*(jjj-70);
for(Int_t jjj=81; jjj<=84; jjj++) ptBins4ip[jjj]=ptBins4ip[80]+0.5*(jjj-80);
for(Int_t jjj=85; jjj<=90; jjj++) ptBins4ip[jjj]=ptBins4ip[84]+1.*(jjj-84);
const Int_t nMultBins4ip=12;
Double_t multBins4ip[nMultBins4ip+1]={0.,20.,50.,100.,500.,1000.,
1500.,2000.,3000.,4000.,5000.,7500.,10000.};
const Int_t nIPBins4ip=400;
Double_t ipBins4ip[nIPBins4ip+1];
for(Int_t jjj=0; jjj<=nIPBins4ip; jjj++) ipBins4ip[jjj]=-1500.+(3000./(Double_t)nIPBins4ip)*(Double_t)jjj;
fHistImpParXYPtMulPionTPCselSPDany = new TH3F("hImpParXYPtMulPionTPCselSPDany"," ; p_{T} (GeV/c) ; d_{0}^{xy} (#mum) ; N_{CL1}",nPtBins4ip,ptBins4ip,nIPBins4ip,ipBins4ip,nMultBins4ip,multBins4ip);
fHistImpParXYPtMulKaonTPCselSPDany = new TH3F("hImpParXYPtMulKaonTPCselSPDany"," ; p_{T} (GeV/c) ; d_{0}^{xy} (#mum) ; N_{CL1}",nPtBins4ip,ptBins4ip,nIPBins4ip,ipBins4ip,nMultBins4ip,multBins4ip);
fHistImpParXYPtMulProtonTPCselSPDany = new TH3F("hImpParXYPtMulProtonTPCselSPDany"," ; p_{T} (GeV/c) ; d_{0}^{xy} (#mum) ; N_{CL1}",nPtBins4ip,ptBins4ip,nIPBins4ip,ipBins4ip,nMultBins4ip,multBins4ip);
fOutput->Add(fHistImpParXYPtMulPionTPCselSPDany);
fOutput->Add(fHistImpParXYPtMulKaonTPCselSPDany);
fOutput->Add(fHistImpParXYPtMulProtonTPCselSPDany);
for(Int_t jb=0; jb<kNumOfFilterBits; jb++){
fHistEtaPhiPtFiltBit[jb] = new TH3F(Form("hEtaPhiPtFiltBit%d",jb)," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistImpParXYPtMulFiltBit[jb] = new TH3F(Form("hImpParXYPtMulPionFiltBit%d",jb)," ; p_{T} (GeV/c) ; d_{0}^{xy} (#mum) ; N_{CL1}",nPtBins4ip,ptBins4ip,nIPBins4ip,ipBins4ip,nMultBins4ip,multBins4ip);
fHistITScluPtFiltBit[jb] = new TH2F(Form("hITScluPtFiltBit%d",jb)," ; p_{T} (GeV/c) ; n ITS clusters",50,0.,10.,7,-0.5,6.5);
fHistSPDcluPtFiltBit[jb] = new TH2F(Form("hSPDcluPtFiltBit%d",jb)," ; p_{T} (GeV/c) ; SPD clusters",50,0.,10.,4,-0.5,3.5);
fHistSPDcluPtFiltBit[jb]->GetYaxis()->SetBinLabel(1,"kNone");
fHistSPDcluPtFiltBit[jb]->GetYaxis()->SetBinLabel(2,"kOnlyFirst");
fHistSPDcluPtFiltBit[jb]->GetYaxis()->SetBinLabel(3,"kOnlySecond");
fHistSPDcluPtFiltBit[jb]->GetYaxis()->SetBinLabel(4,"kBoth");
fHistTPCcluPtFiltBit[jb] = new TH2F(Form("hTPCcluPtFiltBit%d",jb)," ; p_{T} (GeV/c) ; n TPC clusters",50,0.,10.,161,-0.5,160.5);
fHistTPCcrrowsPtFiltBit[jb] = new TH2F(Form("hTPCcrrowsPtFiltBit%d",jb)," ; p_{T} (GeV/c) ; n TPC Crossed Rows",50,0.,10.,161,-0.5,160.5);
fHistTPCCrowOverFindPtFiltBit[jb] = new TH2F(Form("hTPCCrowOverFindPtFiltBit%d",jb)," ; p_{T} (GeV/c) ; #chi^{2}/ndf",50,0.,10.,100,0.,2.);
fHistTPCChi2ndfPtFiltBit[jb] = new TH2F(Form("hTPCChi2ndfPtFiltBit%d",jb)," ; p_{T} (GeV/c) ; #chi^{2}/ndf",50,0.,10.,160,0.,8.);
fHistChi2TPCConstrVsGlobPtFiltBit[jb] = new TH2F(Form("hChi2TPCConstrVsGlobPtFiltBit%d",jb)," ; p_{T} (GeV/c) ; golden #chi^{2}",50,0.,10.,160,0.,40.);
fOutput->Add(fHistEtaPhiPtFiltBit[jb]);
fOutput->Add(fHistImpParXYPtMulFiltBit[jb]);
fOutput->Add(fHistITScluPtFiltBit[jb]);
fOutput->Add(fHistSPDcluPtFiltBit[jb]);
fOutput->Add(fHistTPCcluPtFiltBit[jb]);
fOutput->Add(fHistTPCcrrowsPtFiltBit[jb]);
fOutput->Add(fHistTPCChi2ndfPtFiltBit[jb]);
fOutput->Add(fHistChi2TPCConstrVsGlobPtFiltBit[jb]);
fOutput->Add(fHistTPCCrowOverFindPtFiltBit[jb]);
}
fHistPtResidVsPtTPCselAll = new TH2F("hPtResidVsPtTPCselAll","; p_{T,rec} (GeV/c) ; p_{T,rec}-p_{T,gen} (GeV/c)",fNPtBins,fMinPt,fMaxPt,100,-0.5,0.5);
fHistPtResidVsPtTPCselITSrefAll = new TH2F("hPtResidVsPtTPCselITSrefAll","; p_{T,rec} (GeV/c) ; p_{T,rec}-p_{T,gen} (GeV/c)",fNPtBins,fMinPt,fMaxPt,100,-0.5,0.5);
fHistOneOverPtResidVsPtTPCselAll = new TH2F("hOneOverPtResidVsPtTPCselAll","; p_{T,rec} (GeV/c) ; p_{T,rec}*(1/p_{T,rec}-1/p_{T,gen})",fNPtBins,fMinPt,fMaxPt,100,-0.5,0.5);
fHistOneOverPtResidVsPtTPCselITSrefAll = new TH2F("hOneOverPtResidVsPtTPCselITSrefAll","; p_{T,rec} (GeV/c) ; p_{T,rec}*(1/p_{T,rec}-1/p_{T,gen})",fNPtBins,fMinPt,fMaxPt,100,-0.5,0.5);
fOutput->Add(fHistPtResidVsPtTPCselAll);
fOutput->Add(fHistPtResidVsPtTPCselITSrefAll);
fOutput->Add(fHistOneOverPtResidVsPtTPCselAll);
fOutput->Add(fHistOneOverPtResidVsPtTPCselITSrefAll);
for (int iS = 0; iS < AliPID::kSPECIESC; ++iS) {
fHistPtResidVsPtTPCsel[iS] = new TH2F(Form("hPtResidVsPtTPCsel%s",AliPID::ParticleShortName(iS)), Form("%s ; p_{T,rec} (GeV/c) ; p_{T,rec}-p_{T,gen} (GeV/c)",AliPID::ParticleLatexName(iS)),fNPtBins,fMinPt,fMaxPt,100,-0.5,0.5);
fHistPtResidVsPtTPCselITSref[iS] = new TH2F(Form("hPtResidVsPtTPCselITSref%s",AliPID::ParticleShortName(iS)),Form("%s ; p_{T,rec} (GeV/c) ; p_{T,rec}-p_{T,gen} (GeV/c)",AliPID::ParticleLatexName(iS)),fNPtBins,fMinPt,fMaxPt,100,-0.5,0.5);
fHistOneOverPtResidVsPtTPCsel[iS] = new TH2F(Form("hOneOverPtResidVsPtTPCsel%s",AliPID::ParticleShortName(iS)), Form("%s ; p_{T,rec} (GeV/c) ; p_{T,rec}*(1/p_{T,rec}-1/p_{T,gen})",AliPID::ParticleLatexName(iS)),fNPtBins,fMinPt,fMaxPt,100,-0.5,0.5);
fHistOneOverPtResidVsPtTPCselITSref[iS] = new TH2F(Form("hOneOverPtResidVsPtTPCselITSref%s",AliPID::ParticleShortName(iS)),Form("%s ; p_{T,rec} (GeV/c) ; p_{T,rec}*(1/p_{T,rec}-1/p_{T,gen})",AliPID::ParticleLatexName(iS)),fNPtBins,fMinPt,fMaxPt,100,-0.5,0.5);
fOutput->Add(fHistPtResidVsPtTPCsel[iS]);
fOutput->Add(fHistPtResidVsPtTPCselITSref[iS]);
fOutput->Add(fHistOneOverPtResidVsPtTPCsel[iS]);
fOutput->Add(fHistOneOverPtResidVsPtTPCselITSref[iS]);
}
fHistEtaPhiPtTPCselITSrefGood = new TH3F("hEtaPhiPtTPCselITSrefGood"," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fHistEtaPhiPtTPCselITSrefFake = new TH3F("hEtaPhiPtTPCselITSrefFake"," ; #eta ; #varphi ; p_{T} (GeV/c)",fNEtaBins,-1.,1.,fNPhiBins,0.,2*TMath::Pi(),fNPtBins,fMinPt,fMaxPt);
fOutput->Add(fHistEtaPhiPtTPCselITSrefGood);
fOutput->Add(fHistEtaPhiPtTPCselITSrefFake);
fHistImpParXYPtMulTPCselSPDanyGood = new TH3F("hImpParXYPtMulTPCselSPDanyGood"," ; p_{T} (GeV/c) ; d_{0}^{xy} (#mum) ; N_{CL1}",nPtBins4ip,ptBins4ip,nIPBins4ip,ipBins4ip,nMultBins4ip,multBins4ip);
fHistImpParXYPtMulTPCselSPDanyFake = new TH3F("hImpParXYPtMulTPCselSPDanyFake"," ; p_{T} (GeV/c) ; d_{0}^{xy} (#mum) ; N_{CL1}",nPtBins4ip,ptBins4ip,nIPBins4ip,ipBins4ip,nMultBins4ip,multBins4ip);
fOutput->Add(fHistImpParXYPtMulTPCselSPDanyGood);
fOutput->Add(fHistImpParXYPtMulTPCselSPDanyFake);
fHistImpParXYPtMulTPCselSPDanyPrim = new TH3F("hImpParXYPtMulTPCselSPDanyPrim"," ; p_{T} (GeV/c) ; d_{0}^{xy} (#mum) ; N_{CL1}",nPtBins4ip,ptBins4ip,nIPBins4ip,ipBins4ip,nMultBins4ip,multBins4ip);
fHistImpParXYPtMulTPCselSPDanySecDec = new TH3F("hImpParXYPtMulTPCselSPDanySecDec"," ; p_{T} (GeV/c) ; d_{0}^{xy} (#mum) ; N_{CL1}",nPtBins4ip,ptBins4ip,nIPBins4ip,ipBins4ip,nMultBins4ip,multBins4ip);
fHistImpParXYPtMulTPCselSPDanySecMat = new TH3F("hImpParXYPtMulTPCselSPDanySecMat"," ; p_{T} (GeV/c) ; d_{0}^{xy} (#mum) ; N_{CL1}",nPtBins4ip,ptBins4ip,nIPBins4ip,ipBins4ip,nMultBins4ip,multBins4ip);
fOutput->Add(fHistImpParXYPtMulTPCselSPDanyPrim);
fOutput->Add(fHistImpParXYPtMulTPCselSPDanySecDec);
fOutput->Add(fHistImpParXYPtMulTPCselSPDanySecMat);
fHistInvMassK0s = new TH3F("hInvMassK0s"," ; Inv.Mass (GeV/c^{2}) ; p_{T}(K0s) ; R (cm)",200,0.4,0.6,50,0.,10.,50,0.,50.);
fHistInvMassLambda = new TH3F("hInvMassLambda"," ;Inv.Mass (GeV/c^{2}) ; p_{T}(#Lambda) ; R (cm)",200,1.0,1.2,50,0.,10.,50,0.,50.);
fHistInvMassAntiLambda = new TH3F("hInvMassAntiLambda"," ;Inv.Mass (GeV/c^{2}) ; p_{T}(#bar{#Lambda}) ; R (cm)",200,1.0,1.2,50,0.,10.,50,0.,50.);
fOutput->Add(fHistInvMassK0s);
fOutput->Add(fHistInvMassLambda);
fOutput->Add(fHistInvMassAntiLambda);
PostData(1,fOutput);
PostData(2,fTrackTree);
}
//______________________________________________________________________________
void AliAnalysisTaskCheckAODTracks::UserExec(Option_t *)
{
//
AliAODEvent *aod = (AliAODEvent*) (InputEvent());
if(!aod) {
printf("AliAnalysisTaskCheckAODTracks::UserExec(): bad AOD\n");
return;
}
Double_t magField = aod->GetMagneticField();
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
AliInputEventHandler *inputHandler=(AliInputEventHandler*)mgr->GetInputEventHandler();
AliPIDResponse *pidResp=inputHandler->GetPIDResponse();
TClonesArray *arrayMC=0;
if(fReadMC){
arrayMC = (TClonesArray*)aod->GetList()->FindObject(AliAODMCParticle::StdBranchName());
if(!arrayMC) {
Printf("ERROR: MC particles branch not found!\n");
return;
}
}
fHistNEvents->Fill(0);
if(fUsePhysSel){
Bool_t isPhysSel = (((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected() & fTriggerMask);
if(!isPhysSel) return;
}
fHistNEvents->Fill(1);
Int_t ntracks = aod->GetNumberOfTracks();
Int_t ntracklets = 0;
AliAODTracklets *mult=aod->GetTracklets();
if(mult) ntracklets=mult->GetNumberOfTracklets();
Int_t ncl1 = aod->GetNumberOfITSClusters(1);
Int_t totITSclusters=0;
for(Int_t il=0; il<6; il++) totITSclusters+=aod->GetNumberOfITSClusters(il);
Int_t totTPCclusters=aod->GetNumberOfTPCClusters();
Int_t ntracksFB4=0;
Int_t ntracksFB5=0;
for (Int_t iTrack=0; iTrack < ntracks; iTrack++) {
AliAODTrack * track = (AliAODTrack*)aod->GetTrack(iTrack);
if (!track) continue;
if(track->TestFilterBit(1<<4)) ntracksFB4++;
if(track->TestFilterBit(1<<5)) ntracksFB5++;
}
Double_t vZEROampl=0;
for(Int_t i=0;i<64;i++) vZEROampl+=aod->GetVZEROData()->GetMultiplicity(i);
fHistNtracksFb4VsV0befEvSel->Fill(vZEROampl,ntracksFB4);
fHistNtracksFb5VsV0befEvSel->Fill(vZEROampl,ntracksFB5);
const AliVVertex* vtTrc = aod->GetPrimaryVertex();
const AliVVertex* vtSPD = aod->GetPrimaryVertexSPD();
if (vtTrc->GetNContributors()<2 || vtSPD->GetNContributors()<1) return; // one of vertices is missing
fHistNEvents->Fill(2);
double covTrc[6],covSPD[6];
vtTrc->GetCovarianceMatrix(covTrc);
vtSPD->GetCovarianceMatrix(covSPD);
double dz = vtTrc->GetZ()-vtSPD->GetZ();
double errTot = TMath::Sqrt(covTrc[5]+covSPD[5]);
double errTrc = TMath::Sqrt(covTrc[5]);
double nsigTot = TMath::Abs(dz)/errTot, nsigTrc = TMath::Abs(dz)/errTrc;
if (TMath::Abs(dz)>0.2 || nsigTot>10 || nsigTrc>20) return; // bad vertexing
fHistNEvents->Fill(3);
Float_t xvert=vtTrc->GetX();
Float_t yvert=vtTrc->GetY();
Float_t zvert=vtTrc->GetZ();
if(TMath::Abs(zvert)>10) return;
fHistNEvents->Fill(4);
fHistNtracksFb4VsV0aftEvSel->Fill(vZEROampl,ntracksFB4);
fHistNtracksFb5VsV0aftEvSel->Fill(vZEROampl,ntracksFB5);
Double_t pos[3],cov[6];
vtTrc->GetXYZ(pos);
vtTrc->GetCovarianceMatrix(cov);
const AliESDVertex vESD(pos,cov,100.,100);
fHistNTracks->Fill(ntracks);
fHistNTracksVsTPCclusters->Fill(totTPCclusters,ntracks);
fHistNTracksVsITSclusters->Fill(totITSclusters,ntracks);
fHistITSclustersVsTPCclusters->Fill(totTPCclusters,totITSclusters);
fHistNTracksFB4VsTPCclusters->Fill(totTPCclusters,ntracksFB4);
fHistNTracksFB4VsITSclusters->Fill(totITSclusters,ntracksFB4);
for (Int_t iTrack=0; iTrack < ntracks; iTrack++) {
AliAODTrack * track = (AliAODTrack*)aod->GetTrack(iTrack);
if (!track) continue;
for(Int_t jvar=0; jvar<kNumOfFloatVar; jvar++) fTreeVarFloat[jvar]=-999.;
for(Int_t jvar=0; jvar<kNumOfIntVar; jvar++) fTreeVarInt[jvar]=-999;
fTreeVarFloat[0]=xvert;
fTreeVarFloat[1]=yvert;
fTreeVarFloat[2]=zvert;
fTreeVarInt[0]=ntracks;
fTreeVarInt[1]=ntracklets;
Int_t trid=track->GetID();
Double_t ydum=0.5;
if(trid<0) ydum=-0.5;
for(Int_t jb=0; jb<kNumOfFilterBits; jb++){
if(track->TestFilterBit(1<<jb)) fHistFilterBits->Fill(jb,ydum);
}
Int_t chtrack=track->Charge();
Double_t pttrack=track->Pt();
Double_t ptrack=track->P();
Double_t pxtrack=track->Px();
Double_t pytrack=track->Py();
Double_t pztrack=track->Pz();
Double_t etatrack=track->Eta();
Double_t phitrack=track->Phi();
fTreeVarFloat[3]=track->Px();
fTreeVarFloat[4]=track->Py();
fTreeVarFloat[5]=track->Pz();
fTreeVarFloat[6]=track->Pt();
fTreeVarFloat[7]=track->P();
fTreeVarFloat[8]=track->Eta();
fTreeVarFloat[9]=track->Phi();
Double_t d0z0[2],covd0z0[3];
Bool_t isOK=track->PropagateToDCA(vtTrc,magField,99999.,d0z0,covd0z0);
Float_t impactXY=-999, impactZ=-999;
if(isOK){
impactXY=d0z0[0];
impactZ=d0z0[1];
}
Bool_t itsRefit=kFALSE;
Int_t statusTrack=track->GetStatus();
if(statusTrack&AliESDtrack::kITSrefit) itsRefit=kTRUE;
Int_t nITSclus=track->GetNcls(0);
UChar_t clumap=track->GetITSClusterMap();
if(itsRefit && !(statusTrack&AliESDtrack::kTPCin)){
if(statusTrack&AliESDtrack::kITSpureSA){
fHistITSnClusITSPureSA->Fill(nITSclus);
for(Int_t layer=0; layer<6; layer++) {
if(TESTBIT(clumap,layer)) fHistITSCluInLayITSPureSA->Fill(layer);
}
}else{
fHistITSnClusITSsa->Fill(nITSclus);
for(Int_t layer=0; layer<6; layer++) {
if(TESTBIT(clumap,layer)) fHistITSCluInLayITSsa->Fill(layer);
}
}
}
Int_t nSPDclus=0;
if(track->HasPointOnITSLayer(0)) nSPDclus+=1;
if(track->HasPointOnITSLayer(1)) nSPDclus+=2;
Bool_t spdAny=kFALSE;
if(track->HasPointOnITSLayer(0) || track->HasPointOnITSLayer(1)) spdAny=kTRUE;
Int_t nTPCclus=track->GetNcls(1);
Double_t chi2clus=track->Chi2perNDF();
Double_t goldenChi2=track->GetChi2TPCConstrainedVsGlobal();
Float_t nCrossedRowsTPC = track->GetTPCCrossedRows();
Float_t ratioCrossedRowsOverFindableClustersTPC = 1.0;
if (track->GetTPCNclsF()>0) {
ratioCrossedRowsOverFindableClustersTPC = nCrossedRowsTPC / track->GetTPCNclsF();
}
Int_t tofBC=track->GetTOFBunchCrossing(magField);
fTreeVarFloat[10]=impactXY;
fTreeVarFloat[11]=impactZ;
fTreeVarFloat[12]=chi2clus;
fTreeVarFloat[13]=goldenChi2;
fTreeVarFloat[14]=ratioCrossedRowsOverFindableClustersTPC;
fTreeVarInt[2]=chtrack;
fTreeVarInt[3]=itsRefit;
fTreeVarInt[4]=clumap;
fTreeVarInt[5]=nTPCclus;
fTreeVarInt[6]=tofBC;
Int_t trlabel=track->GetLabel();
Float_t dedx=track->GetTPCsignal();
Int_t filtmap=track->GetFilterMap();
Double_t nSigmaTPC[9]={-999.,-999.,-999.,-999.,-999.,-999.,-999.,-999.,-999.};
if(pidResp){
AliPIDResponse::EDetPidStatus status = pidResp->CheckPIDStatus(AliPIDResponse::kTPC,track);
if (status == AliPIDResponse::kDetPidOk){
for(Int_t jsp=0; jsp<9; jsp++){
nSigmaTPC[jsp]=pidResp->NumberOfSigmasTPC(track,(AliPID::EParticleType)jsp);
}
}
}
fTreeVarFloat[15]=dedx;
fTreeVarFloat[16]=nSigmaTPC[0];
fTreeVarFloat[17]=nSigmaTPC[2];
fTreeVarFloat[18]=nSigmaTPC[3];
fTreeVarFloat[19]=nSigmaTPC[4];
fTreeVarInt[7]=filtmap;
Float_t ptgen=-999.;
Float_t pgen=-999.;
Float_t pxgen=-999.;
Float_t pygen=-999.;
Float_t pzgen=-999.;
Float_t etagen=-999.;
Float_t phigen=-999.;
Int_t hadronSpecies=-1;
Float_t invptgen=-999.;
Int_t isPhysPrim=-999;
if(fReadMC){
AliAODMCParticle* part = dynamic_cast<AliAODMCParticle*>(arrayMC->At(TMath::Abs(trlabel)));
ptgen=part->Pt();
pgen=part->P();
pxgen=part->Px();
pygen=part->Py();
pzgen=part->Pz();
if(ptgen>0.) invptgen=1./ptgen;
etagen=part->Eta();
phigen=part->Phi();
if(part->IsPhysicalPrimary()) isPhysPrim=1;
else if(part->IsSecondaryFromWeakDecay()) isPhysPrim=0;
else if(part->IsSecondaryFromMaterial()) isPhysPrim=-1;
fTreeVarFloat[20]=pxgen;
fTreeVarFloat[21]=pygen;
fTreeVarFloat[22]=pzgen;
fTreeVarFloat[23]=ptgen;
fTreeVarFloat[24]=pgen;
fTreeVarFloat[25]=etagen;
fTreeVarFloat[26]=phigen;
if (fUseMCId) {
int pdg = TMath::Abs(part->GetPdgCode());
for (int iS = 0; iS < AliPID::kSPECIESCN; ++iS) {
if (pdg == AliPID::ParticleCode(iS)) hadronSpecies=iS;
}
}
fTreeVarInt[8]=part->Charge();
fTreeVarInt[9]=trlabel;
fTreeVarInt[10]=part->GetPdgCode();
fTreeVarInt[11]=isPhysPrim;
}
if (fFillTree) fTrackTree->Fill();
for(Int_t jb=0; jb<kNumOfFilterBits; jb++){
if(track->TestFilterBit(1<<jb)){
fHistImpParXYPtMulFiltBit[jb]->Fill(pttrack,impactXY*10000.,ncl1);
fHistEtaPhiPtFiltBit[jb]->Fill(etatrack,phitrack,pttrack);
fHistITScluPtFiltBit[jb]->Fill(pttrack,nITSclus);
fHistSPDcluPtFiltBit[jb]->Fill(pttrack,nSPDclus);
fHistTPCcluPtFiltBit[jb]->Fill(pttrack,nTPCclus);
fHistTPCcrrowsPtFiltBit[jb]->Fill(pttrack,nCrossedRowsTPC);
fHistTPCCrowOverFindPtFiltBit[jb]->Fill(pttrack,ratioCrossedRowsOverFindableClustersTPC);
fHistTPCChi2ndfPtFiltBit[jb]->Fill(pttrack,chi2clus);
fHistChi2TPCConstrVsGlobPtFiltBit[jb]->Fill(pttrack,goldenChi2);
}
}
if(track->GetID()<0) continue;
// convert to ESD track here
AliESDtrack esdTrack(track);
// set the TPC cluster info
esdTrack.SetTPCClusterMap(track->GetTPCClusterMap());
esdTrack.SetTPCSharedMap(track->GetTPCSharedMap());
esdTrack.SetTPCPointsF(track->GetTPCNclsF());
// needed to calculate the impact parameters
esdTrack.RelateToVertex(&vESD,0.,3.);
if(!fTrCutsTPC->AcceptTrack(&esdTrack)) continue;
if(track->GetTPCsignalN()<fMinNumOfTPCPIDclu) continue;
fHistITSnClusTPCsel->Fill(nITSclus);
for(Int_t layer=0; layer<6; layer++) {
if(TESTBIT(clumap,layer)) fHistITSCluInLayTPCsel->Fill(layer);
}
fHistEtaPhiPtTPCsel->Fill(etatrack,phitrack,pttrack);
if(chtrack>0) fHistEtaPhiPtPosChargeTPCsel->Fill(etatrack,phitrack,pttrack);
else if(chtrack<0) fHistEtaPhiPtNegChargeTPCsel->Fill(etatrack,phitrack,pttrack);
if(tofBC==0) fHistEtaPhiPtTPCselTOFbc->Fill(etatrack,phitrack,pttrack);
if(itsRefit){
fHistEtaPhiPtTPCselITSref->Fill(etatrack,phitrack,pttrack);
if(chtrack>0) fHistEtaPhiPtPosChargeTPCselITSref->Fill(etatrack,phitrack,pttrack);
else if(chtrack<0) fHistEtaPhiPtNegChargeTPCselITSref->Fill(etatrack,phitrack,pttrack);
if(tofBC==0) fHistEtaPhiPtTPCselITSrefTOFbc->Fill(etatrack,phitrack,pttrack);
if(spdAny){
fHistEtaPhiPtTPCselSPDany->Fill(etatrack,phitrack,pttrack);
if(chtrack>0) fHistEtaPhiPtPosChargeTPCselSPDany->Fill(etatrack,phitrack,pttrack);
else if(chtrack<0) fHistEtaPhiPtNegChargeTPCselSPDany->Fill(etatrack,phitrack,pttrack);
if(tofBC==0) fHistEtaPhiPtTPCselSPDanyTOFbc->Fill(etatrack,phitrack,pttrack);
if ((track->GetStatus() & AliVTrack::kTOFout) &&
(track->GetStatus() & AliVTrack::kTIME) &&
(track->GetIntegratedLength() > 350.)) {
fHistEtaPhiPtTPCselSPDanyTOFpid->Fill(etatrack,phitrack,pttrack);
}
}
}
fHistTPCchi2PerClusPhiPtTPCsel->Fill(chi2clus,pttrack,phitrack);
if(itsRefit){
fHistTPCchi2PerClusPhiPtTPCselITSref->Fill(chi2clus,pttrack,phitrack);
if(spdAny) fHistTPCchi2PerClusPhiPtTPCselSPDany->Fill(chi2clus,pttrack,phitrack);
}
bool pid[AliPID::kSPECIESCN] = {false};
if (fReadMC && fUseMCId) {
if (hadronSpecies > -1) pid[hadronSpecies] = true;
} else {
for (int iS = 0; iS < AliPID::kSPECIESCN; ++iS)
pid[iS] = TMath::Abs(nSigmaTPC[iS])<3;
}
bool isProton = pid[AliPID::kProton];
bool isKaon = pid[AliPID::kKaon];
bool isPion = pid[AliPID::kPion];
if(itsRefit && spdAny){
if(isPion) fHistImpParXYPtMulPionTPCselSPDany->Fill(pttrack,impactXY*10000.,ncl1);
if(isKaon) fHistImpParXYPtMulKaonTPCselSPDany->Fill(pttrack,impactXY*10000.,ncl1);
if(isProton) fHistImpParXYPtMulProtonTPCselSPDany->Fill(pttrack,impactXY*10000.,ncl1);
}
if(fReadMC && pttrack>0.){
fHistPtResidVsPtTPCselAll->Fill(pttrack,(pttrack-ptgen));
fHistOneOverPtResidVsPtTPCselAll->Fill(pttrack,pttrack*(1./pttrack-invptgen));
if (itsRefit){
fHistPtResidVsPtTPCselITSrefAll->Fill(pttrack,(pttrack-ptgen));
fHistOneOverPtResidVsPtTPCselITSrefAll->Fill(pttrack,pttrack*(1./pttrack-invptgen));
}
for (int iS = 0; iS < AliPID::kSPECIESC; ++iS) {
if (pid[iS]) {
Double_t ptDiff=pttrack*AliPID::ParticleCharge(iS)-ptgen;
Double_t oneOverPtDiff=0;
if(AliPID::ParticleCharge(iS)>0) oneOverPtDiff=pttrack*AliPID::ParticleCharge(iS)*(1./(pttrack*AliPID::ParticleCharge(iS))-invptgen);
fHistPtResidVsPtTPCsel[iS]->Fill(pttrack*AliPID::ParticleCharge(iS),ptDiff);
fHistOneOverPtResidVsPtTPCsel[iS]->Fill(pttrack*AliPID::ParticleCharge(iS),oneOverPtDiff);
if (itsRefit){
fHistPtResidVsPtTPCselITSref[iS]->Fill(pttrack*AliPID::ParticleCharge(iS),ptDiff);
fHistOneOverPtResidVsPtTPCselITSref[iS]->Fill(pttrack*AliPID::ParticleCharge(iS),oneOverPtDiff);
}
}
}
if(trlabel>=0){
fHistEtaPhiPtTPCselITSrefGood->Fill(etatrack,phitrack,pttrack);
if(itsRefit && spdAny) fHistImpParXYPtMulTPCselSPDanyGood->Fill(pttrack,impactXY*10000.,ncl1);
}else{
fHistEtaPhiPtTPCselITSrefFake->Fill(etatrack,phitrack,pttrack);
if(itsRefit && spdAny) fHistImpParXYPtMulTPCselSPDanyFake->Fill(pttrack,impactXY*10000.,ncl1);
}
if(itsRefit && spdAny){
if(isPhysPrim==1) fHistImpParXYPtMulTPCselSPDanyPrim->Fill(pttrack,impactXY*10000.,ncl1);
else if(isPhysPrim==0) fHistImpParXYPtMulTPCselSPDanySecDec->Fill(pttrack,impactXY*10000.,ncl1);
else if(isPhysPrim==-1) fHistImpParXYPtMulTPCselSPDanySecMat->Fill(pttrack,impactXY*10000.,ncl1);
}
}
}
Int_t nv0s = aod->GetNumberOfV0s();
for (Int_t iV0 = 0; iV0 < nv0s; iV0++){
AliAODv0 *v0 = aod->GetV0(iV0);
if (!v0) continue;
Bool_t onFlyStatus=v0->GetOnFlyStatus();
if(onFlyStatus==kTRUE) continue;
AliAODTrack *pTrack=(AliAODTrack *)v0->GetDaughter(0); //0->Positive Daughter
AliAODTrack *nTrack=(AliAODTrack *)v0->GetDaughter(1); //1->Negative Daughter
if (!pTrack || !nTrack) {
Printf("ERROR: Could not retreive one of the daughter track");
continue;
}
Double_t invMassK0s = v0->MassK0Short();
Double_t invMassLambda = v0->MassLambda();
Double_t invMassAntiLambda = v0->MassAntiLambda();
Double_t ptv0=v0->Pt();
Double_t xv0=v0->Xv();
Double_t yv0=v0->Yv();
Double_t rv0=TMath::Sqrt(xv0*xv0+yv0*yv0);
AliESDtrack pEsdTrack(pTrack);
pEsdTrack.SetTPCClusterMap(pTrack->GetTPCClusterMap());
pEsdTrack.SetTPCSharedMap(pTrack->GetTPCSharedMap());
pEsdTrack.SetTPCPointsF(pTrack->GetTPCNclsF());
if(!fTrCutsTPC->AcceptTrack(&pEsdTrack)) continue;
AliESDtrack nEsdTrack(pTrack);
nEsdTrack.SetTPCClusterMap(nTrack->GetTPCClusterMap());
nEsdTrack.SetTPCSharedMap(nTrack->GetTPCSharedMap());
nEsdTrack.SetTPCPointsF(nTrack->GetTPCNclsF());
if(!fTrCutsTPC->AcceptTrack(&nEsdTrack)) continue;
Bool_t keepK0s=kTRUE;
Bool_t keepLambda=kTRUE;
Bool_t keepAntiLambda=kTRUE;
if(!fReadMC){
if(pidResp){
Double_t nsigmap=-999.;
if (pidResp->CheckPIDStatus(AliPIDResponse::kTPC,pTrack) == AliPIDResponse::kDetPidOk){
nsigmap=pidResp->NumberOfSigmasTPC(pTrack,AliPID::kProton);
}
Double_t nsigman=-999.;
if (pidResp->CheckPIDStatus(AliPIDResponse::kTPC,nTrack) == AliPIDResponse::kDetPidOk){
nsigman=pidResp->NumberOfSigmasTPC(nTrack,AliPID::kProton);
}
if(TMath::Abs(nsigmap)>3) keepLambda=kFALSE;
if(TMath::Abs(nsigman)>3) keepAntiLambda=kFALSE;
}
}else{
keepK0s=kFALSE;
keepLambda=kFALSE;
keepAntiLambda=kFALSE;
Int_t labelPos=TMath::Abs(pTrack->GetLabel());
Int_t labelNeg =TMath::Abs(nTrack->GetLabel());
AliAODMCParticle* partPos = dynamic_cast<AliAODMCParticle*>(arrayMC->At(TMath::Abs(labelPos)));
AliAODMCParticle* partNeg = dynamic_cast<AliAODMCParticle*>(arrayMC->At(TMath::Abs(labelNeg)));
if(partPos && partNeg){
Int_t labelMotherPos=partPos->GetMother() ;
Int_t labelMotherNeg=partNeg->GetMother();
if(labelMotherPos==labelMotherNeg && labelMotherPos>-1){
AliAODMCParticle* partV0 = dynamic_cast<AliAODMCParticle*>(arrayMC->At(TMath::Abs(labelMotherPos)));
Int_t pdgV0=partV0->GetPdgCode();
if(TMath::Abs(pdgV0)==310) keepK0s=kTRUE;
if(pdgV0==3122) keepLambda=kTRUE;
if(pdgV0==-3122) keepAntiLambda=kTRUE;
}
}
}
if(TMath::Abs(invMassK0s-0.4976)<0.03){
keepLambda=kFALSE;
keepAntiLambda=kFALSE;
}
if(keepK0s) fHistInvMassK0s->Fill(invMassK0s,ptv0,rv0);
if(keepLambda){
fHistInvMassLambda->Fill(invMassLambda,ptv0,rv0);
}
if(keepAntiLambda){
fHistInvMassAntiLambda->Fill(invMassAntiLambda,ptv0,rv0);
}
}
PostData(1,fOutput);
PostData(2,fTrackTree);
}
//______________________________________________________________________________
void AliAnalysisTaskCheckAODTracks::Terminate(Option_t */*option*/)
{
// Terminate analysis
fOutput = dynamic_cast<TList*> (GetOutputData(1));
if (!fOutput) {
printf("ERROR: fOutput not available\n");
return;
}
fHistNEvents= dynamic_cast<TH1F*>(fOutput->FindObject("hNEvents"));
printf("AliAnalysisTaskCheckAODTracks::Terminate --- Number of events: read = %.0f analysed = %.0f\n",fHistNEvents->GetBinContent(1),fHistNEvents->GetBinContent(5));
return;
}
|
// problem link :- https://leetcode.com/problems/add-two-numbers/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//create a dumy node and also a temp node which will point to the dumy node
ListNode* dumy= new ListNode();
ListNode*temp=dumy;
//initialize carry with 0
int carry=0;
//if l1 or l2 or carry will be null it will simply return the duy node
while(l1!=NULL || l2!=NULL || carry)
{
//intialise the sum to 0
int sum=0;
//if l1 is not null than add into sum variable
if(l1!=NULL)
{
sum+=l1->val;
//and move next
l1=l1->next;
}
//if l2 is not null than add into sum varibale
if(l2!=NULL)
{
//move to next
sum+=l2->val;
l2=l2->next;
}
//add carry to sum
sum+=carry;
//as we know for adding the carry we have to do sum /10
carry=sum/10;
//crete a node
ListNode *node = new ListNode(sum%10);
//link it to the temp node
temp->next=node;
temp=temp->next;
}
//simply returning the dumy node.
return dumy->next;
}
};
|
/**
* Copyright (c) 2016-present, Facebook, 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.
*/
/* Modifications Copyright (c) Microsoft. */
#include "core/providers/cpu/nn/conv.h"
#include "core/util/math_cpuonly.h"
namespace onnxruntime {
template <typename T>
Status Conv<T>::Compute(OpKernelContext* context) const {
const auto* X = context->Input<Tensor>(0);
const auto* W = context->Input<Tensor>(1);
const Tensor* B = context->Input<Tensor>(2); // optional. nullptr if not provided
const int64_t N = X->Shape()[0];
const int64_t C = X->Shape()[1];
const int64_t M = W->Shape()[0];
ORT_RETURN_IF_ERROR(conv_attrs_.ValidateInputShape(X, W));
std::vector<int64_t> kernel_shape;
ORT_RETURN_IF_ERROR(conv_attrs_.ComputeKernelShape(W->Shape(), kernel_shape));
std::vector<int64_t> pads(conv_attrs_.pads);
if (pads.empty()) {
pads.resize(kernel_shape.size() * 2, 0);
}
std::vector<int64_t> dilations(conv_attrs_.dilations);
if (dilations.empty()) {
dilations.resize(kernel_shape.size(), 1);
}
std::vector<int64_t> strides(conv_attrs_.strides);
if (strides.empty()) {
strides.resize(kernel_shape.size(), 1);
}
std::vector<int64_t> Y_dims;
Y_dims.insert(Y_dims.begin(), {N, M});
TensorShape input_shape = X->Shape().Slice(2);
ORT_RETURN_IF_ERROR(conv_attrs_.InferOutputShape(input_shape, kernel_shape, strides, dilations, &pads, &Y_dims));
Tensor* Y = context->Output(0, TensorShape(Y_dims));
TensorShape output_shape = Y->Shape().Slice(2);
const int64_t input_image_size = input_shape.Size();
const int64_t output_image_size = output_shape.Size();
const int64_t kernel_size = TensorShape(kernel_shape).Size();
const int64_t X_offset = C / conv_attrs_.group * input_image_size;
const int64_t Y_offset = Y->Shape().Size() / Y->Shape()[0] / conv_attrs_.group;
const int64_t W_offset = W->Shape().Size() / conv_attrs_.group;
const int64_t kernel_dim = C / conv_attrs_.group * kernel_size;
const int64_t col_buffer_size = kernel_dim * output_image_size;
AllocatorPtr alloc;
ORT_RETURN_IF_ERROR(context->GetTempSpaceAllocator(&alloc));
auto col_data = alloc->Alloc(sizeof(T) * col_buffer_size);
BufferUniquePtr col_buffer(col_data, BufferDeleter(alloc));
T* col_buffer_data = static_cast<T*>(col_buffer.get());
const T* Xdata = X->template Data<T>();
T* Ydata = Y->template MutableData<T>();
TensorShape image_shape = X->Shape().Slice(1);
std::vector<int64_t> col_buffer_shape{kernel_dim};
col_buffer_shape.insert(col_buffer_shape.end(), output_shape.GetDims().begin(),
output_shape.GetDims().end());
const size_t kernel_rank = kernel_shape.size();
concurrency::ThreadPool* tp = context->GetOperatorThreadPool();
for (int image_id = 0; image_id < N; ++image_id) {
for (int group_id = 0; group_id < conv_attrs_.group; ++group_id) {
if (kernel_rank == 2) {
math::Im2col<T, StorageOrder::NCHW>(
Xdata + group_id * X_offset,
C / conv_attrs_.group,
input_shape[0],
input_shape[1],
kernel_shape[0],
kernel_shape[1],
dilations[0],
dilations[1],
pads[0],
pads[1],
pads[2],
pads[3],
strides[0],
strides[1],
col_buffer_data);
} else {
math::Im2colNd<T, StorageOrder::NCHW>()(
Xdata + group_id * X_offset,
image_shape.GetDims().data(),
col_buffer_shape.data(),
C * input_image_size,
col_buffer_size,
kernel_shape.data(),
strides.data(),
dilations.data(),
pads.data(),
static_cast<int>(kernel_shape.size()),
col_buffer_data);
}
math::Gemm<T>(
CblasNoTrans,
CblasNoTrans,
M / conv_attrs_.group,
output_image_size,
kernel_dim,
1,
W->template Data<T>() + group_id * W_offset,
col_buffer_data,
0,
Ydata + group_id * Y_offset,
tp);
}
if (B != nullptr) {
auto Ymatrix = EigenMatrixMap<T>(Ydata, output_image_size, M);
auto Bvec = ConstEigenVectorMap<T>(B->template Data<T>(), M);
Ymatrix.rowwise() += Bvec.transpose();
}
Xdata += X_offset * conv_attrs_.group;
Ydata += Y_offset * conv_attrs_.group;
}
return Status::OK();
}
Status Conv<float>::Compute(OpKernelContext* context) const {
size_t num_inputs = OpKernel::Node().InputDefs().size();
const auto* X = context->Input<Tensor>(0);
const auto* W = context->Input<Tensor>(1);
const Tensor* B = num_inputs == 3 ? context->Input<Tensor>(2) : nullptr;
const int64_t N = X->Shape()[0];
const int64_t C = X->Shape()[1];
const int64_t M = W->Shape()[0];
ORT_RETURN_IF_ERROR(conv_attrs_.ValidateInputShape(X, W));
std::vector<int64_t> kernel_shape;
ORT_RETURN_IF_ERROR(conv_attrs_.ComputeKernelShape(W->Shape(), kernel_shape));
std::vector<int64_t> pads(conv_attrs_.pads);
if (pads.empty()) {
pads.resize(kernel_shape.size() * 2, 0);
}
std::vector<int64_t> dilations(conv_attrs_.dilations);
if (dilations.empty()) {
dilations.resize(kernel_shape.size(), 1);
}
std::vector<int64_t> strides(conv_attrs_.strides);
if (strides.empty()) {
strides.resize(kernel_shape.size(), 1);
}
std::vector<int64_t> Y_dims;
Y_dims.insert(Y_dims.begin(), {N, M});
TensorShape input_shape = X->Shape().Slice(2);
ORT_RETURN_IF_ERROR(conv_attrs_.InferOutputShape(input_shape, kernel_shape, strides, dilations, &pads, &Y_dims));
Tensor* Y = context->Output(0, TensorShape(Y_dims));
// special case when there is a dim value of 0 in the shape.
if (Y->Shape().Size() == 0)
return Status::OK();
TensorShape output_shape = Y->Shape().Slice(2);
AllocatorPtr alloc;
ORT_RETURN_IF_ERROR(context->GetTempSpaceAllocator(&alloc));
const auto* Xdata = X->template Data<float>();
const auto* Bdata = B != nullptr ? B->template Data<float>() : nullptr;
auto* Ydata = Y->template MutableData<float>();
const size_t kernel_rank = kernel_shape.size();
concurrency::ThreadPool* tp = context->GetOperatorThreadPool();
if (kernel_rank == 2 || kernel_rank == 3) {
MLAS_CONV_PARAMETERS Parameters;
size_t WorkingBufferSize;
MlasConvPrepare(&Parameters,
kernel_rank,
static_cast<size_t>(N),
static_cast<size_t>(conv_attrs_.group),
static_cast<size_t>(C / conv_attrs_.group),
input_shape.GetDims().data(),
kernel_shape.data(),
dilations.data(),
pads.data(),
strides.data(),
output_shape.GetDims().data(),
static_cast<size_t>(M / conv_attrs_.group),
&activation_,
&WorkingBufferSize,
tp);
auto working_data = WorkingBufferSize > 0 ? alloc->Alloc(sizeof(float) * WorkingBufferSize) : nullptr;
BufferUniquePtr working_buffer(working_data, BufferDeleter(alloc));
MlasConv(&Parameters,
Xdata,
W->template Data<float>(),
Bdata,
static_cast<float*>(working_buffer.get()),
Ydata,
tp);
} else {
const int64_t input_image_size = input_shape.Size();
const int64_t output_image_size = output_shape.Size();
const int64_t kernel_size = TensorShape(kernel_shape).Size();
const int64_t X_offset = C / conv_attrs_.group * input_image_size;
const int64_t Y_offset = Y->Shape().Size() / Y->Shape()[0] / conv_attrs_.group;
const int64_t W_offset = W->Shape().Size() / conv_attrs_.group;
const int64_t kernel_dim = C / conv_attrs_.group * kernel_size;
const int64_t col_buffer_size = kernel_dim * output_image_size;
auto col_data = alloc->Alloc(sizeof(float) * col_buffer_size);
BufferUniquePtr col_buffer(col_data, BufferDeleter(alloc));
auto* col_buffer_data = static_cast<float*>(col_buffer.get());
TensorShape image_shape = X->Shape().Slice(1);
std::vector<int64_t> col_buffer_shape{kernel_dim};
col_buffer_shape.insert(col_buffer_shape.end(), output_shape.GetDims().begin(),
output_shape.GetDims().end());
for (int image_id = 0; image_id < N; ++image_id) {
for (int group_id = 0; group_id < conv_attrs_.group; ++group_id) {
math::Im2colNd<float, StorageOrder::NCHW>()(
Xdata + group_id * X_offset,
image_shape.GetDims().data(),
col_buffer_shape.data(),
C * input_image_size,
col_buffer_size,
kernel_shape.data(),
strides.data(),
dilations.data(),
pads.data(),
static_cast<int>(kernel_shape.size()),
col_buffer_data);
math::Gemm<float>(
CblasNoTrans,
CblasNoTrans,
M / conv_attrs_.group,
output_image_size,
kernel_dim,
1,
W->template Data<float>() + group_id * W_offset,
col_buffer_data,
0,
Ydata + group_id * Y_offset,
tp);
}
MlasActivation(&activation_, Ydata, Bdata, M, output_image_size, output_image_size);
Xdata += X_offset * conv_attrs_.group;
Ydata += Y_offset * conv_attrs_.group;
}
}
return Status::OK();
}
ONNX_CPU_OPERATOR_VERSIONED_KERNEL(
Conv,
1, 10,
KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
Conv<float>);
ONNX_CPU_OPERATOR_KERNEL(
Conv,
11,
KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
Conv<float>);
} // namespace onnxruntime
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The AMBANKCOIN developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "checkpoints.h"
#include "clientversion.h"
#include "kernel.h"
#include "main.h"
#include "rpc/server.h"
#include "sync.h"
#include "txdb.h"
#include "util.h"
#include "utilmoneystr.h"
#include "zambk/accumulatormap.h"
#include "zambk/accumulators.h"
#include "wallet/wallet.h"
#include "zambk/zambkmodule.h"
#include "zambkchain.h"
#include <stdint.h>
#include <fstream>
#include <iostream>
#include <univalue.h>
#include <mutex>
#include <numeric>
#include <condition_variable>
struct CUpdatedBlock
{
uint256 hash;
int height;
};
static std::mutex cs_blockchange;
static std::condition_variable cond_blockchange;
static CUpdatedBlock latestblock;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL) {
if (chainActive.Tip() == NULL)
return 1.0;
else
blockindex = chainActive.Tip();
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29) {
dDiff *= 256.0;
nShift++;
}
while (nShift > 29) {
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
UniValue blockheaderToJSON(const CBlockIndex* blockindex)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", blockindex->nVersion));
result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
result.push_back(Pair("time", (int64_t)blockindex->nTime));
result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce));
result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
result.push_back(Pair("acc_checkpoint", blockindex->nAccumulatorCheckpoint.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", block.GetHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("acc_checkpoint", block.nAccumulatorCheckpoint.GetHex()));
UniValue txs(UniValue::VARR);
for (const CTransaction& tx : block.vtx) {
if (txDetails) {
UniValue objTx(UniValue::VOBJ);
TxToJSON(tx, uint256(0), objTx);
txs.push_back(objTx);
} else
txs.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txs));
result.push_back(Pair("time", block.GetBlockTime()));
result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
result.push_back(Pair("nonce", (uint64_t)block.nNonce));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex* pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
result.push_back(Pair("modifier", strprintf("%016x", blockindex->nStakeModifier)));
result.push_back(Pair("modifierV2", blockindex->nStakeModifierV2.GetHex()));
result.push_back(Pair("moneysupply",ValueFromAmount(blockindex->nMoneySupply)));
UniValue zambkObj(UniValue::VOBJ);
for (auto denom : libzerocoin::zerocoinDenomList) {
zambkObj.push_back(Pair(std::to_string(denom), ValueFromAmount(blockindex->mapZerocoinSupply.at(denom) * (denom*COIN))));
}
zambkObj.push_back(Pair("total", ValueFromAmount(blockindex->GetZerocoinSupply())));
result.push_back(Pair("zAMBKsupply", zambkObj));
//////////
////////// Coin stake data ////////////////
/////////
if (block.IsProofOfStake()) {
// First grab it
uint256 hashProofOfStakeRet;
std::unique_ptr <CStakeInput> stake;
// Initialize the stake object (we should look for this in some other place and not initialize it every time..)
if (!initStakeInput(block, stake, blockindex->nHeight - 1))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Cannot initialize stake input");
unsigned int nTxTime = block.nTime;
// todo: Add the debug as param..
if (!GetHashProofOfStake(blockindex->pprev, stake.get(), nTxTime, false, hashProofOfStakeRet))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Cannot get proof of stake hash");
UniValue stakeData(UniValue::VOBJ);
stakeData.push_back(Pair("BlockFromHash", stake.get()->GetIndexFrom()->GetBlockHash().GetHex()));
stakeData.push_back(Pair("BlockFromHeight", stake.get()->GetIndexFrom()->nHeight));
stakeData.push_back(Pair("hashProofOfStake", hashProofOfStakeRet.GetHex()));
stakeData.push_back(Pair("stakeModifierHeight", ((stake->IsZAMBK()) ? "Not available" : std::to_string(
stake->getStakeModifierHeight()))));
result.push_back(Pair("CoinStake", stakeData));
}
return result;
}
UniValue getchecksumblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw std::runtime_error(
"getchecksumblock\n"
"\nFinds the first occurrence of a certain accumulator checksum."
"\nReturns the block hash or, if fVerbose=true, the JSON block object\n"
"\nArguments:\n"
"1. \"checksum\" (string, required) The hex encoded accumulator checksum\n"
"2. \"denom\" (integer, required) The denomination of the accumulator\n"
"3. fVerbose (boolean, optional, default=false) true for a json object, false for the hex encoded hash\n"
"\nResult (for fVerbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
" \"moneysupply\" : \"supply\" (numeric) The money supply when this block was added to the blockchain\n"
" \"zAMBKsupply\" :\n"
" {\n"
" \"1\" : n, (numeric) supply of 1 zAMBK denomination\n"
" \"5\" : n, (numeric) supply of 5 zAMBK denomination\n"
" \"10\" : n, (numeric) supply of 10 zAMBK denomination\n"
" \"50\" : n, (numeric) supply of 50 zAMBK denomination\n"
" \"100\" : n, (numeric) supply of 100 zAMBK denomination\n"
" \"500\" : n, (numeric) supply of 500 zAMBK denomination\n"
" \"1000\" : n, (numeric) supply of 1000 zAMBK denomination\n"
" \"5000\" : n, (numeric) supply of 5000 zAMBK denomination\n"
" \"total\" : n, (numeric) The total supply of all zAMBK denominations\n"
" }\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n" +
HelpExampleCli("getchecksumblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\", 5") +
HelpExampleRpc("getchecksumblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\", 5"));
LOCK(cs_main);
// param 0
std::string acc_checksum_str = params[0].get_str();
uint256 checksum_256(acc_checksum_str);
uint32_t acc_checksum = checksum_256.Get32();
// param 1
libzerocoin::CoinDenomination denomination = libzerocoin::IntToZerocoinDenomination(params[1].get_int());
// param 2
bool fVerbose = false;
if (params.size() > 2)
fVerbose = params[2].get_bool();
int checksumHeight = GetChecksumHeight(acc_checksum, denomination);
if (checksumHeight == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = chainActive[checksumHeight];
if (!fVerbose)
return pblockindex->GetBlockHash().GetHex();
CBlock block;
if (!ReadBlockFromDisk(block, pblockindex))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
return blockToJSON(block, pblockindex);
}
UniValue getblockcount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"getblockcount\n"
"\nReturns the number of blocks in the longest block chain.\n"
"\nResult:\n"
"n (numeric) The current block count\n"
"\nExamples:\n" +
HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", ""));
LOCK(cs_main);
return chainActive.Height();
}
UniValue getbestblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"getbestblockhash\n"
"\nReturns the hash of the best (tip) block in the longest block chain.\n"
"\nResult\n"
"\"hex\" (string) the block hash hex encoded\n"
"\nExamples\n" +
HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", ""));
LOCK(cs_main);
return chainActive.Tip()->GetBlockHash().GetHex();
}
void RPCNotifyBlockChange(const uint256 hashBlock)
{
CBlockIndex* pindex = nullptr;
pindex = mapBlockIndex.at(hashBlock);
if(pindex) {
std::lock_guard<std::mutex> lock(cs_blockchange);
latestblock.hash = pindex->GetBlockHash();
latestblock.height = pindex->nHeight;
}
cond_blockchange.notify_all();
}
UniValue waitfornewblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"waitfornewblock ( timeout )\n"
"\nWaits for a specific new block and returns useful info about it.\n"
"\nReturns the current block on timeout or exit.\n"
"\nArguments:\n"
"1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
"\nResult:\n"
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("waitfornewblock", "1000")
+ HelpExampleRpc("waitfornewblock", "1000")
);
int timeout = 0;
if (params.size() > 0)
timeout = params[0].get_int();
CUpdatedBlock block;
{
std::unique_lock<std::mutex> lock(cs_blockchange);
block = latestblock;
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
else
cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("hash", block.hash.GetHex()));
ret.push_back(Pair("height", block.height));
return ret;
}
UniValue waitforblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"waitforblock blockhash ( timeout )\n"
"\nWaits for a specific new block and returns useful info about it.\n"
"\nReturns the current block on timeout or exit.\n"
"\nArguments:\n"
"1. \"blockhash\" (required, std::string) Block hash to wait for.\n"
"2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
"\nResult:\n"
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
+ HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000")
);
int timeout = 0;
uint256 hash = uint256S(params[0].get_str());
if (params.size() > 1)
timeout = params[1].get_int();
CUpdatedBlock block;
{
std::unique_lock<std::mutex> lock(cs_blockchange);
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();});
else
cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("hash", block.hash.GetHex()));
ret.push_back(Pair("height", block.height));
return ret;
}
UniValue waitforblockheight(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"waitforblockheight height ( timeout )\n"
"\nWaits for (at least) block height and returns the height and hash\n"
"of the current tip.\n"
"\nReturns the current block on timeout or exit.\n"
"\nArguments:\n"
"1. height (required, int) Block height to wait for (int)\n"
"2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n"
"\nResult:\n"
"{ (json object)\n"
" \"hash\" : { (string) The blockhash\n"
" \"height\" : { (int) Block height\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("waitforblockheight", "\"100\", 1000")
+ HelpExampleRpc("waitforblockheight", "\"100\", 1000")
);
int timeout = 0;
int height = params[0].get_int();
if (params.size() > 1)
timeout = params[1].get_int();
CUpdatedBlock block;
{
std::unique_lock<std::mutex> lock(cs_blockchange);
if(timeout)
cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();});
else
cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); });
block = latestblock;
}
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("hash", block.hash.GetHex()));
ret.push_back(Pair("height", block.height));
return ret;
}
UniValue getdifficulty(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"getdifficulty\n"
"\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nResult:\n"
"n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nExamples:\n" +
HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", ""));
LOCK(cs_main);
return GetDifficulty();
}
UniValue mempoolToJSON(bool fVerbose = false)
{
if (fVerbose) {
LOCK(mempool.cs);
UniValue o(UniValue::VOBJ);
for (const PAIRTYPE(uint256, CTxMemPoolEntry) & entry : mempool.mapTx) {
const uint256& hash = entry.first;
const CTxMemPoolEntry& e = entry.second;
UniValue info(UniValue::VOBJ);
info.push_back(Pair("size", (int)e.GetTxSize()));
info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
info.push_back(Pair("time", e.GetTime()));
info.push_back(Pair("height", (int)e.GetHeight()));
info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight())));
info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height())));
const CTransaction& tx = e.GetTx();
std::set<std::string> setDepends;
for (const CTxIn& txin : tx.vin) {
if (mempool.exists(txin.prevout.hash))
setDepends.insert(txin.prevout.hash.ToString());
}
UniValue depends(UniValue::VARR);
for (const std::string& dep : setDepends) {
depends.push_back(dep);
}
info.push_back(Pair("depends", depends));
o.push_back(Pair(hash.ToString(), info));
}
return o;
} else {
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
UniValue a(UniValue::VARR);
for (const uint256& hash : vtxid)
a.push_back(hash.ToString());
return a;
}
}
UniValue getrawmempool(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"getrawmempool ( verbose )\n"
"\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
"\nArguments:\n"
"1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
"\nResult: (for verbose = false):\n"
"[ (json array of string)\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nResult: (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
" \"size\" : n, (numeric) transaction size in bytes\n"
" \"fee\" : n, (numeric) transaction fee in ambankcoin\n"
" \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
" \"height\" : n, (numeric) block height when transaction entered pool\n"
" \"startingpriority\" : n, (numeric) priority when transaction entered pool\n"
" \"currentpriority\" : n, (numeric) transaction priority now\n"
" \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
" \"transactionid\", (string) parent transaction id\n"
" ... ]\n"
" }, ...\n"
"]\n"
"\nExamples\n" +
HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true"));
LOCK(cs_main);
bool fVerbose = false;
if (params.size() > 0)
fVerbose = params[0].get_bool();
return mempoolToJSON(fVerbose);
}
UniValue getblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"getblockhash index\n"
"\nReturns hash of block in best-block-chain at index provided.\n"
"\nArguments:\n"
"1. index (numeric, required) The block index\n"
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n" +
HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000"));
LOCK(cs_main);
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > chainActive.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
CBlockIndex* pblockindex = chainActive[nHeight];
return pblockindex->GetBlockHash().GetHex();
}
UniValue getblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"getblock \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbose is true, returns an Object with information about block <hash>.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
" \"moneysupply\" : \"supply\" (numeric) The money supply when this block was added to the blockchain\n"
" \"zAMBKsupply\" :\n"
" {\n"
" \"1\" : n, (numeric) supply of 1 zAMBK denomination\n"
" \"5\" : n, (numeric) supply of 5 zAMBK denomination\n"
" \"10\" : n, (numeric) supply of 10 zAMBK denomination\n"
" \"50\" : n, (numeric) supply of 50 zAMBK denomination\n"
" \"100\" : n, (numeric) supply of 100 zAMBK denomination\n"
" \"500\" : n, (numeric) supply of 500 zAMBK denomination\n"
" \"1000\" : n, (numeric) supply of 1000 zAMBK denomination\n"
" \"5000\" : n, (numeric) supply of 5000 zAMBK denomination\n"
" \"total\" : n, (numeric) The total supply of all zAMBK denominations\n"
" },\n"
" \"CoinStake\" :\n"
" \"BlockFromHash\" : \"hash\", (string) Block hash of the coin stake input\n"
" \"BlockFromHeight\" : n, (numeric) Block Height of the coin stake input\n"
" \"hashProofOfStake\" : \"hash\", (string) Proof of Stake hash\n"
" \"stakeModifierHeight\" : \"nnn\" (string) Stake modifier block height\n"
" }\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n" +
HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") +
HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\""));
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(strHash);
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (!ReadBlockFromDisk(block, pblockindex))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
if (!fVerbose) {
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex);
}
UniValue getblockheader(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"getblockheader \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash' header.\n"
"If verbose is true, returns an Object with information about block <hash> header.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"version\" : n, (numeric) The block version\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash' header.\n"
"\nExamples:\n" +
HelpExampleCli("getblockheader", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"") +
HelpExampleRpc("getblockheader", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\""));
std::string strHash = params[0].get_str();
uint256 hash(strHash);
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (!fVerbose) {
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockheaderToJSON(pblockindex);
}
UniValue gettxoutsetinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"gettxoutsetinfo\n"
"\nReturns statistics about the unspent transaction output set.\n"
"Note this call may take some time.\n"
"\nResult:\n"
"{\n"
" \"height\":n, (numeric) The current block height (index)\n"
" \"bestblock\": \"hex\", (string) the best block hash hex\n"
" \"transactions\": n, (numeric) The number of transactions\n"
" \"txouts\": n, (numeric) The number of output transactions\n"
" \"bytes_serialized\": n, (numeric) The serialized size\n"
" \"hash_serialized\": \"hash\", (string) The serialized hash\n"
" \"total_amount\": x.xxx (numeric) The total amount\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", ""));
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
CCoinsStats stats;
FlushStateToDisk();
if (pcoinsTip->GetStats(stats)) {
ret.push_back(Pair("height", (int64_t)stats.nHeight));
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize));
ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
}
return ret;
}
UniValue gettxout(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw std::runtime_error(
"gettxout \"txid\" n ( includemempool )\n"
"\nReturns details about an unspent transaction output.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. n (numeric, required) vout value\n"
"3. includemempool (boolean, optional) Whether to included the mem pool\n"
"\nResult:\n"
"{\n"
" \"bestblock\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in btc\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of ambankcoin addresses\n"
" \"ambankcoinaddress\" (string) ambankcoin address\n"
" ,...\n"
" ]\n"
" },\n"
" \"version\" : n, (numeric) The version\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n"
"\nExamples:\n"
"\nGet unspent transactions\n" +
HelpExampleCli("listunspent", "") +
"\nView the details\n" +
HelpExampleCli("gettxout", "\"txid\" 1") +
"\nAs a json rpc call\n" +
HelpExampleRpc("gettxout", "\"txid\", 1"));
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
std::string strHash = params[0].get_str();
uint256 hash(strHash);
int n = params[1].get_int();
bool fMempool = true;
if (params.size() > 2)
fMempool = params[2].get_bool();
CCoins coins;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(pcoinsTip, mempool);
if (!view.GetCoins(hash, coins))
return NullUniValue;
mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
} else {
if (!pcoinsTip->GetCoins(hash, coins))
return NullUniValue;
}
if (n < 0 || (unsigned int)n >= coins.vout.size() || coins.vout[n].IsNull())
return NullUniValue;
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
CBlockIndex* pindex = it->second;
ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
ret.push_back(Pair("confirmations", 0));
else
ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1));
ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true);
ret.push_back(Pair("scriptPubKey", o));
ret.push_back(Pair("version", coins.nVersion));
ret.push_back(Pair("coinbase", coins.fCoinBase));
return ret;
}
UniValue verifychain(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"verifychain ( numblocks )\n"
"\nVerifies blockchain database.\n"
"\nArguments:\n"
"1. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n"
"\nResult:\n"
"true|false (boolean) Verified or not\n"
"\nExamples:\n" +
HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", ""));
LOCK(cs_main);
int nCheckLevel = 4;
int nCheckDepth = GetArg("-checkblocks", 288);
if (params.size() > 0)
nCheckDepth = params[0].get_int();
fVerifyingBlocks = true;
bool fVerified = CVerifyDB().VerifyDB(pcoinsTip, nCheckLevel, nCheckDepth);
fVerifyingBlocks = false;
return fVerified;
}
/** Implementation of IsSuperMajority with better feedback */
static UniValue SoftForkMajorityDesc(int minVersion, CBlockIndex* pindex, int nRequired)
{
int nFound = 0;
CBlockIndex* pstart = pindex;
for (int i = 0; i < Params().ToCheckBlockUpgradeMajority() && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("status", nFound >= nRequired));
rv.push_back(Pair("found", nFound));
rv.push_back(Pair("required", nRequired));
rv.push_back(Pair("window", Params().ToCheckBlockUpgradeMajority()));
return rv;
}
static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex)
{
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("id", name));
rv.push_back(Pair("version", version));
rv.push_back(Pair("enforce", SoftForkMajorityDesc(version, pindex, Params().EnforceBlockUpgradeMajority())));
rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, Params().RejectBlockOutdatedMajority())));
return rv;
}
UniValue getblockchaininfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"getblockchaininfo\n"
"Returns an object containing various state info regarding block chain processing.\n"
"\nResult:\n"
"{\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
" \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
" \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
" \"softforks\": [ (array) status of softforks in progress\n"
" {\n"
" \"id\": \"xxxx\", (string) name of softfork\n"
" \"version\": xx, (numeric) block version\n"
" \"enforce\": { (object) progress toward enforcing the softfork rules for new-version blocks\n"
" \"status\": xx, (boolean) true if threshold reached\n"
" \"found\": xx, (numeric) number of blocks with the new version found\n"
" \"required\": xx, (numeric) number of blocks required to trigger\n"
" \"window\": xx, (numeric) maximum size of examined window of recent blocks\n"
" },\n"
" \"reject\": { ... } (object) progress toward rejecting pre-softfork blocks (same fields as \"enforce\")\n"
" }, ...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", ""));
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("chain", Params().NetworkIDString()));
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(chainActive.Tip())));
obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
CBlockIndex* tip = chainActive.Tip();
UniValue softforks(UniValue::VARR);
softforks.push_back(SoftForkDesc("bip65", 5, tip));
obj.push_back(Pair("softforks", softforks));
return obj;
}
/** Comparison function for sorting the getchaintips heads. */
struct CompareBlocksByHeight {
bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
{
/* Make sure that unequal blocks with the same height do not compare
equal. Use the pointers themselves to make a distinction. */
if (a->nHeight != b->nHeight)
return (a->nHeight > b->nHeight);
return a < b;
}
};
UniValue getchaintips(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"getchaintips\n"
"Return information about all known tips in the block tree,"
" including the main chain as well as orphaned branches.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"height\": xxxx, (numeric) height of the chain tip\n"
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
" \"branchlen\": 0 (numeric) zero for main chain\n"
" \"status\": \"active\" (string) \"active\" for the main chain\n"
" },\n"
" {\n"
" \"height\": xxxx,\n"
" \"hash\": \"xxxx\",\n"
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
" }\n"
"]\n"
"Possible values for status:\n"
"1. \"invalid\" This branch contains at least one invalid block\n"
"2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
"3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
"4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
"5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
"\nExamples:\n" +
HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", ""));
LOCK(cs_main);
/* Build up a list of chain tips. We start with the list of all
known blocks, and successively remove blocks that appear as pprev
of another block. */
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
for (const PAIRTYPE(const uint256, CBlockIndex*) & item : mapBlockIndex)
setTips.insert(item.second);
for (const PAIRTYPE(const uint256, CBlockIndex*) & item : mapBlockIndex) {
const CBlockIndex* pprev = item.second->pprev;
if (pprev)
setTips.erase(pprev);
}
// Always report the currently active tip.
setTips.insert(chainActive.Tip());
/* Construct the output array. */
UniValue res(UniValue::VARR);
for (const CBlockIndex* block : setTips) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("height", block->nHeight));
obj.push_back(Pair("hash", block->phashBlock->GetHex()));
const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
obj.push_back(Pair("branchlen", branchLen));
std::string status;
if (chainActive.Contains(block)) {
// This block is part of the currently active chain.
status = "active";
} else if (block->nStatus & BLOCK_FAILED_MASK) {
// This block or one of its ancestors is invalid.
status = "invalid";
} else if (block->nChainTx == 0) {
// This block cannot be connected because full block data for it or one of its parents is missing.
status = "headers-only";
} else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
// This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
status = "valid-fork";
} else if (block->IsValid(BLOCK_VALID_TREE)) {
// The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
status = "valid-headers";
} else {
// No clue.
status = "unknown";
}
obj.push_back(Pair("status", status));
res.push_back(obj);
}
return res;
}
UniValue getfeeinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"getfeeinfo blocks\n"
"\nReturns details of transaction fees over the last n blocks.\n"
"\nArguments:\n"
"1. blocks (int, required) the number of blocks to get transaction data from\n"
"\nResult:\n"
"{\n"
" \"txcount\": xxxxx (numeric) Current tx count\n"
" \"txbytes\": xxxxx (numeric) Sum of all tx sizes\n"
" \"ttlfee\": xxxxx (numeric) Sum of all fees\n"
" \"feeperkb\": xxxxx (numeric) Average fee per kb over the block range\n"
" \"rec_highpriorityfee_perkb\": xxxxx (numeric) Recommended fee per kb to use for a high priority tx\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getfeeinfo", "5") + HelpExampleRpc("getfeeinfo", "5"));
int nBlocks = params[0].get_int();
int nBestHeight;
{
LOCK(cs_main);
nBestHeight = chainActive.Height();
}
int nStartHeight = nBestHeight - nBlocks;
if (nBlocks < 0 || nStartHeight <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid start height");
UniValue newParams(UniValue::VARR);
newParams.push_back(UniValue(nStartHeight));
newParams.push_back(UniValue(nBlocks));
newParams.push_back(UniValue(true)); // fFeeOnly
return getblockindexstats(newParams, false);
}
UniValue mempoolInfoToJSON()
{
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("size", (int64_t) mempool.size()));
ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
//ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
return ret;
}
UniValue getmempoolinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"getmempoolinfo\n"
"\nReturns details on the active state of the TX memory pool.\n"
"\nResult:\n"
"{\n"
" \"size\": xxxxx (numeric) Current tx count\n"
" \"bytes\": xxxxx (numeric) Sum of all tx sizes\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", ""));
return mempoolInfoToJSON();
}
UniValue invalidateblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"invalidateblock \"hash\"\n"
"\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to mark as invalid\n"
"\nExamples:\n" +
HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\""));
std::string strHash = params[0].get_str();
uint256 hash(strHash);
CValidationState state;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
InvalidateBlock(state, pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
UniValue reconsiderblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"reconsiderblock \"hash\"\n"
"\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
"This can be used to undo the effects of invalidateblock.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to reconsider\n"
"\nExamples:\n" +
HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\""));
std::string strHash = params[0].get_str();
uint256 hash(strHash);
CValidationState state;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
ReconsiderBlock(state, pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state);
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
UniValue findserial(const UniValue& params, bool fHelp)
{
if(fHelp || params.size() != 1)
throw std::runtime_error(
"findserial \"serial\"\n"
"\nSearches the zerocoin database for a zerocoin spend transaction that contains the specified serial\n"
"\nArguments:\n"
"1. serial (string, required) the serial of a zerocoin spend to search for.\n"
"\nResult:\n"
"{\n"
" \"success\": true|false (boolean) Whether the serial was found\n"
" \"txid\": \"xxx\" (string) The transaction that contains the spent serial\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("findserial", "\"serial\"") + HelpExampleRpc("findserial", "\"serial\""));
std::string strSerial = params[0].get_str();
CBigNum bnSerial = 0;
bnSerial.SetHex(strSerial);
if (!bnSerial)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid serial");
uint256 txid = 0;
bool fSuccess = zerocoinDB->ReadCoinSpend(bnSerial, txid);
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("success", fSuccess));
ret.push_back(Pair("txid", txid.GetHex()));
return ret;
}
UniValue getaccumulatorvalues(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"getaccumulatorvalues \"height\"\n"
"\nReturns the accumulator values associated with a block height\n"
"\nArguments:\n"
"1. height (numeric, required) the height of the checkpoint.\n"
"\nExamples:\n" +
HelpExampleCli("getaccumulatorvalues", "\"height\"") + HelpExampleRpc("getaccumulatorvalues", "\"height\""));
int nHeight = params[0].get_int();
CBlockIndex* pindex = chainActive[nHeight];
if (!pindex)
throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid block height");
UniValue ret(UniValue::VARR);
for (libzerocoin::CoinDenomination denom : libzerocoin::zerocoinDenomList) {
CBigNum bnValue;
if(!GetAccumulatorValueFromDB(pindex->nAccumulatorCheckpoint, denom, bnValue))
throw JSONRPCError(RPC_DATABASE_ERROR, "failed to find value in database");
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair(std::to_string(denom), bnValue.GetHex()));
ret.push_back(obj);
}
return ret;
}
UniValue getaccumulatorwitness(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw std::runtime_error(
"getaccumulatorwitness \"commitmentCoinValue, coinDenomination\"\n"
"\nReturns the accumulator witness value associated with the coin\n"
"\nArguments:\n"
"1. coinValue (string, required) the commitment value of the coin in HEX.\n"
"2. coinDenomination (numeric, required) the coin denomination.\n"
"\nResult:\n"
"{\n"
" \"Accumulator Value\": \"xxx\" (string) Accumulator hex value\n"
" \"Denomination\": \"d\" (integer) Accumulator denomination\n"
" \"Mints added\": \"d\" (integer) Number of mints added to the accumulator\n"
" \"Witness Value\": \"xxx\" (string) Witness hex value\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getaccumulatorwitness", "\"5fb87fb7bb638e83bfc14bcf33ac6f8064c9884dc72a4e652666abcf42cc47f9da0a7aca58076b0122a19b25629a6b6e7461f188baa7c00865b862cdb270d934873648aa12dd66e3242da40e4c17c78b70fded35e2d9c72933b455fadce9684586b1d48b10570d66feebe51ccebb1d98595217d06f41e66d5a0d9246d46ec3dd\" 5") + HelpExampleRpc("getaccumulatorwitness", "\"5fb87fb7bb638e83bfc14bcf33ac6f8064c9884dc72a4e652666abcf42cc47f9da0a7aca58076b0122a19b25629a6b6e7461f188baa7c00865b862cdb270d934873648aa12dd66e3242da40e4c17c78b70fded35e2d9c72933b455fadce9684586b1d48b10570d66feebe51ccebb1d98595217d06f41e66d5a0d9246d46ec3dd\", 5"));
CBigNum coinValue;
coinValue.SetHex(params[0].get_str());
int d = params[1].get_int();
libzerocoin::CoinDenomination denomination = libzerocoin::IntToZerocoinDenomination(d);
libzerocoin::ZerocoinParams* zcparams = Params().Zerocoin_Params(false);
// Public coin
libzerocoin::PublicCoin pubCoin(zcparams, coinValue, denomination);
//Compute Accumulator and Witness
libzerocoin::Accumulator accumulator(zcparams, pubCoin.getDenomination());
libzerocoin::AccumulatorWitness witness(zcparams, accumulator, pubCoin);
std::string strFailReason = "";
int nMintsAdded = 0;
CZerocoinSpendReceipt receipt;
if (!GenerateAccumulatorWitness(pubCoin, accumulator, witness, nMintsAdded, strFailReason)) {
receipt.SetStatus(_(strFailReason.c_str()), ZAMBK_FAILED_ACCUMULATOR_INITIALIZATION);
throw JSONRPCError(RPC_DATABASE_ERROR, receipt.GetStatusMessage());
}
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("Accumulator Value", accumulator.getValue().GetHex()));
obj.push_back(Pair("Denomination", accumulator.getDenomination()));
obj.push_back(Pair("Mints added",nMintsAdded));
obj.push_back(Pair("Witness Value", witness.getValue().GetHex()));
return obj;
}
void validaterange(const UniValue& params, int& heightStart, int& heightEnd, int minHeightStart)
{
if (params.size() < 2) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Not enough parameters in validaterange");
}
int nBestHeight;
{
LOCK(cs_main);
nBestHeight = chainActive.Height();
}
heightStart = params[0].get_int();
if (heightStart > nBestHeight) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid starting block (%d). Out of range.", heightStart));
}
const int range = params[1].get_int();
if (range < 1) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block range. Must be strictly positive.");
}
heightEnd = heightStart + range - 1;
if (heightStart < minHeightStart && heightEnd >= minHeightStart) {
heightStart = minHeightStart;
}
if (heightEnd > nBestHeight) {
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid ending block (%d). Out of range.", heightEnd));
}
}
UniValue getmintsinblocks(const UniValue& params, bool fHelp) {
if (fHelp || params.size() != 3)
throw std::runtime_error(
"getmintsinblocks height range coinDenomination\n"
"\nReturns the number of mints of a certain denomination"
"\noccurred in blocks [height, height+1, height+2, ..., height+range-1]\n"
"\nArguments:\n"
"1. height (numeric, required) block height where the search starts.\n"
"2. range (numeric, required) number of blocks to include.\n"
"3. coinDenomination (numeric, required) coin denomination.\n"
"\nResult:\n"
"{\n"
" \"Starting block\": \"x\" (integer) First counted block\n"
" \"Ending block\": \"x\" (integer) Last counted block\n"
" \"Number of d-denom mints\": \"x\" (integer) number of mints of the required d denomination\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getmintsinblocks", "1200000 1000 5") +
HelpExampleRpc("getmintsinblocks", "1200000, 1000, 5"));
int heightStart, heightEnd;
validaterange(params, heightStart, heightEnd, Params().Zerocoin_StartHeight());
int d = params[2].get_int();
libzerocoin::CoinDenomination denom = libzerocoin::IntToZerocoinDenomination(d);
if (denom == libzerocoin::CoinDenomination::ZQ_ERROR)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid denomination. Must be in {1, 5, 10, 50, 100, 500, 1000, 5000}");
int num_of_mints = 0;
{
LOCK(cs_main);
CBlockIndex* pindex = chainActive[heightStart];
while (true) {
num_of_mints += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), denom);
if (pindex->nHeight < heightEnd) {
pindex = chainActive.Next(pindex);
} else {
break;
}
}
}
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("Starting block", heightStart));
obj.push_back(Pair("Ending block", heightEnd-1));
obj.push_back(Pair("Number of "+ std::to_string(d) +"-denom mints", num_of_mints));
return obj;
}
UniValue getserials(const UniValue& params, bool fHelp) {
if (fHelp || params.size() < 2 || params.size() > 3)
throw std::runtime_error(
"getserials height range ( fVerbose )\n"
"\nLook the inputs of any tx in a range of blocks and returns the serial numbers for any coinspend.\n"
"\nArguments:\n"
"1. starting_height (numeric, required) the height of the first block to check\n"
"2. range (numeric, required) the amount of blocks to check\n"
"3. fVerbose (boolean, optional, default=False) return verbose output\n"
"\nExamples:\n" +
HelpExampleCli("getserials", "1254000 1000") +
HelpExampleRpc("getserials", "1254000, 1000"));
int heightStart, heightEnd;
validaterange(params, heightStart, heightEnd, Params().Zerocoin_StartHeight());
bool fVerbose = false;
if (params.size() > 2) {
fVerbose = params[2].get_bool();
}
CBlockIndex* pblockindex = nullptr;
{
LOCK(cs_main);
pblockindex = chainActive[heightStart];
}
if (!pblockindex)
throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid block height");
UniValue serialsObj(UniValue::VOBJ); // for fVerbose
UniValue serialsArr(UniValue::VARR);
while (true) {
CBlock block;
if (!ReadBlockFromDisk(block, pblockindex))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
// loop through each tx in the block
for (const CTransaction& tx : block.vtx) {
std::string txid = tx.GetHash().GetHex();
// collect the destination (first output) if fVerbose
std::string spentTo = "";
if (fVerbose) {
if (tx.vout[0].IsZerocoinMint()) {
spentTo = "Zerocoin Mint";
} else if (tx.vout[0].IsEmpty()) {
spentTo = "Zerocoin Stake";
} else {
txnouttype type;
std::vector<CTxDestination> addresses;
int nRequired;
if (!ExtractDestinations(tx.vout[0].scriptPubKey, type, addresses, nRequired)) {
spentTo = strprintf("type: %d", GetTxnOutputType(type));
} else {
spentTo = CBitcoinAddress(addresses[0]).ToString();
}
}
}
// loop through each input
for (const CTxIn& txin : tx.vin) {
bool isPublicSpend = txin.IsZerocoinPublicSpend();
if (txin.IsZerocoinSpend() || isPublicSpend) {
std::string serial_str;
int denom;
if (isPublicSpend) {
CTxOut prevOut;
CValidationState state;
if(!GetOutput(txin.prevout.hash, txin.prevout.n, state, prevOut)){
throw JSONRPCError(RPC_INTERNAL_ERROR, "public zerocoin spend prev output not found");
}
libzerocoin::ZerocoinParams *params = Params().Zerocoin_Params(false);
PublicCoinSpend publicSpend(params);
if (!ZAMBKModule::parseCoinSpend(txin, tx, prevOut, publicSpend)) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "public zerocoin spend parse failed");
}
serial_str = publicSpend.getCoinSerialNumber().ToString(16);
denom = libzerocoin::ZerocoinDenominationToInt(publicSpend.getDenomination());
} else {
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txin);
serial_str = spend.getCoinSerialNumber().ToString(16);
denom = libzerocoin::ZerocoinDenominationToInt(spend.getDenomination());
}
if (!fVerbose) {
serialsArr.push_back(serial_str);
} else {
UniValue s(UniValue::VOBJ);
s.push_back(Pair("serial", serial_str));
s.push_back(Pair("denom", denom));
s.push_back(Pair("bitsize", (int)serial_str.size()*4));
s.push_back(Pair("spentTo", spentTo));
s.push_back(Pair("txid", txid));
s.push_back(Pair("blocknum", pblockindex->nHeight));
s.push_back(Pair("blocktime", block.GetBlockTime()));
serialsArr.push_back(s);
}
}
} // end for vin in tx
} // end for tx in block
if (pblockindex->nHeight < heightEnd) {
LOCK(cs_main);
pblockindex = chainActive.Next(pblockindex);
} else {
break;
}
} // end for blocks
return serialsArr;
}
UniValue getblockindexstats(const UniValue& params, bool fHelp) {
if (fHelp || params.size() < 2 || params.size() > 3)
throw std::runtime_error(
"getblockindexstats height range ( fFeeOnly )\n"
"\nReturns aggregated BlockIndex data for blocks "
"\n[height, height+1, height+2, ..., height+range-1]\n"
"\nArguments:\n"
"1. height (numeric, required) block height where the search starts.\n"
"2. range (numeric, required) number of blocks to include.\n"
"3. fFeeOnly (boolean, optional, default=False) return only fee info.\n"
"\nResult:\n"
"{\n"
" \"first_block\": \"x\" (integer) First counted block\n"
" \"last_block\": \"x\" (integer) Last counted block\n"
" \"txcount\": xxxxx (numeric) tx count (excluding coinbase/coinstake)\n"
" \"txcount_all\": xxxxx (numeric) tx count (including coinbase/coinstake)\n"
" \"mintcount\": { [if fFeeOnly=False]\n"
" \"denom_1\": xxxx (numeric) number of mints of denom_1 occurred over the block range\n"
" \"denom_5\": xxxx (numeric) number of mints of denom_5 occurred over the block range\n"
" ... ... number of mints of other denominations: ..., 10, 50, 100, 500, 1000, 5000\n"
" }\n"
" \"spendcount\": { [if fFeeOnly=False]\n"
" \"denom_1\": xxxx (numeric) number of spends of denom_1 occurred over the block range\n"
" \"denom_5\": xxxx (numeric) number of spends of denom_5 occurred over the block range\n"
" ... ... number of spends of other denominations: ..., 10, 50, 100, 500, 1000, 5000\n"
" }\n"
" \"pubspendcount\": { [if fFeeOnly=False]\n"
" \"denom_1\": xxxx (numeric) number of PUBLIC spends of denom_1 occurred over the block range\n"
" \"denom_5\": xxxx (numeric) number of PUBLIC spends of denom_5 occurred over the block range\n"
" ... ... number of PUBLIC spends of other denominations: ..., 10, 50, 100, 500, 1000, 5000\n"
" }\n"
" \"txbytes\": xxxxx (numeric) Sum of the size of all txes (zAMBK excluded) over block range\n"
" \"ttlfee\": xxxxx (numeric) Sum of the fee amount of all txes (zAMBK mints excluded) over block range\n"
" \"ttlfee_all\": xxxxx (numeric) Sum of the fee amount of all txes (zAMBK mints included) over block range\n"
" \"feeperkb\": xxxxx (numeric) Average fee per kb (excluding zc txes)\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getblockindexstats", "1200000 1000") +
HelpExampleRpc("getblockindexstats", "1200000, 1000"));
int heightStart, heightEnd;
validaterange(params, heightStart, heightEnd);
// return object
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("Starting block", heightStart));
ret.push_back(Pair("Ending block", heightEnd));
bool fFeeOnly = false;
if (params.size() > 2) {
fFeeOnly = params[2].get_bool();
}
CAmount nFees = 0;
CAmount nFees_all = 0;
int64_t nBytes = 0;
int64_t nTxCount = 0;
int64_t nTxCount_all = 0;
std::map<libzerocoin::CoinDenomination, int64_t> mapMintCount;
std::map<libzerocoin::CoinDenomination, int64_t> mapSpendCount;
std::map<libzerocoin::CoinDenomination, int64_t> mapPublicSpendCount;
for (auto& denom : libzerocoin::zerocoinDenomList) {
mapMintCount.insert(std::make_pair(denom, 0));
mapSpendCount.insert(std::make_pair(denom, 0));
mapPublicSpendCount.insert(std::make_pair(denom, 0));
}
CBlockIndex* pindex = nullptr;
{
LOCK(cs_main);
pindex = chainActive[heightStart];
}
if (!pindex)
throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid block height");
while (true) {
CBlock block;
if (!ReadBlockFromDisk(block, pindex)) {
throw JSONRPCError(RPC_DATABASE_ERROR, "failed to read block from disk");
}
CAmount nValueIn = 0;
CAmount nValueOut = 0;
const int ntx = block.vtx.size();
nTxCount_all += ntx;
nTxCount = block.IsProofOfStake() ? nTxCount + ntx - 2 : nTxCount + ntx - 1;
// loop through each tx in block and save size and fee
for (const CTransaction& tx : block.vtx) {
if (tx.IsCoinBase() || (tx.IsCoinStake() && !tx.HasZerocoinSpendInputs()))
continue;
// fetch input value from prevouts and count spends
for (unsigned int j = 0; j < tx.vin.size(); j++) {
if (tx.vin[j].IsZerocoinSpend()) {
if (!fFeeOnly)
mapSpendCount[libzerocoin::IntToZerocoinDenomination(tx.vin[j].nSequence)]++;
continue;
}
if (tx.vin[j].IsZerocoinPublicSpend()) {
if (!fFeeOnly)
mapPublicSpendCount[libzerocoin::IntToZerocoinDenomination(tx.vin[j].nSequence)]++;
continue;
}
COutPoint prevout = tx.vin[j].prevout;
CTransaction txPrev;
uint256 hashBlock;
if(!GetTransaction(prevout.hash, txPrev, hashBlock, true))
throw JSONRPCError(RPC_DATABASE_ERROR, "failed to read tx from disk");
nValueIn += txPrev.vout[prevout.n].nValue;
}
// zc spends have no fee
if (tx.HasZerocoinSpendInputs())
continue;
// sum output values in nValueOut
for (unsigned int j = 0; j < tx.vout.size(); j++) {
nValueOut += tx.vout[j].nValue;
}
// update sums
nFees_all += nValueIn - nValueOut;
if (!tx.HasZerocoinMintOutputs()) {
nFees += nValueIn - nValueOut;
nBytes += tx.GetSerializeSize(SER_NETWORK, CLIENT_VERSION);
}
}
// add mints to map
if (!fFeeOnly) {
for (auto& denom : libzerocoin::zerocoinDenomList) {
mapMintCount[denom] += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), denom);
}
}
if (pindex->nHeight < heightEnd) {
LOCK(cs_main);
pindex = chainActive.Next(pindex);
} else {
break;
}
}
// get fee rate
CFeeRate nFeeRate = CFeeRate(nFees, nBytes);
// return UniValue object
ret.push_back(Pair("txcount", (int64_t)nTxCount));
ret.push_back(Pair("txcount_all", (int64_t)nTxCount_all));
if (!fFeeOnly) {
UniValue mint_obj(UniValue::VOBJ);
UniValue spend_obj(UniValue::VOBJ);
UniValue pubspend_obj(UniValue::VOBJ);
for (auto& denom : libzerocoin::zerocoinDenomList) {
mint_obj.push_back(Pair(strprintf("denom_%d", ZerocoinDenominationToInt(denom)), mapMintCount[denom]));
spend_obj.push_back(Pair(strprintf("denom_%d", ZerocoinDenominationToInt(denom)), mapSpendCount[denom]));
pubspend_obj.push_back(Pair(strprintf("denom_%d", ZerocoinDenominationToInt(denom)), mapPublicSpendCount[denom]));
}
ret.push_back(Pair("mintcount", mint_obj));
ret.push_back(Pair("spendcount", spend_obj));
ret.push_back(Pair("publicspendcount", pubspend_obj));
}
ret.push_back(Pair("txbytes", (int64_t)nBytes));
ret.push_back(Pair("ttlfee", FormatMoney(nFees)));
ret.push_back(Pair("ttlfee_all", FormatMoney(nFees_all)));
ret.push_back(Pair("feeperkb", FormatMoney(nFeeRate.GetFeePerK())));
return ret;
}
|
//===- mlir-cpu-runner.cpp - MLIR CPU Execution Driver---------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
//
// Main entry point to a command line utility that executes an MLIR file on the
// CPU by translating MLIR to LLVM IR before JIT-compiling and executing the
// latter.
//
//===----------------------------------------------------------------------===//
#include "mlir/Support/JitRunner.h"
int main(int argc, char **argv) {
return mlir::JitRunnerMain(argc, argv, nullptr);
}
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* 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 Willow Garage 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/plan_execution/plan_execution.h>
#include <moveit/robot_state/conversions.h>
#include <moveit/trajectory_processing/trajectory_tools.h>
#include <moveit/collision_detection/collision_tools.h>
#include <boost/algorithm/string/join.hpp>
#include <dynamic_reconfigure/server.h>
#include <moveit_ros_planning/PlanExecutionDynamicReconfigureConfig.h>
namespace plan_execution
{
using namespace moveit_ros_planning;
class PlanExecution::DynamicReconfigureImpl
{
public:
DynamicReconfigureImpl(PlanExecution* owner)
: owner_(owner), dynamic_reconfigure_server_(ros::NodeHandle("~/plan_execution"))
{
dynamic_reconfigure_server_.setCallback(
boost::bind(&DynamicReconfigureImpl::dynamicReconfigureCallback, this, _1, _2));
}
private:
void dynamicReconfigureCallback(PlanExecutionDynamicReconfigureConfig& config, uint32_t level)
{
owner_->setMaxReplanAttempts(config.max_replan_attempts);
owner_->setTrajectoryStateRecordingFrequency(config.record_trajectory_state_frequency);
}
PlanExecution* owner_;
dynamic_reconfigure::Server<PlanExecutionDynamicReconfigureConfig> dynamic_reconfigure_server_;
};
}
plan_execution::PlanExecution::PlanExecution(
const planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor,
const trajectory_execution_manager::TrajectoryExecutionManagerPtr& trajectory_execution)
: node_handle_("~")
, planning_scene_monitor_(planning_scene_monitor)
, trajectory_execution_manager_(trajectory_execution)
{
if (!trajectory_execution_manager_)
trajectory_execution_manager_.reset(new trajectory_execution_manager::TrajectoryExecutionManager(
planning_scene_monitor_->getRobotModel(), planning_scene_monitor_->getStateMonitor()));
default_max_replan_attempts_ = 5;
preempt_requested_ = false;
new_scene_update_ = false;
// we want to be notified when new information is available
planning_scene_monitor_->addUpdateCallback(boost::bind(&PlanExecution::planningSceneUpdatedCallback, this, _1));
// start the dynamic-reconfigure server
reconfigure_impl_ = new DynamicReconfigureImpl(this);
}
plan_execution::PlanExecution::~PlanExecution()
{
delete reconfigure_impl_;
}
void plan_execution::PlanExecution::stop()
{
preempt_requested_ = true;
}
std::string plan_execution::PlanExecution::getErrorCodeString(const moveit_msgs::MoveItErrorCodes& error_code)
{
if (error_code.val == moveit_msgs::MoveItErrorCodes::SUCCESS)
return "Success";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME)
return "Invalid group name";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::PLANNING_FAILED)
return "Planning failed.";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN)
return "Invalid motion plan";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::UNABLE_TO_AQUIRE_SENSOR_DATA)
return "Unable to aquire sensor data";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::MOTION_PLAN_INVALIDATED_BY_ENVIRONMENT_CHANGE)
return "Motion plan invalidated by environment change";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::CONTROL_FAILED)
return "Controller failed during execution";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::TIMED_OUT)
return "Timeout reached";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::PREEMPTED)
return "Preempted";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS)
return "Invalid goal constraints";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::INVALID_OBJECT_NAME)
return "Invalid object name";
else if (error_code.val == moveit_msgs::MoveItErrorCodes::FAILURE)
return "Catastrophic failure";
return "Unknown event";
}
void plan_execution::PlanExecution::planAndExecute(ExecutableMotionPlan& plan, const Options& opt)
{
plan.planning_scene_monitor_ = planning_scene_monitor_;
plan.planning_scene_ = planning_scene_monitor_->getPlanningScene();
planAndExecuteHelper(plan, opt);
}
void plan_execution::PlanExecution::planAndExecute(ExecutableMotionPlan& plan,
const moveit_msgs::PlanningScene& scene_diff, const Options& opt)
{
if (planning_scene::PlanningScene::isEmpty(scene_diff))
planAndExecute(plan, opt);
else
{
plan.planning_scene_monitor_ = planning_scene_monitor_;
{
planning_scene_monitor::LockedPlanningSceneRO lscene(planning_scene_monitor_); // lock the scene so that it does
// not modify the world
// representation while diff() is
// called
plan.planning_scene_ = lscene->diff(scene_diff);
}
planAndExecuteHelper(plan, opt);
}
}
void plan_execution::PlanExecution::planAndExecuteHelper(ExecutableMotionPlan& plan, const Options& opt)
{
// perform initial configuration steps & various checks
preempt_requested_ = false;
// run the actual motion plan & execution
unsigned int max_replan_attempts =
opt.replan_ ? (opt.replan_attempts_ > 0 ? opt.replan_attempts_ : default_max_replan_attempts_) : 1;
unsigned int replan_attempts = 0;
bool previously_solved = false;
// run a planning loop for at most the maximum replanning attempts;
// re-planning is executed only in case of known types of failures (e.g., environment changed)
do
{
replan_attempts++;
ROS_INFO("Planning attempt %u of at most %u", replan_attempts, max_replan_attempts);
if (opt.before_plan_callback_)
opt.before_plan_callback_();
new_scene_update_ = false; // we clear any scene updates to be evaluated because we are about to compute a new
// plan, which should consider most recent updates already
// if we never had a solved plan, or there is no specified way of fixing plans, just call the planner; otherwise,
// try to repair the plan we previously had;
bool solved =
(!previously_solved || !opt.repair_plan_callback_) ?
opt.plan_callback_(plan) :
opt.repair_plan_callback_(plan, trajectory_execution_manager_->getCurrentExpectedTrajectoryIndex());
if (preempt_requested_)
break;
// if planning fails in a manner that is not recoverable, we exit the loop,
// otherwise, we attempt to continue, if replanning attempts are left
if (plan.error_code_.val == moveit_msgs::MoveItErrorCodes::PLANNING_FAILED ||
plan.error_code_.val == moveit_msgs::MoveItErrorCodes::INVALID_MOTION_PLAN ||
plan.error_code_.val == moveit_msgs::MoveItErrorCodes::UNABLE_TO_AQUIRE_SENSOR_DATA)
{
if (plan.error_code_.val == moveit_msgs::MoveItErrorCodes::UNABLE_TO_AQUIRE_SENSOR_DATA &&
opt.replan_delay_ > 0.0)
{
ros::WallDuration d(opt.replan_delay_);
d.sleep();
}
continue;
}
// abort if no plan was found
if (solved)
previously_solved = true;
else
break;
if (plan.error_code_.val == moveit_msgs::MoveItErrorCodes::SUCCESS)
{
if (opt.before_execution_callback_)
opt.before_execution_callback_();
if (preempt_requested_)
break;
// execute the trajectory, and monitor its executionm
plan.error_code_ = executeAndMonitor(plan);
}
// if we are done, then we exit the loop
if (plan.error_code_.val == moveit_msgs::MoveItErrorCodes::SUCCESS)
break;
// if execution failed in a manner that we do not consider recoverable, we exit the loop (with failure)
if (plan.error_code_.val != moveit_msgs::MoveItErrorCodes::MOTION_PLAN_INVALIDATED_BY_ENVIRONMENT_CHANGE)
break;
else
{
// othewrise, we wait (if needed)
if (opt.replan_delay_ > 0.0)
{
ROS_INFO("Waiting for a %lf seconds before attempting a new plan ...", opt.replan_delay_);
ros::WallDuration d(opt.replan_delay_);
d.sleep();
ROS_INFO("Done waiting");
}
}
} while (!preempt_requested_ && max_replan_attempts > replan_attempts);
if (preempt_requested_)
{
ROS_DEBUG("PlanExecution was preempted");
plan.error_code_.val = moveit_msgs::MoveItErrorCodes::PREEMPTED;
}
if (opt.done_callback_)
opt.done_callback_();
if (plan.error_code_.val == moveit_msgs::MoveItErrorCodes::SUCCESS)
ROS_DEBUG("PlanExecution finished successfully.");
else
ROS_DEBUG("PlanExecution terminating with error code %d - '%s'", plan.error_code_.val,
getErrorCodeString(plan.error_code_).c_str());
}
bool plan_execution::PlanExecution::isRemainingPathValid(const ExecutableMotionPlan& plan)
{
// check the validity of the currently executed path segment only, since there could be
// changes in the world in between path segments
return isRemainingPathValid(plan, trajectory_execution_manager_->getCurrentExpectedTrajectoryIndex());
}
bool plan_execution::PlanExecution::isRemainingPathValid(const ExecutableMotionPlan& plan,
const std::pair<int, int>& path_segment)
{
if (path_segment.first >= 0 && path_segment.second >= 0 &&
plan.plan_components_[path_segment.first].trajectory_monitoring_)
{
planning_scene_monitor::LockedPlanningSceneRO lscene(plan.planning_scene_monitor_); // lock the scene so that it
// does not modify the world
// representation while
// isStateValid() is called
const robot_trajectory::RobotTrajectory& t = *plan.plan_components_[path_segment.first].trajectory_;
const collision_detection::AllowedCollisionMatrix* acm =
plan.plan_components_[path_segment.first].allowed_collision_matrix_.get();
std::size_t wpc = t.getWayPointCount();
collision_detection::CollisionRequest req;
req.group_name = t.getGroupName();
for (std::size_t i = std::max(path_segment.second - 1, 0); i < wpc; ++i)
{
collision_detection::CollisionResult res;
if (acm)
plan.planning_scene_->checkCollisionUnpadded(req, res, t.getWayPoint(i), *acm);
else
plan.planning_scene_->checkCollisionUnpadded(req, res, t.getWayPoint(i));
if (res.collision || !plan.planning_scene_->isStateFeasible(t.getWayPoint(i), false))
{
// Dave's debacle
ROS_INFO("Trajectory component '%s' is invalid",
plan.plan_components_[path_segment.first].description_.c_str());
// call the same functions again, in verbose mode, to show what issues have been detected
plan.planning_scene_->isStateFeasible(t.getWayPoint(i), true);
req.verbose = true;
res.clear();
if (acm)
plan.planning_scene_->checkCollisionUnpadded(req, res, t.getWayPoint(i), *acm);
else
plan.planning_scene_->checkCollisionUnpadded(req, res, t.getWayPoint(i));
return false;
}
}
}
return true;
}
moveit_msgs::MoveItErrorCodes plan_execution::PlanExecution::executeAndMonitor(const ExecutableMotionPlan& plan)
{
moveit_msgs::MoveItErrorCodes result;
// try to execute the trajectory
execution_complete_ = true;
if (!trajectory_execution_manager_)
{
ROS_ERROR("No trajectory execution manager");
result.val = moveit_msgs::MoveItErrorCodes::CONTROL_FAILED;
return result;
}
if (plan.plan_components_.empty())
{
result.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
return result;
}
execution_complete_ = false;
// push the trajectories we have slated for execution to the trajectory execution manager
int prev = -1;
for (std::size_t i = 0; i < plan.plan_components_.size(); ++i)
{
if (!plan.plan_components_[i].trajectory_ || plan.plan_components_[i].trajectory_->empty())
continue;
// \todo should this be in trajectory_execution ? Maybe. Then that will have to use kinematic_trajectory too;
// spliting trajectories for controllers becomes interesting: tied to groups instead of joints. this could cause
// some problems
// in the meantime we do a hack:
bool unwound = false;
for (std::size_t j = 0; j < i; ++j)
// if we ran unwind on a path for the same group
if (plan.plan_components_[j].trajectory_ &&
plan.plan_components_[j].trajectory_->getGroup() == plan.plan_components_[i].trajectory_->getGroup() &&
!plan.plan_components_[j].trajectory_->empty())
{
plan.plan_components_[i].trajectory_->unwind(plan.plan_components_[j].trajectory_->getLastWayPoint());
unwound = true;
break;
}
if (!unwound)
{
// unwind the path to execute based on the current state of the system
if (prev < 0)
plan.plan_components_[i].trajectory_->unwind(
plan.planning_scene_monitor_ && plan.planning_scene_monitor_->getStateMonitor() ?
*plan.planning_scene_monitor_->getStateMonitor()->getCurrentState() :
plan.planning_scene_->getCurrentState());
else
plan.plan_components_[i].trajectory_->unwind(plan.plan_components_[prev].trajectory_->getLastWayPoint());
}
prev = i;
// convert to message, pass along
moveit_msgs::RobotTrajectory msg;
plan.plan_components_[i].trajectory_->getRobotTrajectoryMsg(msg);
if (!trajectory_execution_manager_->push(msg))
{
trajectory_execution_manager_->clear();
ROS_ERROR_STREAM("Apparently trajectory initialization failed");
execution_complete_ = true;
result.val = moveit_msgs::MoveItErrorCodes::CONTROL_FAILED;
return result;
}
}
if (!trajectory_monitor_ && planning_scene_monitor_->getStateMonitor())
trajectory_monitor_.reset(
new planning_scene_monitor::TrajectoryMonitor(planning_scene_monitor_->getStateMonitor()));
// start recording trajectory states
if (trajectory_monitor_)
trajectory_monitor_->startTrajectoryMonitor();
// start a trajectory execution thread
trajectory_execution_manager_->execute(
boost::bind(&PlanExecution::doneWithTrajectoryExecution, this, _1),
boost::bind(&PlanExecution::successfulTrajectorySegmentExecution, this, &plan, _1));
// wait for path to be done, while checking that the path does not become invalid
ros::Rate r(100);
path_became_invalid_ = false;
while (node_handle_.ok() && !execution_complete_ && !preempt_requested_ && !path_became_invalid_)
{
r.sleep();
// check the path if there was an environment update in the meantime
if (new_scene_update_)
{
new_scene_update_ = false;
if (!isRemainingPathValid(plan))
{
path_became_invalid_ = true;
break;
}
}
}
// stop execution if needed
if (preempt_requested_)
{
ROS_INFO("Stopping execution due to preempt request");
trajectory_execution_manager_->stopExecution();
}
else if (path_became_invalid_)
{
ROS_INFO("Stopping execution because the path to execute became invalid (probably the environment changed)");
trajectory_execution_manager_->stopExecution();
}
else if (!execution_complete_)
{
ROS_WARN("Stopping execution due to unknown reason. Possibly the node is about to shut down.");
trajectory_execution_manager_->stopExecution();
}
// stop recording trajectory states
if (trajectory_monitor_)
trajectory_monitor_->stopTrajectoryMonitor();
// decide return value
if (path_became_invalid_)
result.val = moveit_msgs::MoveItErrorCodes::MOTION_PLAN_INVALIDATED_BY_ENVIRONMENT_CHANGE;
else
{
if (preempt_requested_)
{
result.val = moveit_msgs::MoveItErrorCodes::PREEMPTED;
}
else
{
if (trajectory_execution_manager_->getLastExecutionStatus() ==
moveit_controller_manager::ExecutionStatus::SUCCEEDED)
result.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
else if (trajectory_execution_manager_->getLastExecutionStatus() ==
moveit_controller_manager::ExecutionStatus::TIMED_OUT)
result.val = moveit_msgs::MoveItErrorCodes::TIMED_OUT;
else
result.val = moveit_msgs::MoveItErrorCodes::CONTROL_FAILED;
}
}
return result;
}
void plan_execution::PlanExecution::planningSceneUpdatedCallback(
const planning_scene_monitor::PlanningSceneMonitor::SceneUpdateType update_type)
{
if (update_type & (planning_scene_monitor::PlanningSceneMonitor::UPDATE_GEOMETRY |
planning_scene_monitor::PlanningSceneMonitor::UPDATE_TRANSFORMS))
new_scene_update_ = true;
}
void plan_execution::PlanExecution::doneWithTrajectoryExecution(
const moveit_controller_manager::ExecutionStatus& status)
{
execution_complete_ = true;
}
void plan_execution::PlanExecution::successfulTrajectorySegmentExecution(const ExecutableMotionPlan* plan,
std::size_t index)
{
ROS_DEBUG("Completed '%s'", plan->plan_components_[index].description_.c_str());
// if any side-effects are associated to the trajectory part that just completed, execute them
if (plan->plan_components_[index].effect_on_success_)
if (!plan->plan_components_[index].effect_on_success_(plan))
{
// execution of side-effect failed
ROS_ERROR("Execution of path-completion side-effect failed. Preempting.");
preempt_requested_ = true;
return;
}
// if there is a next trajectory, check it for validity, before we start execution
std::size_t test_index = index;
while (++test_index < plan->plan_components_.size())
if (plan->plan_components_[test_index].trajectory_ && !plan->plan_components_[test_index].trajectory_->empty())
{
if (!isRemainingPathValid(*plan, std::make_pair<int>(test_index, 0)))
path_became_invalid_ = true;
break;
}
}
|
#include <vector>
#include <Rcpp.h>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/index/rtree.hpp>
using namespace Rcpp;
#include "landscape.h"
#include <vector>
#include <algorithm>
#include <functional>
std::mt19937 rng;
void Resources::initResources() {
// generate n central items
std::vector<float> centreCoordX (nClusters);
std::vector<float> centreCoordY (nClusters);
std::uniform_real_distribution<float> item_ran_pos(0.0f, dSize);
std::normal_distribution<float> item_cluster_spread(0.0f, clusterSpread);
for(size_t i = 0; i < static_cast<size_t>(nClusters); i++) {
centreCoordX[i] = item_ran_pos(rng);
centreCoordY[i] = item_ran_pos(rng);
// also add to main set
coordX[i] = centreCoordX[i];
coordY[i] = centreCoordY[i];
}
// generate items around
for(int i = nClusters; i < nItems; i++) {
coordX[i] = (centreCoordX[(i % nClusters)] + item_cluster_spread(rng));
coordY[i] = (centreCoordY[(i % nClusters)] + item_cluster_spread(rng));
// wrap
coordX[i] = fmod(dSize + coordX[i], dSize);
coordY[i] = fmod(dSize + coordY[i], dSize);
}
// dist to set random counter value
std::poisson_distribution<int> distRegen(static_cast<int>(std::floor(static_cast<float>(regen_time) * 0.1)));
// initialise rtree and set counter value
bgi::rtree< value, bgi::quadratic<16> > tmpRtree;
for (int i = 0; i < nItems; ++i)
{
point p = point(coordX[i], coordY[i]);
tmpRtree.insert(std::make_pair(p, i));
counter[i] = distRegen(rng);
// set all to available
available[i] = (counter[i] == 0);
}
std::swap(rtree, tmpRtree);
tmpRtree.clear();
}
void Resources::countAvailable() {
nAvailable = 0;
// counter set to max regeneration value on foraging
for (size_t i = 0; i < static_cast<size_t>(nItems); i++){
if(counter[i] == 0) {
nAvailable ++;
}
}
}
void Resources::regenerate() {
for (int i = 0; i < nItems; i++)
{
counter[i] -= (counter[i] > 0 ? 1 : 0);
available[i] = (counter[i] == 0);
}
// set availability
countAvailable();
}
/// function to export landscape as matrix
//' Returns a test landscape.
//'
//' @param nItems How many items.
//' @param landsize Size as a numeric (float).
//' @param nClusters How many clusters, an integer value.
//' @param clusterSpread Dispersal of items around cluster centres.
//' @param regen_time Regeneration time, in timesteps.
//' @return A data frame of the evolved population traits.
// [[Rcpp::export]]
Rcpp::DataFrame get_test_landscape(
const int nItems, const float landsize,
const int nClusters, const float clusterSpread,
const int regen_time) {
unsigned seed = static_cast<unsigned> (std::chrono::system_clock::now().time_since_epoch().count());
rng.seed(seed);
Resources food (nItems, landsize, nClusters, clusterSpread, regen_time);
food.initResources();
return Rcpp::DataFrame::create(
Rcpp::Named("x") = food.coordX,
Rcpp::Named("y") = food.coordY,
Rcpp::Named("tAvail") = food.counter
);
}
|
#include "LinearAlgebra.h"
void LinearAlgebra::product(matrix& A, vector& v, vector& v1)
{
if (A.value != NULL && v.value != NULL && v.n == A.n)
{
bool flag = true;
if (v1.value == NULL && v1.n != A.m)
{
flag = vec.initialize(v1, A.m);
}
if (flag == true)
{
for (int i = 0; i < A.m; i++)
{
for (int j = 0; j < A.n; j++)
{
v1.value[i] += A.value[i][j] * v.value[j];
}
}
}
}
}
|
/* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "base-precomp.h" // Precompiled headers
#include <mrpt/poses/SO_SE_average.h>
using namespace mrpt;
using namespace mrpt::math;
using namespace mrpt::utils;
using namespace mrpt::poses;
// ----------- SO_average<2> --------------------
SO_average<2>::SO_average() :
enable_exception_on_undeterminate(false),
m_count(0),
m_accum_x(0),m_accum_y(0)
{
}
void SO_average<2>::clear() {
m_count=.0;
m_accum_x=m_accum_y=.0;
}
void SO_average<2>::append(const double orientation_rad) {
append(orientation_rad,1.0);
}
void SO_average<2>::append(const double orientation_rad, const double weight) {
m_count += weight;
m_accum_x += cos(orientation_rad) * weight;
m_accum_y += sin(orientation_rad) * weight;
}
double SO_average<2>::get_average() const
{
ASSERT_ABOVE_(m_count,0);
const double x = m_accum_x / m_count;
const double y = m_accum_y / m_count;
errno=0;
double ang = atan2(y,x);
if (errno==EDOM)
{
if (enable_exception_on_undeterminate)
throw std::runtime_error("[SO_average<2>::get_average()] Undetermined average value");
else ang = 0;
}
return ang;
}
// ----------- SO_average<3> --------------------
SO_average<3>::SO_average() :
enable_exception_on_undeterminate(false),
m_count(0),
m_accum_rot()
{
clear();
}
void SO_average<3>::clear() {
m_count=.0;
m_accum_rot.setZero();
}
void SO_average<3>::append(const Eigen::Matrix3d &M) {
append(M,1.0);
}
void SO_average<3>::append(const Eigen::Matrix3d &M, const double weight) {
m_count += weight;
m_accum_rot += weight*M;
}
// See: eq. (3.7) in "MEANS AND AVERAGING IN THE GROUP OF ROTATIONS", MAHER MOAKHER, 2002.
Eigen::Matrix3d SO_average<3>::get_average() const
{
ASSERT_ABOVE_(m_count,0);
const Eigen::Matrix3d MtM = m_accum_rot.transpose() * m_accum_rot;
Eigen::JacobiSVD<Eigen::Matrix3d> svd(MtM, Eigen::ComputeFullU);
const Eigen::Vector3d vs = svd.singularValues();
errno=0;
const double d1 = 1.0/sqrt(vs[0]);
const double d2 = 1.0/sqrt(vs[1]);
const double d3 = mrpt::utils::sign( m_accum_rot.determinant() )/sqrt(vs[2]);
if (errno!=0)
{
if (enable_exception_on_undeterminate)
throw std::runtime_error("[SO_average<3>::get_average()] Undetermined average value");
else return Eigen::Matrix3d::Identity();
}
Eigen::Matrix3d D = Eigen::Matrix3d::Zero();
D(0,0)=d1; D(1,1)=d2; D(2,2)=d3;
Eigen::Matrix3d ret = m_accum_rot * svd.matrixU() * D * svd.matrixU().transpose();
return ret;
}
// ----------- SE_average<2> --------------------
SE_average<2>::SE_average() :
enable_exception_on_undeterminate(false),
m_count(0),
m_accum_x(0),m_accum_y(0),
m_rot_part()
{
clear();
}
void SE_average<2>::clear() {
m_count=.0;
m_accum_x=m_accum_y=.0;
m_rot_part.clear();
}
void SE_average<2>::append(const mrpt::poses::CPose2D &p) {
append(p,1.0);
}
void SE_average<2>::append(const mrpt::poses::CPose2D &p, const double weight) {
m_count += weight;
m_accum_x += weight * p.x();
m_accum_y += weight * p.y();
m_rot_part.append(p.phi(), weight);
}
void SE_average<2>::get_average(mrpt::poses::CPose2D &ret_mean) const
{
ASSERT_ABOVE_(m_count,0);
ret_mean.x( m_accum_x / m_count );
ret_mean.y( m_accum_y / m_count );
const_cast<SO_average<2>*>(&m_rot_part)->enable_exception_on_undeterminate = this->enable_exception_on_undeterminate;
ret_mean.phi ( m_rot_part.get_average() );
}
// ----------- SE_average<3> --------------------
SE_average<3>::SE_average() :
enable_exception_on_undeterminate(false),
m_count(0),
m_accum_x(0),m_accum_y(0),m_accum_z(0),
m_rot_part()
{
clear();
}
void SE_average<3>::clear() {
m_count=.0;
m_accum_x=m_accum_y=m_accum_z=.0;
m_rot_part.clear();
}
void SE_average<3>::append(const mrpt::poses::CPose3D &p) {
append(p,1.0);
}
void SE_average<3>::append(const mrpt::poses::CPose3D &p, const double weight) {
m_count += weight;
m_accum_x += weight * p.x();
m_accum_y += weight * p.y();
m_accum_z += weight * p.z();
m_rot_part.append(p.getRotationMatrix(), weight);
}
void SE_average<3>::get_average(mrpt::poses::CPose3D &ret_mean) const
{
ASSERT_ABOVE_(m_count,0);
ret_mean.x( m_accum_x / m_count );
ret_mean.y( m_accum_y / m_count );
ret_mean.z( m_accum_z / m_count );
const_cast<SO_average<3>*>(&m_rot_part)->enable_exception_on_undeterminate = this->enable_exception_on_undeterminate;
ret_mean.setRotationMatrix( m_rot_part.get_average() );
}
|
/* THIS FILE WAS AUTOMATICALLY GENERATED BY format.py */
#pragma once
const char *lineitem_sample = "1|15519|785|1|17|24386.670000|0.040000|0.020000|N|O|1996-03-13|1996-02-12|1996-03-22|DELIVER IN PERSON|TRUCK|egular courts above the\n1|6731|732|2|36|58958.280000|0.090000|0.060000|N|O|1996-04-12|1996-02-28|1996-04-20|TAKE BACK RETURN|MAIL|ly final dependencies: slyly bold \n1|6370|371|3|8|10210.960000|0.100000|0.020000|N|O|1996-01-29|1996-03-05|1996-01-31|TAKE BACK RETURN|REG AIR|riously. regular, express dep\n1|214|465|4|28|31197.880000|0.090000|0.060000|N|O|1996-04-21|1996-03-30|1996-05-16|NONE|AIR|lites. fluffily even de\n1|2403|160|5|24|31329.600000|0.100000|0.040000|N|O|1996-03-30|1996-03-14|1996-04-01|NONE|FOB| pending foxes. slyly re\n1|1564|67|6|32|46897.920000|0.070000|0.020000|N|O|1996-01-30|1996-02-07|1996-02-03|DELIVER IN PERSON|MAIL|arefully slyly ex\n2|10617|138|1|38|58049.180000|0.000000|0.050000|N|O|1997-01-28|1997-01-14|1997-02-02|TAKE BACK RETURN|RAIL|ven requests. deposits breach a\n3|430|181|1|45|59869.350000|0.060000|0.000000|R|F|1994-02-02|1994-01-04|1994-02-23|NONE|AIR|ongside of the furiously brave acco\n3|1904|658|2|49|88489.100000|0.100000|0.000000|R|F|1993-11-09|1993-12-20|1993-11-24|TAKE BACK RETURN|RAIL| unusual accounts. eve\n3|12845|370|3|27|47461.680000|0.060000|0.070000|A|F|1994-01-16|1993-11-22|1994-01-23|DELIVER IN PERSON|SHIP|nal foxes wake. \n";
const char *web_page = "1|AAAAAAAABAAAAAAA|1997-09-03||2450810|2452620|Y|98539|http://www.foo.com|welcome|2531|8|3|4\n2|AAAAAAAACAAAAAAA|1997-09-03|2000-09-02|2450814|2452580|N||http://www.foo.com|protected|1564|4|3|1\n3|AAAAAAAACAAAAAAA|2000-09-03||2450814|2452611|N||http://www.foo.com|feedback|1564|4|3|4\n4|AAAAAAAAEAAAAAAA|1997-09-03|1999-09-03|2450812|2452579|N||http://www.foo.com|general|3732|18|7|1\n5|AAAAAAAAEAAAAAAA|1999-09-04|2001-09-02|2450812|2452597|N||http://www.foo.com|welcome|3732|18|3|1\n6|AAAAAAAAEAAAAAAA|2001-09-03||2450814|2452597|N||http://www.foo.com|ad|3732|18|7|4\n7|AAAAAAAAHAAAAAAA|1997-09-03||2450815|2452574|N||http://www.foo.com|feedback|3034|18|7|4\n8|AAAAAAAAIAAAAAAA|1997-09-03|2000-09-02|2450815|2452646|Y|1898|http://www.foo.com|protected|3128|12|2|4\n9|AAAAAAAAIAAAAAAA|2000-09-03||2450807|2452579|Y|84146|http://www.foo.com|welcome|3128|13|5|3\n10|AAAAAAAAKAAAAAAA|1997-09-03|1999-09-03||2452623|N||http://www.foo.com|||||\n11|AAAAAAAAKAAAAAAA|1999-09-04|2001-09-02|2450814|2452611|N||http://www.foo.com|welcome|7046|23|4|4\n12|AAAAAAAAKAAAAAAA|2001-09-03||2450815|2452611|N||http://www.foo.com|protected|7046|17|4|4\n13|AAAAAAAANAAAAAAA|1997-09-03||2450807|2452629|N||http://www.foo.com|protected|2281|6|4|1\n14|AAAAAAAAOAAAAAAA|1997-09-03|2000-09-02|2450810|2452639|N||http://www.foo.com|dynamic|5676|19|6|0\n15|AAAAAAAAOAAAAAAA|2000-09-03||2450810|2452639|N||http://www.foo.com|dynamic|2469|10|5|2\n16|AAAAAAAAABAAAAAA|1997-09-03|1999-09-03|2450814|2452601|Y|33463|http://www.foo.com|feedback|701|2|1|4\n17|AAAAAAAAABAAAAAA|1999-09-04|2001-09-02|2450812|2452645|N||http://www.foo.com|general|701|11|1|3\n18|AAAAAAAAABAAAAAA|2001-09-03||2450812|2452608|N||http://www.foo.com|ad|4080|11|6|3\n19|AAAAAAAADBAAAAAA|1997-09-03||2450808|2452648|Y|57610|http://www.foo.com|general|2347|9|7|4\n20|AAAAAAAAEBAAAAAA|1997-09-03|2000-09-02|2450809|2452555|Y|46487|http://www.foo.com|ad|1147|3|6|0\n21|AAAAAAAAEBAAAAAA|2000-09-03||2450809|2452555|Y|10897|http://www.foo.com|general|1147|3|6|4\n22|AAAAAAAAGBAAAAAA|1997-09-03|1999-09-03|2450812|2452565|Y|20213|http://www.foo.com|general|5663|25|3|4\n23|AAAAAAAAGBAAAAAA|1999-09-04|2001-09-02|2450812|2452623|Y|20213|http://www.foo.com|order|4729|23|6|4\n24|AAAAAAAAGBAAAAAA|2001-09-03||2450812|2452646|Y|20213|http://www.foo.com|dynamic|5918|23|6|1\n25|AAAAAAAAJBAAAAAA|1997-09-03||2450811|2452620|N||http://www.foo.com|feedback|1526|9|4|2\n26|AAAAAAAAKBAAAAAA|1997-09-03|2000-09-02|2450812|2452636|Y|98376|http://www.foo.com|ad|1826|9|3|1\n27|AAAAAAAAKBAAAAAA|2000-09-03||2450812|2452607|Y|98376|http://www.foo.com|protected|1553|9|1|1\n28|AAAAAAAAMBAAAAAA|1997-09-03|1999-09-03|2450807|2452572|N||http://www.foo.com|protected|1308|4|1|2\n29|AAAAAAAAMBAAAAAA|1999-09-04|2001-09-02|2450808|2452611|N||http://www.foo.com|order|1308|4|1|2\n30|AAAAAAAAMBAAAAAA|2001-09-03||2450808|2452611|N||http://www.foo.com|general|3872|18|1|4\n31|AAAAAAAAPBAAAAAA|1997-09-03||2450810|2452596|N||http://www.foo.com|general|1732|3|6|0\n32|AAAAAAAAACAAAAAA|1997-09-03|2000-09-02|2450808|2452585|N||http://www.foo.com|welcome|5104|20|7|4\n33|AAAAAAAAACAAAAAA|2000-09-03||2450808|2452585|N||http://www.foo.com|protected|2129|7|1|0\n34|AAAAAAAACCAAAAAA|1997-09-03|1999-09-03|2450808|2452616|N||http://www.foo.com|welcome|2726|12|5|2\n35|AAAAAAAACCAAAAAA|1999-09-04|2001-09-02|2450808|2452591|N||http://www.foo.com|protected|2726|12|1|2\n36|AAAAAAAACCAAAAAA|2001-09-03||2450812|2452613|N||http://www.foo.com|dynamic|2726|3|1|2\n37|AAAAAAAAFCAAAAAA|1997-09-03||2450809|2452556|N||http://www.foo.com|ad|3076|15|3|0\n38|AAAAAAAAGCAAAAAA|1997-09-03|2000-09-02|2450811|2452583|Y|37285|http://www.foo.com|general|3096|18|3|0\n39|AAAAAAAAGCAAAAAA|2000-09-03||2450815|2452583|N||http://www.foo.com|general|3096|18|3|0\n40|AAAAAAAAICAAAAAA|1997-09-03|1999-09-03|2450813|2452576|N||http://www.foo.com|general|4402|18|4|2\n41|AAAAAAAAICAAAAAA|1999-09-04|2001-09-02|2450813|2452579|Y|16769|http://www.foo.com|welcome|784|3|4|4\n42|AAAAAAAAICAAAAAA|2001-09-03||2450813|2452579|Y|60150|http://www.foo.com|dynamic|1451|3|4|4\n43|AAAAAAAALCAAAAAA|1997-09-03||2450814|2452580|Y|64793|http://www.foo.com|ad|3760|12|3|2\n44|AAAAAAAAMCAAAAAA|1997-09-03|2000-09-02|2450811|2452602|Y|92078|http://www.foo.com|ad|4179|19|7|1\n45|AAAAAAAAMCAAAAAA|2000-09-03||2450811|2452575|Y|98633|http://www.foo.com|feedback|4584|19|7|4\n46|AAAAAAAAOCAAAAAA|1997-09-03|1999-09-03|2450809|2452574|N||http://www.foo.com|protected|1711|4|5|1\n47|AAAAAAAAOCAAAAAA|1999-09-04|2001-09-02|2450815|2452574|N||http://www.foo.com|welcome|1711|4|5|1\n48|AAAAAAAAOCAAAAAA|2001-09-03||2450815|2452622|N||http://www.foo.com|ad|1732|9|5|1\n49|AAAAAAAABDAAAAAA|1997-09-03||2450809|2452618|N||http://www.foo.com|order|4894|20|3|2\n50|AAAAAAAACDAAAAAA|1997-09-03|2000-09-02|2450808|2452615|N||http://www.foo.com|welcome|5262|16|5|2\n51|AAAAAAAACDAAAAAA|2000-09-03||2450811|2452564|N||http://www.foo.com|general|3423|19|7|1\n52|AAAAAAAAEDAAAAAA|1997-09-03|1999-09-03|2450815|2452606|N||http://www.foo.com|welcome|3306|21|7|1\n53|AAAAAAAAEDAAAAAA|1999-09-04|2001-09-02|2450808|2452636|N||http://www.foo.com|dynamic|3306|21|7|1\n54|AAAAAAAAEDAAAAAA|2001-09-03||2450808|2452629|N||http://www.foo.com|protected|1931|7|2|2\n55|AAAAAAAAHDAAAAAA|1997-09-03||2450811|2452549|N||http://www.foo.com|order|3788|19|1|0\n56|AAAAAAAAIDAAAAAA|1997-09-03|2000-09-02|2450815|2452554|N||http://www.foo.com|protected|5733|24|2|2\n57|AAAAAAAAIDAAAAAA|2000-09-03||2450811|2452568|N||http://www.foo.com|ad|5733|16|2|2\n58|AAAAAAAAKDAAAAAA|1997-09-03|1999-09-03|2450813|2452619|Y|7625|http://www.foo.com|ad|6577|24|4|3\n59|AAAAAAAAKDAAAAAA|1999-09-04|2001-09-02|2450813|2452624|Y|80555|http://www.foo.com|general|6577|24|2|3\n60|AAAAAAAAKDAAAAAA|2001-09-03||2450813|2452566|Y|80555|http://www.foo.com|welcome|6577|24|2|3\n";
const char *ontime_sample = "\"Year\",\"Quarter\",\"Month\",\"DayofMonth\",\"DayOfWeek\",\"FlightDate\",\"UniqueCarrier\",\"AirlineID\",\"Carrier\",\"TailNum\",\"FlightNum\",\"OriginAirportID\",\"OriginAirportSeqID\",\"OriginCityMarketID\",\"Origin\",\"OriginCityName\",\"OriginState\",\"OriginStateFips\",\"OriginStateName\",\"OriginWac\",\"DestAirportID\",\"DestAirportSeqID\",\"DestCityMarketID\",\"Dest\",\"DestCityName\",\"DestState\",\"DestStateFips\",\"DestStateName\",\"DestWac\",\"CRSDepTime\",\"DepTime\",\"DepDelay\",\"DepDelayMinutes\",\"DepDel15\",\"DepartureDelayGroups\",\"DepTimeBlk\",\"TaxiOut\",\"WheelsOff\",\"WheelsOn\",\"TaxiIn\",\"CRSArrTime\",\"ArrTime\",\"ArrDelay\",\"ArrDelayMinutes\",\"ArrDel15\",\"ArrivalDelayGroups\",\"ArrTimeBlk\",\"Cancelled\",\"CancellationCode\",\"Diverted\",\"CRSElapsedTime\",\"ActualElapsedTime\",\"AirTime\",\"Flights\",\"Distance\",\"DistanceGroup\",\"CarrierDelay\",\"WeatherDelay\",\"NASDelay\",\"SecurityDelay\",\"LateAircraftDelay\",\"FirstDepTime\",\"TotalAddGTime\",\"LongestAddGTime\",\"DivAirportLandings\",\"DivReachedDest\",\"DivActualElapsedTime\",\"DivArrDelay\",\"DivDistance\",\"Div1Airport\",\"Div1AirportID\",\"Div1AirportSeqID\",\"Div1WheelsOn\",\"Div1TotalGTime\",\"Div1LongestGTime\",\"Div1WheelsOff\",\"Div1TailNum\",\"Div2Airport\",\"Div2AirportID\",\"Div2AirportSeqID\",\"Div2WheelsOn\",\"Div2TotalGTime\",\"Div2LongestGTime\",\"Div2WheelsOff\",\"Div2TailNum\",\"Div3Airport\",\"Div3AirportID\",\"Div3AirportSeqID\",\"Div3WheelsOn\",\"Div3TotalGTime\",\"Div3LongestGTime\",\"Div3WheelsOff\",\"Div3TailNum\",\"Div4Airport\",\"Div4AirportID\",\"Div4AirportSeqID\",\"Div4WheelsOn\",\"Div4TotalGTime\",\"Div4LongestGTime\",\"Div4WheelsOff\",\"Div4TailNum\",\"Div5Airport\",\"Div5AirportID\",\"Div5AirportSeqID\",\"Div5WheelsOn\",\"Div5TotalGTime\",\"Div5LongestGTime\",\"Div5WheelsOff\",\"Div5TailNum\",\n1988,1,1,1,5,1988-01-01,\"AA\",19805,\"AA\",\"\",\"1\",12478,1247801,31703,\"JFK\",\"New York, NY\",\"NY\",\"36\",\"New York\",22,12892,1289201,32575,\"LAX\",\"Los Angeles, CA\",\"CA\",\"06\",\"California\",91,\"0900\",\"0900\",0.00,0.00,0.00,0,\"0900-0959\",,\"\",\"\",,\"1152\",\"1227\",35.00,35.00,1.00,2,\"1100-1159\",0.00,\"\",0.00,352.00,387.00,,1.00,2475.00,10,,,,,,\"\",,,,,,,,\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\n1988,1,1,2,6,1988-01-02,\"AA\",19805,\"AA\",\"\",\"1\",12478,1247801,31703,\"JFK\",\"New York, NY\",\"NY\",\"36\",\"New York\",22,12892,1289201,32575,\"LAX\",\"Los Angeles, CA\",\"CA\",\"06\",\"California\",91,\"0900\",\"0905\",5.00,5.00,0.00,0,\"0900-0959\",,\"\",\"\",,\"1152\",\"1205\",13.00,13.00,0.00,0,\"1100-1159\",0.00,\"\",0.00,352.00,360.00,,1.00,2475.00,10,,,,,,\"\",,,,,,,,\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\n1988,1,1,3,7,1988-01-03,\"AA\",19805,\"AA\",\"\",\"1\",12478,1247801,31703,\"JFK\",\"New York, NY\",\"NY\",\"36\",\"New York\",22,12892,1289201,32575,\"LAX\",\"Los Angeles, CA\",\"CA\",\"06\",\"California\",91,\"0900\",\"0902\",2.00,2.00,0.00,0,\"0900-0959\",,\"\",\"\",,\"1152\",\"1203\",11.00,11.00,0.00,0,\"1100-1159\",0.00,\"\",0.00,352.00,361.00,,1.00,2475.00,10,,,,,,\"\",,,,,,,,\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\n1988,1,1,4,1,1988-01-04,\"AA\",19805,\"AA\",\"\",\"1\",12478,1247801,31703,\"JFK\",\"New York, NY\",\"NY\",\"36\",\"New York\",22,12892,1289201,32575,\"LAX\",\"Los Angeles, CA\",\"CA\",\"06\",\"California\",91,\"0900\",\"1001\",61.00,61.00,1.00,4,\"0900-0959\",,\"\",\"\",,\"1152\",\"1315\",83.00,83.00,1.00,5,\"1100-1159\",0.00,\"\",0.00,352.00,374.00,,1.00,2475.00,10,,,,,,\"\",,,,,,,,\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\n1988,1,1,5,2,1988-01-05,\"AA\",19805,\"AA\",\"\",\"1\",12478,1247801,31703,\"JFK\",\"New York, NY\",\"NY\",\"36\",\"New York\",22,12892,1289201,32575,\"LAX\",\"Los Angeles, CA\",\"CA\",\"06\",\"California\",91,\"0900\",\"0905\",5.00,5.00,0.00,0,\"0900-0959\",,\"\",\"\",,\"1152\",\"1316\",84.00,84.00,1.00,5,\"1100-1159\",0.00,\"\",0.00,352.00,431.00,,1.00,2475.00,10,,,,,,\"\",,,,,,,,\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\n1988,1,1,6,3,1988-01-06,\"AA\",19805,\"AA\",\"\",\"1\",12478,1247801,31703,\"JFK\",\"New York, NY\",\"NY\",\"36\",\"New York\",22,12892,1289201,32575,\"LAX\",\"Los Angeles, CA\",\"CA\",\"06\",\"California\",91,\"0900\",\"0919\",19.00,19.00,1.00,1,\"0900-0959\",,\"\",\"\",,\"1152\",\"1241\",49.00,49.00,1.00,3,\"1100-1159\",0.00,\"\",0.00,352.00,382.00,,1.00,2475.00,10,,,,,,\"\",,,,,,,,\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\n1988,1,1,7,4,1988-01-07,\"AA\",19805,\"AA\",\"\",\"1\",12478,1247801,31703,\"JFK\",\"New York, NY\",\"NY\",\"36\",\"New York\",22,12892,1289201,32575,\"LAX\",\"Los Angeles, CA\",\"CA\",\"06\",\"California\",91,\"0900\",\"0903\",3.00,3.00,0.00,0,\"0900-0959\",,\"\",\"\",,\"1152\",\"1208\",16.00,16.00,1.00,1,\"1100-1159\",0.00,\"\",0.00,352.00,365.00,,1.00,2475.00,10,,,,,,\"\",,,,,,,,\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\n1988,1,1,8,5,1988-01-08,\"AA\",19805,\"AA\",\"\",\"1\",12478,1247801,31703,\"JFK\",\"New York, NY\",\"NY\",\"36\",\"New York\",22,12892,1289201,32575,\"LAX\",\"Los Angeles, CA\",\"CA\",\"06\",\"California\",91,\"0900\",\"0921\",21.00,21.00,1.00,1,\"0900-0959\",,\"\",\"\",,\"1152\",\"1301\",69.00,69.00,1.00,4,\"1100-1159\",0.00,\"\",0.00,352.00,400.00,,1.00,2475.00,10,,,,,,\"\",,,,,,,,\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\n1988,1,1,9,6,1988-01-09,\"AA\",19805,\"AA\",\"\",\"1\",12478,1247801,31703,\"JFK\",\"New York, NY\",\"NY\",\"36\",\"New York\",22,12892,1289201,32575,\"LAX\",\"Los Angeles, CA\",\"CA\",\"06\",\"California\",91,\"0900\",\"0902\",2.00,2.00,0.00,0,\"0900-0959\",,\"\",\"\",,\"1152\",\"1204\",12.00,12.00,0.00,0,\"1100-1159\",0.00,\"\",0.00,352.00,362.00,,1.00,2475.00,10,,,,,,\"\",,,,,,,,\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\"\",,,\"\",,,\"\",\"\",\n";
|
#include <upcxx/upcxx.hpp>
#include <tuple>
int main() {
upcxx::init();
long v = 0;
std::pair<long *,int> sp(&v,1);
using V = double;
upcxx::global_ptr<V> gp = upcxx::new_<V>();
std::pair<upcxx::global_ptr<V>,int> dp(gp,1);
upcxx::rput_irregular(&sp,&sp+1,
&dp,&dp+1).wait();
upcxx::finalize();
}
|
/* Given an array of integers `nums` sorted in ascending order, find the start-
* ing and ending position of given `target` value.
*
* Your algorithm's runtime complexity must be in the order of O(log n).
*
* If the target is not found in the array, return `[-1, -1]`.
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
static vector<int> searchRange(vector<int>& nums, int target){
vector<int> ans;
int size = nums.size();
if (size == 0){
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
if (size == 1){
if (nums[0] == target){
ans.push_back(0);
ans.push_back(0);
} else {
ans.push_back(-1);
ans.push_back(-1);
}
return ans;
}
int l = 0, r = size - 1;
int left, right;
int m;
while (l < r){
m = (l + r) / 2;
if (nums[m] >= target)
r = m;
else
l = m + 1;
}
left = (nums[l] == target) ? l : -1;
l = left, r = size - 1;
while (l < r){
m = (l + r + 1) / 2;
if (nums[m] <= target)
l = m;
else
r = m - 1;
}
right = (nums[r] == target) ? r : -1;
ans.push_back(left);
ans.push_back(right);
return ans;
}
};
int main(int argc, char* args[]){
int a[6] = {5, 7, 7, 8, 8, 10};
vector<int> aa(a, a + 6);
int b[6] = {5, 7, 7, 8, 8, 10};
vector<int> bb(b, b + 6);
vector<int> a_ans = Solution::searchRange(aa, 8);
cout << a_ans[0] << ", " << a_ans[1] << endl;
vector<int> b_ans = Solution::searchRange(bb, 6);
cout << b_ans[0] << ", " << b_ans[1] << endl;
return 0;
}
|
/**
* @file
* @author Jason M. Carter
* @author Aaron E. Ferber
* @date April 2017
* @version
*
* @copyright Copyright 2017 US DOT - Joint Program Office
*
* 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.
*
* Contributors:
* Oak Ridge National Laboratory.
*/
#ifndef CVDP_BSM_FILTER_H
#define CVDP_BSM_FILTER_H
#include <string>
#include <stack>
#include <vector>
#include <random>
#include "rapidjson/reader.h"
#include "cvlib.hpp"
/**
* @mainpage
*
* @section JPO-CVDP
*
* The United States Department of Transportation Joint Program Office (JPO)
* Connected Vehicle Data Privacy (CVDP) Project is developing a variety of methods
* to enhance the privacy of individuals who generated connected vehicle data.
*
* Connected vehicle technology uses in-vehicle wireless transceivers to broadcast
* and receive basic safety messages (BSMs) that include accurate spatiotemporal
* information to enhance transportation safety. Integrated Global Positioning
* System (GPS) measurements are included in BSMs. Databases, some publicly
* available, of BSM sequences, called trajectories, are being used to develop
* safety and traffic management applications. BSMs do not contain explicit
* identifiers that link trajectories to individuals; however, the locations they
* expose may be sensitive and associated with a very small subset of the
* population; protecting these locations from unwanted disclosure is extremely
* important. Developing procedures that minimize the risk of associating
* trajectories with individuals is the objective of this project.
*
* @section The Operational Data Environment (ODE) Privacy Protection Module (PPM)
*
* The PPM operates on streams of raw BSMs generated by the ODE. It determines
* whether individual BSMs should be retained or suppressed (deleted) based on the
* information in that BSM and auxiliary map information used to define a geofence.
* BSM geoposition (latitude and longitude) and speed are used to determine the
* disposition of each BSM processed. The PPM also redacts other BSM fields.
*
* @section Configuration
*
* @section Operation
*/
using ConfigMap = std::unordered_map<std::string,std::string>; ///< An alias to a string key - value configuration for the privacy parameters.
/**
* @brief Functor class to enable use of enums as keys to unordered_maps.
*/
struct EnumHash {
template <typename T>
/**
* @brief Return the hash code of a type that can be cast to a size_t, e.g., an enum.
*
* @return the hash code.
*/
std::size_t operator()(T t) const
{
return static_cast<std::size_t>( t );
}
};
/**
* @brief An IdRedactor encapsulates whether IdRedaction should take place and how it is performed.
*
* If inclusion_set_ is false (the default for the default constructor), ALL IDS will be redacted.
* If inclusion_set_ is true and the inclusion_set is empty, the NO IDS will be redacted.
* If inclusion_set_ is true and the inclusion_set is non-empty, then those IDS in the set will be redacted.
*/
class IdRedactor {
public:
using InclusionSetType = std::unordered_set<std::string>; ///< Alias for the inclusion set type.
/**
* @brief Default Id Redactor constructor.
*
* This constructor sets the following defaults:
* - Redacts all ids.
* - Sets the default redaction value to FFFFFFFF; this is easily changed in the configuration.
*/
IdRedactor();
/**
* @brief Construct an Id Redactor using the provided configuration.
*
* Initializes itself with the default constructor prior to applying configuration settings.
*
* @param conf The privacy configuration with which to setup this IdRedactor.
*/
IdRedactor( const ConfigMap& conf );
/**
* @brief Predicate indicating whether of not all ids are redacted.
*
* @return true if this IdRedactor uses inclusions and the set is non-empty.
*/
bool HasInclusions() const;
/**
* @brief Return the size of the inclusions sets.
*
* @return The size of the inclusions set; -1 if inclusions are not used.
*/
int NumInclusions() const;
/**
* @brief Reset the state of this redactor to redact all ids; this also empties the inclusion set.
*/
void RedactAll();
/**
* @brief Empty the inclusions set; this has the effect of NO LONGER PERFORMING REDACTION.
*
* @return true if the inclusions_set had some items to clear; false if already empty.
*/
bool ClearInclusions();
/**
* @brief Add an id to the set of Ids that require redaction.
*
* If the this redactor was previously set to including
* everything, i.e., NOT use a redaction list, and you add an id using
* this method, the previous behavior will stop and only the id you
* specified in this call will be redacted.
*
* @param id an id that requires redaction. @return true if it was new
* to the set; false otherwise.
*/
bool AddIdInclusion( const std::string& id );
/**
* @brief Remove an id from the set of Ids that require redaction.
*
* @param id an id that no longer should be redacted.
* @return true if the id was removed; false if it wasn't in the set.
*/
bool RemoveIdInclusion( const std::string& id );
/**
* @brief Build and return a new randomly generated unsigned 32-bit identifier in hex to replace the current identifier.
*
* @return a hexidecimal string of a random unsigned 32-bit integer (based on the J2735 specification).
*/
std::string GetRandomId();
/**
* @brief Operator to redact (or retain) an id.
*
* @param id the id to redact.
*
* @return true the id was redacted (modified) in some way; false the id was not changed.
*/
bool operator()( std::string& id );
/**
* @brief Return the value currently being used for redaction.
*
* @return a constanct reference to the value used to replace redacted values.
*/
const std::string& redaction_value() const;
private:
std::mt19937 rgen_; ///< random number generator (mersenne twister).
std::uniform_int_distribution<uint32_t> dist_;
InclusionSetType inclusion_set_; ///< The set of ids on which to perform redaction.
std::string redacted_value_; ///< The value to assign to those ids that require redaction.
bool inclusions_; ///< Flag indicating whether this redactor will use the inclusion_set.
};
/**
* @brief A functor used to determine whether a data element with a velocity field is outside of a specified interval
* [min,max].
*/
class VelocityFilter {
public:
static constexpr double kDefaultMinVelocity = 2.2352; ///< In meters per second = 5 mph.
static constexpr double kDefaultMaxVelocity = 35.7632; ///< In meters per second = 80 mph.
/**
* @brief Construct a velocity filter with the default velocities of min = 5mph and max = 80mph
*/
VelocityFilter();
/**
* @brief Construct a velocity filter using the specified configuration
*
* Note: The default velocities will be set by the default constructor prior to updating those settings with the
* configuration files, i.e., if you set one and not the other in the configuration the other one will be set to
* the default value.
*
* @param conf The configuration with which to setup this Velocity Filter.
*/
VelocityFilter( const ConfigMap& conf );
/**
* @brief Set the minimum velocity for the filter.
*
* @param min the velocity below which items will be filtered.
*/
void set_min( double v );
/**
* @brief Set the maximum velocity for the filter.
*
* @param max the velocity above which items will be filtered.
*/
void set_max( double v );
/**
* @brief Predicate function operator indicating whether this velocity should be filtered, i.e. suppressed.
*
* The retension interval is closed: [min_, max_]
*
* @return true = filter (suppres); false = retain.
*/
bool operator()( double v );
/**
* @brief Predicate function operator indicating whether this velocity should be suppressed; surrogate for filter.
*
* The retention interval is closed: [min_, max_]
*
* @return true = filter (suppress); false = retain.
*/
bool suppress( double v );
/**
* @brief Predicate function operator indicating whether this velocity should be retained.
*
* The retention interval is closed: [min_, max_]
*
* @return true = keep this BMS; false = suppress.
*/
bool retain( double v );
private:
double min_; ///< the minimum velocity for this filter.
double max_; ///< the maximum velocity for this filter.
};
/**
* @brief A surrogate for a Basic Safety Message (BSM). Instances of this class carry the information needed to check whether
* they are contained within a geofence defined using map data.
*
* In anticipation of performaning more advanced privacy filtering or de-identification, the following fields are
* captured:
*
* - velocity
* - postition (latitude and longitude)
* - identifier
*/
class BSM : public geo::Point {
public:
/**
* @brief Construct a Basic Safety Message (BSM) surrogate instance to use for filtering.
*/
BSM();
/**
* @brief Reset this BSM instance to the default values.
*
* We are reusing a single instance for the purpose of troubleshooting. When suppressed the data in this
* instance is ignored. The reset method avoid confusion when there data is retained from the previous Bsm
* instance to the next.
*
*/
void reset();
/**
* @brief Set the BSM's velocity
*
* @param v the BSM's velocity in meters per second.
*/
void set_velocity( double v );
/**
* @brief Get the velocity set for this BSM.
*
* @return this BSM's velocity.
*/
double get_velocity() const;
/**
* @brief Set the BSM's latitude.
*
* @param latitude the latitude in decimal degrees for the BSM.
*/
void set_latitude( double latitude );
/**
* @brief Set the BSM's longitude.
*
* @param longitude the longitude in decimal degrees for the BSM.
*/
void set_longitude( double longitude );
/**
* @brief Set the BSM's secMark.
*
* @param dsec the secMark (DSeconds) field of the BSM.
*/
void set_secmark( uint16_t dsec );
/**
* @brief Get the BSM's secMark.
*
* @return the BSM's current secMark value.
*/
uint16_t get_secmark() const;
/**
* @brief Set the temporary ID field for the BSM
*
* @param id the temporary id for the BSM.
*/
void set_id( const std::string& s );
/**
* @brief Set the original id field for the BSM; for unit testing.
*
* @param the original id in the BSM.
*/
void set_original_id( const std::string& s );
/**
* @brief Get the temporary ID field for the BSM
*
* @return a const reference to the temporary id for the BSM.
*/
const std::string& get_id() const;
/**
* @brief Get the original ID field for the BSM; for unit testing.
*
* @return a const reference to the original id for the BSM.
*/
const std::string& get_original_id() const;
/**
* @brief Get a string representation of this BSM for the log.
*
* @return a string for the log that characterizes this BSM.
*/
std::string logString();
/**
* @brief Write the BSM in readable form to the provided output stream.
*
* @param os the output stream to write the BSM to.
* @param bsm the bsm instance.
*/
friend std::ostream& operator<<( std::ostream& os, const BSM& bsm );
private:
double velocity_; ///< the velocity of the BSM.
uint16_t dsec_; ///< the dsecond field if it exists.
std::string id_; ///< the id of the BSM.
std::string oid_; ///< the original id of the BSM.
char* end_; ///< pointer to the last character parsed.
std::string logstring_; ///< a string to build for logging about the BSM.
};
/**
* @brief A BSMHandler processes individual BSMs specified in JSON. While performing this parsing it updates (creates) a
* BSM instance. A BSMHandler maintains state during the parsing and discontinues parsing if the BSM is determined to
* be outside of the prescribed specification for BSM retention. Handlers are designed to be used repeatedly.
*
* Currently BSMs are retained if the following conditions are met:
*
* - The velocity is within a specified interval [min,max].
* - The position is within a prescribed geofence; the geofence is defined using OSM road segments.
*
* Currently the following BSM fields are redacted:
*
* - The id field is redacted for certain prescribed ids.
*
*/
class BSMHandler : public rapidjson::BaseReaderHandler<rapidjson::UTF8<>, BSMHandler> {
public:
/**
* records the status of the parsing including what caused parsing to stop, i.e., the point to be suppressed.
*/
enum ResultStatus : uint16_t { SUCCESS, SPEED, GEOPOSITION, PARSE, OTHER };
using Ptr = std::shared_ptr<BSMHandler>; ///< Handle to pass this handler around efficiently.
using ResultStringMap = std::unordered_map<ResultStatus,std::string,EnumHash>; ///< Quick retrieval of result string.
static ResultStringMap result_string_map;
static constexpr uint32_t kVelocityFilterFlag = 0x1 << 0;
static constexpr uint32_t kGeofenceFilterFlag = 0x1 << 1;
static constexpr uint32_t kIdRedactFlag = 0x1 << 2;
// must be static const to compose these flags and use in template specialization.
static const unsigned flags = rapidjson::kParseDefaultFlags | rapidjson::kParseNumbersAsStringsFlag;
/**
* @brief Construct a BSMHandler instance using a quad tree of the map data defining the geofence and user-specified
* configuration.
*
* @param quad_ptr the quad tree containing the map elements.
* @param conf the user-specified configuration.
*/
BSMHandler(Quad::Ptr quad_ptr, const ConfigMap& conf );
/**
* @brief Predicate indicating whether the BSM's position is within the prescribed geofence.
*
* @todo: entities use string type values; numeric types would be faster.
*
* @param bsm the BSM to be checked.
* @return true if the BSM is within the geofence; false otherwise.
*/
bool isWithinEntity(BSM &bsm) const;
/**
* @brief Process a BSM presented as a JSON string; the string should not have any newlines in it.
*
* The result of the processing besides SAX fail/succeed status can be obtained using the #get_result method.
*
* @param bsm_json a JSON string of the BSM.
* @return true if the SAX parser did not encounter any errors during parsing; false otherwise.
*
*/
bool process( const std::string& bsm_json );
/**
* @brief Return the result of the most recent BSM processing.
*
* @return the parsing result status including success or if failure which element caused the failure.
*/
const BSMHandler::ResultStatus get_result() const;
/**
* @brief Return the result of the most recent BSM processing as a string.
*
* @return the parsing result status including success or if failure which element caused the failure as a
* string.
*/
const std::string& get_result_string() const;
/**
* @brief Return a reference to the BSM instance generated during processing of a JSON string.
*
* @return a reference to the BSM instance.
*/
BSM& get_bsm();
/**
* @brief Return the processed BSM as a JSON string including any changes made due to redaction of fields. This string
* is suitable for output and does not contain any newlines.
*
* @return a constant reference to the processed BSM as a JSON string.
*/
const std::string& get_json();
/**
* @brief Return the size in characters (bytes) of the JSON represented of the processed BSM.
*
* @return the size of the JSON string in chars or bytes.
*/
std::string::size_type get_bsm_buffer_size();
/**
* @brief Predicate that indicates a new JSON object is being parsed.
*
* @return true if the last token parsed is '{' and the tokens list is not empty.
*/
bool starting_new_object() const;
/**
* @brief Predicate indicating the current JSON object has been completely parsed.
*
* @return true if some JSON tokens have been parsed and the last token parsed was '}'.
*/
bool finished_current_object() const;
/**
* @brief Reset the state of the BSMHandler instance so it is ready to process a new JSON string.
*/
void reset();
/**
* @brief SAX Handler for parsing a null value in a JSON string.
*
* @return false to terminate parsing; true otherwise
*/
bool Null();
/**
* @brief SAX Handler for parsing a boolean value in a JSON string.
*
* @return false to terminate parsing; true otherwise
*/
bool Bool(bool b);
/**
* @brief SAX Handler for parsing an integer value in a JSON string.
*
* @return false to terminate parsing; true otherwise
*/
bool Int(int i);
/**
* @brief SAX Handler for parsing an unsigned integer value in a JSON string.
*
* @return false to terminate parsing; true otherwise
*/
bool Uint(unsigned u);
/**
* @brief SAX Handler for parsing a 64-bit integer value in a JSON string.
*
* @return false to terminate parsing; true otherwise
*/
bool Int64(int64_t i);
/**
* @brief SAX Handler for parsing an unsigned 64-bit value in a JSON string.
*
* @return false to terminate parsing; true otherwise
*/
bool Uint64(uint64_t u);
/**
* @brief SAX Handler for parsing a double value in a JSON string.
*
* @return false to terminate parsing; true otherwise
*/
bool Double(double d);
/**
* @brief SAX Handler for parsing a number presented as a string in a JSON string.
*
* @return false to terminate parsing; true otherwise
*/
bool RawNumber(const char* str, rapidjson::SizeType length, bool copy);
/**
* @brief SAX Handler for parsing a string value in a JSON string.
*
* @return false to terminate parsing; true otherwise
*/
bool String(const char* str, rapidjson::SizeType length, bool copy);
/**
* @brief SAX Handler for parsing the beginning of a new JSON object.
*
* @return false to terminate parsing; true otherwise
*/
bool StartObject();
/**
* @brief SAX Handler for parsing the end of a new JSON object.
*
* @param memberCount the number of JSON elements in the preceeding object.
* @return false to terminate parsing; true otherwise.
*/
bool EndObject(rapidjson::SizeType memberCount);
/**
* @brief SAX Handler for parsing the key for a JSON element.
*
* @return false to terminate parsing; true otherwise
*/
bool Key(const char* str, rapidjson::SizeType length, bool copy);
/**
* @brief SAX Handler for parsing the beginning of a JSON array.
*
* @return false to terminate parsing; true otherwise
*/
bool StartArray();
/**
* @brief SAX Handler for parsing the end of a JSON array.
*
* @return false to terminate parsing; true otherwise
*/
bool EndArray(rapidjson::SizeType elementCount);
template<uint32_t FLAG>
bool is_active() {
return activated_ & FLAG;
}
template<uint32_t FLAG>
const uint32_t activate() {
activated_ |= FLAG;
return activated_;
}
template<uint32_t FLAG>
const uint32_t deactivate() {
activated_ &= ~FLAG;
return activated_;
}
const uint32_t get_activation_flag() const;
const std::string& get_current_key() const;
bool get_next_value() const;
const StrVector& get_object_stack() const;
const StrVector& get_tokens() const;
const VelocityFilter& get_velocity_filter() const;
const IdRedactor& get_id_redactor() const;
const double get_box_extension() const;
private:
rapidjson::Reader reader_; ///< JSON reader.
uint32_t activated_; ///< A flag word indicating which features of the privacy protection are activiated.
ResultStatus result_; ///< Indicates the current state of BSM parsing and what causes failure.
BSM bsm_; ///< The BSM instance that is being built through parsing.
Quad::Ptr quad_ptr_; ///< A pointer to the quad tree containing the map elements.
bool get_value_; ///< Indicates the next value should be saved.
bool finalized_; ///< Indicates the JSON string after redaction has been created and retrieved.
std::string current_key_; ///< The current key being processed by the SAX JSON parser.
StrVector object_stack_; ///< A vector that retains the objects being parsed from the JSON; used as a stack.
StrVector tokens_; ///< A vector containing all the tokens necessary to generate the JSON of the filtered BSM.
std::string json_; ///< The JSON string after redaction.
VelocityFilter vf_; ///< The velocity filter functor instance.
IdRedactor idr_; ///< The ID Redactor to use during parsing of BSMs.
double box_extension_; ///< The number of meters to extend the boxes that surround edges and define the geofence.
};
#endif
|
// Copyright (c) 2016 ASMlover. All rights reserved.
//
// ____ __
// /\ _`\ /\ \
// \ \ \/\_\\ \ \___ __ ___ ____
// \ \ \/_/_\ \ _ `\ /'__`\ / __`\ /',__\
// \ \ \L\ \\ \ \ \ \/\ \L\.\_/\ \L\ \/\__, `\
// \ \____/ \ \_\ \_\ \__/.\_\ \____/\/\____/
// \/___/ \/_/\/_/\/__/\/_/\/___/ \/___/
//
// 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 ofconditions 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 materialsprovided 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
// 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.
#pragma once
#include <Chaos/Base/Platform.hh>
#include <Chaos/Base/Types.hh>
#include <Chaos/Kern/KernCommon.hh>
namespace Chaos {
template <typename T>
class ThreadLocalSingleton final : private UnCopyable {
class Deleter {
public:
Chaos::_Tls_t tls_;
Deleter(void) {
Chaos::kern_tls_create(&tls_, &ThreadLocalSingleton::destructor);
}
~Deleter(void) {
Chaos::kern_tls_delete(tls_);
}
void set_value(T* value) {
CHAOS_CHECK(nullptr == Chaos::kern_tls_getspecific(tls_),
"ThreadLocalSingleton::Deleter::set_value "
"- current tls should be nullptr");
Chaos::kern_tls_setspecific(tls_, value);
}
};
static __chaos_tl T* t_value_;
static Deleter deleter_;
ThreadLocalSingleton(void) = delete;
~ThreadLocalSingleton(void) = delete;
static void destructor(void* obj) {
if (nullptr == t_value_ && nullptr != obj) {
// FIXME: fixed calling in another thread
T* del_obj = static_cast<T*>(obj);
delete del_obj;
return;
}
CHAOS_CHECK(obj == t_value_,
"ThreadLocalSingleton::destructor "
"- destruction obj should be `t_value_`");
if (nullptr != t_value_) {
delete t_value_;
t_value_ = nullptr;
}
}
public:
static T& get_instance(void) {
if (nullptr == t_value_) {
t_value_ = new T();
deleter_.set_value(t_value_);
}
return *t_value_;
}
static T* get_pointer(void) {
return t_value_;
}
};
template <typename T>
__chaos_tl T* ThreadLocalSingleton<T>::t_value_ = nullptr;
template <typename T>
typename ThreadLocalSingleton<T>::Deleter ThreadLocalSingleton<T>::deleter_;
}
|
// Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <vector>
#include <memory>
#include <transformations_visibility.hpp>
#include <ngraph/pass/graph_rewrite.hpp>
namespace ngraph {
namespace pass {
class TRANSFORMATIONS_API ConvertOpSet1ToLegacy;
} // namespace pass
} // namespace ngraph
class ngraph::pass::ConvertOpSet1ToLegacy: public ngraph::pass::FunctionPass {
public:
NGRAPH_RTTI_DECLARATION;
bool run_on_function(std::shared_ptr<ngraph::Function> f) override;
};
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2005, 2006 StatPro Italia srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file observablevalue.hpp
\brief observable and assignable proxy to concrete value
*/
#ifndef quantlib_observable_value_hpp
#define quantlib_observable_value_hpp
#include <ql/patterns/observable.hpp>
namespace QuantLib {
//! %observable and assignable proxy to concrete value
/*! Observers can be registered with instances of this class so
that they are notified when a different value is assigned to
such instances. Client code can copy the contained value or
pass it to functions via implicit conversion.
\note it is not possible to call non-const method on the
returned value. This is by design, as this possibility
would necessarily bypass the notification code; client
code should modify the value via re-assignment instead.
*/
template <class T>
class ObservableValue {
public:
ObservableValue();
ObservableValue(const T&);
ObservableValue(const ObservableValue<T>&);
//! \name controlled assignment
//@{
ObservableValue<T>& operator=(const T&);
ObservableValue<T>& operator=(const ObservableValue<T>&);
//@}
//! implicit conversion
operator T() const;
operator ext::shared_ptr<Observable>() const;
//! explicit inspector
const T& value() const;
private:
T value_;
ext::shared_ptr<Observable> observable_;
};
// template definition
template <class T>
ObservableValue<T>::ObservableValue()
: value_(), observable_(new Observable) {}
template <class T>
ObservableValue<T>::ObservableValue(const T& t)
: value_(t), observable_(new Observable) {}
template <class T>
ObservableValue<T>::ObservableValue(const ObservableValue<T>& t)
: value_(t.value_), observable_(new Observable) {}
template <class T>
ObservableValue<T>& ObservableValue<T>::operator=(const T& t) {
value_ = t;
observable_->notifyObservers();
return *this;
}
template <class T>
ObservableValue<T>&
ObservableValue<T>::operator=(const ObservableValue<T>& t) {
value_ = t.value_;
observable_->notifyObservers();
return *this;
}
template <class T>
ObservableValue<T>::operator T() const {
return value_;
}
template <class T>
ObservableValue<T>::operator ext::shared_ptr<Observable>() const {
return observable_;
}
template <class T>
const T& ObservableValue<T>::value() const {
return value_;
}
}
#endif
|
#include <debugger/io/namedpipe.h>
#include <Windows.h>
#include <debugger/client/run.h>
#include <debugger/io/base.h>
#include <debugger/io/helper.h>
#include <debugger/client/stdinput.h>
#include <base/util/format.h>
#include <base/path/self.h>
#include <functional>
void request_runInTerminal(vscode::io::base* io, std::function<void(vscode::wprotocol&)> args)
{
vscode::wprotocol res;
for (auto _ : res.Object())
{
res("type").String("request");
//res("seq").Int64(seq++);
res("command").String("runInTerminal");
for (auto _ : res("arguments").Object())
{
args(res);
}
}
vscode::io_output(io, res);
}
bool create_terminal_with_debugger(stdinput& io, vscode::rprotocol& req, const std::wstring& port)
{
auto& args = req["arguments"];
request_runInTerminal(&io, [&](vscode::wprotocol& res) {
fs::path dbg_path = base::path::self().remove_filename();
std::string luaexe;
if (args.HasMember("luaexe") && args["luaexe"].IsString()) {
luaexe = args["luaexe"].Get<std::string>();
}
else {
luaexe = base::w2u((dbg_path / L"lua.exe").wstring());
}
res("kind").String(args["console"] == "integratedTerminal" ? "integrated" : "external");
res("title").String("Lua Debug");
if (args.HasMember("cwd") && args["cwd"].IsString()) {
res("cwd").String(args["cwd"]);
}
else {
res("cwd").String(base::w2u(fs::path(luaexe).remove_filename().wstring()));
}
if (args.HasMember("env") && args["env"].IsObject()) {
for (auto _ : res("env").Object()) {
for (auto& v : args["env"].GetObject()) {
if (v.name.IsString()) {
if (v.value.IsString()) {
res(v.name).String(v.value);
}
else if (v.value.IsNull()) {
res(v.name).Null();
}
}
}
}
}
for (auto _ : res("args").Array()) {
res.String(luaexe);
std::string script = create_install_script(req, dbg_path, port, true);
res.String("-e");
res.String(script);
if (args.HasMember("arg0")) {
if (args["arg0"].IsString()) {
auto& v = args["arg0"];
res.String(v);
}
else if (args["arg0"].IsArray()) {
for (auto& v : args["arg0"].GetArray()) {
if (v.IsString()) {
res.String(v);
}
}
}
}
std::string program = ".lua";
if (args.HasMember("program") && args["program"].IsString()) {
program = args["program"].Get<std::string>();
}
res.String(program);
if (args.HasMember("arg") && args["arg"].IsArray()) {
for (auto& v : args["arg"].GetArray()) {
if (v.IsString()) {
res.String(v);
}
}
}
}
});
return true;
}
|
/** \copyright
* Copyright (c) 2013, Balazs Racz
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file main.cxx
*
* Main file for the io board application on the STM32F3-Discovery board.
*
* @author Balazs Racz
* @date 25 August 2015
*/
#include "os/os.h"
#include "nmranet_config.h"
#include "openlcb/SimpleStack.hxx"
#include "openlcb/ConfiguredConsumer.hxx"
#include "openlcb/ConfiguredProducer.hxx"
#include "freertos_drivers/st/Stm32Gpio.hxx"
#include "freertos_drivers/common/BlinkerGPIO.hxx"
#include "config.hxx"
#include "hardware.hxx"
// These preprocessor symbols are used to select which physical connections
// will be enabled in the main(). See @ref appl_main below.
//#define SNIFF_ON_SERIAL
//#define SNIFF_ON_USB
#define HAVE_PHYSICAL_CAN_PORT
// Changes the default behavior by adding a newline after each gridconnect
// packet. Makes it easier for debugging the raw device.
OVERRIDE_CONST(gc_generate_newlines, 1);
// Specifies how much RAM (in bytes) we allocate to the stack of the main
// thread. Useful tuning parameter in case the application runs out of memory.
OVERRIDE_CONST(main_thread_stack_size, 2500);
// Specifies the 48-bit OpenLCB node identifier. This must be unique for every
// hardware manufactured, so in production this should be replaced by some
// easily incrementable method.
extern const openlcb::NodeID NODE_ID = 0x050101011412ULL;
// Sets up a comprehensive OpenLCB stack for a single virtual node. This stack
// contains everything needed for a usual peripheral node -- all
// CAN-bus-specific components, a virtual node, PIP, SNIP, Memory configuration
// protocol, ACDI, CDI, a bunch of memory spaces, etc.
openlcb::SimpleCanStack stack(NODE_ID);
// ConfigDef comes from config.hxx and is specific to the particular device and
// target. It defines the layout of the configuration memory space and is also
// used to generate the cdi.xml file. Here we instantiate the configuration
// layout. The argument of offset zero is ignored and will be removed later.
openlcb::ConfigDef cfg(0);
// Defines weak constants used by the stack to tell it which device contains
// the volatile configuration information. This device name appears in
// HwInit.cxx that creates the device drivers.
extern const char *const openlcb::CONFIG_FILENAME = "/dev/eeprom";
// The size of the memory space to export over the above device.
extern const size_t openlcb::CONFIG_FILE_SIZE =
cfg.seg().size() + cfg.seg().offset();
static_assert(openlcb::CONFIG_FILE_SIZE <= 512, "Need to adjust eeprom size");
// The SNIP user-changeable information in also stored in the above eeprom
// device. In general this could come from different eeprom segments, but it is
// simpler to keep them together.
extern const char *const openlcb::SNIP_DYNAMIC_FILENAME =
openlcb::CONFIG_FILENAME;
// Defines the GPIO ports used for the producers and the consumers.
// The first LED is driven by the blinker device from BlinkerGPIO.hxx. We just
// create an alias for symmetry.
typedef BLINKER_Pin LED_1_Pin;
// Instantiates the actual producer and consumer objects for the given GPIO
// pins from above. The ConfiguredConsumer class takes care of most of the
// complicated setup and operation requirements. We need to give it the virtual
// node pointer, the configuration configuration from the CDI definition, and
// the hardware pin definition. The virtual node pointer comes from the stack
// object. The configuration structure comes from the CDI definition object,
// segment 'seg', in which there is a repeated group 'consumers', and we assign
// the individual entries to the individual consumers. Each consumer gets its
// own GPIO pin.
openlcb::ConfiguredConsumer consumer_0(
stack.node(), cfg.seg().consumers().entry<0>(), LED_1_Pin());
openlcb::ConfiguredConsumer consumer_1(
stack.node(), cfg.seg().consumers().entry<1>(), LED_2_Pin());
openlcb::ConfiguredConsumer consumer_2(
stack.node(), cfg.seg().consumers().entry<2>(), LED_3_Pin());
openlcb::ConfiguredConsumer consumer_3(
stack.node(), cfg.seg().consumers().entry<3>(), LED_4_Pin());
openlcb::ConfiguredConsumer consumer_4(
stack.node(), cfg.seg().consumers().entry<4>(), LED_5_Pin());
openlcb::ConfiguredConsumer consumer_5(
stack.node(), cfg.seg().consumers().entry<5>(), LED_6_Pin());
openlcb::ConfiguredConsumer consumer_6(
stack.node(), cfg.seg().consumers().entry<6>(), LED_7_Pin());
openlcb::ConfiguredConsumer consumer_7(
stack.node(), cfg.seg().consumers().entry<7>(), LED_8_Pin());
// Similar syntax for the producers.
openlcb::ConfiguredProducer producer_sw1(
stack.node(), cfg.seg().producers().entry<0>(), SW1_Pin());
// The producers need to be polled repeatedly for changes and to execute the
// debouncing algorithm. This class instantiates a refreshloop and adds the two
// producers to it.
openlcb::RefreshLoop loop(
stack.node(), {producer_sw1.polling()});
/** Entry point to application.
* @param argc number of command line arguments
* @param argv array of command line arguments
* @return 0, should never return
*/
int appl_main(int argc, char *argv[])
{
// The necessary physical ports must be added to the stack.
//
// It is okay to enable multiple physical ports, in which case the stack
// will behave as a bridge between them. For example enabling both the
// physical CAN port and the USB port will make this firmware act as an
// USB-CAN adapter in addition to the producers/consumers created above.
//
// If a port is enabled, it must be functional or else the stack will
// freeze waiting for that port to send the packets out.
#if defined(HAVE_PHYSICAL_CAN_PORT)
stack.add_can_port_select("/dev/can0");
#endif
#if defined(SNIFF_ON_USB)
stack.add_gridconnect_port("/dev/serUSB0");
#endif
#if defined(SNIFF_ON_SERIAL)
stack.add_gridconnect_port("/dev/ser0");
#endif
// This command donates the main thread to the operation of the
// stack. Alternatively the stack could be started in a separate stack and
// then application-specific business logic could be executed ion a busy
// loop in the main thread.
stack.loop_executor();
return 0;
}
|
// Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "PrivateDataBase.h"
namespace facebook {
namespace react {
PrivateDataBase::~PrivateDataBase() {}
} }
|
#include "geohash/base32.hpp"
namespace geohash {
// Invalid character in an encoding
const char Base32::kInvalid_ = std::numeric_limits<char>::max();
// Encoding characters
const std::array<char, 32> Base32::encode_ =
std::array<char, 32>({'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b',
'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'});
} // namespace geohash
|
// Copyright (c) 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 "ui/events/x/touch_factory_x11.h"
#include <X11/Xatom.h>
#include <X11/cursorfont.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <X11/extensions/XIproto.h>
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/sys_info.h"
#include "ui/events/event_switches.h"
#include "ui/events/x/device_data_manager_x11.h"
#include "ui/events/x/device_list_cache_x.h"
#include "ui/gfx/x/x11_types.h"
namespace ui {
TouchFactory::TouchFactory()
: pointer_device_lookup_(),
touch_device_available_(false),
touch_events_disabled_(false),
touch_device_list_(),
max_touch_points_(-1),
virtual_core_keyboard_device_(-1),
id_generator_(0) {
if (!DeviceDataManagerX11::GetInstance()->IsXInput2Available())
return;
XDisplay* display = gfx::GetXDisplay();
UpdateDeviceList(display);
CommandLine* cmdline = CommandLine::ForCurrentProcess();
touch_events_disabled_ = cmdline->HasSwitch(switches::kTouchEvents) &&
cmdline->GetSwitchValueASCII(switches::kTouchEvents) ==
switches::kTouchEventsDisabled;
}
TouchFactory::~TouchFactory() {
}
// static
TouchFactory* TouchFactory::GetInstance() {
return Singleton<TouchFactory>::get();
}
// static
void TouchFactory::SetTouchDeviceListFromCommandLine() {
// Get a list of pointer-devices that should be treated as touch-devices.
// This is primarily used for testing/debugging touch-event processing when a
// touch-device isn't available.
std::string touch_devices =
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kTouchDevices);
if (!touch_devices.empty()) {
std::vector<std::string> devs;
std::vector<unsigned int> device_ids;
unsigned int devid;
base::SplitString(touch_devices, ',', &devs);
for (std::vector<std::string>::iterator iter = devs.begin();
iter != devs.end(); ++iter) {
if (base::StringToInt(*iter, reinterpret_cast<int*>(&devid)))
device_ids.push_back(devid);
else
DLOG(WARNING) << "Invalid touch-device id: " << *iter;
}
ui::TouchFactory::GetInstance()->SetTouchDeviceList(device_ids);
}
}
void TouchFactory::UpdateDeviceList(Display* display) {
// Detect touch devices.
touch_device_available_ = false;
touch_device_lookup_.reset();
touch_device_list_.clear();
touchscreen_ids_.clear();
max_touch_points_ = -1;
#if !defined(USE_XI2_MT)
// NOTE: The new API for retrieving the list of devices (XIQueryDevice) does
// not provide enough information to detect a touch device. As a result, the
// old version of query function (XListInputDevices) is used instead.
// If XInput2 is not supported, this will return null (with count of -1) so
// we assume there cannot be any touch devices.
// With XI2.1 or older, we allow only single touch devices.
XDeviceList dev_list =
DeviceListCacheX::GetInstance()->GetXDeviceList(display);
Atom xi_touchscreen = XInternAtom(display, XI_TOUCHSCREEN, false);
for (int i = 0; i < dev_list.count; i++) {
if (dev_list[i].type == xi_touchscreen) {
touch_device_lookup_[dev_list[i].id] = true;
touch_device_list_[dev_list[i].id] = false;
touch_device_available_ = true;
}
}
#endif
if (!DeviceDataManagerX11::GetInstance()->IsXInput2Available())
return;
// Instead of asking X for the list of devices all the time, let's maintain a
// list of pointer devices we care about.
// It should not be necessary to select for slave devices. XInput2 provides
// enough information to the event callback to decide which slave device
// triggered the event, thus decide whether the 'pointer event' is a
// 'mouse event' or a 'touch event'.
// However, on some desktops, some events from a master pointer are
// not delivered to the client. So we select for slave devices instead.
// If the touch device has 'GrabDevice' set and 'SendCoreEvents' unset (which
// is possible), then the device is detected as a floating device, and a
// floating device is not connected to a master device. So it is necessary to
// also select on the floating devices.
pointer_device_lookup_.reset();
XIDeviceList xi_dev_list =
DeviceListCacheX::GetInstance()->GetXI2DeviceList(display);
for (int i = 0; i < xi_dev_list.count; i++) {
XIDeviceInfo* devinfo = xi_dev_list.devices + i;
if (devinfo->use == XIFloatingSlave || devinfo->use == XIMasterPointer) {
#if defined(USE_XI2_MT)
for (int k = 0; k < devinfo->num_classes; ++k) {
XIAnyClassInfo* xiclassinfo = devinfo->classes[k];
if (xiclassinfo->type == XITouchClass) {
XITouchClassInfo* tci =
reinterpret_cast<XITouchClassInfo*>(xiclassinfo);
// Only care direct touch device (such as touch screen) right now
if (tci->mode == XIDirectTouch) {
touch_device_lookup_[devinfo->deviceid] = true;
touch_device_list_[devinfo->deviceid] = true;
touch_device_available_ = true;
if (tci->num_touches > 0 && tci->num_touches > max_touch_points_)
max_touch_points_ = tci->num_touches;
}
}
}
#endif
pointer_device_lookup_[devinfo->deviceid] = true;
} else if (devinfo->use == XIMasterKeyboard) {
virtual_core_keyboard_device_ = devinfo->deviceid;
}
#if defined(USE_XI2_MT)
if (devinfo->use == XIFloatingSlave || devinfo->use == XISlavePointer) {
for (int k = 0; k < devinfo->num_classes; ++k) {
XIAnyClassInfo* xiclassinfo = devinfo->classes[k];
if (xiclassinfo->type == XITouchClass) {
XITouchClassInfo* tci =
reinterpret_cast<XITouchClassInfo*>(xiclassinfo);
// Only care direct touch device (such as touch screen) right now
if (tci->mode == XIDirectTouch)
CacheTouchscreenIds(display, devinfo->deviceid);
}
}
}
#endif
}
}
bool TouchFactory::ShouldProcessXI2Event(XEvent* xev) {
DCHECK_EQ(GenericEvent, xev->type);
XIEvent* event = static_cast<XIEvent*>(xev->xcookie.data);
XIDeviceEvent* xiev = reinterpret_cast<XIDeviceEvent*>(event);
#if defined(USE_XI2_MT)
if (event->evtype == XI_TouchBegin ||
event->evtype == XI_TouchUpdate ||
event->evtype == XI_TouchEnd) {
return !touch_events_disabled_ && IsTouchDevice(xiev->deviceid);
}
#endif
// Make sure only key-events from the virtual core keyboard are processed.
if (event->evtype == XI_KeyPress || event->evtype == XI_KeyRelease) {
return (virtual_core_keyboard_device_ < 0) ||
(virtual_core_keyboard_device_ == xiev->deviceid);
}
if (event->evtype != XI_ButtonPress &&
event->evtype != XI_ButtonRelease &&
event->evtype != XI_Motion)
return true;
if (!pointer_device_lookup_[xiev->deviceid])
return false;
return IsTouchDevice(xiev->deviceid) ? !touch_events_disabled_ : true;
}
void TouchFactory::SetupXI2ForXWindow(Window window) {
// Setup mask for mouse events. It is possible that a device is loaded/plugged
// in after we have setup XInput2 on a window. In such cases, we need to
// either resetup XInput2 for the window, so that we get events from the new
// device, or we need to listen to events from all devices, and then filter
// the events from uninteresting devices. We do the latter because that's
// simpler.
XDisplay* display = gfx::GetXDisplay();
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
memset(mask, 0, sizeof(mask));
#if defined(USE_XI2_MT)
XISetMask(mask, XI_TouchBegin);
XISetMask(mask, XI_TouchUpdate);
XISetMask(mask, XI_TouchEnd);
#endif
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
#if defined(OS_CHROMEOS)
if (base::SysInfo::IsRunningOnChromeOS()) {
XISetMask(mask, XI_KeyPress);
XISetMask(mask, XI_KeyRelease);
}
#endif
XIEventMask evmask;
evmask.deviceid = XIAllDevices;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
XISelectEvents(display, window, &evmask, 1);
XFlush(display);
}
void TouchFactory::SetTouchDeviceList(
const std::vector<unsigned int>& devices) {
touch_device_lookup_.reset();
touch_device_list_.clear();
for (std::vector<unsigned int>::const_iterator iter = devices.begin();
iter != devices.end(); ++iter) {
DCHECK(*iter < touch_device_lookup_.size());
touch_device_lookup_[*iter] = true;
touch_device_list_[*iter] = false;
}
}
bool TouchFactory::IsTouchDevice(unsigned deviceid) const {
return deviceid < touch_device_lookup_.size() ?
touch_device_lookup_[deviceid] : false;
}
bool TouchFactory::IsMultiTouchDevice(unsigned int deviceid) const {
return (deviceid < touch_device_lookup_.size() &&
touch_device_lookup_[deviceid]) ?
touch_device_list_.find(deviceid)->second :
false;
}
bool TouchFactory::QuerySlotForTrackingID(uint32 tracking_id, int* slot) {
if (!id_generator_.HasGeneratedIDFor(tracking_id))
return false;
*slot = static_cast<int>(id_generator_.GetGeneratedID(tracking_id));
return true;
}
int TouchFactory::GetSlotForTrackingID(uint32 tracking_id) {
return id_generator_.GetGeneratedID(tracking_id);
}
void TouchFactory::AcquireSlotForTrackingID(uint32 tracking_id) {
tracking_id_refcounts_[tracking_id]++;
}
void TouchFactory::ReleaseSlotForTrackingID(uint32 tracking_id) {
tracking_id_refcounts_[tracking_id]--;
if (tracking_id_refcounts_[tracking_id] == 0)
id_generator_.ReleaseNumber(tracking_id);
}
bool TouchFactory::IsTouchDevicePresent() {
return !touch_events_disabled_ && touch_device_available_;
}
int TouchFactory::GetMaxTouchPoints() const {
return max_touch_points_;
}
void TouchFactory::ResetForTest() {
pointer_device_lookup_.reset();
touch_device_lookup_.reset();
touch_device_available_ = false;
touch_events_disabled_ = false;
touch_device_list_.clear();
touchscreen_ids_.clear();
tracking_id_refcounts_.clear();
max_touch_points_ = -1;
id_generator_.ResetForTest();
}
void TouchFactory::SetTouchDeviceForTest(
const std::vector<unsigned int>& devices) {
touch_device_lookup_.reset();
touch_device_list_.clear();
for (std::vector<unsigned int>::const_iterator iter = devices.begin();
iter != devices.end(); ++iter) {
DCHECK(*iter < touch_device_lookup_.size());
touch_device_lookup_[*iter] = true;
touch_device_list_[*iter] = true;
}
touch_device_available_ = true;
touch_events_disabled_ = false;
}
void TouchFactory::SetPointerDeviceForTest(
const std::vector<unsigned int>& devices) {
pointer_device_lookup_.reset();
for (std::vector<unsigned int>::const_iterator iter = devices.begin();
iter != devices.end(); ++iter) {
pointer_device_lookup_[*iter] = true;
}
}
void TouchFactory::CacheTouchscreenIds(Display* display, int device_id) {
XDevice* device = XOpenDevice(display, device_id);
if (!device)
return;
Atom actual_type_return;
int actual_format_return;
unsigned long nitems_return;
unsigned long bytes_after_return;
unsigned char *prop_return;
const char kDeviceProductIdString[] = "Device Product ID";
Atom device_product_id_atom =
XInternAtom(display, kDeviceProductIdString, false);
if (device_product_id_atom != None &&
XGetDeviceProperty(display, device, device_product_id_atom, 0, 2,
False, XA_INTEGER, &actual_type_return,
&actual_format_return, &nitems_return,
&bytes_after_return, &prop_return) == Success) {
if (actual_type_return == XA_INTEGER &&
actual_format_return == 32 &&
nitems_return == 2) {
// An actual_format_return of 32 implies that the returned data is an
// array of longs. See the description of |prop_return| in `man
// XGetDeviceProperty` for details.
long* ptr = reinterpret_cast<long*>(prop_return);
// Internal displays will have a vid and pid of 0. Ignore them.
// ptr[0] is the vid, and ptr[1] is the pid.
if (ptr[0] || ptr[1])
touchscreen_ids_.insert(std::make_pair(ptr[0], ptr[1]));
}
XFree(prop_return);
}
XCloseDevice(display, device);
}
} // namespace ui
|
/*
// Struct_definition.h defines different types of sturctures being used in the implementation of MSCKF
*/
#ifndef STRUCT_DEF_H
#define STRUCT_DEF_H
#include <Eigen/Dense>
#include <map>
#include <set>
#include "Parameters.hpp"
#include <deque>
#define PI 3.1415926535
#define NaN -1
typedef Eigen::Matrix<double, 15, 15> Matrix15;
typedef Eigen::Matrix<double, 16, 16> Matrix16;
typedef Eigen::Matrix<double,4,1> quaternion;
struct Feature
{
/* ----- Structure to store Camera Feature Points ----- */
double u;
double v;
};
struct IMURawData
{
Eigen::Vector3d imuData;
double timeStamp;
};
struct IMUdata
{
/* --------- Structure to store Raw IMU Data ---------- */
Eigen::Vector3d a;
Eigen::Vector3d g;
/* -------- Operator to copy structure members -------- */
IMUdata& operator=(const IMUdata& old)
{
a = old.a;
g = old.g;
return *this;
}
};
struct StampedIMUData
{
double timestamp;
IMUdata imudata;
};
struct StampedAccData{
double timestamp;
Eigen::Vector3d accdata;
};
struct StampedGyroData{
double timestamp;
Eigen::Vector3d gyrodata;
};
struct CalibrationParameter{
float Td;
CalibrationParameter()
{
Td = 0;
}
};
struct IMUstate
{
/* ------ Structure of IMU Part of State Vector ------- */
Eigen::Vector3d p_b_G;
Eigen::Vector3d v_b_G;
quaternion q_B_G;
Eigen::Vector3d ba;
Eigen::Vector3d bg;
CalibrationParameter calibParam;
Eigen::Vector3d w_b;
/* ------------------- Constructor -------------------- */
IMUstate()
{
p_b_G.setZero();
v_b_G.setZero();
q_B_G.setIdentity();
ba.setZero();
bg.setZero();
calibParam. Td = 0;
w_b.setZero();
}
/* -------- Operator to copy structure members -------- */
IMUstate& operator=(const IMUstate& old)
{
p_b_G = old.p_b_G;
v_b_G = old.v_b_G;
q_B_G = old.q_B_G;
ba = old.ba;
bg = old.bg;
w_b = old.w_b;
calibParam = old.calibParam;
return *this;
}
};
struct IMUGroundTruth
{
/* ------ Structure of IMU Part of State Vector ------- */
double timeStamp;
Eigen::Vector3d p_b_G;
Eigen::Vector3d v_b_G;
quaternion q_B_G;
Eigen::Vector3d bias_w;
Eigen::Vector3d bias_a;
/* ------------------- Constructor -------------------- */
IMUGroundTruth()
{
timeStamp = 0.0;
p_b_G.setZero();
v_b_G.setZero();
q_B_G.setIdentity();
bias_a.setZero();
bias_w.setZero();
}
/* -------- Operator to copy structure members -------- */
IMUGroundTruth& operator=(const IMUGroundTruth& old)
{
p_b_G = old.p_b_G;
v_b_G = old.v_b_G;
q_B_G = old.q_B_G;
bias_a = old.bias_a;
bias_w = old.bias_w;
timeStamp = old.timeStamp;
return *this;
}
};
struct Bodystate
{
/* --- Structure of Camera/Body Part of State Vector -- */
int state_k;
Eigen::Vector3d p_b_G;
Eigen::Vector3d v_b_G;
quaternion q_B_G;
Eigen::Vector3d w_b;
std::set<int> trackedFeatureID; // TODO:: need to be modified as a set
/* -------- Operator to copy structure members -------- */
Bodystate& operator=(const Bodystate& old)
{
state_k = old.state_k;
p_b_G = old.p_b_G;
v_b_G = old.v_b_G;
q_B_G = old.q_B_G;
trackedFeatureID = old.trackedFeatureID;
return *this;
}
Bodystate()
{
state_k = 0;
p_b_G.setZero();
v_b_G.setZero();
q_B_G.setIdentity();
trackedFeatureID.clear();
}
};
struct Camstate{
Eigen::Vector3d p_c_G;
quaternion q_C_G;
Camstate(){
p_c_G.setZero();
q_C_G.setIdentity();
}
};
struct FeatureTrack
{
/* - Structure of Features and corresponding Body States - */
int featureID;
std::vector<Feature> observations;
std::map<int, std::vector<Feature>, std::less<int>, Eigen::aligned_allocator<std::pair<int, std::vector<Feature>>>> featureTracks;
std::vector<int> bodyStateID;
std::vector<Bodystate, Eigen::aligned_allocator<Bodystate>> bodyStateBuffer;
/* -------- Operator to copy structure members -------- */
FeatureTrack& operator=(const FeatureTrack& old)
{
featureID = old.featureID;
observations = old.observations;
featureTracks = old.featureTracks;
bodyStateID = old.bodyStateID;
bodyStateBuffer = old.bodyStateBuffer;
return *this;
}
FeatureTrack(){
featureID = 0;
observations.clear();
featureTracks.clear();
bodyStateID.clear();
bodyStateBuffer.clear();
}
};
struct StateVector
{
/* -------- Structure of Complete State Vector -------- */
IMUstate imuState;
Eigen::Matrix<double, 16, 16> imuCovariance; // imu + calib
Eigen::MatrixXd bodyCovariance;
Eigen::MatrixXd imuBodyCovariance;
std::vector<Bodystate, Eigen::aligned_allocator<Bodystate>> bodyStateBuffer;
//CalibrationParameter camCalibState;
//Eigen::MatrixXd camCalibCovariance;
/* -------- Operator to copy structure members -------- */
StateVector& operator=(const StateVector& old)
{
imuState = old.imuState;
imuCovariance = old.imuCovariance;
bodyCovariance = old.bodyCovariance;
imuBodyCovariance = old.imuBodyCovariance;
bodyStateBuffer = old.bodyStateBuffer;
//camCalibState = old.camCalibState;
//camCalibCovariance = old.camCalibCovariance;
return *this;
}
StateVector(){
imuCovariance.setZero();
bodyCovariance.setZero();
imuBodyCovariance.setZero();
//bodyStateBuffer.clear();
//camCalibCovariance.setZero();
}
};
struct ImageNameStruct{
std::string imageName;
double imageTimeStamp;
};
typedef struct IMUMeanData_{
double gx_mean;
double gy_mean;
double gz_mean;
double ax_mean;
double ay_mean;
double az_mean;
}IMUMeanData;
void getParameter(std::string cameParam,std::string imuParam,cameraParameters & camParam, noiseParameters & initNoiseParam);
std::vector<ImageNameStruct> getImageList( std::ifstream& imageListFile);
std::vector<StampedIMUData> getIMUReading(std::ifstream& IMURecordFile);
std::vector<StampedIMUData> getIMUReadingEuroc(std::ifstream& IMURecordFile);
std::vector<StampedIMUData> getIMUReadingDvt(std::ifstream& IMURecordFile);
std::vector<ImageNameStruct> getImageListDvt( std::ifstream& imageListFile);
std::vector<StampedAccData> getAccReading(std::ifstream & AccRecordFile);
std::vector<StampedGyroData> getGyroReading(std::ifstream & gyroRecordFile);
std::vector<IMUGroundTruth> getGroundTruthEuroc(std::ifstream & groundTruthFile);
#endif
|
#include "FWCore/Utilities/interface/Exception.h"
#include "SimG4Core/Geometry/interface/DD4hep_DDG4Builder.h"
#include "SimG4Core/Geometry/interface/SensitiveDetectorCatalog.h"
#include "DetectorDescription/DDCMS/interface/DDCompactView.h"
#include "DetectorDescription/DDCMS/interface/DDDetector.h"
#include <DDG4/Geant4Converter.h>
#include <DDG4/Geant4GeometryInfo.h>
#include <DDG4/Geant4Mapping.h>
#include <DD4hep/Detector.h>
#include <DD4hep/Filter.h>
#include "G4LogicalVolume.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4ReflectionFactory.hh"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <algorithm>
using namespace cms;
using namespace dd4hep;
using namespace dd4hep::sim;
DDG4Builder::DDG4Builder(const cms::DDCompactView *cpv, dd4hep::sim::Geant4GeometryMaps::VolumeMap &lvmap, bool check)
: compactView_(cpv), map_(lvmap), check_(check) {}
G4VPhysicalVolume *DDG4Builder::BuildGeometry(SensitiveDetectorCatalog &catalog) {
G4ReflectionFactory *refFact = G4ReflectionFactory::Instance();
refFact->SetScalePrecision(100. * refFact->GetScalePrecision());
const cms::DDDetector *det = compactView_->detector();
DetElement world = det->description()->world();
const Detector &detector = *det->description();
// GET FULL G4 GEOMETRY
Geant4Converter g4Geo(detector);
g4Geo.debugMaterials = false;
Geant4GeometryInfo *geometry = g4Geo.create(world).detach();
map_ = geometry->g4Volumes;
// FIND & STORE ALL G4 LOGICAL VOLUMES DEFINED AS SENSITIVE IN CMSSW XMLS
std::vector<std::pair<G4LogicalVolume *, const dd4hep::SpecPar *>> dd4hepVec;
const dd4hep::SpecParRegistry &specPars = det->specpars();
dd4hep::SpecParRefs specs;
specPars.filter(specs, "SensitiveDetector");
for (auto const &it : map_) {
bool foundMatch = false; // Stop search at first occurrence
for (auto const &fit : specs) {
for (auto const &pit : fit.second->paths) {
if (dd4hep::dd::compareEqualName(dd4hep::dd::noNamespace(dd4hep::dd::realTopName(pit)),
dd4hep::dd::noNamespace(it.first.name()))) {
dd4hepVec.emplace_back(&*it.second, &*fit.second);
foundMatch = true;
break;
}
}
if (foundMatch)
break;
}
}
// ADD ALL SELECTED G4 LOGICAL VOLUMES TO SENSITIVE DETECTORS CATALOGUE
for (auto const &it : dd4hepVec) {
// Sensitive detector info
const G4String &sensitiveDetectorG4Name = it.first->GetName();
auto sClassName = it.second->strValue("SensitiveDetector");
auto sROUName = it.second->strValue("ReadOutName");
// Add to catalogue
catalog.insert({sClassName.data(), sClassName.size()}, {sROUName.data(), sROUName.size()}, sensitiveDetectorG4Name);
edm::LogVerbatim("SimG4CoreApplication") << " DDG4SensitiveConverter: Sensitive " << sensitiveDetectorG4Name
<< " Class Name " << sClassName << " ROU Name " << sROUName;
// Reflected sensors also need to be added to the senstive detectors catalogue!
// Similar treatment here with DD4hep, as what was done for old DD.
const G4String &sensitiveDetectorG4ReflectedName = sensitiveDetectorG4Name + "_refl";
const G4LogicalVolumeStore *const allG4LogicalVolumes = G4LogicalVolumeStore::GetInstance();
const bool hasG4ReflectedVolume =
std::find_if(
allG4LogicalVolumes->begin(), allG4LogicalVolumes->end(), [&](G4LogicalVolume *const aG4LogicalVolume) {
return (aG4LogicalVolume->GetName() == sensitiveDetectorG4ReflectedName);
}) != allG4LogicalVolumes->end();
if (hasG4ReflectedVolume) {
// Add reflected sensitive detector to catalogue
catalog.insert(
{sClassName.data(), sClassName.size()}, {sROUName.data(), sROUName.size()}, sensitiveDetectorG4ReflectedName);
edm::LogVerbatim("SimG4CoreApplication")
<< " DDG4SensitiveConverter: Sensitive " << sensitiveDetectorG4ReflectedName << " Class Name " << sClassName
<< " ROU Name " << sROUName;
}
}
return geometry->world();
}
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2015-2017 The HERB developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "clientversion.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "protocol.h"
#include "sync.h"
#include "timedata.h"
#include "util.h"
#include "version.h"
#include <boost/foreach.hpp>
#include "json/json_spirit_value.h"
using namespace json_spirit;
using namespace std;
Value getconnectioncount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getconnectioncount\n"
"\nReturns the number of connections to other nodes.\n"
"\nbResult:\n"
"n (numeric) The connection count\n"
"\nExamples:\n" +
HelpExampleCli("getconnectioncount", "") + HelpExampleRpc("getconnectioncount", ""));
LOCK(cs_vNodes);
return (int)vNodes.size();
}
Value ping(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"ping\n"
"\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
"Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
"Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n"
"\nExamples:\n" +
HelpExampleCli("ping", "") + HelpExampleRpc("ping", ""));
// Request that each node send a ping during next message processing pass
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pNode, vNodes) {
pNode->fPingQueued = true;
}
return Value::null;
}
static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
vstats.clear();
LOCK(cs_vNodes);
vstats.reserve(vNodes.size());
BOOST_FOREACH (CNode* pnode, vNodes) {
CNodeStats stats;
pnode->copyStats(stats);
vstats.push_back(stats);
}
}
Value getpeerinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpeerinfo\n"
"\nReturns data about each connected network node as a json array of objects.\n"
"\nbResult:\n"
"[\n"
" {\n"
" \"id\": n, (numeric) Peer index\n"
" \"addr\":\"host:port\", (string) The ip address and port of the peer\n"
" \"addrlocal\":\"ip:port\", (string) local address\n"
" \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n"
" \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n"
" \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n"
" \"bytessent\": n, (numeric) The total bytes sent\n"
" \"bytesrecv\": n, (numeric) The total bytes received\n"
" \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"pingtime\": n, (numeric) ping time\n"
" \"pingwait\": n, (numeric) ping wait\n"
" \"version\": v, (numeric) The peer version, such as 7001\n"
" \"subver\": \"/HERB Core:x.x.x.x/\", (string) The string version\n"
" \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n"
" \"startingheight\": n, (numeric) The starting height (block) of the peer\n"
" \"banscore\": n, (numeric) The ban score\n"
" \"synced_headers\": n, (numeric) The last header we have in common with this peer\n"
" \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n"
" \"inflight\": [\n"
" n, (numeric) The heights of blocks we're currently asking from this peer\n"
" ...\n"
" ]\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getpeerinfo", "") + HelpExampleRpc("getpeerinfo", ""));
vector<CNodeStats> vstats;
CopyNodeStats(vstats);
Array ret;
BOOST_FOREACH (const CNodeStats& stats, vstats) {
Object obj;
CNodeStateStats statestats;
bool fStateStats = GetNodeStateStats(stats.nodeid, statestats);
obj.push_back(Pair("id", stats.nodeid));
obj.push_back(Pair("addr", stats.addrName));
if (!(stats.addrLocal.empty()))
obj.push_back(Pair("addrlocal", stats.addrLocal));
obj.push_back(Pair("services", strprintf("%016x", stats.nServices)));
obj.push_back(Pair("lastsend", stats.nLastSend));
obj.push_back(Pair("lastrecv", stats.nLastRecv));
obj.push_back(Pair("bytessent", stats.nSendBytes));
obj.push_back(Pair("bytesrecv", stats.nRecvBytes));
obj.push_back(Pair("conntime", stats.nTimeConnected));
obj.push_back(Pair("pingtime", stats.dPingTime));
if (stats.dPingWait > 0.0)
obj.push_back(Pair("pingwait", stats.dPingWait));
obj.push_back(Pair("version", stats.nVersion));
// Use the sanitized form of subver here, to avoid tricksy remote peers from
// corrupting or modifiying the JSON output by putting special characters in
// their ver message.
obj.push_back(Pair("subver", stats.cleanSubVer));
obj.push_back(Pair("inbound", stats.fInbound));
obj.push_back(Pair("startingheight", stats.nStartingHeight));
if (fStateStats) {
obj.push_back(Pair("banscore", statestats.nMisbehavior));
obj.push_back(Pair("synced_headers", statestats.nSyncHeight));
obj.push_back(Pair("synced_blocks", statestats.nCommonHeight));
Array heights;
BOOST_FOREACH (int height, statestats.vHeightInFlight) {
heights.push_back(height);
}
obj.push_back(Pair("inflight", heights));
}
obj.push_back(Pair("whitelisted", stats.fWhitelisted));
ret.push_back(obj);
}
return ret;
}
Value addnode(const Array& params, bool fHelp)
{
string strCommand;
if (params.size() == 2)
strCommand = params[1].get_str();
if (fHelp || params.size() != 2 ||
(strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
throw runtime_error(
"addnode \"node\" \"add|remove|onetry\"\n"
"\nAttempts add or remove a node from the addnode list.\n"
"Or try a connection to a node once.\n"
"\nArguments:\n"
"1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n"
"2. \"command\" (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n"
"\nExamples:\n" +
HelpExampleCli("addnode", "\"192.168.0.6:55500\" \"onetry\"") + HelpExampleRpc("addnode", "\"192.168.0.6:55500\", \"onetry\""));
string strNode = params[0].get_str();
if (strCommand == "onetry") {
CAddress addr;
OpenNetworkConnection(addr, NULL, strNode.c_str());
return Value::null;
}
LOCK(cs_vAddedNodes);
vector<string>::iterator it = vAddedNodes.begin();
for (; it != vAddedNodes.end(); it++)
if (strNode == *it)
break;
if (strCommand == "add") {
if (it != vAddedNodes.end())
throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added");
vAddedNodes.push_back(strNode);
} else if (strCommand == "remove") {
if (it == vAddedNodes.end())
throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
vAddedNodes.erase(it);
}
return Value::null;
}
Value getaddednodeinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getaddednodeinfo dns ( \"node\" )\n"
"\nReturns information about the given added node, or all added nodes\n"
"(note that onetry addnodes are not listed here)\n"
"If dns is false, only a list of added nodes will be provided,\n"
"otherwise connected information will also be available.\n"
"\nArguments:\n"
"1. dns (boolean, required) If false, only a list of added nodes will be provided, otherwise connected information will also be available.\n"
"2. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"addednode\" : \"192.168.0.201\", (string) The node ip address\n"
" \"connected\" : true|false, (boolean) If connected\n"
" \"addresses\" : [\n"
" {\n"
" \"address\" : \"192.168.0.201:55500\", (string) The herb server host and port\n"
" \"connected\" : \"outbound\" (string) connection, inbound or outbound\n"
" }\n"
" ,...\n"
" ]\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getaddednodeinfo", "true") + HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"") + HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\""));
bool fDns = params[0].get_bool();
list<string> laddedNodes(0);
if (params.size() == 1) {
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
laddedNodes.push_back(strAddNode);
} else {
string strNode = params[1].get_str();
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
if (strAddNode == strNode) {
laddedNodes.push_back(strAddNode);
break;
}
if (laddedNodes.size() == 0)
throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
}
Array ret;
if (!fDns) {
BOOST_FOREACH (string& strAddNode, laddedNodes) {
Object obj;
obj.push_back(Pair("addednode", strAddNode));
ret.push_back(obj);
}
return ret;
}
list<pair<string, vector<CService> > > laddedAddreses(0);
BOOST_FOREACH (string& strAddNode, laddedNodes) {
vector<CService> vservNode(0);
if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
laddedAddreses.push_back(make_pair(strAddNode, vservNode));
else {
Object obj;
obj.push_back(Pair("addednode", strAddNode));
obj.push_back(Pair("connected", false));
Array addresses;
obj.push_back(Pair("addresses", addresses));
}
}
LOCK(cs_vNodes);
for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++) {
Object obj;
obj.push_back(Pair("addednode", it->first));
Array addresses;
bool fConnected = false;
BOOST_FOREACH (CService& addrNode, it->second) {
bool fFound = false;
Object node;
node.push_back(Pair("address", addrNode.ToString()));
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->addr == addrNode) {
fFound = true;
fConnected = true;
node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound"));
break;
}
if (!fFound)
node.push_back(Pair("connected", "false"));
addresses.push_back(node);
}
obj.push_back(Pair("connected", fConnected));
obj.push_back(Pair("addresses", addresses));
ret.push_back(obj);
}
return ret;
}
Value getnettotals(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"getnettotals\n"
"\nReturns information about network traffic, including bytes in, bytes out,\n"
"and current time.\n"
"\nResult:\n"
"{\n"
" \"totalbytesrecv\": n, (numeric) Total bytes received\n"
" \"totalbytessent\": n, (numeric) Total bytes sent\n"
" \"timemillis\": t (numeric) Total cpu time\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getnettotals", "") + HelpExampleRpc("getnettotals", ""));
Object obj;
obj.push_back(Pair("totalbytesrecv", CNode::GetTotalBytesRecv()));
obj.push_back(Pair("totalbytessent", CNode::GetTotalBytesSent()));
obj.push_back(Pair("timemillis", GetTimeMillis()));
return obj;
}
static Array GetNetworksInfo()
{
Array networks;
for (int n = 0; n < NET_MAX; ++n) {
enum Network network = static_cast<enum Network>(n);
if (network == NET_UNROUTABLE)
continue;
proxyType proxy;
Object obj;
GetProxy(network, proxy);
obj.push_back(Pair("name", GetNetworkName(network)));
obj.push_back(Pair("limited", IsLimited(network)));
obj.push_back(Pair("reachable", IsReachable(network)));
obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.ToStringIPPort() : string()));
networks.push_back(obj);
}
return networks;
}
Value getnetworkinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getnetworkinfo\n"
"Returns an object containing various state info regarding P2P networking.\n"
"\nResult:\n"
"{\n"
" \"version\": xxxxx, (numeric) the server version\n"
" \"subversion\": \"/HERB Core:x.x.x.x/\", (string) the server subversion string\n"
" \"protocolversion\": xxxxx, (numeric) the protocol version\n"
" \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n"
" \"timeoffset\": xxxxx, (numeric) the time offset\n"
" \"connections\": xxxxx, (numeric) the number of connections\n"
" \"networks\": [ (array) information per network\n"
" {\n"
" \"name\": \"xxx\", (string) network (ipv4, ipv6 or onion)\n"
" \"limited\": true|false, (boolean) is the network limited using -onlynet?\n"
" \"reachable\": true|false, (boolean) is the network reachable?\n"
" \"proxy\": \"host:port\" (string) the proxy that is used for this network, or empty if none\n"
" }\n"
" ,...\n"
" ],\n"
" \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee for non-free transactions in herb/kb\n"
" \"localaddresses\": [ (array) list of local addresses\n"
" {\n"
" \"address\": \"xxxx\", (string) network address\n"
" \"port\": xxx, (numeric) network port\n"
" \"score\": xxx (numeric) relative score\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getnetworkinfo", "") + HelpExampleRpc("getnetworkinfo", ""));
Object obj;
obj.push_back(Pair("version", CLIENT_VERSION));
obj.push_back(Pair("subversion",
FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>())));
obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
obj.push_back(Pair("localservices", strprintf("%016x", nLocalServices)));
obj.push_back(Pair("timeoffset", GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("networks", GetNetworksInfo()));
obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
Array localAddresses;
{
LOCK(cs_mapLocalHost);
BOOST_FOREACH (const PAIRTYPE(CNetAddr, LocalServiceInfo) & item, mapLocalHost) {
Object rec;
rec.push_back(Pair("address", item.first.ToString()));
rec.push_back(Pair("port", item.second.nPort));
rec.push_back(Pair("score", item.second.nScore));
localAddresses.push_back(rec);
}
}
obj.push_back(Pair("localaddresses", localAddresses));
return obj;
}
|
#include "sass.hpp"
#include <cctype>
#include <iostream>
#include <iomanip>
#include "util.hpp"
#include "position.hpp"
#include "prelexer.hpp"
#include "constants.hpp"
namespace Sass {
// using namespace Lexer;
using namespace Constants;
namespace Prelexer {
/*
def string_re(open, close)
/#{open}((?:\\.|\#(?!\{)|[^#{close}\\#])*)(#{close}|#\{)/m
end
end
# A hash of regular expressions that are used for tokenizing strings.
#
# The key is a `[Symbol, Boolean]` pair.
# The symbol represents which style of quotation to use,
# while the boolean represents whether or not the string
# is following an interpolated segment.
STRING_REGULAR_EXPRESSIONS = {
:double => {
/#{open}((?:\\.|\#(?!\{)|[^#{close}\\#])*)(#{close}|#\{)/m
false => string_re('"', '"'),
true => string_re('', '"')
},
:single => {
false => string_re("'", "'"),
true => string_re('', "'")
},
:uri => {
false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
},
# Defined in https://developer.mozilla.org/en/CSS/@-moz-document as a
# non-standard version of http://www.w3.org/TR/css3-conditional/
:url_prefix => {
false => /url-prefix\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
},
:domain => {
false => /domain\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
}
}
*/
/*
/#{open}
(
\\.
|
\# (?!\{)
|
[^#{close}\\#]
)*
(#{close}|#\{)
/m
false => string_re('"', '"'),
true => string_re('', '"')
*/
extern const char string_double_negates[] = "\"\\#";
const char* re_string_double_close(const char* src)
{
return sequence <
// valid chars
zero_plus <
alternatives <
// escaped char
sequence <
exactly <'\\'>,
any_char
>,
// non interpolate hash
sequence <
exactly <'#'>,
negate <
exactly <'{'>
>
>,
// other valid chars
neg_class_char <
string_double_negates
>
>
>,
// quoted string closer
// or interpolate opening
alternatives <
exactly <'"'>,
lookahead < exactly< hash_lbrace > >
>
>(src);
}
const char* re_string_double_open(const char* src)
{
return sequence <
// quoted string opener
exactly <'"'>,
// valid chars
zero_plus <
alternatives <
// escaped char
sequence <
exactly <'\\'>,
any_char
>,
// non interpolate hash
sequence <
exactly <'#'>,
negate <
exactly <'{'>
>
>,
// other valid chars
neg_class_char <
string_double_negates
>
>
>,
// quoted string closer
// or interpolate opening
alternatives <
exactly <'"'>,
lookahead < exactly< hash_lbrace > >
>
>(src);
}
extern const char string_single_negates[] = "'\\#";
const char* re_string_single_close(const char* src)
{
return sequence <
// valid chars
zero_plus <
alternatives <
// escaped char
sequence <
exactly <'\\'>,
any_char
>,
// non interpolate hash
sequence <
exactly <'#'>,
negate <
exactly <'{'>
>
>,
// other valid chars
neg_class_char <
string_single_negates
>
>
>,
// quoted string closer
// or interpolate opening
alternatives <
exactly <'\''>,
lookahead < exactly< hash_lbrace > >
>
>(src);
}
const char* re_string_single_open(const char* src)
{
return sequence <
// quoted string opener
exactly <'\''>,
// valid chars
zero_plus <
alternatives <
// escaped char
sequence <
exactly <'\\'>,
any_char
>,
// non interpolate hash
sequence <
exactly <'#'>,
negate <
exactly <'{'>
>
>,
// other valid chars
neg_class_char <
string_single_negates
>
>
>,
// quoted string closer
// or interpolate opening
alternatives <
exactly <'\''>,
lookahead < exactly< hash_lbrace > >
>
>(src);
}
/*
:uri => {
false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
},
*/
const char* re_string_uri_close(const char* src)
{
return sequence <
non_greedy<
alternatives<
class_char< real_uri_chars >,
uri_character,
NONASCII,
ESCAPE
>,
alternatives<
sequence < optional < W >, exactly <')'> >,
lookahead < exactly< hash_lbrace > >
>
>,
optional <
sequence < optional < W >, exactly <')'> >
>
>(src);
}
const char* re_string_uri_open(const char* src)
{
return sequence <
exactly <'u'>,
exactly <'r'>,
exactly <'l'>,
exactly <'('>,
W,
alternatives<
quoted_string,
non_greedy<
alternatives<
class_char< real_uri_chars >,
uri_character,
NONASCII,
ESCAPE
>,
alternatives<
sequence < W, exactly <')'> >,
exactly< hash_lbrace >
>
>
>
>(src);
}
// Match a line comment (/.*?(?=\n|\r\n?|\Z)/.
const char* line_comment(const char* src)
{
return sequence<
exactly <
slash_slash
>,
non_greedy<
any_char,
end_of_line
>
>(src);
}
// Match a block comment.
const char* block_comment(const char* src)
{
return sequence<
delimited_by<
slash_star,
star_slash,
false
>
>(src);
}
/* not use anymore - remove?
const char* block_comment_prefix(const char* src) {
return exactly<slash_star>(src);
}
// Match either comment.
const char* comment(const char* src) {
return line_comment(src);
}
*/
// Match zero plus white-space or line_comments
const char* optional_css_whitespace(const char* src) {
return zero_plus< alternatives<spaces, line_comment> >(src);
}
const char* css_whitespace(const char* src) {
return one_plus< alternatives<spaces, line_comment> >(src);
}
// Match optional_css_whitepace plus block_comments
const char* optional_css_comments(const char* src) {
return zero_plus< alternatives<spaces, line_comment, block_comment> >(src);
}
const char* css_comments(const char* src) {
return one_plus< alternatives<spaces, line_comment, block_comment> >(src);
}
// Match one backslash escaped char /\\./
const char* escape_seq(const char* src)
{
return sequence<
exactly<'\\'>,
alternatives <
minmax_range<
1, 3, xdigit
>,
any_char
>,
optional <
exactly <' '>
>
>(src);
}
// Match identifier start
const char* identifier_alpha(const char* src)
{
return alternatives<
unicode_seq,
alpha,
unicode,
exactly<'-'>,
exactly<'_'>,
NONASCII,
ESCAPE,
escape_seq
>(src);
}
// Match identifier after start
const char* identifier_alnum(const char* src)
{
return alternatives<
unicode_seq,
alnum,
unicode,
exactly<'-'>,
exactly<'_'>,
NONASCII,
ESCAPE,
escape_seq
>(src);
}
// Match CSS identifiers.
const char* strict_identifier(const char* src)
{
return sequence<
one_plus < strict_identifier_alpha >,
zero_plus < strict_identifier_alnum >
// word_boundary not needed
>(src);
}
// Match CSS identifiers.
const char* identifier(const char* src)
{
return sequence<
zero_plus< exactly<'-'> >,
one_plus < identifier_alpha >,
zero_plus < identifier_alnum >
// word_boundary not needed
>(src);
}
const char* strict_identifier_alpha(const char* src)
{
return alternatives <
alpha,
unicode,
escape_seq,
exactly<'_'>
>(src);
}
const char* strict_identifier_alnum(const char* src)
{
return alternatives <
alnum,
unicode,
escape_seq,
exactly<'_'>
>(src);
}
// Match a single CSS unit
const char* one_unit(const char* src)
{
return sequence <
optional < exactly <'-'> >,
strict_identifier_alpha,
zero_plus < alternatives<
strict_identifier_alnum,
sequence <
one_plus < exactly<'-'> >,
strict_identifier_alpha
>
> >
>(src);
}
// Match numerator/denominator CSS units
const char* multiple_units(const char* src)
{
return
sequence <
one_unit,
zero_plus <
sequence <
exactly <'*'>,
one_unit
>
>
>(src);
}
// Match complex CSS unit identifiers
const char* unit_identifier(const char* src)
{
return sequence <
multiple_units,
optional <
sequence <
exactly <'/'>,
multiple_units
> >
>(src);
}
const char* identifier_alnums(const char* src)
{
return one_plus< identifier_alnum >(src);
}
// Match number prefix ([\+\-]+)
const char* number_prefix(const char* src) {
return alternatives <
exactly < '+' >,
sequence <
exactly < '-' >,
optional_css_whitespace,
exactly< '-' >
>
>(src);
}
// Match interpolant schemas
const char* identifier_schema(const char* src) {
return sequence <
one_plus <
sequence <
zero_plus <
alternatives <
sequence <
optional <
exactly <'$'>
>,
identifier
>,
exactly <'-'>
>
>,
interpolant,
zero_plus <
alternatives <
digits,
sequence <
optional <
exactly <'$'>
>,
identifier
>,
quoted_string,
exactly<'-'>
>
>
>
>,
negate <
exactly<'%'>
>
> (src);
}
// interpolants can be recursive/nested
const char* interpolant(const char* src) {
return recursive_scopes< exactly<hash_lbrace>, exactly<rbrace> >(src);
}
// $re_squote = /'(?:$re_itplnt|\\.|[^'])*'/
const char* single_quoted_string(const char* src) {
// match a single quoted string, while skipping interpolants
return sequence <
exactly <'\''>,
zero_plus <
alternatives <
// skip escapes
sequence <
exactly < '\\' >,
re_linebreak
>,
escape_seq,
unicode_seq,
// skip interpolants
interpolant,
// skip non delimiters
any_char_but < '\'' >
>
>,
exactly <'\''>
>(src);
}
// $re_dquote = /"(?:$re_itp|\\.|[^"])*"/
const char* double_quoted_string(const char* src) {
// match a single quoted string, while skipping interpolants
return sequence <
exactly <'"'>,
zero_plus <
alternatives <
// skip escapes
sequence <
exactly < '\\' >,
re_linebreak
>,
escape_seq,
unicode_seq,
// skip interpolants
interpolant,
// skip non delimiters
any_char_but < '"' >
>
>,
exactly <'"'>
>(src);
}
// $re_quoted = /(?:$re_squote|$re_dquote)/
const char* quoted_string(const char* src) {
// match a quoted string, while skipping interpolants
return alternatives<
single_quoted_string,
double_quoted_string
>(src);
}
const char* sass_value(const char* src) {
return alternatives <
quoted_string,
identifier,
percentage,
hex,
dimension,
number
>(src);
}
// this is basically `one_plus < sass_value >`
// takes care to not parse invalid combinations
const char* value_combinations(const char* src) {
// `2px-2px` is invalid combo
bool was_number = false;
const char* pos = src;
while (src) {
if ((pos = alternatives < quoted_string, identifier, percentage, hex >(src))) {
was_number = false;
src = pos;
} else if (!was_number && !exactly<'+'>(src) && (pos = alternatives < dimension, number >(src))) {
was_number = true;
src = pos;
} else {
break;
}
}
return src;
}
// must be at least one interpolant
// can be surrounded by sass values
// make sure to never parse (dim)(dim)
// since this wrongly consumes `2px-1px`
// `2px1px` is valid number (unit `px1px`)
const char* value_schema(const char* src)
{
return sequence <
one_plus <
sequence <
optional < value_combinations >,
interpolant,
optional < value_combinations >
>
>
>(src);
}
// Match CSS '@' keywords.
const char* at_keyword(const char* src) {
return sequence<exactly<'@'>, identifier>(src);
}
/*
tok(%r{
(
\\.
|
(?!url\()
[^"'/\#!;\{\}] # "
|
/(?![\*\/])
|
\#(?!\{)
|
!(?![a-z]) # TODO: never consume "!" when issue 1126 is fixed.
)+
}xi) || tok(COMMENT) || tok(SINGLE_LINE_COMMENT) || interp_string || interp_uri ||
interpolation(:warn_for_color)
*/
const char* re_almost_any_value_token(const char* src) {
return alternatives <
one_plus <
alternatives <
sequence <
exactly <'\\'>,
any_char
>,
sequence <
negate <
sequence <
exactly < url_kwd >,
exactly <'('>
>
>,
neg_class_char <
almost_any_value_class
>
>,
sequence <
exactly <'/'>,
negate <
alternatives <
exactly <'/'>,
exactly <'*'>
>
>
>,
sequence <
exactly <'\\'>,
exactly <'#'>,
negate <
exactly <'{'>
>
>,
sequence <
exactly <'!'>,
negate <
alpha
>
>
>
>,
block_comment,
line_comment,
interpolant,
space,
sequence <
exactly<'u'>,
exactly<'r'>,
exactly<'l'>,
exactly<'('>,
zero_plus <
alternatives <
class_char< real_uri_chars >,
uri_character,
NONASCII,
ESCAPE
>
>,
// false => /url\(#{W}(#{URLCHAR}*?)(#{W}\)|#\{)/,
// true => /(#{URLCHAR}*?)(#{W}\)|#\{)/
exactly<')'>
>
>(src);
}
/*
DIRECTIVES = Set[:mixin, :include, :function, :return, :debug, :warn, :for,
:each, :while, :if, :else, :extend, :import, :media, :charset, :content,
:_moz_document, :at_root, :error]
*/
const char* re_special_directive(const char* src) {
return alternatives <
word < mixin_kwd >,
word < include_kwd >,
word < function_kwd >,
word < return_kwd >,
word < debug_kwd >,
word < warn_kwd >,
word < for_kwd >,
word < each_kwd >,
word < while_kwd >,
word < if_kwd >,
word < else_kwd >,
word < extend_kwd >,
word < import_kwd >,
word < media_kwd >,
word < charset_kwd >,
word < content_kwd >,
// exactly < moz_document_kwd >,
word < at_root_kwd >,
word < error_kwd >
>(src);
}
const char* re_prefixed_directive(const char* src) {
return sequence <
optional <
sequence <
exactly <'-'>,
one_plus < alnum >,
exactly <'-'>
>
>,
exactly < supports_kwd >
>(src);
}
const char* re_reference_combinator(const char* src) {
return sequence <
optional <
sequence <
zero_plus <
exactly <'-'>
>,
identifier,
exactly <'|'>
>
>,
zero_plus <
exactly <'-'>
>,
identifier
>(src);
}
const char* static_reference_combinator(const char* src) {
return sequence <
exactly <'/'>,
re_reference_combinator,
exactly <'/'>
>(src);
}
const char* schema_reference_combinator(const char* src) {
return sequence <
exactly <'/'>,
optional <
sequence <
css_ip_identifier,
exactly <'|'>
>
>,
css_ip_identifier,
exactly <'/'>
> (src);
}
const char* kwd_import(const char* src) {
return word<import_kwd>(src);
}
const char* kwd_at_root(const char* src) {
return word<at_root_kwd>(src);
}
const char* kwd_with_directive(const char* src) {
return word<with_kwd>(src);
}
const char* kwd_without_directive(const char* src) {
return word<without_kwd>(src);
}
const char* kwd_media(const char* src) {
return word<media_kwd>(src);
}
const char* kwd_supports_directive(const char* src) {
return word<supports_kwd>(src);
}
const char* kwd_mixin(const char* src) {
return word<mixin_kwd>(src);
}
const char* kwd_function(const char* src) {
return word<function_kwd>(src);
}
const char* kwd_return_directive(const char* src) {
return word<return_kwd>(src);
}
const char* kwd_include_directive(const char* src) {
return word<include_kwd>(src);
}
const char* kwd_content_directive(const char* src) {
return word<content_kwd>(src);
}
const char* kwd_charset_directive(const char* src) {
return word<charset_kwd>(src);
}
const char* kwd_extend(const char* src) {
return word<extend_kwd>(src);
}
const char* kwd_if_directive(const char* src) {
return word<if_kwd>(src);
}
const char* kwd_else_directive(const char* src) {
return word<else_kwd>(src);
}
const char* elseif_directive(const char* src) {
return sequence< exactly< else_kwd >,
optional_css_comments,
word< if_after_else_kwd > >(src);
}
const char* kwd_for_directive(const char* src) {
return word<for_kwd>(src);
}
const char* kwd_from(const char* src) {
return word<from_kwd>(src);
}
const char* kwd_to(const char* src) {
return word<to_kwd>(src);
}
const char* kwd_through(const char* src) {
return word<through_kwd>(src);
}
const char* kwd_each_directive(const char* src) {
return word<each_kwd>(src);
}
const char* kwd_in(const char* src) {
return word<in_kwd>(src);
}
const char* kwd_while_directive(const char* src) {
return word<while_kwd>(src);
}
const char* name(const char* src) {
return one_plus< alternatives< alnum,
exactly<'-'>,
exactly<'_'>,
escape_seq > >(src);
}
const char* kwd_warn(const char* src) {
return word<warn_kwd>(src);
}
const char* kwd_err(const char* src) {
return word<error_kwd>(src);
}
const char* kwd_dbg(const char* src) {
return word<debug_kwd>(src);
}
/* not used anymore - remove?
const char* directive(const char* src) {
return sequence< exactly<'@'>, identifier >(src);
} */
const char* kwd_null(const char* src) {
return word<null_kwd>(src);
}
const char* css_identifier(const char* src) {
return sequence <
zero_plus <
exactly <'-'>
>,
identifier
>(src);
}
const char* css_ip_identifier(const char* src) {
return sequence <
zero_plus <
exactly <'-'>
>,
alternatives <
identifier,
interpolant
>
>(src);
}
// Match CSS type selectors
const char* namespace_prefix(const char* src) {
return sequence <
optional <
alternatives <
exactly <'*'>,
css_identifier
>
>,
exactly <'|'>,
negate <
exactly <'='>
>
>(src);
}
// Match CSS type selectors
const char* namespace_schema(const char* src) {
return sequence <
optional <
alternatives <
exactly <'*'>,
css_ip_identifier
>
>,
exactly<'|'>,
negate <
exactly <'='>
>
>(src);
}
const char* hyphens_and_identifier(const char* src) {
return sequence< zero_plus< exactly< '-' > >, identifier_alnums >(src);
}
const char* hyphens_and_name(const char* src) {
return sequence< zero_plus< exactly< '-' > >, name >(src);
}
const char* universal(const char* src) {
return sequence< optional<namespace_schema>, exactly<'*'> >(src);
}
// Match CSS id names.
const char* id_name(const char* src) {
return sequence<exactly<'#'>, identifier_alnums >(src);
}
// Match CSS class names.
const char* class_name(const char* src) {
return sequence<exactly<'.'>, identifier >(src);
}
// Attribute name in an attribute selector.
const char* attribute_name(const char* src) {
return alternatives< sequence< optional<namespace_schema>, identifier>,
identifier >(src);
}
// match placeholder selectors
const char* placeholder(const char* src) {
return sequence<exactly<'%'>, identifier_alnums >(src);
}
// Match CSS numeric constants.
const char* op(const char* src) {
return class_char<op_chars>(src);
}
const char* sign(const char* src) {
return class_char<sign_chars>(src);
}
const char* unsigned_number(const char* src) {
return alternatives<sequence< zero_plus<digits>,
exactly<'.'>,
one_plus<digits> >,
digits>(src);
}
const char* number(const char* src) {
return sequence< optional<sign>, unsigned_number>(src);
}
const char* coefficient(const char* src) {
return alternatives< sequence< optional<sign>, digits >,
sign >(src);
}
const char* binomial(const char* src) {
return sequence <
optional < sign >,
optional < digits >,
exactly <'n'>,
zero_plus < sequence <
optional_css_whitespace, sign,
optional_css_whitespace, digits
> >
>(src);
}
const char* percentage(const char* src) {
return sequence< number, exactly<'%'> >(src);
}
const char* ampersand(const char* src) {
return exactly<'&'>(src);
}
/* not used anymore - remove?
const char* em(const char* src) {
return sequence< number, exactly<em_kwd> >(src);
} */
const char* dimension(const char* src) {
return sequence<number, unit_identifier >(src);
}
const char* hex(const char* src) {
const char* p = sequence< exactly<'#'>, one_plus<xdigit> >(src);
ptrdiff_t len = p - src;
return (len != 4 && len != 7) ? 0 : p;
}
const char* hexa(const char* src) {
const char* p = sequence< exactly<'#'>, one_plus<xdigit> >(src);
ptrdiff_t len = p - src;
return (len != 4 && len != 7 && len != 9) ? 0 : p;
}
const char* hex0(const char* src) {
const char* p = sequence< exactly<'0'>, exactly<'x'>, one_plus<xdigit> >(src);
ptrdiff_t len = p - src;
return (len != 5 && len != 8) ? 0 : p;
}
/* no longer used - remove?
const char* rgb_prefix(const char* src) {
return word<rgb_kwd>(src);
}*/
// Match CSS uri specifiers.
const char* uri_prefix(const char* src) {
return sequence <
exactly <
url_kwd
>,
zero_plus <
sequence <
exactly <'-'>,
one_plus <
alpha
>
>
>,
exactly <'('>
>(src);
}
// TODO: rename the following two functions
/* no longer used - remove?
const char* uri(const char* src) {
return sequence< exactly<url_kwd>,
optional<spaces>,
quoted_string,
optional<spaces>,
exactly<')'> >(src);
}*/
/* no longer used - remove?
const char* url_value(const char* src) {
return sequence< optional< sequence< identifier, exactly<':'> > >, // optional protocol
one_plus< sequence< zero_plus< exactly<'/'> >, filename > >, // one or more folders and/or trailing filename
optional< exactly<'/'> > >(src);
}*/
/* no longer used - remove?
const char* url_schema(const char* src) {
return sequence< optional< sequence< identifier, exactly<':'> > >, // optional protocol
filename_schema >(src); // optional trailing slash
}*/
// Match CSS "!important" keyword.
const char* kwd_important(const char* src) {
return sequence< exactly<'!'>,
optional_css_whitespace,
word<important_kwd> >(src);
}
// Match CSS "!optional" keyword.
const char* kwd_optional(const char* src) {
return sequence< exactly<'!'>,
optional_css_whitespace,
word<optional_kwd> >(src);
}
// Match Sass "!default" keyword.
const char* default_flag(const char* src) {
return sequence< exactly<'!'>,
optional_css_whitespace,
word<default_kwd> >(src);
}
// Match Sass "!global" keyword.
const char* global_flag(const char* src) {
return sequence< exactly<'!'>,
optional_css_whitespace,
word<global_kwd> >(src);
}
// Match CSS pseudo-class/element prefixes.
const char* pseudo_prefix(const char* src) {
return sequence< exactly<':'>, optional< exactly<':'> > >(src);
}
// Match CSS function call openers.
const char* functional_schema(const char* src) {
return sequence <
one_plus <
sequence <
zero_plus <
alternatives <
identifier,
exactly <'-'>
>
>,
one_plus <
sequence <
interpolant,
alternatives <
digits,
identifier,
exactly<'+'>,
exactly<'-'>
>
>
>
>
>,
negate <
exactly <'%'>
>,
lookahead <
exactly <'('>
>
> (src);
}
const char* re_nothing(const char* src) {
return src;
}
const char* re_functional(const char* src) {
return sequence< identifier, optional < block_comment >, exactly<'('> >(src);
}
const char* re_pseudo_selector(const char* src) {
return sequence< identifier, optional < block_comment >, exactly<'('> >(src);
}
// Match the CSS negation pseudo-class.
const char* pseudo_not(const char* src) {
return word< pseudo_not_kwd >(src);
}
// Match CSS 'odd' and 'even' keywords for functional pseudo-classes.
const char* even(const char* src) {
return word<even_kwd>(src);
}
const char* odd(const char* src) {
return word<odd_kwd>(src);
}
// Match CSS attribute-matching operators.
const char* exact_match(const char* src) { return exactly<'='>(src); }
const char* class_match(const char* src) { return exactly<tilde_equal>(src); }
const char* dash_match(const char* src) { return exactly<pipe_equal>(src); }
const char* prefix_match(const char* src) { return exactly<caret_equal>(src); }
const char* suffix_match(const char* src) { return exactly<dollar_equal>(src); }
const char* substring_match(const char* src) { return exactly<star_equal>(src); }
// Match CSS combinators.
/* not used anymore - remove?
const char* adjacent_to(const char* src) {
return sequence< optional_spaces, exactly<'+'> >(src);
}
const char* precedes(const char* src) {
return sequence< optional_spaces, exactly<'~'> >(src);
}
const char* parent_of(const char* src) {
return sequence< optional_spaces, exactly<'>'> >(src);
}
const char* ancestor_of(const char* src) {
return sequence< spaces, negate< exactly<'{'> > >(src);
}*/
// Match SCSS variable names.
const char* variable(const char* src) {
return sequence<exactly<'$'>, identifier>(src);
}
// parse `calc`, `-a-calc` and `--b-c-calc`
// but do not parse `foocalc` or `foo-calc`
const char* calc_fn_call(const char* src) {
return sequence <
optional < sequence <
hyphens,
one_plus < sequence <
strict_identifier,
hyphens
> >
> >,
exactly < calc_fn_kwd >,
word_boundary
>(src);
}
// Match Sass boolean keywords.
const char* kwd_true(const char* src) {
return word<true_kwd>(src);
}
const char* kwd_false(const char* src) {
return word<false_kwd>(src);
}
const char* kwd_only(const char* src) {
return keyword < only_kwd >(src);
}
const char* kwd_and(const char* src) {
return keyword < and_kwd >(src);
}
const char* kwd_or(const char* src) {
return keyword < or_kwd >(src);
}
const char* kwd_not(const char* src) {
return keyword < not_kwd >(src);
}
const char* kwd_eq(const char* src) {
return exactly<eq>(src);
}
const char* kwd_neq(const char* src) {
return exactly<neq>(src);
}
const char* kwd_gt(const char* src) {
return exactly<gt>(src);
}
const char* kwd_gte(const char* src) {
return exactly<gte>(src);
}
const char* kwd_lt(const char* src) {
return exactly<lt>(src);
}
const char* kwd_lte(const char* src) {
return exactly<lte>(src);
}
// match specific IE syntax
const char* ie_progid(const char* src) {
return sequence <
word<progid_kwd>,
exactly<':'>,
alternatives< identifier_schema, identifier >,
zero_plus< sequence<
exactly<'.'>,
alternatives< identifier_schema, identifier >
> >,
zero_plus < sequence<
exactly<'('>,
optional_css_whitespace,
optional < sequence<
alternatives< variable, identifier_schema, identifier >,
optional_css_whitespace,
exactly<'='>,
optional_css_whitespace,
alternatives< variable, identifier_schema, identifier, quoted_string, number, hexa >,
zero_plus< sequence<
optional_css_whitespace,
exactly<','>,
optional_css_whitespace,
sequence<
alternatives< variable, identifier_schema, identifier >,
optional_css_whitespace,
exactly<'='>,
optional_css_whitespace,
alternatives< variable, identifier_schema, identifier, quoted_string, number, hexa >
>
> >
> >,
optional_css_whitespace,
exactly<')'>
> >
>(src);
}
const char* ie_expression(const char* src) {
return sequence < word<expression_kwd>, exactly<'('>, skip_over_scopes< exactly<'('>, exactly<')'> > >(src);
}
const char* ie_property(const char* src) {
return alternatives < ie_expression, ie_progid >(src);
}
// const char* ie_args(const char* src) {
// return sequence< alternatives< ie_keyword_arg, value_schema, quoted_string, interpolant, number, identifier, delimited_by< '(', ')', true> >,
// zero_plus< sequence< optional_css_whitespace, exactly<','>, optional_css_whitespace, alternatives< ie_keyword_arg, value_schema, quoted_string, interpolant, number, identifier, delimited_by<'(', ')', true> > > > >(src);
// }
const char* ie_keyword_arg_property(const char* src) {
return alternatives <
variable,
identifier_schema,
identifier
>(src);
}
const char* ie_keyword_arg_value(const char* src) {
return alternatives <
variable,
identifier_schema,
identifier,
quoted_string,
number,
hexa,
sequence <
exactly < '(' >,
skip_over_scopes <
exactly < '(' >,
exactly < ')' >
>
>
>(src);
}
const char* ie_keyword_arg(const char* src) {
return sequence <
ie_keyword_arg_property,
optional_css_whitespace,
exactly<'='>,
optional_css_whitespace,
ie_keyword_arg_value
>(src);
}
// Path matching functions.
/* not used anymore - remove?
const char* folder(const char* src) {
return sequence< zero_plus< any_char_except<'/'> >,
exactly<'/'> >(src);
}
const char* folders(const char* src) {
return zero_plus< folder >(src);
}*/
/* not used anymore - remove?
const char* chunk(const char* src) {
char inside_str = 0;
const char* p = src;
size_t depth = 0;
while (true) {
if (!*p) {
return 0;
}
else if (!inside_str && (*p == '"' || *p == '\'')) {
inside_str = *p;
}
else if (*p == inside_str && *(p-1) != '\\') {
inside_str = 0;
}
else if (*p == '(' && !inside_str) {
++depth;
}
else if (*p == ')' && !inside_str) {
if (depth == 0) return p;
else --depth;
}
++p;
}
// unreachable
return 0;
}
*/
// follow the CSS spec more closely and see if this helps us scan URLs correctly
/* not used anymore - remove?
const char* NL(const char* src) {
return alternatives< exactly<'\n'>,
sequence< exactly<'\r'>, exactly<'\n'> >,
exactly<'\r'>,
exactly<'\f'> >(src);
}*/
const char* H(const char* src) {
return std::isxdigit(*src) ? src+1 : 0;
}
const char* W(const char* src) {
return zero_plus< alternatives<
space,
exactly< '\t' >,
exactly< '\r' >,
exactly< '\n' >,
exactly< '\f' >
> >(src);
}
const char* UUNICODE(const char* src) {
return sequence< exactly<'\\'>,
between<H, 1, 6>,
optional< W >
>(src);
}
const char* NONASCII(const char* src) {
return nonascii(src);
}
const char* ESCAPE(const char* src) {
return alternatives<
UUNICODE,
sequence<
exactly<'\\'>,
alternatives<
NONASCII,
escapable_character
>
>
>(src);
}
const char* list_terminator(const char* src) {
return alternatives <
exactly<';'>,
exactly<'}'>,
exactly<'{'>,
exactly<')'>,
exactly<']'>,
exactly<':'>,
end_of_file,
exactly<ellipsis>,
default_flag,
global_flag
>(src);
};
const char* space_list_terminator(const char* src) {
return alternatives <
exactly<','>,
list_terminator
>(src);
};
// const char* real_uri_prefix(const char* src) {
// return alternatives<
// exactly< url_kwd >,
// exactly< url_prefix_kwd >
// >(src);
// }
const char* real_uri_suffix(const char* src) {
return sequence< W, exactly< ')' > >(src);
}
const char* real_uri_value(const char* src) {
return
sequence<
non_greedy<
alternatives<
class_char< real_uri_chars >,
uri_character,
NONASCII,
ESCAPE
>,
alternatives<
real_uri_suffix,
exactly< hash_lbrace >
>
>
>
(src);
}
const char* static_string(const char* src) {
const char* pos = src;
const char * s = quoted_string(pos);
Token t(pos, s);
const unsigned int p = count_interval< interpolant >(t.begin, t.end);
return (p == 0) ? t.end : 0;
}
const char* unicode_seq(const char* src) {
return sequence <
alternatives <
exactly< 'U' >,
exactly< 'u' >
>,
exactly< '+' >,
padded_token <
6, xdigit,
exactly < '?' >
>
>(src);
}
const char* static_component(const char* src) {
return alternatives< identifier,
static_string,
percentage,
hex,
exactly<'|'>,
// exactly<'+'>,
sequence < number, unit_identifier >,
number,
sequence< exactly<'!'>, word<important_kwd> >
>(src);
}
const char* static_property(const char* src) {
return
sequence <
zero_plus<
sequence <
optional_css_comments,
alternatives <
exactly<','>,
exactly<'('>,
exactly<')'>,
kwd_optional,
quoted_string,
interpolant,
identifier,
percentage,
dimension,
variable,
alnum,
sequence <
exactly <'\\'>,
any_char
>
>
>
>,
lookahead <
sequence <
optional_css_comments,
alternatives <
exactly <';'>,
exactly <'}'>,
end_of_file
>
>
>
>(src);
}
const char* static_value(const char* src) {
return sequence< sequence<
static_component,
zero_plus< identifier >
>,
zero_plus < sequence<
alternatives<
sequence< optional_spaces, alternatives<
exactly < '/' >,
exactly < ',' >,
exactly < ' ' >
>, optional_spaces >,
spaces
>,
static_component
> >,
zero_plus < spaces >,
alternatives< exactly<';'>, exactly<'}'> >
>(src);
}
const char* parenthese_scope(const char* src) {
return sequence <
exactly < '(' >,
skip_over_scopes <
exactly < '(' >,
exactly < ')' >
>
>(src);
}
const char* re_selector_list(const char* src) {
return alternatives <
// partial bem selector
sequence <
ampersand,
one_plus <
exactly < '-' >
>,
word_boundary,
optional_spaces
>,
// main selector matching
one_plus <
alternatives <
// consume whitespace and comments
spaces, block_comment, line_comment,
// match `/deep/` selector (pass-trough)
// there is no functionality for it yet
schema_reference_combinator,
// match selector ops /[*&%,\[\]]/
class_char < selector_lookahead_ops >,
// match selector combinators /[>+~]/
class_char < selector_combinator_ops >,
// match attribute compare operators
sequence <
exactly <'('>,
optional_spaces,
optional <re_selector_list>,
optional_spaces,
exactly <')'>
>,
alternatives <
exact_match, class_match, dash_match,
prefix_match, suffix_match, substring_match
>,
// main selector match
sequence <
// allow namespace prefix
optional < namespace_schema >,
// modifiers prefixes
alternatives <
sequence <
exactly <'#'>,
// not for interpolation
negate < exactly <'{'> >
>,
// class match
exactly <'.'>,
// single or double colon
optional < pseudo_prefix >
>,
// accept hypens in token
one_plus < sequence <
// can start with hyphens
zero_plus < exactly<'-'> >,
// now the main token
alternatives <
kwd_optional,
exactly <'*'>,
quoted_string,
interpolant,
identifier,
variable,
percentage,
binomial,
dimension,
alnum
>
> >,
// can also end with hyphens
zero_plus < exactly<'-'> >
>
>
>
>(src);
}
const char* type_selector(const char* src) {
return sequence< optional<namespace_schema>, identifier>(src);
}
const char* re_type_selector(const char* src) {
return alternatives< type_selector, universal, quoted_string, dimension, percentage, number, identifier_alnums >(src);
}
const char* re_type_selector2(const char* src) {
return alternatives< type_selector, universal, quoted_string, dimension, percentage, number, identifier_alnums >(src);
}
const char* re_static_expression(const char* src) {
return sequence< number, optional_spaces, exactly<'/'>, optional_spaces, number >(src);
}
// lexer special_fn: these functions cannot be overloaded
// (/((-[\w-]+-)?(calc|element)|expression|progid:[a-z\.]*)\(/i)
const char* re_special_fun(const char* src) {
// match this first as we test prefix hyphens
if (const char* calc = calc_fn_call(src)) {
return calc;
}
return sequence <
optional <
sequence <
exactly <'-'>,
one_plus <
alternatives <
alpha,
exactly <'+'>,
exactly <'-'>
>
>
>
>,
alternatives <
word < expression_kwd >,
sequence <
sequence <
exactly < progid_kwd >,
exactly <':'>
>,
zero_plus <
alternatives <
char_range <'a', 'z'>,
exactly <'.'>
>
>
>
>
>(src);
}
}
}
|
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/rds/model/ResetDBParameterGroupResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <utility>
using namespace Aws::RDS::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils::Logging;
using namespace Aws::Utils;
using namespace Aws;
ResetDBParameterGroupResult::ResetDBParameterGroupResult()
{
}
ResetDBParameterGroupResult::ResetDBParameterGroupResult(const AmazonWebServiceResult<XmlDocument>& result)
{
*this = result;
}
ResetDBParameterGroupResult& ResetDBParameterGroupResult::operator =(const AmazonWebServiceResult<XmlDocument>& result)
{
const XmlDocument& xmlDocument = result.GetPayload();
XmlNode rootNode = xmlDocument.GetRootElement();
XmlNode resultNode = rootNode;
if (rootNode.GetName() != "ResetDBParameterGroupResult")
{
resultNode = rootNode.FirstChild("ResetDBParameterGroupResult");
}
if(!resultNode.IsNull())
{
XmlNode dBParameterGroupNameNode = resultNode.FirstChild("DBParameterGroupName");
if(!dBParameterGroupNameNode.IsNull())
{
m_dBParameterGroupName = StringUtils::Trim(dBParameterGroupNameNode.GetText().c_str());
}
}
XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
m_responseMetadata = responseMetadataNode;
AWS_LOGSTREAM_DEBUG("Aws::RDS::Model::ResetDBParameterGroupResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() );
return *this;
}
|
/**
* pugixml parser - version 1.6
* --------------------------------------------------------
* Copyright (C) 2006-2015, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
* Report bugs and download new versions at http://pugixml.org/
*
* This library is distributed under the MIT License. See notice at the end
* of this file.
*
* This work is based on the pugxml parser, which is:
* Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
*/
#ifndef PUGIXML_VERSION
// Define version macro; evaluates to major * 100 + minor so that it's safe to use in less-than comparisons
# define PUGIXML_VERSION 160
#endif
// Include user configuration file (this can define various configuration macros)
#include "pugiconfig.hpp"
#ifndef HEADER_PUGIXML_HPP
#define HEADER_PUGIXML_HPP
// Include stddef.h for size_t and ptrdiff_t
#include <stddef.h>
// Include exception header for XPath
#if !defined(PUGIXML_NO_XPATH) && !defined(PUGIXML_NO_EXCEPTIONS)
# include <exception>
#endif
// Include STL headers
#ifndef PUGIXML_NO_STL
# include <iterator>
# include <iosfwd>
# include <string>
#endif
// Macro for deprecated features
#ifndef PUGIXML_DEPRECATED
# if defined(__GNUC__)
# define PUGIXML_DEPRECATED __attribute__((deprecated))
# elif defined(_MSC_VER) && _MSC_VER >= 1300
# define PUGIXML_DEPRECATED __declspec(deprecated)
# else
# define PUGIXML_DEPRECATED
# endif
#endif
// If no API is defined, assume default
#ifndef PUGIXML_API
# define PUGIXML_API
#endif
// If no API for classes is defined, assume default
#ifndef PUGIXML_CLASS
# define PUGIXML_CLASS PUGIXML_API
#endif
// If no API for functions is defined, assume default
#ifndef PUGIXML_FUNCTION
# define PUGIXML_FUNCTION PUGIXML_API
#endif
// If the platform is known to have long long support, enable long long functions
#ifndef PUGIXML_HAS_LONG_LONG
# if __cplusplus >= 201103
# define PUGIXML_HAS_LONG_LONG
# elif defined(_MSC_VER) && _MSC_VER >= 1400
# define PUGIXML_HAS_LONG_LONG
# endif
#endif
// Character interface macros
#ifdef PUGIXML_WCHAR_MODE
# define PUGIXML_TEXT(t) L ## t
# define PUGIXML_CHAR wchar_t
#else
# define PUGIXML_TEXT(t) t
# define PUGIXML_CHAR char
#endif
namespace pugi
{
// Character type used for all internal storage and operations; depends on PUGIXML_WCHAR_MODE
typedef PUGIXML_CHAR char_t;
#ifndef PUGIXML_NO_STL
// String type used for operations that work with STL string; depends on PUGIXML_WCHAR_MODE
typedef std::basic_string<PUGIXML_CHAR, std::char_traits<PUGIXML_CHAR>, std::allocator<PUGIXML_CHAR> > string_t;
#endif
}
// The PugiXML namespace
namespace pugi
{
// Tree node types
enum xml_node_type
{
node_null, // Empty (null) node handle
node_document, // A document tree's absolute root
node_element, // Element tag, i.e. '<node/>'
node_pcdata, // Plain character data, i.e. 'text'
node_cdata, // Character data, i.e. '<![CDATA[text]]>'
node_comment, // Comment tag, i.e. '<!-- text -->'
node_pi, // Processing instruction, i.e. '<?name?>'
node_declaration, // Document declaration, i.e. '<?xml version="1.0"?>'
node_doctype // Document type declaration, i.e. '<!DOCTYPE doc>'
};
// Parsing options
// Minimal parsing mode (equivalent to turning all other flags off).
// Only elements and PCDATA sections are added to the DOM tree, no text conversions are performed.
const unsigned int parse_minimal = 0x0000;
// This flag determines if processing instructions (node_pi) are added to the DOM tree. This flag is off by default.
const unsigned int parse_pi = 0x0001;
// This flag determines if comments (node_comment) are added to the DOM tree. This flag is off by default.
const unsigned int parse_comments = 0x0002;
// This flag determines if CDATA sections (node_cdata) are added to the DOM tree. This flag is on by default.
const unsigned int parse_cdata = 0x0004;
// This flag determines if plain character data (node_pcdata) that consist only of whitespace are added to the DOM tree.
// This flag is off by default; turning it on usually results in slower parsing and more memory consumption.
const unsigned int parse_ws_pcdata = 0x0008;
// This flag determines if character and entity references are expanded during parsing. This flag is on by default.
const unsigned int parse_escapes = 0x0010;
// This flag determines if EOL characters are normalized (converted to #xA) during parsing. This flag is on by default.
const unsigned int parse_eol = 0x0020;
// This flag determines if attribute values are normalized using CDATA normalization rules during parsing. This flag is on by default.
const unsigned int parse_wconv_attribute = 0x0040;
// This flag determines if attribute values are normalized using NMTOKENS normalization rules during parsing. This flag is off by default.
const unsigned int parse_wnorm_attribute = 0x0080;
// This flag determines if document declaration (node_declaration) is added to the DOM tree. This flag is off by default.
const unsigned int parse_declaration = 0x0100;
// This flag determines if document type declaration (node_doctype) is added to the DOM tree. This flag is off by default.
const unsigned int parse_doctype = 0x0200;
// This flag determines if plain character data (node_pcdata) that is the only child of the parent node and that consists only
// of whitespace is added to the DOM tree.
// This flag is off by default; turning it on may result in slower parsing and more memory consumption.
const unsigned int parse_ws_pcdata_single = 0x0400;
// This flag determines if leading and trailing whitespace is to be removed from plain character data. This flag is off by default.
const unsigned int parse_trim_pcdata = 0x0800;
// This flag determines if plain character data that does not have a parent node is added to the DOM tree, and if an empty document
// is a valid document. This flag is off by default.
const unsigned int parse_fragment = 0x1000;
// The default parsing mode.
// Elements, PCDATA and CDATA sections are added to the DOM tree, character/reference entities are expanded,
// End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules.
const unsigned int parse_default = parse_cdata | parse_escapes | parse_wconv_attribute | parse_eol;
// The full parsing mode.
// Nodes of all types are added to the DOM tree, character/reference entities are expanded,
// End-of-Line characters are normalized, attribute values are normalized using CDATA normalization rules.
const unsigned int parse_full = parse_default | parse_pi | parse_comments | parse_declaration | parse_doctype;
// These flags determine the encoding of input data for XML document
enum xml_encoding
{
encoding_auto, // Auto-detect input encoding using BOM or < / <? detection; use UTF8 if BOM is not found
encoding_utf8, // UTF8 encoding
encoding_utf16_le, // Little-endian UTF16
encoding_utf16_be, // Big-endian UTF16
encoding_utf16, // UTF16 with native endianness
encoding_utf32_le, // Little-endian UTF32
encoding_utf32_be, // Big-endian UTF32
encoding_utf32, // UTF32 with native endianness
encoding_wchar, // The same encoding wchar_t has (either UTF16 or UTF32)
encoding_latin1
};
// Formatting flags
// Indent the nodes that are written to output stream with as many indentation strings as deep the node is in DOM tree. This flag is on by default.
const unsigned int format_indent = 0x01;
// Write encoding-specific BOM to the output stream. This flag is off by default.
const unsigned int format_write_bom = 0x02;
// Use raw output mode (no indentation and no line breaks are written). This flag is off by default.
const unsigned int format_raw = 0x04;
// Omit default XML declaration even if there is no declaration in the document. This flag is off by default.
const unsigned int format_no_declaration = 0x08;
// Don't escape attribute values and PCDATA contents. This flag is off by default.
const unsigned int format_no_escapes = 0x10;
// Open file using text mode in xml_document::save_file. This enables special character (i.e. new-line) conversions on some systems. This flag is off by default.
const unsigned int format_save_file_text = 0x20;
// Write every attribute on a new line with appropriate indentation. This flag is off by default.
const unsigned int format_indent_attributes = 0x40;
// The default set of formatting flags.
// Nodes are indented depending on their depth in DOM tree, a default declaration is output if document has none.
const unsigned int format_default = format_indent;
// Forward declarations
struct xml_attribute_struct;
struct xml_node_struct;
class xml_node_iterator;
class xml_attribute_iterator;
class xml_named_node_iterator;
class xml_tree_walker;
struct xml_parse_result;
class xml_node;
class xml_text;
#ifndef PUGIXML_NO_XPATH
class xpath_node;
class xpath_node_set;
class xpath_query;
class xpath_variable_set;
#endif
// Range-based for loop support
template <typename It> class xml_object_range
{
public:
typedef It const_iterator;
typedef It iterator;
xml_object_range(It b, It e): _begin(b), _end(e)
{
}
It begin() const { return _begin; }
It end() const { return _end; }
private:
It _begin, _end;
};
// Writer interface for node printing (see xml_node::print)
class PUGIXML_CLASS xml_writer
{
public:
virtual ~xml_writer() {}
// Write memory chunk into stream/file/whatever
virtual void write(const void* data, size_t size) = 0;
};
// xml_writer implementation for FILE*
class PUGIXML_CLASS xml_writer_file: public xml_writer
{
public:
// Construct writer from a FILE* object; void* is used to avoid header dependencies on stdio
xml_writer_file(void* file);
virtual void write(const void* data, size_t size);
private:
void* file;
};
#ifndef PUGIXML_NO_STL
// xml_writer implementation for streams
class PUGIXML_CLASS xml_writer_stream: public xml_writer
{
public:
// Construct writer from an output stream object
xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream);
xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream);
virtual void write(const void* data, size_t size);
private:
std::basic_ostream<char, std::char_traits<char> >* narrow_stream;
std::basic_ostream<wchar_t, std::char_traits<wchar_t> >* wide_stream;
};
#endif
// A light-weight handle for manipulating attributes in DOM tree
class PUGIXML_CLASS xml_attribute
{
friend class xml_attribute_iterator;
friend class xml_node;
private:
xml_attribute_struct* _attr;
typedef void (*unspecified_bool_type)(xml_attribute***);
public:
// Default constructor. Constructs an empty attribute.
xml_attribute();
// Constructs attribute from internal pointer
explicit xml_attribute(xml_attribute_struct* attr);
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Comparison operators (compares wrapped attribute pointers)
bool operator==(const xml_attribute& r) const;
bool operator!=(const xml_attribute& r) const;
bool operator<(const xml_attribute& r) const;
bool operator>(const xml_attribute& r) const;
bool operator<=(const xml_attribute& r) const;
bool operator>=(const xml_attribute& r) const;
// Check if attribute is empty
bool empty() const;
// Get attribute name/value, or "" if attribute is empty
const char_t* name() const;
const char_t* value() const;
// Get attribute value, or the default value if attribute is empty
const char_t* as_string(const char_t* def = PUGIXML_TEXT("")) const;
// Get attribute value as a number, or the default value if conversion did not succeed or attribute is empty
int as_int(int def = 0) const;
unsigned int as_uint(unsigned int def = 0) const;
double as_double(double def = 0) const;
float as_float(float def = 0) const;
#ifdef PUGIXML_HAS_LONG_LONG
long long as_llong(long long def = 0) const;
unsigned long long as_ullong(unsigned long long def = 0) const;
#endif
// Get attribute value as bool (returns true if first character is in '1tTyY' set), or the default value if attribute is empty
bool as_bool(bool def = false) const;
// Set attribute name/value (returns false if attribute is empty or there is not enough memory)
bool set_name(const char_t* rhs);
bool set_value(const char_t* rhs);
// Set attribute value with type conversion (numbers are converted to strings, boolean is converted to "true"/"false")
bool set_value(int rhs);
bool set_value(unsigned int rhs);
bool set_value(double rhs);
bool set_value(float rhs);
bool set_value(bool rhs);
#ifdef PUGIXML_HAS_LONG_LONG
bool set_value(long long rhs);
bool set_value(unsigned long long rhs);
#endif
// Set attribute value (equivalent to set_value without error checking)
xml_attribute& operator=(const char_t* rhs);
xml_attribute& operator=(int rhs);
xml_attribute& operator=(unsigned int rhs);
xml_attribute& operator=(double rhs);
xml_attribute& operator=(float rhs);
xml_attribute& operator=(bool rhs);
#ifdef PUGIXML_HAS_LONG_LONG
xml_attribute& operator=(long long rhs);
xml_attribute& operator=(unsigned long long rhs);
#endif
// Get next/previous attribute in the attribute list of the parent node
xml_attribute next_attribute() const;
xml_attribute previous_attribute() const;
// Get hash value (unique for handles to the same object)
size_t hash_value() const;
// Get internal pointer
xml_attribute_struct* internal_object() const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xml_attribute& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xml_attribute& lhs, bool rhs);
#endif
// A light-weight handle for manipulating nodes in DOM tree
class PUGIXML_CLASS xml_node
{
friend class xml_attribute_iterator;
friend class xml_node_iterator;
friend class xml_named_node_iterator;
protected:
xml_node_struct* _root;
typedef void (*unspecified_bool_type)(xml_node***);
public:
// Default constructor. Constructs an empty node.
xml_node();
// Constructs node from internal pointer
explicit xml_node(xml_node_struct* p);
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Comparison operators (compares wrapped node pointers)
bool operator==(const xml_node& r) const;
bool operator!=(const xml_node& r) const;
bool operator<(const xml_node& r) const;
bool operator>(const xml_node& r) const;
bool operator<=(const xml_node& r) const;
bool operator>=(const xml_node& r) const;
// Check if node is empty.
bool empty() const;
// Get node type
xml_node_type type() const;
// Get node name, or "" if node is empty or it has no name
const char_t* name() const;
// Get node value, or "" if node is empty or it has no value
// Note: For <node>text</node> node.value() does not return "text"! Use child_value() or text() methods to access text inside nodes.
const char_t* value() const;
// Get attribute list
xml_attribute first_attribute() const;
xml_attribute last_attribute() const;
// Get children list
xml_node first_child() const;
xml_node last_child() const;
// Get next/previous sibling in the children list of the parent node
xml_node next_sibling() const;
xml_node previous_sibling() const;
// Get parent node
xml_node parent() const;
// Get root of DOM tree this node belongs to
xml_node root() const;
// Get text object for the current node
xml_text text() const;
// Get child, attribute or next/previous sibling with the specified name
xml_node child(const char_t* name) const;
xml_attribute attribute(const char_t* name) const;
xml_node next_sibling(const char_t* name) const;
xml_node previous_sibling(const char_t* name) const;
// Get attribute, starting the search from a hint (and updating hint so that searching for a sequence of attributes is fast)
xml_attribute attribute(const char_t* name, xml_attribute& hint) const;
// Get child value of current node; that is, value of the first child node of type PCDATA/CDATA
const char_t* child_value() const;
// Get child value of child with specified name. Equivalent to child(name).child_value().
const char_t* child_value(const char_t* name) const;
// Set node name/value (returns false if node is empty, there is not enough memory, or node can not have name/value)
bool set_name(const char_t* rhs);
bool set_value(const char_t* rhs);
// Add attribute with specified name. Returns added attribute, or empty attribute on errors.
xml_attribute append_attribute(const char_t* name);
xml_attribute prepend_attribute(const char_t* name);
xml_attribute insert_attribute_after(const char_t* name, const xml_attribute& attr);
xml_attribute insert_attribute_before(const char_t* name, const xml_attribute& attr);
// Add a copy of the specified attribute. Returns added attribute, or empty attribute on errors.
xml_attribute append_copy(const xml_attribute& proto);
xml_attribute prepend_copy(const xml_attribute& proto);
xml_attribute insert_copy_after(const xml_attribute& proto, const xml_attribute& attr);
xml_attribute insert_copy_before(const xml_attribute& proto, const xml_attribute& attr);
// Add child node with specified type. Returns added node, or empty node on errors.
xml_node append_child(xml_node_type type = node_element);
xml_node prepend_child(xml_node_type type = node_element);
xml_node insert_child_after(xml_node_type type, const xml_node& node);
xml_node insert_child_before(xml_node_type type, const xml_node& node);
// Add child element with specified name. Returns added node, or empty node on errors.
xml_node append_child(const char_t* name);
xml_node prepend_child(const char_t* name);
xml_node insert_child_after(const char_t* name, const xml_node& node);
xml_node insert_child_before(const char_t* name, const xml_node& node);
// Add a copy of the specified node as a child. Returns added node, or empty node on errors.
xml_node append_copy(const xml_node& proto);
xml_node prepend_copy(const xml_node& proto);
xml_node insert_copy_after(const xml_node& proto, const xml_node& node);
xml_node insert_copy_before(const xml_node& proto, const xml_node& node);
// Move the specified node to become a child of this node. Returns moved node, or empty node on errors.
xml_node append_move(const xml_node& moved);
xml_node prepend_move(const xml_node& moved);
xml_node insert_move_after(const xml_node& moved, const xml_node& node);
xml_node insert_move_before(const xml_node& moved, const xml_node& node);
// Remove specified attribute
bool remove_attribute(const xml_attribute& a);
bool remove_attribute(const char_t* name);
// Remove specified child
bool remove_child(const xml_node& n);
bool remove_child(const char_t* name);
// Parses buffer as an XML document fragment and appends all nodes as children of the current node.
// Copies/converts the buffer, so it may be deleted or changed after the function returns.
// Note: append_buffer allocates memory that has the lifetime of the owning document; removing the appended nodes does not immediately reclaim that memory.
xml_parse_result append_buffer(const void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Find attribute using predicate. Returns first attribute for which predicate returned true.
template <typename Predicate> xml_attribute find_attribute(Predicate pred) const
{
if (!_root) return xml_attribute();
for (xml_attribute attrib = first_attribute(); attrib; attrib = attrib.next_attribute())
if (pred(attrib))
return attrib;
return xml_attribute();
}
// Find child node using predicate. Returns first child for which predicate returned true.
template <typename Predicate> xml_node find_child(Predicate pred) const
{
if (!_root) return xml_node();
for (xml_node node = first_child(); node; node = node.next_sibling())
if (pred(node))
return node;
return xml_node();
}
// Find node from subtree using predicate. Returns first node from subtree (depth-first), for which predicate returned true.
template <typename Predicate> xml_node find_node(Predicate pred) const
{
if (!_root) return xml_node();
xml_node cur = first_child();
while (cur._root && cur._root != _root)
{
if (pred(cur)) return cur;
if (cur.first_child()) cur = cur.first_child();
else if (cur.next_sibling()) cur = cur.next_sibling();
else
{
while (!cur.next_sibling() && cur._root != _root) cur = cur.parent();
if (cur._root != _root) cur = cur.next_sibling();
}
}
return xml_node();
}
// Find child node by attribute name/value
xml_node find_child_by_attribute(const char_t* name, const char_t* attr_name, const char_t* attr_value) const;
xml_node find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const;
#ifndef PUGIXML_NO_STL
// Get the absolute node path from root as a text string.
string_t path(char_t delimiter = '/') const;
#endif
// Search for a node by path consisting of node names and . or .. elements.
xml_node first_element_by_path(const char_t* path, char_t delimiter = '/') const;
// Recursively traverse subtree with xml_tree_walker
bool traverse(xml_tree_walker& walker);
#ifndef PUGIXML_NO_XPATH
// Select single node by evaluating XPath query. Returns first node from the resulting node set.
xpath_node select_node(const char_t* query, xpath_variable_set* variables = 0) const;
xpath_node select_node(const xpath_query& query) const;
// Select node set by evaluating XPath query
xpath_node_set select_nodes(const char_t* query, xpath_variable_set* variables = 0) const;
xpath_node_set select_nodes(const xpath_query& query) const;
// (deprecated: use select_node instead) Select single node by evaluating XPath query.
xpath_node select_single_node(const char_t* query, xpath_variable_set* variables = 0) const;
xpath_node select_single_node(const xpath_query& query) const;
#endif
// Print subtree using a writer object
void print(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const;
#ifndef PUGIXML_NO_STL
// Print subtree to stream
void print(std::basic_ostream<char, std::char_traits<char> >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto, unsigned int depth = 0) const;
void print(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& os, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, unsigned int depth = 0) const;
#endif
// Child nodes iterators
typedef xml_node_iterator iterator;
iterator begin() const;
iterator end() const;
// Attribute iterators
typedef xml_attribute_iterator attribute_iterator;
attribute_iterator attributes_begin() const;
attribute_iterator attributes_end() const;
// Range-based for support
xml_object_range<xml_node_iterator> children() const;
xml_object_range<xml_named_node_iterator> children(const char_t* name) const;
xml_object_range<xml_attribute_iterator> attributes() const;
// Get node offset in parsed file/string (in char_t units) for debugging purposes
ptrdiff_t offset_debug() const;
// Get hash value (unique for handles to the same object)
size_t hash_value() const;
// Get internal pointer
xml_node_struct* internal_object() const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xml_node& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xml_node& lhs, bool rhs);
#endif
// A helper for working with text inside PCDATA nodes
class PUGIXML_CLASS xml_text
{
friend class xml_node;
xml_node_struct* _root;
typedef void (*unspecified_bool_type)(xml_text***);
explicit xml_text(xml_node_struct* root);
xml_node_struct* _data_new();
xml_node_struct* _data() const;
public:
// Default constructor. Constructs an empty object.
xml_text();
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Check if text object is empty
bool empty() const;
// Get text, or "" if object is empty
const char_t* get() const;
// Get text, or the default value if object is empty
const char_t* as_string(const char_t* def = PUGIXML_TEXT("")) const;
// Get text as a number, or the default value if conversion did not succeed or object is empty
int as_int(int def = 0) const;
unsigned int as_uint(unsigned int def = 0) const;
double as_double(double def = 0) const;
float as_float(float def = 0) const;
#ifdef PUGIXML_HAS_LONG_LONG
long long as_llong(long long def = 0) const;
unsigned long long as_ullong(unsigned long long def = 0) const;
#endif
// Get text as bool (returns true if first character is in '1tTyY' set), or the default value if object is empty
bool as_bool(bool def = false) const;
// Set text (returns false if object is empty or there is not enough memory)
bool set(const char_t* rhs);
// Set text with type conversion (numbers are converted to strings, boolean is converted to "true"/"false")
bool set(int rhs);
bool set(unsigned int rhs);
bool set(double rhs);
bool set(float rhs);
bool set(bool rhs);
#ifdef PUGIXML_HAS_LONG_LONG
bool set(long long rhs);
bool set(unsigned long long rhs);
#endif
// Set text (equivalent to set without error checking)
xml_text& operator=(const char_t* rhs);
xml_text& operator=(int rhs);
xml_text& operator=(unsigned int rhs);
xml_text& operator=(double rhs);
xml_text& operator=(float rhs);
xml_text& operator=(bool rhs);
#ifdef PUGIXML_HAS_LONG_LONG
xml_text& operator=(long long rhs);
xml_text& operator=(unsigned long long rhs);
#endif
// Get the data node (node_pcdata or node_cdata) for this object
xml_node data() const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xml_text& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xml_text& lhs, bool rhs);
#endif
// Child node iterator (a bidirectional iterator over a collection of xml_node)
class PUGIXML_CLASS xml_node_iterator
{
friend class xml_node;
private:
mutable xml_node _wrap;
xml_node _parent;
xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent);
public:
// Iterator traits
typedef ptrdiff_t difference_type;
typedef xml_node value_type;
typedef xml_node* pointer;
typedef xml_node& reference;
#ifndef PUGIXML_NO_STL
typedef std::bidirectional_iterator_tag iterator_category;
#endif
// Default constructor
xml_node_iterator();
// Construct an iterator which points to the specified node
xml_node_iterator(const xml_node& node);
// Iterator operators
bool operator==(const xml_node_iterator& rhs) const;
bool operator!=(const xml_node_iterator& rhs) const;
xml_node& operator*() const;
xml_node* operator->() const;
const xml_node_iterator& operator++();
xml_node_iterator operator++(int);
const xml_node_iterator& operator--();
xml_node_iterator operator--(int);
};
// Attribute iterator (a bidirectional iterator over a collection of xml_attribute)
class PUGIXML_CLASS xml_attribute_iterator
{
friend class xml_node;
private:
mutable xml_attribute _wrap;
xml_node _parent;
xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent);
public:
// Iterator traits
typedef ptrdiff_t difference_type;
typedef xml_attribute value_type;
typedef xml_attribute* pointer;
typedef xml_attribute& reference;
#ifndef PUGIXML_NO_STL
typedef std::bidirectional_iterator_tag iterator_category;
#endif
// Default constructor
xml_attribute_iterator();
// Construct an iterator which points to the specified attribute
xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent);
// Iterator operators
bool operator==(const xml_attribute_iterator& rhs) const;
bool operator!=(const xml_attribute_iterator& rhs) const;
xml_attribute& operator*() const;
xml_attribute* operator->() const;
const xml_attribute_iterator& operator++();
xml_attribute_iterator operator++(int);
const xml_attribute_iterator& operator--();
xml_attribute_iterator operator--(int);
};
// Named node range helper
class PUGIXML_CLASS xml_named_node_iterator
{
friend class xml_node;
public:
// Iterator traits
typedef ptrdiff_t difference_type;
typedef xml_node value_type;
typedef xml_node* pointer;
typedef xml_node& reference;
#ifndef PUGIXML_NO_STL
typedef std::bidirectional_iterator_tag iterator_category;
#endif
// Default constructor
xml_named_node_iterator();
// Construct an iterator which points to the specified node
xml_named_node_iterator(const xml_node& node, const char_t* name);
// Iterator operators
bool operator==(const xml_named_node_iterator& rhs) const;
bool operator!=(const xml_named_node_iterator& rhs) const;
xml_node& operator*() const;
xml_node* operator->() const;
const xml_named_node_iterator& operator++();
xml_named_node_iterator operator++(int);
const xml_named_node_iterator& operator--();
xml_named_node_iterator operator--(int);
private:
mutable xml_node _wrap;
xml_node _parent;
const char_t* _name;
xml_named_node_iterator(xml_node_struct* ref, xml_node_struct* parent, const char_t* name);
};
// Abstract tree walker class (see xml_node::traverse)
class PUGIXML_CLASS xml_tree_walker
{
friend class xml_node;
private:
int _depth;
protected:
// Get current traversal depth
int depth() const;
public:
xml_tree_walker();
virtual ~xml_tree_walker();
// Callback that is called when traversal begins
virtual bool begin(xml_node& node);
// Callback that is called for each node traversed
virtual bool for_each(xml_node& node) = 0;
// Callback that is called when traversal ends
virtual bool end(xml_node& node);
};
// Parsing status, returned as part of xml_parse_result object
enum xml_parse_status
{
status_ok = 0, // No error
status_file_not_found, // File was not found during load_file()
status_io_error, // Error reading from file/stream
status_out_of_memory, // Could not allocate memory
status_internal_error, // Internal error occurred
status_unrecognized_tag, // Parser could not determine tag type
status_bad_pi, // Parsing error occurred while parsing document declaration/processing instruction
status_bad_comment, // Parsing error occurred while parsing comment
status_bad_cdata, // Parsing error occurred while parsing CDATA section
status_bad_doctype, // Parsing error occurred while parsing document type declaration
status_bad_pcdata, // Parsing error occurred while parsing PCDATA section
status_bad_start_element, // Parsing error occurred while parsing start element tag
status_bad_attribute, // Parsing error occurred while parsing element attribute
status_bad_end_element, // Parsing error occurred while parsing end element tag
status_end_element_mismatch,// There was a mismatch of start-end tags (closing tag had incorrect name, some tag was not closed or there was an excessive closing tag)
status_append_invalid_root, // Unable to append nodes since root type is not node_element or node_document (exclusive to xml_node::append_buffer)
status_no_document_element // Parsing resulted in a document without element nodes
};
// Parsing result
struct PUGIXML_CLASS xml_parse_result
{
// Parsing status (see xml_parse_status)
xml_parse_status status;
// Last parsed offset (in char_t units from start of input data)
ptrdiff_t offset;
// Source document encoding
xml_encoding encoding;
// Default constructor, initializes object to failed state
xml_parse_result();
// Cast to bool operator
operator bool() const;
// Get error description
const char* description() const;
};
// Document class (DOM tree root)
class PUGIXML_CLASS xml_document: public xml_node
{
private:
char_t* _buffer;
char _memory[192];
// Non-copyable semantics
xml_document(const xml_document&);
xml_document& operator=(const xml_document&);
void create();
void destroy();
public:
// Default constructor, makes empty document
xml_document();
// Destructor, invalidates all node/attribute handles to this document
~xml_document();
// Removes all nodes, leaving the empty document
void reset();
// Removes all nodes, then copies the entire contents of the specified document
void reset(const xml_document& proto);
#ifndef PUGIXML_NO_STL
// Load document from stream.
xml_parse_result load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
xml_parse_result load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options = parse_default);
#endif
// (deprecated: use load_string instead) Load document from zero-terminated string. No encoding conversions are applied.
xml_parse_result load(const char_t* contents, unsigned int options = parse_default);
// Load document from zero-terminated string. No encoding conversions are applied.
xml_parse_result load_string(const char_t* contents, unsigned int options = parse_default);
// Load document from file
xml_parse_result load_file(const char* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
xml_parse_result load_file(const wchar_t* path, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Load document from buffer. Copies/converts the buffer, so it may be deleted or changed after the function returns.
xml_parse_result load_buffer(const void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data).
// You should ensure that buffer data will persist throughout the document's lifetime, and free the buffer memory manually once document is destroyed.
xml_parse_result load_buffer_inplace(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Load document from buffer, using the buffer for in-place parsing (the buffer is modified and used for storage of document data).
// You should allocate the buffer with pugixml allocation function; document will free the buffer when it is no longer needed (you can't use it anymore).
xml_parse_result load_buffer_inplace_own(void* contents, size_t size, unsigned int options = parse_default, xml_encoding encoding = encoding_auto);
// Save XML document to writer (semantics is slightly different from xml_node::print, see documentation for details).
void save(xml_writer& writer, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
#ifndef PUGIXML_NO_STL
// Save XML document to stream (semantics is slightly different from xml_node::print, see documentation for details).
void save(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
void save(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default) const;
#endif
// Save XML to file
bool save_file(const char* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
bool save_file(const wchar_t* path, const char_t* indent = PUGIXML_TEXT("\t"), unsigned int flags = format_default, xml_encoding encoding = encoding_auto) const;
// Get document element
xml_node document_element() const;
};
#ifndef PUGIXML_NO_XPATH
// XPath query return type
enum xpath_value_type
{
xpath_type_none, // Unknown type (query failed to compile)
xpath_type_node_set, // Node set (xpath_node_set)
xpath_type_number, // Number
xpath_type_string, // String
xpath_type_boolean // Boolean
};
// XPath parsing result
struct PUGIXML_CLASS xpath_parse_result
{
// Error message (0 if no error)
const char* error;
// Last parsed offset (in char_t units from string start)
ptrdiff_t offset;
// Default constructor, initializes object to failed state
xpath_parse_result();
// Cast to bool operator
operator bool() const;
// Get error description
const char* description() const;
};
// A single XPath variable
class PUGIXML_CLASS xpath_variable
{
friend class xpath_variable_set;
protected:
xpath_value_type _type;
xpath_variable* _next;
xpath_variable(xpath_value_type type);
// Non-copyable semantics
xpath_variable(const xpath_variable&);
xpath_variable& operator=(const xpath_variable&);
public:
// Get variable name
const char_t* name() const;
// Get variable type
xpath_value_type type() const;
// Get variable value; no type conversion is performed, default value (false, NaN, empty string, empty node set) is returned on type mismatch error
bool get_boolean() const;
double get_number() const;
const char_t* get_string() const;
const xpath_node_set& get_node_set() const;
// Set variable value; no type conversion is performed, false is returned on type mismatch error
bool set(bool value);
bool set(double value);
bool set(const char_t* value);
bool set(const xpath_node_set& value);
};
// A set of XPath variables
class PUGIXML_CLASS xpath_variable_set
{
private:
xpath_variable* _data[64];
void _assign(const xpath_variable_set& rhs);
void _swap(xpath_variable_set& rhs);
xpath_variable* _find(const char_t* name) const;
static bool _clone(xpath_variable* var, xpath_variable** out_result);
static void _destroy(xpath_variable* var);
public:
// Default constructor/destructor
xpath_variable_set();
~xpath_variable_set();
// Copy constructor/assignment operator
xpath_variable_set(const xpath_variable_set& rhs);
xpath_variable_set& operator=(const xpath_variable_set& rhs);
#if __cplusplus >= 201103
// Move semantics support
xpath_variable_set(xpath_variable_set&& rhs);
xpath_variable_set& operator=(xpath_variable_set&& rhs);
#endif
// Add a new variable or get the existing one, if the types match
xpath_variable* add(const char_t* name, xpath_value_type type);
// Set value of an existing variable; no type conversion is performed, false is returned if there is no such variable or if types mismatch
bool set(const char_t* name, bool value);
bool set(const char_t* name, double value);
bool set(const char_t* name, const char_t* value);
bool set(const char_t* name, const xpath_node_set& value);
// Get existing variable by name
xpath_variable* get(const char_t* name);
const xpath_variable* get(const char_t* name) const;
};
// A compiled XPath query object
class PUGIXML_CLASS xpath_query
{
private:
void* _impl;
xpath_parse_result _result;
typedef void (*unspecified_bool_type)(xpath_query***);
// Non-copyable semantics
xpath_query(const xpath_query&);
xpath_query& operator=(const xpath_query&);
public:
// Construct a compiled object from XPath expression.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on compilation errors.
explicit xpath_query(const char_t* query, xpath_variable_set* variables = 0);
// Constructor
xpath_query();
// Destructor
~xpath_query();
#if __cplusplus >= 201103
// Move semantics support
xpath_query(xpath_query&& rhs);
xpath_query& operator=(xpath_query&& rhs);
#endif
// Get query expression return type
xpath_value_type return_type() const;
// Evaluate expression as boolean value in the specified context; performs type conversion if necessary.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
bool evaluate_boolean(const xpath_node& n) const;
// Evaluate expression as double value in the specified context; performs type conversion if necessary.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
double evaluate_number(const xpath_node& n) const;
#ifndef PUGIXML_NO_STL
// Evaluate expression as string value in the specified context; performs type conversion if necessary.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
string_t evaluate_string(const xpath_node& n) const;
#endif
// Evaluate expression as string value in the specified context; performs type conversion if necessary.
// At most capacity characters are written to the destination buffer, full result size is returned (includes terminating zero).
// If PUGIXML_NO_EXCEPTIONS is not defined, throws std::bad_alloc on out of memory errors.
// If PUGIXML_NO_EXCEPTIONS is defined, returns empty set instead.
size_t evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const;
// Evaluate expression as node set in the specified context.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on type mismatch and std::bad_alloc on out of memory errors.
// If PUGIXML_NO_EXCEPTIONS is defined, returns empty node set instead.
xpath_node_set evaluate_node_set(const xpath_node& n) const;
// Evaluate expression as node set in the specified context.
// Return first node in document order, or empty node if node set is empty.
// If PUGIXML_NO_EXCEPTIONS is not defined, throws xpath_exception on type mismatch and std::bad_alloc on out of memory errors.
// If PUGIXML_NO_EXCEPTIONS is defined, returns empty node instead.
xpath_node evaluate_node(const xpath_node& n) const;
// Get parsing result (used to get compilation errors in PUGIXML_NO_EXCEPTIONS mode)
const xpath_parse_result& result() const;
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
};
#ifndef PUGIXML_NO_EXCEPTIONS
// XPath exception class
class PUGIXML_CLASS xpath_exception: public std::exception
{
private:
xpath_parse_result _result;
public:
// Construct exception from parse result
explicit xpath_exception(const xpath_parse_result& result);
// Get error message
virtual const char* what() const throw();
// Get parse result
const xpath_parse_result& result() const;
};
#endif
// XPath node class (either xml_node or xml_attribute)
class PUGIXML_CLASS xpath_node
{
private:
xml_node _node;
xml_attribute _attribute;
typedef void (*unspecified_bool_type)(xpath_node***);
public:
// Default constructor; constructs empty XPath node
xpath_node();
// Construct XPath node from XML node/attribute
xpath_node(const xml_node& node);
xpath_node(const xml_attribute& attribute, const xml_node& parent);
// Get node/attribute, if any
xml_node node() const;
xml_attribute attribute() const;
// Get parent of contained node/attribute
xml_node parent() const;
// Safe bool conversion operator
operator unspecified_bool_type() const;
// Borland C++ workaround
bool operator!() const;
// Comparison operators
bool operator==(const xpath_node& n) const;
bool operator!=(const xpath_node& n) const;
};
#ifdef __BORLANDC__
// Borland C++ workaround
bool PUGIXML_FUNCTION operator&&(const xpath_node& lhs, bool rhs);
bool PUGIXML_FUNCTION operator||(const xpath_node& lhs, bool rhs);
#endif
// A fixed-size collection of XPath nodes
class PUGIXML_CLASS xpath_node_set
{
public:
// Collection type
enum type_t
{
type_unsorted, // Not ordered
type_sorted, // Sorted by document order (ascending)
type_sorted_reverse // Sorted by document order (descending)
};
// Constant iterator type
typedef const xpath_node* const_iterator;
// We define non-constant iterator to be the same as constant iterator so that various generic algorithms (i.e. boost foreach) work
typedef const xpath_node* iterator;
// Default constructor. Constructs empty set.
xpath_node_set();
// Constructs a set from iterator range; data is not checked for duplicates and is not sorted according to provided type, so be careful
xpath_node_set(const_iterator begin, const_iterator end, type_t type = type_unsorted);
// Destructor
~xpath_node_set();
// Copy constructor/assignment operator
xpath_node_set(const xpath_node_set& ns);
xpath_node_set& operator=(const xpath_node_set& ns);
#if __cplusplus >= 201103
// Move semantics support
xpath_node_set(xpath_node_set&& rhs);
xpath_node_set& operator=(xpath_node_set&& rhs);
#endif
// Get collection type
type_t type() const;
// Get collection size
size_t size() const;
// Indexing operator
const xpath_node& operator[](size_t index) const;
// Collection iterators
const_iterator begin() const;
const_iterator end() const;
// Sort the collection in ascending/descending order by document order
void sort(bool reverse = false);
// Get first node in the collection by document order
xpath_node first() const;
// Check if collection is empty
bool empty() const;
private:
type_t _type;
xpath_node _storage;
xpath_node* _begin;
xpath_node* _end;
void _assign(const_iterator begin, const_iterator end, type_t type);
void _move(xpath_node_set& rhs);
};
#endif
#ifndef PUGIXML_NO_STL
// Convert wide string to UTF8
std::basic_string<char, std::char_traits<char>, std::allocator<char> > PUGIXML_FUNCTION as_utf8(const wchar_t* str);
std::basic_string<char, std::char_traits<char>, std::allocator<char> > PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >& str);
// Convert UTF8 to wide string
std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > PUGIXML_FUNCTION as_wide(const char* str);
std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > PUGIXML_FUNCTION as_wide(const std::basic_string<char, std::char_traits<char>, std::allocator<char> >& str);
#endif
// Memory allocation function interface; returns pointer to allocated memory or NULL on failure
typedef void* (*allocation_function)(size_t size);
// Memory deallocation function interface
typedef void (*deallocation_function)(void* ptr);
// Override default memory management functions. All subsequent allocations/deallocations will be performed via supplied functions.
void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate);
// Get current memory management functions
allocation_function PUGIXML_FUNCTION get_memory_allocation_function();
deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function();
}
#if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC))
namespace std
{
// Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier)
std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_node_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_attribute_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION _Iter_cat(const pugi::xml_named_node_iterator&);
}
#endif
#if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC)
namespace std
{
// Workarounds for (non-standard) iterator category detection
std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_node_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_attribute_iterator&);
std::bidirectional_iterator_tag PUGIXML_FUNCTION __iterator_category(const pugi::xml_named_node_iterator&);
}
#endif
#endif
// Make sure implementation is included in header-only mode
// Use macro expansion in #include to work around QMake (QTBUG-11923)
#if defined(PUGIXML_HEADER_ONLY) && !defined(PUGIXML_SOURCE)
# define PUGIXML_SOURCE "pugixml.cpp"
# include PUGIXML_SOURCE
#endif
/**
* Copyright (c) 2006-2015 Arseny Kapoulkine
*
* 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.
*/
|
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "bin/file.h"
#include "bin/builtin.h"
#include "bin/dartutils.h"
#include "bin/io_buffer.h"
#include "bin/utils.h"
#include "include/bin/dart_io_api.h"
#include "include/dart_api.h"
#include "include/dart_tools_api.h"
namespace dart {
namespace bin {
// Are we capturing output from stdout for the VM service?
static bool capture_stdout = false;
// Are we capturing output from stderr for the VM service?
static bool capture_stderr = false;
void SetCaptureStdout(bool value) {
capture_stdout = value;
}
void SetCaptureStderr(bool value) {
capture_stderr = value;
}
bool ShouldCaptureStdout() {
return capture_stdout;
}
bool ShouldCaptureStderr() {
return capture_stderr;
}
bool File::ReadFully(void* buffer, int64_t num_bytes) {
int64_t remaining = num_bytes;
char* current_buffer = reinterpret_cast<char*>(buffer);
while (remaining > 0) {
int64_t bytes_read = Read(current_buffer, remaining);
if (bytes_read <= 0) {
return false;
}
remaining -= bytes_read; // Reduce the number of remaining bytes.
current_buffer += bytes_read; // Move the buffer forward.
}
return true;
}
bool File::WriteFully(const void* buffer, int64_t num_bytes) {
int64_t remaining = num_bytes;
const char* current_buffer = reinterpret_cast<const char*>(buffer);
while (remaining > 0) {
// On Windows, narrowing conversion from int64_t to DWORD will cause
// unexpected error.
// On MacOS, a single write() with more than kMaxInt32 will have
// "invalid argument" error.
// Therefore, limit the size for single write.
int64_t byte_to_write = remaining > kMaxInt32 ? kMaxInt32 : remaining;
int64_t bytes_written = Write(current_buffer, byte_to_write);
if (bytes_written < 0) {
return false;
}
remaining -= bytes_written; // Reduce the number of remaining bytes.
current_buffer += bytes_written; // Move the buffer forward.
}
if (capture_stdout || capture_stderr) {
intptr_t fd = GetFD();
const char* result = nullptr;
if ((fd == STDOUT_FILENO) && capture_stdout) {
result = Dart_ServiceSendDataEvent(
"Stdout", "WriteEvent", reinterpret_cast<const uint8_t*>(buffer),
num_bytes);
} else if ((fd == STDERR_FILENO) && capture_stderr) {
result = Dart_ServiceSendDataEvent(
"Stderr", "WriteEvent", reinterpret_cast<const uint8_t*>(buffer),
num_bytes);
}
ASSERT(result == nullptr);
}
return true;
}
File::FileOpenMode File::DartModeToFileMode(DartFileOpenMode mode) {
ASSERT((mode == File::kDartRead) || (mode == File::kDartWrite) ||
(mode == File::kDartAppend) || (mode == File::kDartWriteOnly) ||
(mode == File::kDartWriteOnlyAppend));
if (mode == File::kDartWrite) {
return File::kWriteTruncate;
}
if (mode == File::kDartAppend) {
return File::kWrite;
}
if (mode == File::kDartWriteOnly) {
return File::kWriteOnlyTruncate;
}
if (mode == File::kDartWriteOnlyAppend) {
return File::kWriteOnly;
}
return File::kRead;
}
} // namespace bin
} // namespace dart
|
#include "CondFormats/EcalObjects/interface/EcalTPGGroups.h"
#include "CondFormats/EcalObjects/interface/EcalTPGWeightGroup.h"
#include "CondFormats/EcalObjects/interface/EcalTPGWeightIdMap.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <SimCalorimetry/EcalTrigPrimAlgos/interface/EcalFenixAmplitudeFilter.h>
#include <iostream>
EcalFenixAmplitudeFilter::EcalFenixAmplitudeFilter(bool tpInfoPrintout)
: inputsAlreadyIn_(0), stripid_{0}, shift_(6), tpInfoPrintout_(tpInfoPrintout) {}
EcalFenixAmplitudeFilter::~EcalFenixAmplitudeFilter() {}
int EcalFenixAmplitudeFilter::setInput(int input, int fgvb) {
if (input > 0X3FFFF) {
edm::LogError("EcalTPG") << "ERROR IN INPUT OF EVEN AMPLITUDE FILTER";
return -1;
}
if (inputsAlreadyIn_ < 5) {
buffer_[inputsAlreadyIn_] = input;
fgvbBuffer_[inputsAlreadyIn_] = fgvb;
inputsAlreadyIn_++;
} else {
for (int i = 0; i < 4; i++) {
buffer_[i] = buffer_[i + 1];
fgvbBuffer_[i] = fgvbBuffer_[i + 1];
}
buffer_[4] = input;
fgvbBuffer_[4] = fgvb;
}
return 1;
}
void EcalFenixAmplitudeFilter::process(std::vector<int> &addout,
std::vector<int> &output,
std::vector<int> &fgvbIn,
std::vector<int> &fgvbOut) {
inputsAlreadyIn_ = 0;
for (unsigned int i = 0; i < 5; i++) {
buffer_[i] = 0;
fgvbBuffer_[i] = 0;
}
for (unsigned int i = 0; i < addout.size(); i++) {
setInput(addout[i], fgvbIn[i]);
process();
if (tpInfoPrintout_) {
if (i >= 4) {
edm::LogVerbatim("EcalTPG") << i << " " << stripid_ << " " << weights_[0] << " " << weights_[1] << " "
<< weights_[2] << " " << weights_[3] << " " << weights_[4] << " "
<< weights_[0] / 64.0 << " " << weights_[1] / 64.0 << " " << weights_[2] / 64.0
<< " " << weights_[3] / 64.0 << " " << weights_[4] / 64.0 << " [" << buffer_[0]
<< ", " << buffer_[1] << ", " << buffer_[2] << ", " << buffer_[3] << ", "
<< buffer_[4] << "]"
<< " --> output: " << processedOutput_ << " EVEN";
}
}
output[i] = processedOutput_;
fgvbOut[i] = processedFgvbOutput_;
}
// shift the result by 1!
for (unsigned int i = 0; i < (output.size()); i++) {
if (i != output.size() - 1) {
output[i] = output[i + 1];
fgvbOut[i] = fgvbOut[i + 1];
} else {
output[i] = 0;
fgvbOut[i] = 0;
}
}
return;
}
void EcalFenixAmplitudeFilter::process() {
processedOutput_ = 0;
processedFgvbOutput_ = 0;
if (inputsAlreadyIn_ < 5) // 5 digis required to produce first ET value
return;
int output = 0;
int fgvbInt = 0;
for (int i = 0; i < 5; i++) {
output += (weights_[i] * buffer_[i]) >> shift_;
if ((fgvbBuffer_[i] == 1 && i == 3) || fgvbInt == 1) {
fgvbInt = 1;
}
}
if (output < 0)
output = 0;
if (output > 0X3FFFF)
output = 0X3FFFF;
processedOutput_ = output;
processedFgvbOutput_ = fgvbInt;
}
void EcalFenixAmplitudeFilter::setParameters(uint32_t raw,
const EcalTPGWeightIdMap *ecaltpgWeightMap,
const EcalTPGWeightGroup *ecaltpgWeightGroup) {
stripid_ = raw;
uint32_t params_[5];
const EcalTPGGroups::EcalTPGGroupsMap &groupmap = ecaltpgWeightGroup->getMap();
EcalTPGGroups::EcalTPGGroupsMapItr it = groupmap.find(raw);
if (it != groupmap.end()) {
uint32_t weightid = (*it).second;
const EcalTPGWeightIdMap::EcalTPGWeightMap &weightmap = ecaltpgWeightMap->getMap();
EcalTPGWeightIdMap::EcalTPGWeightMapItr itw = weightmap.find(weightid);
(*itw).second.getValues(params_[0], params_[1], params_[2], params_[3], params_[4]);
for (int i = 0; i < 5; ++i) {
weights_[i] = (params_[i] & 0x40) ? (int)(params_[i] | 0xffffffc0) : (int)(params_[i]);
}
} else
edm::LogWarning("EcalTPG") << " could not find EcalTPGGroupsMap entry for " << raw;
}
|
#define CATCH_CONFIG_MAIN
#include <flyweight/object.hpp>
#include <string>
#include <catch.hpp>
TEST_CASE("object-constructor", "[object][constructor]") {
flyweight::object<std::string> empty { };
CHECK(empty.get().empty());
}
TEST_CASE("object-value-constrctor") {
flyweight::object<std::string> value { "value-constructor" };
CHECK_FALSE(value->empty());
CHECK(value->size() == 17);
}
TEST_CASE("object-copy-constructor") {
flyweight::object<std::string> value { "copy" };
flyweight::object<std::string> copy { value };
CHECK(value.get() == copy.get());
}
TEST_CASE("value-assign-operator") {
flyweight::object<std::string> value { };
std::string text { "value" };
value = text;
CHECK(text == value.get());
}
TEST_CASE("copy-assign-operator") {
flyweight::object<std::string> value { "value" };
flyweight::object<std::string> copy { };
copy = value;
CHECK(value.get() == copy.get());
}
TEST_CASE("conversion-operator") {
flyweight::object<std::string> value { "conversion" };
std::string converted = value;
CHECK(value.get() == converted);
}
TEST_CASE("arrow-operator") {
flyweight::object<std::string> value { "arrow" };
CHECK(value->size() == 5);
}
TEST_CASE("operator-equal") {
std::string text { "equal" };
flyweight::object<std::string> lhs { text };
flyweight::object<std::string> rhs { text };
CHECK(lhs == text);
CHECK(rhs == text);
CHECK(lhs == rhs);
}
TEST_CASE("operator-not-equal") {
std::string text { "not-equal" };
flyweight::object<std::string> lhs { "lhs" };
flyweight::object<std::string> rhs { "rhs" };
CHECK(lhs != text);
CHECK(rhs != text);
CHECK(lhs != rhs);
}
TEST_CASE("operator-greater-equal") {
std::string text { "abcde" };
flyweight::object<std::string> lhs { "bcdef" };
flyweight::object<std::string> rhs { "bcdef" };
CHECK(lhs >= text);
CHECK(rhs >= text);
CHECK(lhs >= rhs);
}
TEST_CASE("operator-less-equal") {
std::string text { "bcdef" };
flyweight::object<std::string> lhs { "abcde" };
flyweight::object<std::string> rhs { "abcde" };
CHECK(lhs <= text);
CHECK(rhs <= text);
CHECK(lhs <= rhs);
}
TEST_CASE("operator-greater") {
std::string text { "abcde" };
flyweight::object<std::string> lhs { "cdefg" };
flyweight::object<std::string> rhs { "bcdef" };
CHECK(lhs > text);
CHECK(rhs > text);
CHECK(lhs > rhs);
}
TEST_CASE("operator-less") {
std::string text { "cdefg" };
flyweight::object<std::string> lhs { "abcde" };
flyweight::object<std::string> rhs { "bcdef" };
CHECK(lhs < text);
CHECK(rhs < text);
CHECK(lhs < rhs);
}
|
#define SECURITY_WIN32 // For sspi.h
#include "intrinfix.h"
#include "windows.fixed.h"
#include <sdkddkver.h>
#include <mmsystem.h>
#include <dsound.h>
|
/*=========================================================================
Program: Image Guided Surgery Software Toolkit
Module: igstkTubeReaderTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) ISC Insight Software Consortium. All rights reserved.
See IGSTKCopyright.txt or http://www.igstk.org/copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "igstkTubeReader.h"
#include "igstkLogger.h"
#include "itkStdStreamLogOutput.h"
igstkObserverObjectMacro( TubeObject,
igstk::TubeReader::TubeModifiedEvent,
igstk::TubeObject);
int igstkTubeReaderTest( int argc, char * argv [] )
{
igstk::RealTimeClock::Initialize();
if( argc < 3 )
{
std::cerr << "Error: Missing command line arguments" << std::endl;
std::cerr << "Usage : " << std::endl;
std::cerr << argv[0] << " inputGoodFileName ";
std::cerr << " inputBadFileName " << std::endl;
return 1;
}
typedef igstk::TubeReader ReaderType;
ReaderType::Pointer reader = ReaderType::New();
typedef igstk::Object::LoggerType LoggerType;
typedef itk::StdStreamLogOutput LogOutputType;
// logger object created for logging mouse activities
LoggerType::Pointer logger = LoggerType::New();
LogOutputType::Pointer logOutput = LogOutputType::New();
logOutput->SetStream( std::cout );
logger->AddLogOutput( logOutput );
logger->SetPriorityLevel( itk::Logger::DEBUG );
reader->SetLogger( logger );
std::string name = reader->GetNameOfClass();
std::cout << "Name of class = " << name << std::endl;
reader->Print( std::cout );
// Test error condition: on purpose request to read an object
// without having provided the filename
reader->RequestReadObject();
// Test empty name
std::string emptyname;
reader->RequestSetFileName( emptyname );
// Test file doesn't exist
std::string filenameThatDoesntExist = "/This/FileName/Does/Not/Exist";
reader->RequestSetFileName( filenameThatDoesntExist );
// Test file that is a directory
std::string filenameIsADirectory = ".";
reader->RequestSetFileName( filenameIsADirectory );
// Test file that exists
std::string filenameThatExists = argv[1];
reader->RequestSetFileName( filenameThatExists );
// Request to read the object from the file
reader->RequestReadObject();
// Now reading a corrupted file
std::string filenameWithCorruptedContent = argv[2];
reader->RequestSetFileName( filenameWithCorruptedContent );
reader->RequestReadObject();
// Attach an observer
TubeObjectObserver::Pointer observer = TubeObjectObserver::New();
reader->AddObserver(igstk::TubeReader::TubeModifiedEvent(),observer);
reader->RequestGetOutput();
if(!observer->GotTubeObject())
{
std::cout << "No MeshObject!" << std::endl;
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
observer->GetTubeObject()->Print( std::cout );
return EXIT_SUCCESS;
}
|
/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Portions copyright 2007 ThoughtWorks, 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.
*/
// stdafx.cpp : source file that includes just the standard includes
// test.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
|
/**
* A collection of fluid runaway source terms.
*/
#include <algorithm>
#include "DREAM/DREAMException.hpp"
#include "DREAM/Equations/RunawaySourceTermHandler.hpp"
#include "FVM/Equation/Operator.hpp"
#include "FVM/Grid/Grid.hpp"
#include "FVM/Matrix.hpp"
using namespace DREAM;
using namespace std;
/**
* Constructor.
*/
RunawaySourceTermHandler::RunawaySourceTermHandler() { }
/**
* Destructor.
*/
RunawaySourceTermHandler::~RunawaySourceTermHandler() {
this->applyToAll([](FVM::EquationTerm *eqterm) {
delete eqterm;
});
}
/**
* Apply the given operator to all source terms that
* have been initialized.
*/
void RunawaySourceTermHandler::applyToAll(std::function<void(FVM::EquationTerm*)> op) {
if (this->avalanche != nullptr)
op(this->avalanche);
if (this->compton != nullptr)
op(this->compton);
if (this->dreicer != nullptr)
op(this->dreicer);
if (this->hottail != nullptr)
op(this->hottail);
if (!this->tritium.empty()) {
for (auto t : this->tritium)
op(t);
}
}
void RunawaySourceTermHandler::applyToAll(const std::function<void(FVM::EquationTerm*)> op) const {
if (this->avalanche != nullptr)
op(this->avalanche);
if (this->compton != nullptr)
op(this->compton);
if (this->dreicer != nullptr)
op(this->dreicer);
if (this->hottail != nullptr)
op(this->hottail);
if (!this->tritium.empty()) {
for (auto t : this->tritium)
op(t);
}
}
/**
* Add the available source terms to the given operators.
*
* op_nRE: Operator operating on n_re (runaway electron density).
* op_nTot: Operator operating on n_tot (total electron density).
* op_ni: Operator operating on n_i (ions).
* op_nRE_neg: Operator operating on n_re_neg (density of runaways travelling in the xi0<0 direction).
*/
void RunawaySourceTermHandler::AddToOperators(
FVM::Operator *op_nRE, FVM::Operator *op_nTot,
FVM::Operator *op_ni, FVM::Operator *op_nRE_neg
) {
// n_re
if (this->avalanche != nullptr) {
if (op_nRE == nullptr)
throw DREAMException(
"RunawaySourceTermHandler: Avalanche generation enabled, but no operator "
"for n_re provided."
);
else
op_nRE->AddTerm(this->avalanche);
if (op_nRE_neg != nullptr &&
this->avalanche_neg != nullptr &&
this->avalanche_negpos != nullptr) {
op_nRE_neg->AddTerm(this->avalanche_neg);
op_nRE_neg->AddTerm(this->avalanche_negpos);
}
}
if (this->dreicer != nullptr) {
if (op_nRE == nullptr)
throw DREAMException(
"RunawaySourceTermHandler: Fluid Dreicer generation enabled, but no operator "
"for n_re provided."
);
else
op_nRE->AddTerm(this->dreicer);
}
if (this->hottail != nullptr) {
if (op_nRE == nullptr)
throw DREAMException(
"RunawaySourceTermHandler: Fluid hottail generation enabled, but no operator "
"for n_re provided."
);
else
op_nRE->AddTerm(this->hottail);
}
// n_tot
if (this->compton != nullptr) {
if (op_nTot == nullptr)
throw DREAMException(
"RunawaySourceTermHandler: Compton source term enabled, but no operator "
"for n_tot provided."
);
else
op_nTot->AddTerm(this->compton);
}
// n_i
if (!this->tritium.empty()) {
if (op_ni == nullptr)
throw DREAMException(
"RunawaySourceTermHandler: Tritium source term enabled, but no operator "
"for n_i provided."
);
else
for (auto t : this->tritium)
op_ni->AddTerm(t);
}
}
|
// Copyright (c) 2013, 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.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "port/port_posix.h"
#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include "util/logging.h"
namespace rocksdb {
namespace port {
static void PthreadCall(const char* label, int result) {
if (result != 0) {
fprintf(stderr, "pthread %s: %s\n", label, strerror(result));
abort();
}
}
Mutex::Mutex(bool adaptive) {
#ifdef OS_LINUX
if (!adaptive) {
PthreadCall("init mutex", pthread_mutex_init(&mu_, NULL));
} else {
pthread_mutexattr_t mutex_attr;
PthreadCall("init mutex attr", pthread_mutexattr_init(&mutex_attr));
PthreadCall("set mutex attr",
pthread_mutexattr_settype(&mutex_attr,
PTHREAD_MUTEX_ADAPTIVE_NP));
PthreadCall("init mutex", pthread_mutex_init(&mu_, &mutex_attr));
PthreadCall("destroy mutex attr",
pthread_mutexattr_destroy(&mutex_attr));
}
#else // ignore adaptive for non-linux platform
PthreadCall("init mutex", pthread_mutex_init(&mu_, NULL));
#endif // OS_LINUX
}
Mutex::~Mutex() { PthreadCall("destroy mutex", pthread_mutex_destroy(&mu_)); }
void Mutex::Lock() { PthreadCall("lock", pthread_mutex_lock(&mu_)); }
void Mutex::Unlock() { PthreadCall("unlock", pthread_mutex_unlock(&mu_)); }
CondVar::CondVar(Mutex* mu)
: mu_(mu) {
PthreadCall("init cv", pthread_cond_init(&cv_, NULL));
}
CondVar::~CondVar() { PthreadCall("destroy cv", pthread_cond_destroy(&cv_)); }
void CondVar::Wait() {
PthreadCall("wait", pthread_cond_wait(&cv_, &mu_->mu_));
}
void CondVar::Signal() {
PthreadCall("signal", pthread_cond_signal(&cv_));
}
void CondVar::SignalAll() {
PthreadCall("broadcast", pthread_cond_broadcast(&cv_));
}
RWMutex::RWMutex() { PthreadCall("init mutex", pthread_rwlock_init(&mu_, NULL)); }
RWMutex::~RWMutex() { PthreadCall("destroy mutex", pthread_rwlock_destroy(&mu_)); }
void RWMutex::ReadLock() { PthreadCall("read lock", pthread_rwlock_rdlock(&mu_)); }
void RWMutex::WriteLock() { PthreadCall("write lock", pthread_rwlock_wrlock(&mu_)); }
void RWMutex::Unlock() { PthreadCall("unlock", pthread_rwlock_unlock(&mu_)); }
void InitOnce(OnceType* once, void (*initializer)()) {
PthreadCall("once", pthread_once(once, initializer));
}
} // namespace port
} // namespace rocksdb
|
#ifndef OSMIUM_IO_OUTPUT_ITERATOR_HPP
#define OSMIUM_IO_OUTPUT_ITERATOR_HPP
/*
This file is part of Osmium (http://osmcode.org/libosmium).
Copyright 2013-2016 Jochen Topf <jochen@topf.org> and others (see README).
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <cstddef>
#include <iterator>
#include <memory>
#include <utility>
#include <osmium/memory/buffer.hpp>
#include <osmium/osm/diff_object.hpp>
#include <osmium/util/compatibility.hpp>
namespace osmium {
namespace memory {
class Item;
} // namespace memory
namespace io {
template <typename TDest>
class OutputIterator {
TDest* m_destination;
public:
using iterator_category = std::output_iterator_tag;
using value_type = void;
using difference_type = void;
using pointer = void;
using reference = void;
explicit OutputIterator(TDest& destination) :
m_destination(&destination) {
}
/**
* @deprecated
* Use of buffer size argument on OutputIterator
* constructor is deprecated. Call Writer::set_buffer_size()
* instead if you want to change the default.
*/
OSMIUM_DEPRECATED OutputIterator(TDest& destination, const size_t buffer_size) :
m_destination(&destination) {
destination.set_buffer_size(buffer_size);
}
OutputIterator(const OutputIterator&) = default;
OutputIterator(OutputIterator&&) = default;
OutputIterator& operator=(const OutputIterator&) = default;
OutputIterator& operator=(OutputIterator&&) = default;
~OutputIterator() = default;
/**
* @deprecated
* Calling OutputIterator<Writer>::flush() is usually not
* needed any more. Call flush() on the Writer instead if needed.
*/
OSMIUM_DEPRECATED void flush() {
m_destination->flush();
}
OutputIterator& operator=(const osmium::memory::Item& item) {
(*m_destination)(item);
return *this;
}
OutputIterator& operator=(const osmium::DiffObject& diff) {
return this->operator=(diff.curr());
}
OutputIterator& operator*() {
return *this;
}
OutputIterator& operator++() {
return *this;
}
OutputIterator& operator++(int) {
return *this;
}
}; // class OutputIterator
template <typename TDest>
OutputIterator<TDest> make_output_iterator(TDest& destination) {
return OutputIterator<TDest>{destination};
}
/**
* @deprecated
* Use of buffer size argument on make_output_iterator is deprecated.
* Call Writer::set_buffer_size() instead if you want to change the
* default.
*/
template <typename TDest>
OSMIUM_DEPRECATED OutputIterator<TDest> make_output_iterator(TDest& destination, const size_t buffer_size) {
destination.set_buffer_size(buffer_size);
return OutputIterator<TDest>{destination};
}
} // namespace io
} // namespace osmium
#endif // OSMIUM_IO_OUTPUT_ITERATOR_HPP
|
/*
* Copyright (c) 2014, 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 <sstream>
#include <osquery/core.h>
#include <osquery/logger.h>
#include <osquery/sql.h>
#include <osquery/tables.h>
#include <osquery/registry.h>
namespace osquery {
FLAG(int32, value_max, 512, "Maximum returned row value size");
const std::map<ConstraintOperator, std::string> kSQLOperatorRepr = {
{EQUALS, "="},
{GREATER_THAN, ">"},
{LESS_THAN_OR_EQUALS, "<="},
{LESS_THAN, "<"},
{GREATER_THAN_OR_EQUALS, ">="},
};
typedef unsigned char byte;
SQL::SQL(const std::string& q) { status_ = query(q, results_); }
const QueryData& SQL::rows() const { return results_; }
bool SQL::ok() { return status_.ok(); }
const Status& SQL::getStatus() const { return status_; }
std::string SQL::getMessageString() { return status_.toString(); }
void escapeNonPrintableBytes(std::string& data) {
std::string escaped;
// clang-format off
char const hex_chars[16] = {
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'A',
'B',
'C',
'D',
'E',
'F',
};
// clang-format on
bool needs_replacement = false;
for (size_t i = 0; i < data.length(); i++) {
if (((byte)data[i]) < 0x20 || ((byte)data[i]) >= 0x80) {
needs_replacement = true;
escaped += "\\x";
escaped += hex_chars[(((byte)data[i])) >> 4];
escaped += hex_chars[((byte)data[i] & 0x0F) >> 0];
} else {
escaped += data[i];
}
}
// Only replace if any escapes were made.
if (needs_replacement) {
data = escaped;
}
}
void SQL::escapeResults() {
for (auto& row : results_) {
for (auto& column : row) {
escapeNonPrintableBytes(column.second);
}
}
}
QueryData SQL::selectAllFrom(const std::string& table) {
PluginResponse response;
PluginRequest request = {{"action", "generate"}};
Registry::call("table", table, request, response);
return response;
}
QueryData SQL::selectAllFrom(const std::string& table,
const std::string& column,
ConstraintOperator op,
const std::string& expr) {
PluginResponse response;
PluginRequest request = {{"action", "generate"}};
QueryContext ctx;
ctx.constraints[column].add(Constraint(op, expr));
TablePlugin::setRequestFromContext(ctx, request);
Registry::call("table", table, request, response);
return response;
}
Status SQLPlugin::call(const PluginRequest& request, PluginResponse& response) {
response.clear();
if (request.count("action") == 0) {
return Status(1, "SQL plugin must include a request action");
}
if (request.at("action") == "query") {
return this->query(request.at("query"), response);
} else if (request.at("action") == "columns") {
TableColumns columns;
auto status = this->getQueryColumns(request.at("query"), columns);
// Convert columns to response
for (const auto& column : columns) {
response.push_back({{"n", column.first}, {"t", column.second}});
}
return status;
} else if (request.at("action") == "attach") {
// Attach a virtual table name using an optional included definition.
return this->attach(request.at("table"));
} else if (request.at("action") == "detach") {
this->detach(request.at("table"));
return Status(0, "OK");
}
return Status(1, "Unknown action");
}
Status query(const std::string& q, QueryData& results) {
return Registry::call(
"sql", "sql", {{"action", "query"}, {"query", q}}, results);
}
Status getQueryColumns(const std::string& q, TableColumns& columns) {
PluginResponse response;
auto status = Registry::call(
"sql", "sql", {{"action", "columns"}, {"query", q}}, response);
// Convert response to columns
for (const auto& item : response) {
columns.push_back(make_pair(item.at("n"), item.at("t")));
}
return status;
}
}
|
/**
* Calculate the sum of two integers a and b, but you are not allowed to
* use the operate + and -.
*
* Example 1:
* Input: a = 1, b = 2
* Output: 3
*
* Example 2:
* Input a = -2, b = 3
* Output: 1
*/
class Solution {
public:
int getSum(int a, int b) {
int ans = a ^ b;
int c = a & b;
while (c != 0) {
c = (c & 0xFFFFFFFF) << 1;
int ans_prim = ans ^ C;
c = ans & c;
ans = ans_prim;
}
return ans;
}
};
|
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2019 The BDRcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "masternode-payments.h"
#include "addrman.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "obfuscation.h"
#include "spork.h"
#include "sync.h"
#include "util.h"
#include "utilmoneystr.h"
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
/** Object for who's going to get paid on which blocks */
CMasternodePayments masternodePayments;
CCriticalSection cs_vecPayments;
CCriticalSection cs_mapMasternodeBlocks;
CCriticalSection cs_mapMasternodePayeeVotes;
//
// CMasternodePaymentDB
//
CMasternodePaymentDB::CMasternodePaymentDB()
{
pathDB = GetDataDir() / "mnpayments.dat";
strMagicMessage = "MasternodePayments";
}
bool CMasternodePaymentDB::Write(const CMasternodePayments& objToSave)
{
int64_t nStart = GetTimeMillis();
// serialize, checksum data up to that point, then append checksum
CDataStream ssObj(SER_DISK, CLIENT_VERSION);
ssObj << strMagicMessage; // masternode cache file specific magic message
ssObj << FLATDATA(Params().MessageStart()); // network specific magic number
ssObj << objToSave;
uint256 hash = Hash(ssObj.begin(), ssObj.end());
ssObj << hash;
// open output file, and associate with CAutoFile
FILE* file = fopen(pathDB.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathDB.string());
// Write and commit header, data
try {
fileout << ssObj;
} catch (std::exception& e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
fileout.fclose();
LogPrintf("Written info to mnpayments.dat %dms\n", GetTimeMillis() - nStart);
return true;
}
CMasternodePaymentDB::ReadResult CMasternodePaymentDB::Read(CMasternodePayments& objToLoad, bool fDryRun)
{
int64_t nStart = GetTimeMillis();
// open input file, and associate with CAutoFile
FILE* file = fopen(pathDB.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull()) {
error("%s : Failed to open file %s", __func__, pathDB.string());
return FileError;
}
// use file size to size memory buffer
int fileSize = boost::filesystem::file_size(pathDB);
int dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (dataSize < 0)
dataSize = 0;
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char*)&vchData[0], dataSize);
filein >> hashIn;
} catch (std::exception& e) {
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return HashReadError;
}
filein.fclose();
CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
if (hashIn != hashTmp) {
error("%s : Checksum mismatch, data corrupted", __func__);
return IncorrectHash;
}
unsigned char pchMsgTmp[4];
std::string strMagicMessageTmp;
try {
// de-serialize file header (masternode cache file specific magic message) and ..
ssObj >> strMagicMessageTmp;
// ... verify the message matches predefined one
if (strMagicMessage != strMagicMessageTmp) {
error("%s : Invalid masternode payement cache magic message", __func__);
return IncorrectMagicMessage;
}
// de-serialize file header (network specific magic number) and ..
ssObj >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) {
error("%s : Invalid network magic number", __func__);
return IncorrectMagicNumber;
}
// de-serialize data into CMasternodePayments object
ssObj >> objToLoad;
} catch (std::exception& e) {
objToLoad.Clear();
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return IncorrectFormat;
}
LogPrintf("Loaded info from mnpayments.dat %dms\n", GetTimeMillis() - nStart);
LogPrintf(" %s\n", objToLoad.ToString());
if (!fDryRun) {
LogPrintf("Masternode payments manager - cleaning....\n");
objToLoad.CleanPaymentList();
LogPrintf("Masternode payments manager - result:\n");
LogPrintf(" %s\n", objToLoad.ToString());
}
return Ok;
}
void DumpMasternodePayments()
{
int64_t nStart = GetTimeMillis();
CMasternodePaymentDB paymentdb;
CMasternodePayments tempPayments;
LogPrintf("Verifying mnpayments.dat format...\n");
CMasternodePaymentDB::ReadResult readResult = paymentdb.Read(tempPayments, true);
// there was an error and it was not an error on file opening => do not proceed
if (readResult == CMasternodePaymentDB::FileError)
LogPrintf("Missing mnpayments file - mnpayments.dat, will try to recreate\n");
else if (readResult != CMasternodePaymentDB::Ok) {
LogPrintf("Error reading mnpayments.dat: ");
if (readResult == CMasternodePaymentDB::IncorrectFormat)
LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
else {
LogPrintf("file format is unknown or invalid, please fix it manually\n");
return;
}
}
LogPrintf("Writting info to mnpayments.dat...\n");
LogPrintf("Finished in %dms\n",GetTimeMillis() - nStart);
paymentdb.Write(masternodePayments);
}
bool IsBlockValueValid(const CBlock& block, CAmount nExpectedValue, CAmount nMinted)
{
CBlockIndex* pindexPrev = chainActive.Tip();
if (pindexPrev == NULL) return true;
int nHeight = 0;
if (pindexPrev->GetBlockHash() == block.hashPrevBlock) {
nHeight = pindexPrev->nHeight + 1;
} else { //out of order
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
nHeight = (*mi).second->nHeight + 1;
}
if (nHeight == 0) {
LogPrintf("IsBlockValueValid() : WARNING: Couldn't find previous block\n");
}
if (!masternodeSync.IsSynced()) {
if (nMinted > nExpectedValue) {
return false;
}
} else {
//are these blocks even enabled
return nMinted <= nExpectedValue;
}
return true;
}
bool IsBlockPayeeValid(const CBlock& block, int nBlockHeight)
{
if (!masternodeSync.IsSynced()) {
LogPrint("mnpayments", "Client not synced, skipping block payee checks\n");
return true;
}
const CTransaction& txNew = (nBlockHeight > Params().LAST_POW_BLOCK() ? block.vtx[1] : block.vtx[0]);
//check for masternode payee
if (masternodePayments.IsTransactionValid(txNew, nBlockHeight))
return true;
LogPrintf("Invalid mn payment detected %s\n", txNew.ToString().c_str());
if (IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT))
return false;
LogPrintf("Masternode payment enforcement is disabled, accepting block\n");
return true;
}
void FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake)
{
CBlockIndex* pindexPrev = chainActive.Tip();
if (!pindexPrev) return;
masternodePayments.FillBlockPayee(txNew, nFees, fProofOfStake);
}
std::string GetRequiredPaymentsString(int nBlockHeight)
{
return masternodePayments.GetRequiredPaymentsString(nBlockHeight);
}
void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int64_t nFees, bool fProofOfStake)
{
CBlockIndex* pindexPrev = chainActive.Tip();
if (!pindexPrev) return;
bool hasPayment = true;
CScript payee;
//spork
if (!masternodePayments.GetBlockPayee(pindexPrev->nHeight + 1, payee)) {
//no masternode detected
CMasternode* winningNode = mnodeman.GetCurrentMasterNode(1);
if (winningNode) {
payee = GetScriptForDestination(winningNode->pubKeyCollateralAddress.GetID());
} else {
LogPrintf("CreateNewBlock: Failed to detect masternode to pay\n");
hasPayment = false;
}
}
CAmount blockValue = GetBlockValue(pindexPrev->nHeight);
CAmount masternodePayment = GetMasternodePayment(pindexPrev->nHeight, blockValue);
if (!fProofOfStake && pindexPrev->nHeight < Params().LAST_POW_BLOCK()) {
txNew.vout[0].nValue = blockValue;
hasPayment = false; // no payments to mn in pow
}
if (hasPayment) {
if (fProofOfStake) {
/**For Proof Of Stake vout[0] must be null
* Stake reward can be split into many different outputs, so we must
* use vout.size() to align with several different cases.
* An additional output is appended as the masternode payment
*/
unsigned int i = txNew.vout.size();
txNew.vout.resize(i + 1);
txNew.vout[i].scriptPubKey = payee;
txNew.vout[i].nValue = masternodePayment;
//subtract mn payment from the stake reward
txNew.vout[i - 1].nValue -= masternodePayment;
} else {
txNew.vout.resize(2);
txNew.vout[1].scriptPubKey = payee;
txNew.vout[1].nValue = masternodePayment;
txNew.vout[0].nValue = blockValue - masternodePayment;
}
CTxDestination address1;
ExtractDestination(payee, address1);
CBitcoinAddress address2(address1);
LogPrintf("Masternode payment of %s to %s\n", FormatMoney(masternodePayment).c_str(), address2.ToString().c_str());
}
}
int CMasternodePayments::GetMinMasternodePaymentsProto()
{
if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES))
return ActiveProtocol(); // Allow only updated peers
else
return MIN_PEER_PROTO_VERSION_BEFORE_ENFORCEMENT; // Also allow old peers as long as they are allowed to run
}
void CMasternodePayments::ProcessMessageMasternodePayments(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if (!masternodeSync.IsBlockchainSynced()) return;
if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality
if (strCommand == "mnget") { //Masternode Payments Request Sync
if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality
int nCountNeeded;
vRecv >> nCountNeeded;
if (Params().NetworkID() == CBaseChainParams::MAIN) {
if (pfrom->HasFulfilledRequest("mnget")) {
LogPrintf("mnget - peer already asked me for the list\n");
Misbehaving(pfrom->GetId(), 20);
return;
}
}
pfrom->FulfilledRequest("mnget");
masternodePayments.Sync(pfrom, nCountNeeded);
LogPrint("mnpayments", "mnget - Sent Masternode winners to peer %i\n", pfrom->GetId());
} else if (strCommand == "mnw") { //Masternode Payments Declare Winner
//this is required in litemodef
CMasternodePaymentWinner winner;
vRecv >> winner;
if (pfrom->nVersion < ActiveProtocol()) return;
int nHeight;
{
TRY_LOCK(cs_main, locked);
if (!locked || chainActive.Tip() == NULL) return;
nHeight = chainActive.Tip()->nHeight;
}
if (masternodePayments.mapMasternodePayeeVotes.count(winner.GetHash())) {
LogPrint("mnpayments", "mnw - Already seen - %s bestHeight %d\n", winner.GetHash().ToString().c_str(), nHeight);
masternodeSync.AddedMasternodeWinner(winner.GetHash());
return;
}
int nFirstBlock = nHeight - (mnodeman.CountEnabled() * 1.25);
if (winner.nBlockHeight < nFirstBlock || winner.nBlockHeight > nHeight + 20) {
LogPrint("mnpayments", "mnw - winner out of range - FirstBlock %d Height %d bestHeight %d\n", nFirstBlock, winner.nBlockHeight, nHeight);
return;
}
std::string strError = "";
if (!winner.IsValid(pfrom, strError)) {
// if(strError != "") LogPrintf("mnw - invalid message - %s\n", strError);
return;
}
if (!masternodePayments.CanVote(winner.vinMasternode.prevout, winner.nBlockHeight)) {
// LogPrintf("mnw - masternode already voted - %s\n", winner.vinMasternode.prevout.ToStringShort());
return;
}
if (!winner.SignatureValid()) {
// LogPrintf("mnw - invalid signature\n");
if (masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20);
// it could just be a non-synced masternode
mnodeman.AskForMN(pfrom, winner.vinMasternode);
return;
}
CTxDestination address1;
ExtractDestination(winner.payee, address1);
CBitcoinAddress address2(address1);
// LogPrint("mnpayments", "mnw - winning vote - Addr %s Height %d bestHeight %d - %s\n", address2.ToString().c_str(), winner.nBlockHeight, nHeight, winner.vinMasternode.prevout.ToStringShort());
if (masternodePayments.AddWinningMasternode(winner)) {
winner.Relay();
masternodeSync.AddedMasternodeWinner(winner.GetHash());
}
}
}
bool CMasternodePaymentWinner::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode)
{
std::string errorMessage;
std::string strMasterNodeSignMessage;
std::string strMessage = vinMasternode.prevout.ToStringShort() +
boost::lexical_cast<std::string>(nBlockHeight) +
payee.ToString();
if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) {
LogPrintf("CMasternodePing::Sign() - Error: %s\n", errorMessage.c_str());
return false;
}
if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePing::Sign() - Error: %s\n", errorMessage.c_str());
return false;
}
return true;
}
bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee)
{
if (mapMasternodeBlocks.count(nBlockHeight)) {
return mapMasternodeBlocks[nBlockHeight].GetPayee(payee);
}
return false;
}
// Is this masternode scheduled to get paid soon?
// -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 winners
bool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
int nHeight;
{
TRY_LOCK(cs_main, locked);
if (!locked || chainActive.Tip() == NULL) return false;
nHeight = chainActive.Tip()->nHeight;
}
CScript mnpayee;
mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID());
CScript payee;
for (int64_t h = nHeight; h <= nHeight + 8; h++) {
if (h == nNotBlockHeight) continue;
if (mapMasternodeBlocks.count(h)) {
if (mapMasternodeBlocks[h].GetPayee(payee)) {
if (mnpayee == payee) {
return true;
}
}
}
}
return false;
}
bool CMasternodePayments::AddWinningMasternode(CMasternodePaymentWinner& winnerIn)
{
uint256 blockHash = 0;
if (!GetBlockHash(blockHash, winnerIn.nBlockHeight - 100)) {
return false;
}
{
LOCK2(cs_mapMasternodePayeeVotes, cs_mapMasternodeBlocks);
if (mapMasternodePayeeVotes.count(winnerIn.GetHash())) {
return false;
}
mapMasternodePayeeVotes[winnerIn.GetHash()] = winnerIn;
if (!mapMasternodeBlocks.count(winnerIn.nBlockHeight)) {
CMasternodeBlockPayees blockPayees(winnerIn.nBlockHeight);
mapMasternodeBlocks[winnerIn.nBlockHeight] = blockPayees;
}
}
mapMasternodeBlocks[winnerIn.nBlockHeight].AddPayee(winnerIn.payee, 1);
return true;
}
bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew)
{
LOCK(cs_vecPayments);
int nMaxSignatures = 0;
int nMasternode_Drift_Count = 0;
std::string strPayeesPossible = "";
CAmount nReward = GetBlockValue(nBlockHeight);
if (IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {
// Get a stable number of masternodes by ignoring newly activated (< 8000 sec old) masternodes
nMasternode_Drift_Count = mnodeman.stable_size() + Params().MasternodeCountDrift();
}
else {
//account for the fact that all peers do not see the same masternode count. A allowance of being off our masternode count is given
//we only need to look at an increased masternode count because as count increases, the reward decreases. This code only checks
//for mnPayment >= required, so it only makes sense to check the max node count allowed.
nMasternode_Drift_Count = mnodeman.size() + Params().MasternodeCountDrift();
}
CAmount requiredMasternodePayment = GetMasternodePayment(nBlockHeight, nReward, nMasternode_Drift_Count);
//require at least 6 signatures
BOOST_FOREACH (CMasternodePayee& payee, vecPayments)
if (payee.nVotes >= nMaxSignatures && payee.nVotes >= MNPAYMENTS_SIGNATURES_REQUIRED)
nMaxSignatures = payee.nVotes;
// if we don't have at least 6 signatures on a payee, approve whichever is the longest chain
if (nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true;
BOOST_FOREACH (CMasternodePayee& payee, vecPayments) {
bool found = false;
BOOST_FOREACH (CTxOut out, txNew.vout) {
if (payee.scriptPubKey == out.scriptPubKey) {
if(out.nValue >= requiredMasternodePayment)
found = true;
else
LogPrintf("Masternode payment is out of drift range. Paid=%s Min=%s\n", FormatMoney(out.nValue).c_str(), FormatMoney(requiredMasternodePayment).c_str());
}
}
if (payee.nVotes >= MNPAYMENTS_SIGNATURES_REQUIRED) {
if (found) return true;
CTxDestination address1;
ExtractDestination(payee.scriptPubKey, address1);
CBitcoinAddress address2(address1);
if (strPayeesPossible == "") {
strPayeesPossible += address2.ToString();
} else {
strPayeesPossible += "," + address2.ToString();
}
}
}
LogPrintf("CMasternodePayments::IsTransactionValid - Missing required payment of %s to %s\n", FormatMoney(requiredMasternodePayment).c_str(), strPayeesPossible.c_str());
return false;
}
std::string CMasternodeBlockPayees::GetRequiredPaymentsString()
{
LOCK(cs_vecPayments);
std::string ret = "Unknown";
BOOST_FOREACH (CMasternodePayee& payee, vecPayments) {
CTxDestination address1;
ExtractDestination(payee.scriptPubKey, address1);
CBitcoinAddress address2(address1);
if (ret != "Unknown") {
ret += ", " + address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.nVotes);
} else {
ret = address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.nVotes);
}
}
return ret;
}
std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if (mapMasternodeBlocks.count(nBlockHeight)) {
return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString();
}
return "Unknown";
}
bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if (mapMasternodeBlocks.count(nBlockHeight)) {
return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew);
}
return true;
}
void CMasternodePayments::CleanPaymentList()
{
LOCK2(cs_mapMasternodePayeeVotes, cs_mapMasternodeBlocks);
int nHeight;
{
TRY_LOCK(cs_main, locked);
if (!locked || chainActive.Tip() == NULL) return;
nHeight = chainActive.Tip()->nHeight;
}
//keep up to five cycles for historical sake
int nLimit = std::max(int(mnodeman.size() * 1.25), 1000);
std::map<uint256, CMasternodePaymentWinner>::iterator it = mapMasternodePayeeVotes.begin();
while (it != mapMasternodePayeeVotes.end()) {
CMasternodePaymentWinner winner = (*it).second;
if (nHeight - winner.nBlockHeight > nLimit) {
LogPrint("mnpayments", "CMasternodePayments::CleanPaymentList - Removing old Masternode payment - block %d\n", winner.nBlockHeight);
masternodeSync.mapSeenSyncMNW.erase((*it).first);
mapMasternodePayeeVotes.erase(it++);
mapMasternodeBlocks.erase(winner.nBlockHeight);
} else {
++it;
}
}
}
bool CMasternodePaymentWinner::IsValid(CNode* pnode, std::string& strError)
{
CMasternode* pmn = mnodeman.Find(vinMasternode);
if (!pmn) {
strError = strprintf("Unknown Masternode %s", vinMasternode.prevout.hash.ToString());
LogPrintf("CMasternodePaymentWinner::IsValid - %s\n", strError);
mnodeman.AskForMN(pnode, vinMasternode);
return false;
}
if (pmn->protocolVersion < ActiveProtocol()) {
strError = strprintf("Masternode protocol too old %d - req %d", pmn->protocolVersion, ActiveProtocol());
LogPrintf("CMasternodePaymentWinner::IsValid - %s\n", strError);
return false;
}
int n = mnodeman.GetMasternodeRank(vinMasternode, nBlockHeight - 100, ActiveProtocol());
if (n > MNPAYMENTS_SIGNATURES_TOTAL) {
//It's common to have masternodes mistakenly think they are in the top 10
// We don't want to print all of these messages, or punish them unless they're way off
if (n > MNPAYMENTS_SIGNATURES_TOTAL * 2) {
strError = strprintf("Masternode not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL * 2, n);
LogPrintf("CMasternodePaymentWinner::IsValid - %s\n", strError);
if (masternodeSync.IsSynced()) Misbehaving(pnode->GetId(), 20);
}
return false;
}
return true;
}
bool CMasternodePayments::ProcessBlock(int nBlockHeight)
{
if (!fMasterNode) return false;
//reference node - hybrid mode
int n = mnodeman.GetMasternodeRank(activeMasternode.vin, nBlockHeight - 100, ActiveProtocol());
if (n == -1) {
LogPrint("mnpayments", "CMasternodePayments::ProcessBlock - Unknown Masternode\n");
return false;
}
if (n > MNPAYMENTS_SIGNATURES_TOTAL) {
LogPrint("mnpayments", "CMasternodePayments::ProcessBlock - Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, n);
return false;
}
if (nBlockHeight <= nLastBlockHeight) return false;
CMasternodePaymentWinner newWinner(activeMasternode.vin);
LogPrintf("CMasternodePayments::ProcessBlock() Start nHeight %d - vin %s. \n", nBlockHeight, activeMasternode.vin.prevout.hash.ToString());
// pay to the oldest MN that still had no payment but its input is old enough and it was active long enough
int nCount = 0;
CMasternode* pmn = mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount);
if (pmn != NULL) {
LogPrintf("CMasternodePayments::ProcessBlock() Found by FindOldestNotInVec \n");
newWinner.nBlockHeight = nBlockHeight;
CScript payee = GetScriptForDestination(pmn->pubKeyCollateralAddress.GetID());
newWinner.AddPayee(payee);
CTxDestination address1;
ExtractDestination(payee, address1);
CBitcoinAddress address2(address1);
LogPrintf("CMasternodePayments::ProcessBlock() Winner payee %s nHeight %d. \n", address2.ToString().c_str(), newWinner.nBlockHeight);
} else {
LogPrintf("CMasternodePayments::ProcessBlock() Failed to find masternode to pay\n");
}
std::string errorMessage;
CPubKey pubKeyMasternode;
CKey keyMasternode;
if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) {
LogPrintf("CMasternodePayments::ProcessBlock() - Error upon calling SetKey: %s\n", errorMessage.c_str());
return false;
}
LogPrintf("CMasternodePayments::ProcessBlock() - Signing Winner\n");
if (newWinner.Sign(keyMasternode, pubKeyMasternode)) {
LogPrintf("CMasternodePayments::ProcessBlock() - AddWinningMasternode\n");
if (AddWinningMasternode(newWinner)) {
newWinner.Relay();
nLastBlockHeight = nBlockHeight;
return true;
}
}
return false;
}
void CMasternodePaymentWinner::Relay()
{
CInv inv(MSG_MASTERNODE_WINNER, GetHash());
RelayInv(inv);
}
bool CMasternodePaymentWinner::SignatureValid()
{
CMasternode* pmn = mnodeman.Find(vinMasternode);
if (pmn != NULL) {
std::string strMessage = vinMasternode.prevout.ToStringShort() +
boost::lexical_cast<std::string>(nBlockHeight) +
payee.ToString();
std::string errorMessage = "";
if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) {
return error("CMasternodePaymentWinner::SignatureValid() - Got bad Masternode address signature %s\n", vinMasternode.prevout.hash.ToString());
}
return true;
}
return false;
}
void CMasternodePayments::Sync(CNode* node, int nCountNeeded)
{
LOCK(cs_mapMasternodePayeeVotes);
int nHeight;
{
TRY_LOCK(cs_main, locked);
if (!locked || chainActive.Tip() == NULL) return;
nHeight = chainActive.Tip()->nHeight;
}
int nCount = (mnodeman.CountEnabled() * 1.25);
if (nCountNeeded > nCount) nCountNeeded = nCount;
int nInvCount = 0;
std::map<uint256, CMasternodePaymentWinner>::iterator it = mapMasternodePayeeVotes.begin();
while (it != mapMasternodePayeeVotes.end()) {
CMasternodePaymentWinner winner = (*it).second;
if (winner.nBlockHeight >= nHeight - nCountNeeded && winner.nBlockHeight <= nHeight + 20) {
node->PushInventory(CInv(MSG_MASTERNODE_WINNER, winner.GetHash()));
nInvCount++;
}
++it;
}
node->PushMessage("ssc", MASTERNODE_SYNC_MNW, nInvCount);
}
std::string CMasternodePayments::ToString() const
{
std::ostringstream info;
info << "Votes: " << (int)mapMasternodePayeeVotes.size() << ", Blocks: " << (int)mapMasternodeBlocks.size();
return info.str();
}
int CMasternodePayments::GetOldestBlock()
{
LOCK(cs_mapMasternodeBlocks);
int nOldestBlock = std::numeric_limits<int>::max();
std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin();
while (it != mapMasternodeBlocks.end()) {
if ((*it).first < nOldestBlock) {
nOldestBlock = (*it).first;
}
it++;
}
return nOldestBlock;
}
int CMasternodePayments::GetNewestBlock()
{
LOCK(cs_mapMasternodeBlocks);
int nNewestBlock = 0;
std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin();
while (it != mapMasternodeBlocks.end()) {
if ((*it).first > nNewestBlock) {
nNewestBlock = (*it).first;
}
it++;
}
return nNewestBlock;
}
|
/***************************************************************
leetcode-hard-135:Candy
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Input: [1,0,2]
Output: 5
Input: [1,2,2]
Output: 4
****************************************************************/
/*
分两边考虑:
1、拥有高rating的孩子比他的左边孩子多一块糖
2、拥有高rating的孩子比他的右边孩子多一块糖
ratings: 1 2 3 0 6 6 5 4
left2right: 1 2 3 1 2 1 1 1
right2left: 1 1 2 1 1 3 2 1
max: 1 2 3 1 2 3 2 1
sum: 15
*/
#include<vector>
using namespace std;
int candy(vector<int>& ratings) {
if (ratings.size()<=1) return ratings.size();
vector<int> candy(ratings.size(), 1);
for (int i=1;i<ratings.size();i++) {
if (ratings[i-1]<ratings[i]) {
candy[i] = candy[i-1] + 1;
}
}
int res = candy[ratings.size()-1];
for (int i=ratings.size()-2;i>=0;i--) {
if (ratings[i]>ratings[i+1]) {
if (candy[i]<candy[i+1]+1) {
candy[i] = candy[i+1] + 1;
}
}
res += candy[i];
}
return res;
}
|
#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
static const char UNUSED *startlife_strings[] = {
QT_TRANSLATE_NOOP("startlife-core", ""
"(1 = keep tx meta data e.g. account owner and payment request information, 2 "
"= drop tx meta data)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Allow JSON-RPC connections from specified source. Valid for <ip> are a "
"single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or "
"a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"),
QT_TRANSLATE_NOOP("startlife-core", ""
"An error occurred while setting up the RPC address %s port %u for listening: "
"%s"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Bind to given address and whitelist peers connecting to it. Use [host]:port "
"notation for IPv6"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Bind to given address to listen for JSON-RPC connections. Use [host]:port "
"notation for IPv6. This option can be specified multiple times (default: "
"bind to all interfaces)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Cannot obtain a lock on data directory %s. StartLife Core is probably already "
"running."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Change automatic finalized budget voting behavior. mode=auto: Vote for only "
"exact finalized budget match to my generated budget. (string, default: auto)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Continuously rate-limit free transactions to <n>*1000 bytes per minute "
"(default:%u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Create new files with system default permissions, instead of umask 077 (only "
"effective with disabled wallet functionality)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Delete all wallet transactions and only recover those parts of the "
"blockchain through -rescan on startup"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Disable all StartLife specific functionality (Masternodes, Obfuscation, SwiftTX, "
"Budgeting) (0-1, default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Distributed under the MIT software license, see the accompanying file "
"COPYING or <http://www.opensource.org/licenses/mit-license.php>."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Enable swifttx, show confirmations for locked transactions (bool, default: "
"%s)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Enable use of automated obfuscation for funds stored in this wallet (0-1, "
"default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Enter regression test mode, which uses a special chain in which blocks can "
"be solved instantly."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Error: Listening for incoming connections failed (listen returned error %s)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Error: Unsupported argument -socks found. Setting SOCKS version isn't "
"possible anymore, only SOCKS5 proxies are supported."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Execute command when a relevant alert is received or we see a really long "
"fork (%s in cmd is replaced by message)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Execute command when a wallet transaction changes (%s in cmd is replaced by "
"TxID)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Execute command when the best block changes (%s in cmd is replaced by block "
"hash)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Fees (in STLC/Kb) smaller than this are considered zero fee for relaying "
"(default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Fees (in STLC/Kb) smaller than this are considered zero fee for transaction "
"creation (default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Flush database activity from memory pool to disk log every <n> megabytes "
"(default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Found unconfirmed denominated outputs, will wait till they confirm to "
"continue."),
QT_TRANSLATE_NOOP("startlife-core", ""
"How thorough the block verification of -checkblocks is (0-4, default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"If paytxfee is not set, include enough fee so transactions begin "
"confirmation on average within n blocks (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"In this mode -genproclimit controls how many blocks are generated "
"immediately."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay "
"fee of %s to prevent stuck transactions)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Log transaction priority and fee per kB when mining blocks (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Maintain a full transaction index, used by the getrawtransaction rpc call "
"(default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Maximum size of data in data carrier transactions we relay and mine "
"(default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Maximum total fees to use in a single wallet transaction, setting too low "
"may abort large transactions (default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Number of seconds to keep misbehaving peers from reconnecting (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Obfuscation uses exact denominated amounts to send funds, you might simply "
"need to anonymize some more coins."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Output debugging information (default: %u, supplying <category> is optional)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Provide liquidity to Obfuscation by infrequently mixing coins on a continual "
"basis (0-100, default: %u, 1=very frequent, high fees, 100=very infrequent, "
"low fees)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Query for peer addresses via DNS lookup, if low on addresses (default: 1 "
"unless -connect)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Require high priority for relaying free or low-fee transactions (default:%u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Send trace/debug info to console instead of debug.log file (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Set the number of script verification threads (%u to %d, 0 = auto, <0 = "
"leave that many cores free, default: %d)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Set the number of threads for coin generation if enabled (-1 = all cores, "
"default: %d)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Show N confirmations for a successfully locked transaction (0-9999, default: "
"%u)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"SwiftTX requires inputs with at least 6 confirmations, you might need to "
"wait a few minutes and try again."),
QT_TRANSLATE_NOOP("startlife-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"mining or merchant applications"),
QT_TRANSLATE_NOOP("startlife-core", ""
"This product includes software developed by the OpenSSL Project for use in "
"the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software "
"written by Eric Young and UPnP software written by Thomas Bernard."),
QT_TRANSLATE_NOOP("startlife-core", ""
"To use startlifed, or the -server option to startlife-qt, you must set an rpcpassword "
"in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=startliferpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"StartLife Alert\" admin@foo.com\n"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Unable to bind to %s on this computer. StartLife Core is probably already running."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Unable to locate enough Obfuscation denominated funds for this transaction."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Unable to locate enough Obfuscation non-denominated funds for this "
"transaction that are not equal 10000 STLC."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Unable to locate enough funds for this transaction that are not equal 10000 "
"STLC."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: "
"%s)"),
QT_TRANSLATE_NOOP("startlife-core", ""
"Warning: -maxtxfee is set very high! Fees this large could be paid on a "
"single transaction."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong StartLife Core will not work properly."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Warning: The network does not appear to fully agree! Some miners appear to "
"be experiencing issues."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Warning: We do not appear to fully agree with our peers! You may need to "
"upgrade, or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as "
"wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect "
"you should restore from a backup."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Whitelist peers connecting from the given netmask or IP address. Can be "
"specified multiple times."),
QT_TRANSLATE_NOOP("startlife-core", ""
"Whitelisted peers cannot be DoS banned and their transactions are always "
"relayed, even if they are already in the mempool, useful e.g. for a gateway"),
QT_TRANSLATE_NOOP("startlife-core", ""
"You must specify a masternodeprivkey in the configuration. Please see "
"documentation for help."),
QT_TRANSLATE_NOOP("startlife-core", "(50020 could be used only on mainnet)"),
QT_TRANSLATE_NOOP("startlife-core", "(default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", "(default: 1)"),
QT_TRANSLATE_NOOP("startlife-core", "(must be 50020 for mainnet)"),
QT_TRANSLATE_NOOP("startlife-core", "<category> can be:\n"),
QT_TRANSLATE_NOOP("startlife-core", "Accept command line and JSON-RPC commands"),
QT_TRANSLATE_NOOP("startlife-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"),
QT_TRANSLATE_NOOP("startlife-core", "Accept public REST requests (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Acceptable ciphers (default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Add a node to connect to and attempt to keep the connection open"),
QT_TRANSLATE_NOOP("startlife-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("startlife-core", "Already have that input."),
QT_TRANSLATE_NOOP("startlife-core", "Always query for peer addresses via DNS lookup (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("startlife-core", "Block creation options:"),
QT_TRANSLATE_NOOP("startlife-core", "Can't denominate: no compatible inputs left."),
QT_TRANSLATE_NOOP("startlife-core", "Can't find random Masternode."),
QT_TRANSLATE_NOOP("startlife-core", "Can't mix while sync in progress."),
QT_TRANSLATE_NOOP("startlife-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("startlife-core", "Cannot resolve -bind address: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Cannot resolve -externalip address: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Cannot resolve -whitebind address: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Cannot write default address"),
QT_TRANSLATE_NOOP("startlife-core", "Collateral not valid."),
QT_TRANSLATE_NOOP("startlife-core", "Connect only to the specified node(s)"),
QT_TRANSLATE_NOOP("startlife-core", "Connect through SOCKS5 proxy"),
QT_TRANSLATE_NOOP("startlife-core", "Connect to a node to retrieve peer addresses, and disconnect"),
QT_TRANSLATE_NOOP("startlife-core", "Connection options:"),
QT_TRANSLATE_NOOP("startlife-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"),
QT_TRANSLATE_NOOP("startlife-core", "Copyright (C) 2014-%i The Dash Core Developers"),
QT_TRANSLATE_NOOP("startlife-core", "Copyright (C) 2015-%i The StartLife Core Developers"),
QT_TRANSLATE_NOOP("startlife-core", "Corrupted block database detected"),
QT_TRANSLATE_NOOP("startlife-core", "Could not parse -rpcbind value %s as network address"),
QT_TRANSLATE_NOOP("startlife-core", "Could not parse masternode.conf"),
QT_TRANSLATE_NOOP("startlife-core", "Debugging/Testing options:"),
QT_TRANSLATE_NOOP("startlife-core", "Disable safemode, override a real safe mode event (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Discover own IP address (default: 1 when listening and no -externalip)"),
QT_TRANSLATE_NOOP("startlife-core", "Do not load the wallet and disable wallet RPC calls"),
QT_TRANSLATE_NOOP("startlife-core", "Do you want to rebuild the block database now?"),
QT_TRANSLATE_NOOP("startlife-core", "Done loading"),
QT_TRANSLATE_NOOP("startlife-core", "Enable the client to act as a masternode (0-1, default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Entries are full."),
QT_TRANSLATE_NOOP("startlife-core", "Error connecting to Masternode."),
QT_TRANSLATE_NOOP("startlife-core", "Error initializing block database"),
QT_TRANSLATE_NOOP("startlife-core", "Error initializing wallet database environment %s!"),
QT_TRANSLATE_NOOP("startlife-core", "Error loading block database"),
QT_TRANSLATE_NOOP("startlife-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("startlife-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("startlife-core", "Error loading wallet.dat: Wallet requires newer version of StartLife Core"),
QT_TRANSLATE_NOOP("startlife-core", "Error opening block database"),
QT_TRANSLATE_NOOP("startlife-core", "Error reading from database, shutting down."),
QT_TRANSLATE_NOOP("startlife-core", "Error recovering public key."),
QT_TRANSLATE_NOOP("startlife-core", "Error"),
QT_TRANSLATE_NOOP("startlife-core", "Error: A fatal internal error occured, see debug.log for details"),
QT_TRANSLATE_NOOP("startlife-core", "Error: Can't select current denominated inputs"),
QT_TRANSLATE_NOOP("startlife-core", "Error: Disk space is low!"),
QT_TRANSLATE_NOOP("startlife-core", "Error: Unsupported argument -tor found, use -onion."),
QT_TRANSLATE_NOOP("startlife-core", "Error: Wallet locked, unable to create transaction!"),
QT_TRANSLATE_NOOP("startlife-core", "Error: You already have pending entries in the Obfuscation pool"),
QT_TRANSLATE_NOOP("startlife-core", "Failed to listen on any port. Use -listen=0 if you want this."),
QT_TRANSLATE_NOOP("startlife-core", "Failed to read block"),
QT_TRANSLATE_NOOP("startlife-core", "Fee (in STLC/kB) to add to transactions you send (default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Finalizing transaction."),
QT_TRANSLATE_NOOP("startlife-core", "Force safe mode (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Found enough users, signing ( waiting %s )"),
QT_TRANSLATE_NOOP("startlife-core", "Found enough users, signing ..."),
QT_TRANSLATE_NOOP("startlife-core", "Generate coins (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "How many blocks to check at startup (default: %u, 0 = all)"),
QT_TRANSLATE_NOOP("startlife-core", "If <category> is not supplied, output all debugging information."),
QT_TRANSLATE_NOOP("startlife-core", "Importing..."),
QT_TRANSLATE_NOOP("startlife-core", "Imports blocks from external blk000??.dat file"),
QT_TRANSLATE_NOOP("startlife-core", "Include IP addresses in debug output (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Incompatible mode."),
QT_TRANSLATE_NOOP("startlife-core", "Incompatible version."),
QT_TRANSLATE_NOOP("startlife-core", "Incorrect or no genesis block found. Wrong datadir for network?"),
QT_TRANSLATE_NOOP("startlife-core", "Information"),
QT_TRANSLATE_NOOP("startlife-core", "Initialization sanity check failed. StartLife Core is shutting down."),
QT_TRANSLATE_NOOP("startlife-core", "Input is not valid."),
QT_TRANSLATE_NOOP("startlife-core", "Insufficient funds."),
QT_TRANSLATE_NOOP("startlife-core", "Invalid -onion address: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid -proxy address: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid amount for -maxtxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid amount for -mintxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid amount for -paytxfee=<amount>: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid amount for -reservebalance=<amount>"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid masternodeprivkey. Please see documenation."),
QT_TRANSLATE_NOOP("startlife-core", "Invalid netmask specified in -whitelist: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid port detected in masternode.conf"),
QT_TRANSLATE_NOOP("startlife-core", "Invalid private key."),
QT_TRANSLATE_NOOP("startlife-core", "Invalid script detected."),
QT_TRANSLATE_NOOP("startlife-core", "Keep N STLC anonymized (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Last Obfuscation was too recent."),
QT_TRANSLATE_NOOP("startlife-core", "Last successful Obfuscation action was too recent."),
QT_TRANSLATE_NOOP("startlife-core", "Limit size of signature cache to <n> entries (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Line: %d"),
QT_TRANSLATE_NOOP("startlife-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Listen for connections on <port> (default: %u or testnet: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Loading addresses..."),
QT_TRANSLATE_NOOP("startlife-core", "Loading block index..."),
QT_TRANSLATE_NOOP("startlife-core", "Loading budget cache..."),
QT_TRANSLATE_NOOP("startlife-core", "Loading masternode cache..."),
QT_TRANSLATE_NOOP("startlife-core", "Loading masternode payment cache..."),
QT_TRANSLATE_NOOP("startlife-core", "Loading wallet... (%3.2f %%)"),
QT_TRANSLATE_NOOP("startlife-core", "Loading wallet..."),
QT_TRANSLATE_NOOP("startlife-core", "Lock is already in place."),
QT_TRANSLATE_NOOP("startlife-core", "Lock masternodes from masternode configuration file (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Maintain at most <n> connections to peers (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Masternode options:"),
QT_TRANSLATE_NOOP("startlife-core", "Masternode queue is full."),
QT_TRANSLATE_NOOP("startlife-core", "Masternode:"),
QT_TRANSLATE_NOOP("startlife-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Missing input transaction information."),
QT_TRANSLATE_NOOP("startlife-core", "Mixing in progress..."),
QT_TRANSLATE_NOOP("startlife-core", "Need to specify a port with -whitebind: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "No Masternodes detected."),
QT_TRANSLATE_NOOP("startlife-core", "No compatible Masternode found."),
QT_TRANSLATE_NOOP("startlife-core", "No funds detected in need of denominating."),
QT_TRANSLATE_NOOP("startlife-core", "No matching denominations found for mixing."),
QT_TRANSLATE_NOOP("startlife-core", "Node relay options:"),
QT_TRANSLATE_NOOP("startlife-core", "Non-standard public key detected."),
QT_TRANSLATE_NOOP("startlife-core", "Not compatible with existing transactions."),
QT_TRANSLATE_NOOP("startlife-core", "Not enough file descriptors available."),
QT_TRANSLATE_NOOP("startlife-core", "Not in the Masternode list."),
QT_TRANSLATE_NOOP("startlife-core", "Number of automatic wallet backups (default: 10)"),
QT_TRANSLATE_NOOP("startlife-core", "Obfuscation is idle."),
QT_TRANSLATE_NOOP("startlife-core", "Obfuscation options:"),
QT_TRANSLATE_NOOP("startlife-core", "Obfuscation request complete:"),
QT_TRANSLATE_NOOP("startlife-core", "Obfuscation request incomplete:"),
QT_TRANSLATE_NOOP("startlife-core", "Only accept block chain matching built-in checkpoints (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"),
QT_TRANSLATE_NOOP("startlife-core", "Options:"),
QT_TRANSLATE_NOOP("startlife-core", "Password for JSON-RPC connections"),
QT_TRANSLATE_NOOP("startlife-core", "Prepend debug output with timestamp (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("startlife-core", "RPC server options:"),
QT_TRANSLATE_NOOP("startlife-core", "RPC support for HTTP persistent connections (default: %d)"),
QT_TRANSLATE_NOOP("startlife-core", "Randomly drop 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("startlife-core", "Randomly fuzz 1 of every <n> network messages"),
QT_TRANSLATE_NOOP("startlife-core", "Rebuild block chain index from current blk000??.dat files"),
QT_TRANSLATE_NOOP("startlife-core", "Receive and display P2P network alerts (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Relay and mine data carrier transactions (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Relay non-P2SH multisig (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("startlife-core", "Rescanning..."),
QT_TRANSLATE_NOOP("startlife-core", "Run a thread to flush wallet periodically (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("startlife-core", "Send transactions as zero-fee transactions if possible (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Server certificate file (default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Server private key (default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Session not complete!"),
QT_TRANSLATE_NOOP("startlife-core", "Session timed out."),
QT_TRANSLATE_NOOP("startlife-core", "Set database cache size in megabytes (%d to %d, default: %d)"),
QT_TRANSLATE_NOOP("startlife-core", "Set external address:port to get to this masternode (example: %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Set key pool size to <n> (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Set maximum block size in bytes (default: %d)"),
QT_TRANSLATE_NOOP("startlife-core", "Set minimum block size in bytes (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Set the masternode private key"),
QT_TRANSLATE_NOOP("startlife-core", "Set the number of threads to service RPC calls (default: %d)"),
QT_TRANSLATE_NOOP("startlife-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Show all debugging options (usage: --help -help-debug)"),
QT_TRANSLATE_NOOP("startlife-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("startlife-core", "Signing failed."),
QT_TRANSLATE_NOOP("startlife-core", "Signing timed out."),
QT_TRANSLATE_NOOP("startlife-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("startlife-core", "Specify configuration file (default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"),
QT_TRANSLATE_NOOP("startlife-core", "Specify data directory"),
QT_TRANSLATE_NOOP("startlife-core", "Specify masternode configuration file (default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Specify pid file (default: %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Specify wallet file (within data directory)"),
QT_TRANSLATE_NOOP("startlife-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("startlife-core", "Spend unconfirmed change when sending transactions (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Stop running after importing blocks from disk (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Submitted following entries to masternode: %u / %d"),
QT_TRANSLATE_NOOP("startlife-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"),
QT_TRANSLATE_NOOP("startlife-core", "Submitted to masternode, waiting in queue %s"),
QT_TRANSLATE_NOOP("startlife-core", "SwiftTX options:"),
QT_TRANSLATE_NOOP("startlife-core", "Synchronization failed"),
QT_TRANSLATE_NOOP("startlife-core", "Synchronization finished"),
QT_TRANSLATE_NOOP("startlife-core", "Synchronization pending..."),
QT_TRANSLATE_NOOP("startlife-core", "Synchronizing budgets..."),
QT_TRANSLATE_NOOP("startlife-core", "Synchronizing masternode winners..."),
QT_TRANSLATE_NOOP("startlife-core", "Synchronizing masternodes..."),
QT_TRANSLATE_NOOP("startlife-core", "Synchronizing sporks..."),
QT_TRANSLATE_NOOP("startlife-core", "This help message"),
QT_TRANSLATE_NOOP("startlife-core", "This is experimental software."),
QT_TRANSLATE_NOOP("startlife-core", "This is intended for regression testing tools and app development."),
QT_TRANSLATE_NOOP("startlife-core", "This is not a Masternode."),
QT_TRANSLATE_NOOP("startlife-core", "Threshold for disconnecting misbehaving peers (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Transaction amount too small"),
QT_TRANSLATE_NOOP("startlife-core", "Transaction amounts must be positive"),
QT_TRANSLATE_NOOP("startlife-core", "Transaction created successfully."),
QT_TRANSLATE_NOOP("startlife-core", "Transaction fees are too high."),
QT_TRANSLATE_NOOP("startlife-core", "Transaction not valid."),
QT_TRANSLATE_NOOP("startlife-core", "Transaction too large for fee policy"),
QT_TRANSLATE_NOOP("startlife-core", "Transaction too large"),
QT_TRANSLATE_NOOP("startlife-core", "Transmitting final transaction."),
QT_TRANSLATE_NOOP("startlife-core", "Unable to bind to %s on this computer (bind returned error %s)"),
QT_TRANSLATE_NOOP("startlife-core", "Unable to sign spork message, wrong key?"),
QT_TRANSLATE_NOOP("startlife-core", "Unknown network specified in -onlynet: '%s'"),
QT_TRANSLATE_NOOP("startlife-core", "Unknown state: id = %u"),
QT_TRANSLATE_NOOP("startlife-core", "Upgrade wallet to latest format"),
QT_TRANSLATE_NOOP("startlife-core", "Use N separate masternodes to anonymize funds (2-8, default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Use OpenSSL (https) for JSON-RPC connections"),
QT_TRANSLATE_NOOP("startlife-core", "Use UPnP to map the listening port (default: %u)"),
QT_TRANSLATE_NOOP("startlife-core", "Use UPnP to map the listening port (default: 1 when listening)"),
QT_TRANSLATE_NOOP("startlife-core", "Use the test network"),
QT_TRANSLATE_NOOP("startlife-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("startlife-core", "Value more than Obfuscation pool maximum allows."),
QT_TRANSLATE_NOOP("startlife-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("startlife-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("startlife-core", "Wallet %s resides outside data directory %s"),
QT_TRANSLATE_NOOP("startlife-core", "Wallet is locked."),
QT_TRANSLATE_NOOP("startlife-core", "Wallet needed to be rewritten: restart StartLife Core to complete"),
QT_TRANSLATE_NOOP("startlife-core", "Wallet options:"),
QT_TRANSLATE_NOOP("startlife-core", "Wallet window title"),
QT_TRANSLATE_NOOP("startlife-core", "Warning"),
QT_TRANSLATE_NOOP("startlife-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("startlife-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."),
QT_TRANSLATE_NOOP("startlife-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."),
QT_TRANSLATE_NOOP("startlife-core", "Will retry..."),
QT_TRANSLATE_NOOP("startlife-core", "You need to rebuild the database using -reindex to change -txindex"),
QT_TRANSLATE_NOOP("startlife-core", "Your entries added successfully."),
QT_TRANSLATE_NOOP("startlife-core", "Your transaction was accepted into the pool!"),
QT_TRANSLATE_NOOP("startlife-core", "Zapping all transactions from wallet..."),
QT_TRANSLATE_NOOP("startlife-core", "on startup"),
QT_TRANSLATE_NOOP("startlife-core", "wallet.dat corrupt, salvage failed"),
};
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/Portability.h>
#if FOLLY_HAS_COROUTINES
#include <folly/executors/InlineExecutor.h>
#include <folly/executors/ManualExecutor.h>
#include <folly/experimental/coro/Baton.h>
#include <folly/experimental/coro/BlockingWait.h>
#include <folly/experimental/coro/Invoke.h>
#include <folly/experimental/coro/Mutex.h>
#include <folly/experimental/coro/SharedMutex.h>
#include <folly/experimental/coro/Task.h>
#include <folly/experimental/coro/detail/InlineTask.h>
#include <folly/futures/Future.h>
#include <folly/portability/GTest.h>
#include <type_traits>
using namespace folly;
static_assert(
std::is_same<
folly::coro::semi_await_result_t<folly::coro::Task<void>>,
void>::value,
"");
static_assert(
std::is_same<
folly::coro::semi_await_result_t<folly::coro::Task<int>>,
int>::value,
"");
static_assert(
std::is_same<
folly::coro::semi_await_result_t<folly::coro::detail::InlineTask<void>>,
void>::value,
"");
static_assert(
std::is_same<
folly::coro::semi_await_result_t<folly::coro::detail::InlineTask<int>>,
int>::value,
"");
static_assert(
std::is_same<folly::coro::semi_await_result_t<folly::coro::Baton&>, void>::
value,
"");
static_assert(
std::is_same<
folly::coro::semi_await_result_t<decltype(
std::declval<folly::coro::SharedMutex&>().co_scoped_lock_shared())>,
folly::coro::SharedLock<folly::coro::SharedMutex>>::value,
"");
namespace {
const RequestToken testToken1("corotest1");
const RequestToken testToken2("corotest2");
class TestRequestData : public RequestData {
public:
explicit TestRequestData(std::string key) noexcept : key_(std::move(key)) {}
bool hasCallback() override { return false; }
const std::string& key() const noexcept { return key_; }
private:
std::string key_;
};
} // namespace
static coro::Task<void> childRequest(coro::Mutex& m, coro::Baton& b) {
ShallowCopyRequestContextScopeGuard requestScope;
auto* parentContext = dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData(testToken1));
EXPECT_TRUE(parentContext != nullptr);
auto childKey = parentContext->key() + ".child";
RequestContext::get()->setContextData(
testToken2, std::make_unique<TestRequestData>(childKey));
auto* childContext = dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData(testToken2));
CHECK(childContext != nullptr);
{
auto lock = co_await m.co_scoped_lock();
CHECK_EQ(
parentContext,
dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData(testToken1)));
CHECK_EQ(
childContext,
dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData(testToken2)));
co_await b;
CHECK_EQ(
parentContext,
dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData(testToken1)));
CHECK_EQ(
childContext,
dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData(testToken2)));
}
CHECK_EQ(
parentContext,
dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData(testToken1)));
CHECK_EQ(
childContext,
dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData(testToken2)));
}
static coro::Task<void> parentRequest(int id) {
ShallowCopyRequestContextScopeGuard requestScope;
// Should have captured the value at the time the coroutine was co_awaited
// rather than at the time the coroutine was called.
auto* globalData = dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData("global"));
CHECK(globalData != nullptr);
CHECK_EQ("other value", globalData->key());
std::string key = folly::to<std::string>("request", id);
RequestContext::get()->setContextData(
testToken1, std::make_unique<TestRequestData>(key));
auto* contextData = RequestContext::get()->getContextData(testToken1);
CHECK(contextData != nullptr);
coro::Mutex mutex;
coro::Baton baton1;
coro::Baton baton2;
auto fut1 = childRequest(mutex, baton1)
.scheduleOn(co_await coro::co_current_executor)
.start();
auto fut2 = childRequest(mutex, baton1)
.scheduleOn(co_await coro::co_current_executor)
.start();
CHECK_EQ(contextData, RequestContext::get()->getContextData(testToken1));
baton1.post();
baton2.post();
(void)co_await std::move(fut1);
CHECK_EQ(contextData, RequestContext::get()->getContextData(testToken1));
// Check that context from child operation doesn't leak into this coroutine.
CHECK(RequestContext::get()->getContextData(testToken2) == nullptr);
(void)co_await std::move(fut2);
// Check that context from child operation doesn't leak into this coroutine.
CHECK(RequestContext::get()->getContextData(testToken2) == nullptr);
}
class TaskTest : public testing::Test {};
TEST_F(TaskTest, RequestContextIsPreservedAcrossSuspendResume) {
ManualExecutor executor;
RequestContextScopeGuard requestScope;
RequestContext::get()->setContextData(
"global", std::make_unique<TestRequestData>("global value"));
// Context should be captured at coroutine co_await time and not at
// call time.
auto task1 = parentRequest(1).scheduleOn(&executor);
auto task2 = parentRequest(2).scheduleOn(&executor);
{
RequestContextScopeGuard nestedRequestScope;
RequestContext::get()->setContextData(
"global", std::make_unique<TestRequestData>("other value"));
// Start execution of the tasks.
auto fut1 = std::move(task1).start();
auto fut2 = std::move(task2).start();
// Check that the contexts set by starting the tasks don't bleed out
// to the caller.
CHECK(RequestContext::get()->getContextData(testToken1) == nullptr);
CHECK(RequestContext::get()->getContextData(testToken2) == nullptr);
CHECK_EQ(
"other value",
dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData("global"))
->key());
executor.drain();
CHECK(fut1.isReady());
CHECK(fut2.isReady());
// Check that the contexts set by the coroutines executing on the executor
// do not leak out to the caller.
CHECK(RequestContext::get()->getContextData(testToken1) == nullptr);
CHECK(RequestContext::get()->getContextData(testToken2) == nullptr);
CHECK_EQ(
"other value",
dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData("global"))
->key());
}
}
TEST_F(TaskTest, ContextPreservedAcrossMutexLock) {
folly::coro::Mutex mutex;
auto handleRequest =
[&](folly::coro::Baton& event) -> folly::coro::Task<void> {
RequestContextScopeGuard requestScope;
RequestData* contextDataPtr = nullptr;
{
auto contextData = std::make_unique<TestRequestData>("some value");
contextDataPtr = contextData.get();
RequestContext::get()->setContextData(
"mutex_test", std::move(contextData));
}
auto lock = co_await mutex.co_scoped_lock();
// Check that the request context was preserved across mutex lock
// acquisition.
CHECK_EQ(
RequestContext::get()->getContextData("mutex_test"), contextDataPtr);
co_await event;
// Check that request context was preserved across baton wait.
CHECK_EQ(
RequestContext::get()->getContextData("mutex_test"), contextDataPtr);
};
folly::ManualExecutor manualExecutor;
folly::coro::Baton event1;
folly::coro::Baton event2;
auto t1 = handleRequest(event1).scheduleOn(&manualExecutor).start();
auto t2 = handleRequest(event2).scheduleOn(&manualExecutor).start();
manualExecutor.drain();
event1.post();
manualExecutor.drain();
event2.post();
manualExecutor.drain();
EXPECT_TRUE(t1.isReady());
EXPECT_TRUE(t2.isReady());
EXPECT_FALSE(t1.hasException());
EXPECT_FALSE(t2.hasException());
}
TEST_F(TaskTest, RequestContextSideEffectsArePreserved) {
auto f =
[&](folly::coro::Baton& baton) -> folly::coro::detail::InlineTask<void> {
RequestContext::create();
RequestContext::get()->setContextData(
testToken1, std::make_unique<TestRequestData>("test"));
EXPECT_NE(RequestContext::get()->getContextData(testToken1), nullptr);
// HACK: Need to use co_viaIfAsync() to ensure request context is preserved
// across suspend-point.
co_await folly::coro::co_viaIfAsync(
&folly::InlineExecutor::instance(), baton);
EXPECT_NE(RequestContext::get()->getContextData(testToken1), nullptr);
co_return;
};
auto g = [&](folly::coro::Baton& baton) -> folly::coro::Task<void> {
EXPECT_EQ(RequestContext::get()->getContextData(testToken1), nullptr);
co_await f(baton);
EXPECT_NE(RequestContext::get()->getContextData(testToken1), nullptr);
EXPECT_EQ(
dynamic_cast<TestRequestData*>(
RequestContext::get()->getContextData(testToken1))
->key(),
"test");
};
folly::ManualExecutor executor;
folly::coro::Baton baton;
auto t = g(baton).scheduleOn(&executor).start();
executor.drain();
baton.post();
executor.drain();
EXPECT_TRUE(t.isReady());
EXPECT_FALSE(t.hasException());
}
TEST_F(TaskTest, FutureTailCall) {
EXPECT_EQ(
42,
folly::coro::blockingWait(
folly::coro::co_invoke([&]() -> folly::coro::Task<int> {
co_return co_await folly::makeSemiFuture().deferValue(
[](auto) { return folly::makeSemiFuture(42); });
})));
}
TEST_F(TaskTest, FutureRoundtrip) {
folly::coro::blockingWait([]() -> folly::coro::Task<void> {
co_yield folly::coro::co_result(co_await folly::coro::co_awaitTry(
[]() -> folly::coro::Task<void> { co_return; }().semi()));
}());
EXPECT_THROW(
folly::coro::blockingWait([]() -> folly::coro::Task<void> {
co_yield folly::coro::co_result(co_await folly::coro::co_awaitTry(
[]() -> folly::coro::Task<void> {
co_yield folly::coro::co_error(std::runtime_error(""));
}()
.semi()));
}()),
std::runtime_error);
}
// NOTE: This function is unused.
// We just want to make sure this compiles without errors or warnings.
folly::coro::Task<void>
checkAwaitingFutureOfUnitDoesntWarnAboutDiscardedResult() {
co_await folly::makeSemiFuture();
using namespace std::literals::chrono_literals;
co_await folly::futures::sleep(1ms);
}
folly::coro::Task<int&> returnIntRef(int& value) {
co_return value;
}
TEST_F(TaskTest, TaskOfLvalueReference) {
int value = 123;
auto&& result = folly::coro::blockingWait(returnIntRef(value));
static_assert(std::is_same_v<decltype(result), int&>);
CHECK_EQ(&value, &result);
}
TEST_F(TaskTest, TaskOfLvalueReferenceAsTry) {
folly::coro::blockingWait([]() -> folly::coro::Task<void> {
int value = 123;
auto&& result = co_await co_awaitTry(returnIntRef(value));
CHECK(result.hasValue());
CHECK_EQ(&value, &result.value().get());
int& valueRef = co_await returnIntRef(value);
CHECK_EQ(&value, &valueRef);
}());
}
TEST_F(TaskTest, CancellationPropagation) {
folly::coro::blockingWait([]() -> folly::coro::Task<void> {
auto token = co_await folly::coro::co_current_cancellation_token;
CHECK(!token.canBeCancelled());
folly::CancellationSource cancelSource;
co_await folly::coro::co_withCancellation(
cancelSource.getToken(), [&]() -> folly::coro::Task<void> {
auto token2 = co_await folly::coro::co_current_cancellation_token;
CHECK(token2.canBeCancelled());
CHECK(!token2.isCancellationRequested());
// The cancellation token should implicitly propagate into the
//
co_await[&]()->folly::coro::Task<void> {
auto token3 = co_await folly::coro::co_current_cancellation_token;
CHECK(token3 == token2);
cancelSource.requestCancellation();
CHECK(token3.isCancellationRequested());
}
();
CHECK(token2.isCancellationRequested());
}());
}());
}
TEST_F(TaskTest, CancellationPropagatesThroughCoAwaitTry) {
folly::CancellationSource source;
folly::Try<int> result =
folly::coro::blockingWait(folly::coro::co_withCancellation(
source.getToken(),
folly::coro::co_awaitTry([&]() -> folly::coro::Task<int> {
auto cancelToken =
co_await folly::coro::co_current_cancellation_token;
EXPECT_TRUE(cancelToken == source.getToken());
co_return 42;
}())));
EXPECT_EQ(42, result.value());
}
TEST_F(TaskTest, StartInlineUnsafe) {
folly::coro::blockingWait([]() -> folly::coro::Task<void> {
auto executor = co_await folly::coro::co_current_executor;
bool hasStarted = false;
bool hasFinished = false;
auto makeTask = [&]() -> folly::coro::Task<void> {
hasStarted = true;
co_await folly::coro::co_reschedule_on_current_executor;
hasFinished = true;
};
auto sf = makeTask().scheduleOn(executor).startInlineUnsafe();
// Check that the task started inline on the current thread.
// It should not yet have completed, however, since the rest
// of the coroutine needs this coroutine to suspend so the
// executor can schedule the rest of it.
CHECK(hasStarted);
CHECK(!hasFinished);
co_await std::move(sf);
CHECK(hasFinished);
}());
}
TEST_F(TaskTest, YieldTry) {
folly::coro::blockingWait([]() -> folly::coro::Task<void> {
auto innerTaskVoid = []() -> folly::coro::Task<void> {
co_yield folly::coro::co_error(std::runtime_error(""));
}();
auto retVoid = co_await co_awaitTry([&]() -> folly::coro::Task<void> {
co_yield folly::coro::co_result(
co_await co_awaitTry(std::move(innerTaskVoid)));
}());
EXPECT_TRUE(retVoid.hasException());
innerTaskVoid = []() -> folly::coro::Task<void> { co_return; }();
retVoid = co_await co_awaitTry([&]() -> folly::coro::Task<void> {
co_yield folly::coro::co_result(
co_await co_awaitTry(std::move(innerTaskVoid)));
}());
EXPECT_FALSE(retVoid.hasException());
auto innerTaskInt = []() -> folly::coro::Task<int> {
co_yield folly::coro::co_error(std::runtime_error(""));
}();
auto retInt = co_await co_awaitTry([&]() -> folly::coro::Task<int> {
co_yield folly::coro::co_result(
co_await co_awaitTry(std::move(innerTaskInt)));
}());
EXPECT_TRUE(retInt.hasException());
innerTaskInt = []() -> folly::coro::Task<int> { co_return 0; }();
retInt = co_await co_awaitTry([&]() -> folly::coro::Task<int> {
co_yield folly::coro::co_result(
co_await co_awaitTry(std::move(innerTaskInt)));
}());
EXPECT_TRUE(retInt.hasValue());
}());
}
TEST_F(TaskTest, MakeTask) {
folly::coro::blockingWait([]() -> folly::coro::Task<void> {
auto ret = co_await folly::coro::makeTask(42);
EXPECT_EQ(ret, 42);
co_await folly::coro::makeTask();
co_await folly::coro::makeTask(folly::unit);
auto err = co_await co_awaitTry(folly::coro::makeErrorTask<int>(
folly::make_exception_wrapper<std::runtime_error>("")));
EXPECT_TRUE(err.hasException());
err = co_await co_awaitTry(folly::coro::makeResultTask(folly::Try<int>(
folly::make_exception_wrapper<std::runtime_error>(""))));
EXPECT_TRUE(err.hasException());
auto try1 = co_await co_awaitTry(
folly::coro::makeResultTask(folly::Try<folly::Unit>(
folly::make_exception_wrapper<std::runtime_error>(""))));
EXPECT_TRUE(try1.hasException());
try1 = co_await co_awaitTry(
folly::coro::makeResultTask(folly::Try<folly::Unit>(folly::unit)));
EXPECT_TRUE(try1.hasValue());
// test move happens immediately (i.e. no dangling reference)
struct {
int i{0};
} s;
auto t = folly::coro::makeTask(std::move(s));
s.i = 1;
auto s2 = co_await std::move(t);
EXPECT_EQ(s2.i, 0);
}());
}
TEST_F(TaskTest, CoAwaitTryWithScheduleOn) {
folly::coro::blockingWait([]() -> folly::coro::Task<void> {
auto t = []() -> folly::coro::Task<int> { co_return 42; }();
folly::Try<int> result = co_await folly::coro::co_awaitTry(
std::move(t).scheduleOn(folly::getGlobalCPUExecutor()));
EXPECT_EQ(42, result.value());
}());
}
TEST_F(TaskTest, CoAwaitTryWithScheduleOnAndCancellation) {
folly::coro::blockingWait([]() -> folly::coro::Task<void> {
folly::CancellationSource cancelSrc;
auto makeTask = [&]() -> folly::coro::Task<int> {
auto ct = co_await folly::coro::co_current_cancellation_token;
EXPECT_FALSE(ct.isCancellationRequested());
cancelSrc.requestCancellation();
EXPECT_TRUE(ct.isCancellationRequested());
co_return 42;
};
{
folly::Try<int> result = co_await folly::coro::co_withCancellation(
cancelSrc.getToken(),
folly::coro::co_awaitTry(
makeTask().scheduleOn(folly::getGlobalCPUExecutor())));
EXPECT_EQ(42, result.value());
}
cancelSrc = {};
{
folly::Try<int> result =
co_await folly::coro::co_awaitTry(folly::coro::co_withCancellation(
cancelSrc.getToken(),
makeTask().scheduleOn(folly::getGlobalCPUExecutor())));
EXPECT_EQ(42, result.value());
}
}());
}
#endif
|
#include <assert.h>
#include <pcap/pcap.h>
#include <sys/ioctl.h>
#include <cstring>
#include <string.h>
#include "pcap_session.h"
using namespace v8;
Nan::Persistent<Function> PcapSession::constructor;
PcapSession::PcapSession() {};
PcapSession::~PcapSession() {};
void PcapSession::Init(Local<Object> exports) {
Nan::HandleScope scope;
// Prepare constructor template
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("PcapSession").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
Nan::SetPrototypeMethod(tpl, "open_live", OpenLive);
Nan::SetPrototypeMethod(tpl, "open_offline", OpenOffline);
Nan::SetPrototypeMethod(tpl, "dispatch", Dispatch);
Nan::SetPrototypeMethod(tpl, "start_polling", StartPolling);
Nan::SetPrototypeMethod(tpl, "close", Close);
Nan::SetPrototypeMethod(tpl, "stats", Stats);
Nan::SetPrototypeMethod(tpl, "inject", Inject);
constructor.Reset(tpl->GetFunction(Nan::GetCurrentContext()).ToLocalChecked());
Nan::Set(exports, Nan::New("PcapSession").ToLocalChecked(), tpl->GetFunction(Nan::GetCurrentContext()).ToLocalChecked());
}
void PcapSession::New(const Nan::FunctionCallbackInfo<Value>& info) {
Nan::HandleScope scope;
if (info.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
PcapSession* obj = new PcapSession();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
Local<Function> cons = Nan::New<Function>(constructor);
info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked());
}
}
// PacketReady is called from within pcap, still on the stack of Dispatch. It should be called
// only one time per Dispatch, but sometimes it gets called 0 times. PacketReady invokes the
// JS callback associated with the dispatch() call in JS.
//
// Stack:
// 1. readWatcher.callback (pcap.js)
// 2. session.dispatch (pcap.js)
// 3. Dispatch (pcap_session.cc)
// 4. pcap_dispatch (libpcap)
// 5. PacketReady (pcap_session.cc)
// 6. session.dispatch callback (pcap.js)
//
void PcapSession::PacketReady(u_char *s, const struct pcap_pkthdr* pkthdr, const u_char* packet) {
Nan::HandleScope scope;
PcapSession* session = (PcapSession *)s;
if (session->pcap_dump_handle != NULL) {
pcap_dump((u_char *) session->pcap_dump_handle, pkthdr, packet);
}
size_t copy_len = pkthdr->caplen;
if (copy_len > session->buffer_length) {
copy_len = session->buffer_length;
}
memcpy(session->buffer_data, packet, copy_len);
// copy header data to fixed offsets in second buffer from user
memcpy(session->header_data, &(pkthdr->ts.tv_sec), 4);
memcpy(session->header_data + 4, &(pkthdr->ts.tv_usec), 4);
memcpy(session->header_data + 8, &(pkthdr->caplen), 4);
memcpy(session->header_data + 12, &(pkthdr->len), 4);
Nan::TryCatch try_catch;
Nan::Call(session->packet_ready_cb, 0, NULL);
if (try_catch.HasCaught()) {
Nan::FatalException(try_catch);
}
}
void PcapSession::Dispatch(const Nan::FunctionCallbackInfo<Value>& info)
{
Nan::HandleScope scope;
if (info.Length() != 2) {
Nan::ThrowTypeError("Dispatch takes exactly two arguments");
return;
}
if (!node::Buffer::HasInstance(info[0])) {
Nan::ThrowTypeError("First argument must be a buffer");
return;
}
if (!node::Buffer::HasInstance(info[1])) {
Nan::ThrowTypeError("Second argument must be a buffer");
return;
}
PcapSession* session = Nan::ObjectWrap::Unwrap<PcapSession>(info.This());
Local<Object> buffer_obj = info[0]->ToObject(Nan::GetCurrentContext()).FromMaybe(Local<v8::Object>());
session->buffer_data = node::Buffer::Data(buffer_obj);
session->buffer_length = node::Buffer::Length(buffer_obj);
Local<Object> header_obj = info[1]->ToObject(Nan::GetCurrentContext()).FromMaybe(Local<v8::Object>());
session->header_data = node::Buffer::Data(header_obj);
int packet_count;
do {
packet_count = pcap_dispatch(session->pcap_handle, 1, PacketReady, (u_char *)session);
if (packet_count == -2) {
FinalizeClose(session);
}
} while (packet_count > 0);
info.GetReturnValue().Set(Nan::New<Integer>(packet_count));
}
void PcapSession::Open(bool live, const Nan::FunctionCallbackInfo<Value>& info)
{
Nan::HandleScope scope;
char errbuf[PCAP_ERRBUF_SIZE];
if (info.Length() == 10) {
if (!info[0]->IsString()) {
Nan::ThrowTypeError("pcap Open: info[0] must be a String");
return;
}
if (!info[1]->IsString()) {
Nan::ThrowTypeError("pcap Open: info[1] must be a String");
return;
}
if (!info[2]->IsInt32()) {
Nan::ThrowTypeError("pcap Open: info[2] must be a Number");
return;
}
if (!info[3]->IsInt32()) {
Nan::ThrowTypeError("pcap Open: info[3] must be a Number");
return;
}
if (!info[4]->IsString()) {
Nan::ThrowTypeError("pcap Open: info[4] must be a String");
return;
}
if (!info[5]->IsFunction()) {
Nan::ThrowTypeError("pcap Open: info[5] must be a Function");
return;
}
if (!info[6]->IsBoolean()) {
Nan::ThrowTypeError("pcap Open: info[6] must be a Boolean");
return;
}
if (!info[7]->IsInt32()) {
Nan::ThrowTypeError("pcap Open: info[7] must be a Number");
return;
}
if (!info[8]->IsFunction()) { // warning function
Nan::ThrowTypeError("pcap Open: info[8] must be a Function");
return;
}
if (!info[9]->IsBoolean()) {
Nan::ThrowTypeError("pcap Open: info[9] must be a Boolean");
return;
}
} else {
Nan::ThrowTypeError("pcap Open: expecting 8 arguments");
return;
}
Nan::Utf8String device(info[0]->ToString(Nan::GetCurrentContext()).FromMaybe(Local<v8::String>()));
Nan::Utf8String filter(info[1]->ToString(Nan::GetCurrentContext()).FromMaybe(Local<v8::String>()));
int buffer_size = Nan::To<int32_t>(info[2]).FromJust();
int snap_length = Nan::To<int32_t>(info[3]).FromJust();
int buffer_timeout = Nan::To<int32_t>(info[7]).FromJust();
Nan::Utf8String pcap_output_filename(info[4]->ToString(Nan::GetCurrentContext()).FromMaybe(Local<v8::String>()));
PcapSession* session = Nan::ObjectWrap::Unwrap<PcapSession>(info.This());
session->packet_ready_cb.SetFunction(info[5].As<Function>());
session->pcap_dump_handle = NULL;
if (live) {
if (pcap_lookupnet((char *) *device, &session->net, &session->mask, errbuf) == -1) {
session->net = 0;
session->mask = 0;
Local<Value> str = Nan::New(errbuf).ToLocalChecked();
Nan::Call(info[8].As<Function>(), Nan::GetCurrentContext()->Global(), 1, &str);
}
session->pcap_handle = pcap_create((char *) *device, errbuf);
if (session->pcap_handle == NULL) {
Nan::ThrowError(errbuf);
return;
}
// 64KB is the max IPv4 packet size
if (pcap_set_snaplen(session->pcap_handle, snap_length) != 0) {
Nan::ThrowError("error setting snaplen");
return;
}
if (Nan::To<int32_t>(info[9]).FromJust()) {
if (pcap_set_promisc(session->pcap_handle, 1) != 0) {
Nan::ThrowError("error setting promiscuous mode");
return;
}
}
// Try to set buffer size. Sometimes the OS has a lower limit that it will silently enforce.
if (pcap_set_buffer_size(session->pcap_handle, buffer_size) != 0) {
Nan::ThrowError("error setting buffer size");
return;
}
if (buffer_timeout > 0) {
// set "timeout" on read, even though we are also setting nonblock below. On Linux this is required.
if (pcap_set_timeout(session->pcap_handle, buffer_timeout) != 0) {
Nan::ThrowError("error setting read timeout");
return;
}
}
// timeout <= 0 is undefined behaviour, we'll set immediate mode instead. (timeout is ignored in immediate mode)
if (pcap_set_immediate_mode(session->pcap_handle, (buffer_timeout <= 0)) != 0) {
Nan::ThrowError("error setting immediate mode");
return;
}
if (Nan::To<int32_t>(info[6]).FromJust()) {
if (pcap_set_rfmon(session->pcap_handle, 1) != 0) {
Nan::ThrowError(pcap_geterr(session->pcap_handle));
return;
}
}
if (pcap_activate(session->pcap_handle) != 0) {
Nan::ThrowError(pcap_geterr(session->pcap_handle));
return;
}
if (strlen((char *) *pcap_output_filename) > 0) {
session->pcap_dump_handle = pcap_dump_open(session->pcap_handle, (char *) *pcap_output_filename);
if (session->pcap_dump_handle == NULL) {
Nan::ThrowError("error opening dump");
return;
}
}
if (pcap_setnonblock(session->pcap_handle, 1, errbuf) == -1) {
Nan::ThrowError(errbuf);
return;
}
} else {
// Device is the path to the savefile
session->pcap_handle = pcap_open_offline((char *) *device, errbuf);
if (session->pcap_handle == NULL) {
Nan::ThrowError(errbuf);
return;
}
}
if (filter.length() != 0) {
if (pcap_compile(session->pcap_handle, &session->fp, (char *) *filter, 1, session->net) == -1) {
Nan::ThrowError(pcap_geterr(session->pcap_handle));
return;
}
if (pcap_setfilter(session->pcap_handle, &session->fp) == -1) {
Nan::ThrowError(pcap_geterr(session->pcap_handle));
return;
}
pcap_freecode(&session->fp);
}
// Work around buffering bug in BPF on OSX 10.6 as of May 19, 2010
// This may result in dropped packets under load because it disables the (broken) buffer
// http://seclists.org/tcpdump/2010/q1/110
#if defined(__APPLE_CC__) || defined(__APPLE__)
#include <net/bpf.h>
int fd = pcap_get_selectable_fd(session->pcap_handle);
if (fd < 0) {
Nan::ThrowError(pcap_geterr(session->pcap_handle));
return;
}
int v = 1;
ioctl(fd, BIOCIMMEDIATE, &v);
// TODO - check return value
#endif
int link_type = pcap_datalink(session->pcap_handle);
Local<Value> ret;
switch (link_type) {
case DLT_NULL:
ret = Nan::New("LINKTYPE_NULL").ToLocalChecked();
break;
case DLT_EN10MB: // most wifi interfaces pretend to be "ethernet"
ret = Nan::New("LINKTYPE_ETHERNET").ToLocalChecked();
break;
case DLT_IEEE802_11_RADIO: // 802.11 "monitor mode"
ret = Nan::New("LINKTYPE_IEEE802_11_RADIO").ToLocalChecked();
break;
case DLT_RAW: // "raw IP"
ret = Nan::New("LINKTYPE_RAW").ToLocalChecked();
break;
case DLT_LINUX_SLL: // "Linux cooked capture"
ret = Nan::New("LINKTYPE_LINUX_SLL").ToLocalChecked();
break;
default:
snprintf(errbuf, PCAP_ERRBUF_SIZE, "Unknown linktype %d", link_type);
ret = Nan::New(errbuf).ToLocalChecked();
break;
}
info.GetReturnValue().Set(ret);
}
void PcapSession::OpenLive(const Nan::FunctionCallbackInfo<Value>& info)
{
return Open(true, info);
}
void PcapSession::OpenOffline(const Nan::FunctionCallbackInfo<Value>& info)
{
return Open(false, info);
}
void PcapSession::Close(const Nan::FunctionCallbackInfo<Value>& info)
{
Nan::HandleScope scope;
PcapSession* session = Nan::ObjectWrap::Unwrap<PcapSession>(info.Holder());
if (session->pcap_dump_handle != NULL) {
pcap_dump_close(session->pcap_dump_handle);
session->pcap_dump_handle = NULL;
}
if (session->pcap_handle != NULL) {
pcap_breakloop(session->pcap_handle);
}
}
void PcapSession::FinalizeClose(PcapSession * session) {
if (session->poll_init) {
uv_poll_stop(&session->poll_handle);
uv_unref((uv_handle_t*) &session->poll_handle);
session->poll_init = false;
delete session->poll_resource;
}
pcap_close(session->pcap_handle);
session->pcap_handle = NULL;
session->packet_ready_cb.Reset();
}
void PcapSession::poll_handler(uv_poll_t* handle, int status, int events)
{
Nan::HandleScope scope;
PcapSession* session = reinterpret_cast<PcapSession*>(handle->data);
Local<String> callback_symbol = Nan::New("read_callback").ToLocalChecked();
Local<Value> callback_v = Nan::Get(session->handle(), callback_symbol).ToLocalChecked();
if(!callback_v->IsFunction()) return;
Local<Function> callback = Local<Function>::Cast(callback_v);
Nan::TryCatch try_catch;
session->poll_resource->runInAsyncScope(Nan::GetCurrentContext()->Global(), callback, 0, NULL);
if (try_catch.HasCaught())
Nan::FatalException(try_catch);
}
void PcapSession::StartPolling(const Nan::FunctionCallbackInfo<Value>& info)
{
Nan::HandleScope scope;
PcapSession* session = Nan::ObjectWrap::Unwrap<PcapSession>(info.Holder());
if (session->poll_init) return;
if (session->pcap_handle == NULL) {
Nan::ThrowError("Error: pcap session already closed");
return;
}
int fd = pcap_get_selectable_fd(session->pcap_handle);
if (fd < 0) {
Nan::ThrowError(pcap_geterr(session->pcap_handle));
return;
}
session->poll_handle.data = session;
if (uv_poll_init(Nan::GetCurrentEventLoop(), &session->poll_handle, fd) < 0) {
Nan::ThrowError("Couldn't initialize UV poll");
return;
}
session->poll_init = true;
if (uv_poll_start(&session->poll_handle, UV_READABLE, poll_handler) < 0) {
Nan::ThrowError("Couldn't start UV poll");
return;
}
uv_ref((uv_handle_t*) &session->poll_handle);
session->poll_resource = new Nan::AsyncResource("pcap:PcapSession", info.Holder());
}
void PcapSession::Stats(const Nan::FunctionCallbackInfo<Value>& info)
{
Nan::HandleScope scope;
struct pcap_stat ps;
PcapSession* session = Nan::ObjectWrap::Unwrap<PcapSession>(info.Holder());
if (session->pcap_handle == NULL) {
Nan::ThrowError("Error: pcap session already closed");
return;
}
if (pcap_stats(session->pcap_handle, &ps) == -1) {
Nan::ThrowError("Error in pcap_stats");
return;
// TODO - use pcap_geterr to figure out what the error was
}
Local<Object> stats_obj = Nan::New<Object>();
Nan::Set(stats_obj, Nan::New("ps_recv").ToLocalChecked(), Nan::New<Integer>(ps.ps_recv));
Nan::Set(stats_obj, Nan::New("ps_drop").ToLocalChecked(), Nan::New<Integer>(ps.ps_drop));
Nan::Set(stats_obj, Nan::New("ps_ifdrop").ToLocalChecked(), Nan::New<Integer>(ps.ps_ifdrop));
// ps_ifdrop may not be supported on this platform, but there's no good way to tell, is there?
info.GetReturnValue().Set(stats_obj);
}
void PcapSession::Inject(const Nan::FunctionCallbackInfo<Value>& info)
{
Nan::HandleScope scope;
if (info.Length() != 1) {
Nan::ThrowTypeError("Inject takes exactly one argument");
return;
}
if (!node::Buffer::HasInstance(info[0])) {
Nan::ThrowTypeError("First argument must be a buffer");
return;
}
PcapSession* session = Nan::ObjectWrap::Unwrap<PcapSession>(info.Holder());
if (session->pcap_handle == NULL) {
Nan::ThrowError("Error: pcap session already closed");
return;
}
char * bufferData = NULL;
size_t bufferLength = 0;
Local<Object> buffer_obj = info[0]->ToObject(Nan::GetCurrentContext()).FromMaybe(Local<v8::Object>());
bufferData = node::Buffer::Data(buffer_obj);
bufferLength = node::Buffer::Length(buffer_obj);
if (pcap_inject(session->pcap_handle, bufferData, bufferLength) != (int)bufferLength) {
Nan::ThrowError("Pcap inject failed.");
return;
}
return;
}
|
// MIT License
//
// Copyright (c) 2020 Olivier Le Doeuff
//
// 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 <Qaterial/Qaterial.hpp>
#include <Qaterial/HotReload/HotReload.hpp>
#ifdef QATERIALHOTRELOAD_ENABLE_SFPM
# include <SortFilterProxyModel/SortFilterProxyModel.hpp>
#endif
#include <QtGui/QIcon>
#include <QtQml/QQmlApplicationEngine>
#include <QtQml/QtQml>
#include <QtWidgets/QApplication>
#ifdef Q_OS_WIN
# include <Windows.h>
#endif
void qtMsgOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
qaterial::HotReload::log(type, context, msg);
{
const auto timestamp = QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
const auto category = [type]() -> QString
{
switch(type)
{
case QtDebugMsg: return "debug";
case QtWarningMsg: return "warning";
case QtCriticalMsg: return "error";
case QtFatalMsg: return "error";
case QtInfoMsg: return "info";
default: return "unknown";
}
}();
const auto log = "[" + timestamp + "] [" + context.category + "] [" + category + "] : " + msg;
#if defined(Q_OS_WIN)
const auto winLog = log + "\n";
OutputDebugStringW(reinterpret_cast<const wchar_t*>(winLog.utf16()));
#elif defined(Q_OS_ANDROID)
android_default_message_handler(type, context, msg);
#endif
}
}
int main(int argc, char* argv[])
{
#if defined(QATERIALHOTRELOAD_IGNORE_ENV)
const QString executable = argv[0];
# if defined(Q_OS_WINDOWS)
const auto executablePath = executable.mid(0, executable.lastIndexOf("\\"));
QCoreApplication::setLibraryPaths({executablePath});
# endif
#endif
qInstallMessageHandler(qtMsgOutput);
QApplication app(argc, argv);
QQmlApplicationEngine engine;
// ──── REGISTER APPLICATION ────
QGuiApplication::setOrganizationName("Qaterial");
QGuiApplication::setApplicationName("Qaterial Hot Reload");
QGuiApplication::setOrganizationDomain("https://olivierldff.github.io/Qaterial/");
const QString version = QString::number(qaterial::versionMajor()) + QStringLiteral(".") + QString::number(qaterial::versionMinor()) +
QStringLiteral(".") + QString::number(qaterial::versionPatch()) + QStringLiteral(".0x") +
QString::number(qaterial::versionTag(), 16).rightJustified(8, QChar('0'));
QGuiApplication::setApplicationVersion(version);
QGuiApplication::setWindowIcon(QIcon(":/Qaterial/HotReload/Images/icon.svg"));
QCommandLineParser parser;
const QCommandLineOption resetImport(QStringList({"reset-imports"}), QCoreApplication::translate("main", "Force reset of imports"));
parser.addOption(resetImport);
const QCommandLineOption resetCurrentFile(QStringList({"reset-current-file"}),
QCoreApplication::translate("main", "Force reset of current file"));
parser.addOption(resetCurrentFile);
parser.process(app);
// ──── LOAD AND REGISTER QML ────
#if defined(QATERIALHOTRELOAD_IGNORE_ENV)
engine.setImportPathList({QLibraryInfo::location(QLibraryInfo::Qml2ImportsPath), "qrc:/", "qrc:/qt-project.org/imports"});
#else
engine.addImportPath("qrc:/");
#endif
// Load Qaterial
qaterial::loadQmlResources();
qaterial::registerQmlTypes();
qaterial::HotReload::registerSingleton();
if(parser.isSet(resetImport))
qaterial::HotReload::resetImportPath();
if(parser.isSet(resetCurrentFile))
qaterial::HotReload::resetCurrentFile();
#ifdef QATERIALHOTRELOAD_ENABLE_SFPM
qqsfpm::registerQmlTypes();
#endif
// ──── LOAD QML MAIN ────
engine.load(QUrl("qrc:/Qaterial/HotReload/Main.qml"));
if(engine.rootObjects().isEmpty())
return -1;
// ──── START EVENT LOOP ────
return QGuiApplication::exec();
}
|
#include "ColonialFlags/ColonialFlagRegion.h"
#include "gtest/gtest.h"
TEST(Mappers_ColonialFlagRegionTests, flagsDefaultToEmpty)
{
std::stringstream input;
const mappers::ColonialFlagRegion region(input, "region");
ASSERT_TRUE(region.getRegionalFlags().empty());
}
TEST(Mappers_ColonialFlagRegionTests, flagsCanBeLoaded)
{
std::stringstream input;
input << "flag = { name = \"Alaska\" }\n";
input << "flag = { name = \"Alyeska\" unique = true }\n";
const mappers::ColonialFlagRegion region(input, "region");
ASSERT_EQ(2, region.getRegionalFlags().size());
ASSERT_EQ("alaska", region.getRegionalFlags().at("alaska").getName());
ASSERT_EQ("alyeska", region.getRegionalFlags().at("alyeska").getName());
ASSERT_TRUE(region.getRegionalFlags().at("alyeska").isUnique());
}
TEST(Mappers_ColonialFlagRegionTests, regionsIsPassedDownToFlags)
{
std::stringstream input;
input << "flag = { name = \"Alaska\" }\n";
input << "flag = { name = \"Alyeska\" unique = true }\n";
const mappers::ColonialFlagRegion region(input, "region");
ASSERT_EQ("region", region.getRegionalFlags().at("alaska").getRegion());
ASSERT_EQ("region", region.getRegionalFlags().at("alyeska").getRegion());
}
|
#include "gvariantproxy.h"
using namespace v8;
Nan::Persistent<FunctionTemplate> GVariantProxy::constructor;
GVariantProxy::GVariantProxy() {
}
GVariantProxy::~GVariantProxy() {
if (dict != NULL) {
g_variant_dict_unref(dict);
g_variant_unref(variant);
dict = NULL;
variant = NULL;
}
}
void GVariantProxy::init(GVariant* var) {
variant = var;
dict = g_variant_dict_new(variant);
}
static NAN_PROPERTY_GETTER(GetNamedProperty) {
Nan::HandleScope scope;
GVariantProxy* self = node::ObjectWrap::Unwrap<GVariantProxy>(info.Holder());
const gchar* val;
if (self->dict != NULL) {
Nan::Utf8String* prop = new Nan::Utf8String(property);
if (!g_variant_dict_lookup(self->dict, **prop, "s", &val)) val = NULL;
delete prop;
}
if (val == NULL) return;
else info.GetReturnValue().Set(Nan::New<String>(val).ToLocalChecked());
}
static NAN_PROPERTY_SETTER(SetNamedProperty) {
Nan::HandleScope scope;
GVariantProxy* self = node::ObjectWrap::Unwrap<GVariantProxy>(info.Holder());
if (self->dict == NULL) return;
Nan::Utf8String* prop = new Nan::Utf8String(property);
Nan::Utf8String* val = new Nan::Utf8String(value);
gchar* valstr = NULL;
if (!value->IsUndefined() && !value->IsNull()) {
valstr = **val;
}
g_variant_dict_insert(self->dict, **prop, "s", valstr);
delete val;
delete prop;
return;
}
static NAN_PROPERTY_QUERY(QueryNamedProperty) {
Nan::HandleScope scope;
gboolean hasProp = FALSE;
GVariantProxy* self = node::ObjectWrap::Unwrap<GVariantProxy>(info.Holder());
if (self->dict != NULL) {
Nan::Utf8String* prop = new Nan::Utf8String(property);
hasProp = g_variant_dict_contains(self->dict, **prop);
delete prop;
}
info.GetReturnValue().Set(Nan::New<Integer>(hasProp));
}
static NAN_PROPERTY_DELETER(DeleteNamedProperty) {
Nan::HandleScope scope;
bool hasProp = FALSE;
GVariantProxy* self = node::ObjectWrap::Unwrap<GVariantProxy>(info.Holder());
Nan::Utf8String* prop = NULL;
if (self->dict != NULL) {
prop = new Nan::Utf8String(property);
hasProp = g_variant_dict_contains(self->dict, **prop);
}
if (hasProp) {
const gchar* stub = NULL;
g_variant_dict_insert(self->dict, **prop, "s", &stub);
}
if (prop != NULL) delete prop;
info.GetReturnValue().Set(Nan::New<Boolean>(hasProp));
}
static NAN_PROPERTY_ENUMERATOR(EnumerateNamedProperties) {
Nan::HandleScope scope;
Local<Array> array = Nan::New<Array>();
GVariantProxy* self = node::ObjectWrap::Unwrap<GVariantProxy>(info.Holder());
if (self->dict == NULL) info.GetReturnValue().Set(array);
GVariantIter iter;
GVariant* val;
gchar* key;
g_variant_iter_init(&iter, self->variant);
int i = 0;
while (g_variant_iter_next(&iter, "{sv}", &key, &val)) {
if (!g_strcmp0(key, "uri")) continue;
Nan::Set(array, i++, Nan::New<String>(key).ToLocalChecked());
g_free(key);
}
info.GetReturnValue().Set(array);
}
void GVariantProxy::Init(Local<Object> target) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(GVariantProxy::New);
Local<ObjectTemplate> otmpl = tpl->InstanceTemplate();
otmpl->SetInternalFieldCount(1);
Nan::SetNamedPropertyHandler(
otmpl,
GetNamedProperty,
SetNamedProperty,
QueryNamedProperty,
DeleteNamedProperty,
EnumerateNamedProperties
);
tpl->SetClassName(Nan::New("GVariantProxy").ToLocalChecked());
target->Set(Nan::New("GVariantProxy").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
constructor.Reset(tpl);
}
NAN_METHOD(GVariantProxy::New) {
Nan::HandleScope scope;
GVariantProxy* self = new GVariantProxy();
self->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
|
#include "GpioOutput.hpp"
#include "Logging.hpp"
#include "SignalProvider.hpp"
using namespace std;
// Name returns the instance name
string GpioOutput::Name(void)
{
return this->chip.name() + "/" + this->line.name();
}
void GpioOutput::Apply(void)
{
if (this->newLevel != this->level)
{
this->level = this->newLevel;
log_debug("output gpio " + this->Name() + " changed to " +
to_string(this->level ^ this->activeLow));
this->line.set_value(this->level);
}
}
void GpioOutput::Update(void)
{
this->newLevel = this->in->GetLevel() ? 1 : 0;
}
GpioOutput::GpioOutput(struct ConfigOutput* cfg, SignalProvider& prov) :
level(-1), newLevel(-1), activeLow(cfg->ActiveLow)
{
::std::bitset<32> flags = 0;
if (cfg->GpioChipName == "")
{
this->line = gpiod::find_line(cfg->Name);
this->chip = this->line.get_chip();
}
else
{
this->chip.open(cfg->GpioChipName, gpiod::chip::OPEN_LOOKUP);
this->line = this->chip.find_line(cfg->Name);
}
try
{
if (this->line.name() == "")
{
throw runtime_error("GPIO line " + cfg->Name + " not found");
}
}
catch (logic_error& exc)
{
throw runtime_error("GPIO line " + cfg->Name + " not found");
}
this->in = prov.FindOrAdd(cfg->SignalName);
this->in->AddReceiver(this);
if (cfg->ActiveLow)
flags |= gpiod::line_request::FLAG_ACTIVE_LOW;
if (cfg->OpenDrain)
flags |= gpiod::line_request::FLAG_OPEN_DRAIN;
if (cfg->OpenSource)
flags |= gpiod::line_request::FLAG_OPEN_SOURCE;
#ifdef WITH_GPIOD_PULLUPS
if (cfg->PullDown)
flags |= gpiod::line_request::FLAG_BIAS_PULL_DOWN;
if (cfg->PullUp)
flags |= gpiod::line_request::FLAG_BIAS_PULL_UP;
if (cfg->DisableBias)
flags |= gpiod::line_request::FLAG_BIAS_DISABLE;
#endif
::gpiod::line_request requestOutput = {
"pwrseqd", gpiod::line_request::DIRECTION_OUTPUT, flags};
try
{
this->line.request(requestOutput);
}
catch (exception& e)
{
throw runtime_error("Failed to request gpio line " + cfg->GpioChipName +
" " + cfg->Name + ": " + e.what());
}
log_debug("using gpio " + this->Name() + " as output ");
}
GpioOutput::~GpioOutput()
{
this->line.release();
}
|
/*===================================================================
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 <mitkTestingMacros.h>
#include <mitkToFCameraPMDMITKPlayerController.h>
#include <mitkToFConfig.h>
/**Documentation
* test for the class "ToFCameraPMDMITKPlayerController".
*/
int mitkToFCameraPMDMITKPlayerControllerTest(int /* argc */, char* /*argv*/[])
{
MITK_TEST_BEGIN("ToFCameraPMDMITKPlayerController");
mitk::ToFCameraPMDMITKPlayerController::Pointer testObject = mitk::ToFCameraPMDMITKPlayerController::New();
MITK_TEST_CONDITION_REQUIRED(!(testObject.GetPointer() == NULL) ,"Testing initialization class");
MITK_TEST_CONDITION_REQUIRED(testObject->GetCaptureHeight()== 200 ,"Testing initialization of CaptureHeight");
MITK_TEST_CONDITION_REQUIRED(testObject->GetCaptureWidth()== 200 ,"Testing initialization of CaptureWidth");
// test empty file behavior
std::string testFile = "";
testObject->SetInputFileName(testFile);
MITK_TEST_CONDITION_REQUIRED(testObject->OpenCameraConnection(),"Testing open camera without valid data");
//MITK_TEST_CONDITION_REQUIRED(!testObject->CloseCameraConnection(),"Testing closing of connection");
//test valid data behavior
//CAVE: The following test cases are valid once rawData recording is fixed. Currently the
// functionality is not working therefor the test cases are excluded!!
//std::string filePath = MITK_TOF_DATA_DIR;
//testFile = "/aa_raw.pic";
//filePath.append(testFile);
//testObject->SetInputFileName(filePath);
//MITK_TEST_CONDITION_REQUIRED( testObject->OpenCameraConnection(),"Testing open camera with valid data");
//MITK_TEST_CONDITION_REQUIRED( testObject->GetIntegrationTime() == 2500,"Testing correct setting of integration time!");
//MITK_TEST_CONDITION_REQUIRED( testObject->GetModulationFrequency() == 20,"Testing correct setting of modulation frequency!");
//
////test source data passing and updating!
//int size = testObject->GetSourceDataStructSize();
//MITK_TEST_CONDITION_REQUIRED( size != 0 , "Testing correct setting of source data size!" )
//char* sourceData = NULL;
//testObject->GetSourceData( sourceData );
//MITK_TEST_CONDITION_REQUIRED( sourceData == NULL, "Testing setting of source data without update camera!");
//testObject->UpdateCamera();
//sourceData = new char[size];
//testObject->GetSourceData(sourceData);
//MITK_TEST_CONDITION_REQUIRED( sourceData != NULL, "Testing setting of source data with update camera!");
//delete[] sourceData;
MITK_TEST_CONDITION( testObject->CloseCameraConnection(),"Closing Connection!");
MITK_TEST_END();
}git st
|
#include "CameraImageWrapper.h"
#include <QColor>
#include <QApplication>
#include <QDesktopWidget>
CameraImageWrapper::CameraImageWrapper() : LuminanceSource()
{
}
CameraImageWrapper::CameraImageWrapper(CameraImageWrapper& otherInstance) : LuminanceSource()
{
image = otherInstance.getOriginalImage().copy();
}
CameraImageWrapper::~CameraImageWrapper()
{
}
int CameraImageWrapper::getWidth() const
{
return image.width();
}
int CameraImageWrapper::getHeight() const
{
return image.height();
}
unsigned char CameraImageWrapper::getPixel(int x, int y) const
{
QRgb pixel = image.pixel(x,y);
return qGray(pixel);//((qRed(pixel) + qGreen(pixel) + qBlue(pixel)) / 3);
}
unsigned char* CameraImageWrapper::copyMatrix() const
{
unsigned char* newMatrix = (unsigned char*)malloc(image.width()*image.height()*sizeof(unsigned char));
int cnt = 0;
for(int i=0; i<image.width(); i++)
{
for(int j=0; j<image.height(); j++)
{
newMatrix[cnt++] = getPixel(i,j);
}
}
return newMatrix;
}
void CameraImageWrapper::setImage(QString fileName)
{
image.load(fileName);
if(image.width() > QApplication::desktop()->width())
image = image.scaled(QApplication::desktop()->width(), image.height(), Qt::IgnoreAspectRatio);
if(image.height() > QApplication::desktop()->height())
image = image.scaled(image.width(), QApplication::desktop()->height(), Qt::IgnoreAspectRatio);
}
void CameraImageWrapper::setImage(QImage newImage)
{
image = newImage.copy();
if(image.width() > 640)
image = image.scaled(640, image.height(), Qt::KeepAspectRatio);
}
QImage CameraImageWrapper::grayScaleImage(QImage::Format f)
{
QImage tmp(image.width(), image.height(), f);
for(int i=0; i<image.width(); i++)
{
for(int j=0; j<image.height(); j++)
{
int pix = (int)getPixel(i,j);
tmp.setPixel(i,j, qRgb(pix ,pix,pix));
}
}
return tmp;
//return image.convertToFormat(f);
}
QImage CameraImageWrapper::getOriginalImage()
{
return image;
}
|
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str1,str2;
char ex;
cin >>str1>>str2;
cout <<str1.size()<<" "<<str2.size()<<endl;
cout <<str1+str2<<endl;
swap(str1[0],str2[0]);
cout <<str1<<" "<<str2;
return 0;
}
|
// to use c++ style logging
// specifically define this before including loguru.hpp
#define LOGURU_WITH_STREAMS 1
#include <grpcpp/grpcpp.h>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <iostream>
#include <map>
#include <memory>
#include <mongocxx/client.hpp>
#include <mongocxx/exception/operation_exception.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/pool.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include <stdexcept>
#include <string>
#include <thread>
#include "protos/zirconiumbank.grpc.pb.h"
#include "server/transaction_mgr.hpp"
#include "utils/cxxopts.hpp"
#include "utils/loguru.hpp"
#include "utils/zirconium_utils.hpp"
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_array;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;
// gRPC namespaces
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using grpc::StatusCode;
// zirconium grpc-proto namespaces
using zirconium::bank::AuthUser;
using zirconium::bank::Balance;
using zirconium::bank::RequestAmount;
using zirconium::bank::TransferReq;
using zirconium::bank::WebService;
class WebServiceImpl final : public WebService::Service {
/**
* BalanceEnquiry: Gets the balance of a AuthUser
*/
Status BalanceEnquiry(ServerContext* context, const AuthUser* auth_user, Balance* balance) override {
// get a client from the pool
auto client = conn_pool_->acquire();
// log the auth data from the request
logAuthData_(auth_user->username(), auth_user->pin());
// check if the user is authenticated and also fetch the document
auto [is_authenticated, user] = getAuthData_(auth_user->username(), auth_user->pin(), *(client));
if (not is_authenticated) {
LOG_S(WARNING) << "UNAUTHENTICATED User: " << auth_user->username();
return Status(StatusCode::UNAUTHENTICATED, "username or pin wrong!");
}
// the user is authenticated
balance->set_value(user->view()["balance"].get_int32());
return Status::OK;
}
/**
* UpdateAmount : updates the balance of the user with the given amount
* Tested Works ✅
*/
Status UpdateAmount(ServerContext* context, const RequestAmount* update_req, Balance* balance) override {
LOG_S(INFO) << "UpdateAmount called by peer: " << context->peer();
// get a client from the pool
auto client = conn_pool_->acquire();
// get the "zirconium" db
auto db = (*client)["zirconium"];
const auto auth_user = update_req->user();
logAuthData_(auth_user.username(), auth_user.pin());
try {
auto [is_authenticated, user] = getAuthData_(auth_user.username(), auth_user.pin(), (*client));
if (not is_authenticated) {
LOG_S(WARNING) << "UNAUTHENTICATED User: " << auth_user.username();
return Status(StatusCode::UNAUTHENTICATED, "username or pin wrong!");
}
// the user is authenticated
auto update_user_amount = [&](mongocxx::client_session& session) {
// get the transaction options
auto txn_opts = zirconium::transaction_mgr::get_transaction_opts();
// initiate the transaction
session.start_transaction(txn_opts);
// container for the updated user
bsoncxx::stdx::optional<bsoncxx::document::value> updated_user;
// try the transaction
try {
// read fuser value from db
auto curr_user = db["bank"].find_one(session, make_document(kvp("username", auth_user.username())));
auto curr_user_balance = curr_user->view()["balance"].get_int32().value;
// guard to check if from_user has necessary balance
if (curr_user_balance + update_req->value() < 0) {
// insufficient balance
throw zirconium::exception("insufficient balance");
}
// increment/decrement the balance of user
updated_user = db["bank"].find_one_and_update(
session,
curr_user->view(),
make_document(
kvp("$inc", make_document(kvp("balance", update_req->value())))),
mongocxx::options::find_one_and_update().return_document(mongocxx::options::return_document::k_after));
// set the new balance as responce
balance->set_value(updated_user->view()["balance"].get_int32());
} catch (const mongocxx::operation_exception& oe) {
session.abort_transaction();
throw oe;
}
// run this if the transaction was successful
auto on_success = [&](void) {
LOG_S(INFO) << "UPDATED: " << bsoncxx::to_json(*updated_user) << "\n";
auto update_type = update_req->value() >= 0 ? "credited" : "debited";
LOG_S(INFO) << "UpdateAmount [ Account " << updated_user->view()["username"].get_utf8().value.to_string() << " " << update_type << " with ₹ " << std::abs(update_req->value()) << " new balance: " << updated_user->view()["balance"].get_int32() << " ]";
};
// commit the transaction and retry if failure
zirconium::transaction_mgr::commit_with_retry(session, on_success);
};
// create a session and start a transaction
auto session = (*client).start_session();
try {
zirconium::transaction_mgr::run_transaction_with_retry(update_user_amount, session);
} catch (const mongocxx::operation_exception& oe) {
LOG_S(ERROR) << "Error during commit: " << oe.what() << ", for session: " << bsoncxx::to_json(session.id());
}
} catch (zirconium::exception& ex) {
LOG_S(ERROR) << "Precondition failed: " << ex.what();
return Status(StatusCode::FAILED_PRECONDITION, ex.what());
} catch (std::exception& ex) {
LOG_S(ERROR) << "Internal Server Error: " << ex.what();
return Status(StatusCode::INTERNAL, "Internal Server Error, Cannot Update Amount");
}
return Status::OK;
}
/**
* Transfer Amount: Transfer amount from current user to to_user
* Tested Works ✅
*/
Status TransferAmount(ServerContext* context, const TransferReq* transfer_req, Balance* balance) override {
LOG_S(INFO) << "TransferAmount called by peer: " << context->peer();
// get a client from the pool
auto client = conn_pool_->acquire();
// get the "zirconium" db
auto db = (*client)["zirconium"];
// curr_user
const auto auth_user = transfer_req->from_user();
const auto to_user = transfer_req->to_user();
// guard to check if the to_user is same as curr_user
if (to_user == auth_user.username()) {
return Status(StatusCode::FAILED_PRECONDITION, "to_user is same as curr_user");
}
logAuthData_(auth_user.username(), auth_user.pin());
try {
auto [is_authenticated, user] = getAuthData_(auth_user.username(), auth_user.pin(), (*client));
// check if the user is authenticated
if (not is_authenticated) {
LOG_S(WARNING) << "UNAUTHENTICATED User: " << auth_user.username();
return Status(StatusCode::UNAUTHENTICATED, "username or pin wrong!");
}
// the user is authenticated
// transaction function
auto transfer_user_amount = [&](mongocxx::client_session& session) {
// get the transaction options
auto txn_opts = zirconium::transaction_mgr::get_transaction_opts();
// initiate the transaction
session.start_transaction(txn_opts);
// container for the updated user
bsoncxx::stdx::optional<bsoncxx::document::value> updated_from_user;
// try the transaction
try {
// read to_user value from db
auto curr_to_user = db["bank"].find_one(session, make_document(kvp("username", to_user)));
// this is unnecessary, can be ommited
if (not curr_to_user) {
// to_user does not exist, abort transaction
throw zirconium::exception("to_user does not exist");
}
// read from_user value from db
auto curr_from_user = db["bank"].find_one(session, make_document(kvp("username", auth_user.username())));
auto curr_from_user_balance = curr_from_user->view()["balance"].get_int32().value;
// guard to check if from_user has necessary balance
if (curr_from_user_balance - transfer_req->amount() < 0) {
// insufficient balance
throw zirconium::exception("insufficient balance");
}
// decrement the balance of from_user
updated_from_user = db["bank"].find_one_and_update(
session,
curr_from_user->view(),
make_document(
kvp("$inc", make_document(
kvp("balance", -transfer_req->amount())))),
mongocxx::options::find_one_and_update().return_document(mongocxx::options::return_document::k_after));
// increment the balance of to_user
db["bank"].find_one_and_update(
session,
curr_to_user->view(),
make_document(
kvp("$inc", make_document(
kvp("balance", transfer_req->amount())))),
mongocxx::options::find_one_and_update());
// set the new balance as responce
balance->set_value(updated_from_user->view()["balance"].get_int32());
} catch (const mongocxx::operation_exception& oe) {
session.abort_transaction();
throw oe;
} catch (const zirconium::exception& ex) {
session.abort_transaction();
throw ex;
}
// run this if the transaction was successful
auto on_success = [&](void) {
LOG_S(INFO) << "UPDATED: " << bsoncxx::to_json(*updated_from_user) << "\n";
auto update_type = transfer_req->amount() >= 0 ? "credited" : "debited";
LOG_S(INFO) << "UpdateAmount [ Account " << updated_from_user->view()["username"].get_utf8().value.to_string() << " " << update_type << " with ₹ " << std::abs(transfer_req->amount()) << " new balance: " << updated_from_user->view()["balance"].get_int32() << " ]";
};
// commit the transaction and retry if failure
zirconium::transaction_mgr::commit_with_retry(session, on_success);
};
// create a session and start a transaction
auto session = client->start_session();
try {
zirconium::transaction_mgr::run_transaction_with_retry(transfer_user_amount, session);
} catch (const mongocxx::operation_exception& oe) {
// some expection occured during commit
LOG_S(ERROR) << "Error during commit: " << oe.what() << ", for session: " << bsoncxx::to_json(session.id());
}
} catch (zirconium::exception& ex) {
LOG_S(ERROR) << "Precondition failed: " << ex.what();
return Status(StatusCode::FAILED_PRECONDITION, ex.what());
} catch (const std::exception& ex) {
LOG_S(ERROR) << "Internal Server Error: " << ex.what();
return Status(StatusCode::INTERNAL, "Internal Server Error, Cannot Transfer Amount");
} catch (...) {
// something notorious has happened if you reach here
// stop the server
LOG_S(FATAL) << "shutting down";
}
return Status::OK;
}
public:
void initiaize(const std::string& mongo_uri) {
conn_pool_ = std::make_unique<mongocxx::pool>(mongocxx::uri{mongo_uri});
};
private:
std::unique_ptr<mongocxx::pool> conn_pool_;
void logAuthData_(std::string user, std::string pin) {
LOG_S(INFO) << "Received AuthUser: [ username: " << user << ", pin: " << pin << " ]";
}
std::tuple<bool, bsoncxx::stdx::optional<bsoncxx::document::value>> getAuthData_(std::string username, std::string pin, mongocxx::client& client) {
auto db = client["zirconium"];
bool is_authenticated = false;
bsoncxx::stdx::optional<bsoncxx::document::value> user = db["bank"].find_one(document{} << "username" << username << finalize);
if (user) {
LOG_S(INFO) << "Found User from DB: " << bsoncxx::to_json(*user);
if (pin == user->view()["pin"].get_utf8().value.to_string()) {
is_authenticated = true;
}
} else {
LOG_S(ERROR) << username << " not found !";
}
return std::make_tuple(is_authenticated, user);
}
};
void RunServer(const std::string& server_addr, const std::string& mongo_uri) {
WebServiceImpl service;
// initialize the service with mongo db name "zirconium"
service.initiaize(mongo_uri);
ServerBuilder builder;
// Listen on the given address without any authentication mechanism.
builder.AddListeningPort(server_addr, grpc::InsecureServerCredentials());
// Register "service" as the instance through which we'll communicate with
// clients. In this case it corresponds to an *synchronous* service.
builder.RegisterService(&service);
// Finally assemble the server.
std::unique_ptr<Server> server(builder.BuildAndStart());
LOG_S(INFO) << "Server listening on " << server_addr;
// Wait for the server to shutdown. Note that some other thread must be
// responsible for shutting down the server for this call to ever return.
server->Wait();
}
int main(int argc, char* argv[]) {
// turn off the printing thread info in the output
// loguru::g_preamble_thread = false;
// turn off the uptime in the output
loguru::g_preamble_uptime = false;
cxxopts::Options options("zirconium_server", "Server for Zirconium Bank");
options
.positional_help("[optional args]")
.show_positional_help();
options
.add_options()("config", "config file", cxxopts::value<std::string>())("h,help", "print help");
auto result = options.parse(argc, argv);
if (result.count("help")) {
std::cout << options.help() << "\n";
exit(0);
}
// check for the config file
if (!result.count("config")) {
LOG_S(ERROR) << "config file not provided";
}
auto config = zirconium::parse_config(result["config"].as<std::string>());
// check if the config was provided correctly
if ((config.find("server_addr") == config.end()) or (config.find("mongo_addr") == config.end())) {
throw std::runtime_error("config file incorrect, server_addr or mongo_addr not found");
}
// instantiate the mongo connection
mongocxx::instance instance{}; // This should be done only once.
std::string mongo_addr(config["mongo_addr"]);
// create a pool
// mongocxx::pool pool{uri};
std::string server_addr(config["server_addr"]);
// run the server with the pool
RunServer(server_addr, mongo_addr);
return 0;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkOSPRayRendererNode.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifdef _WIN32
#define _USE_MATH_DEFINES
#endif
#include "vtkOSPRayRendererNode.h"
#include "vtkAbstractVolumeMapper.h"
#include "vtkBoundingBox.h"
#include "vtkCamera.h"
#include "vtkCollectionIterator.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationDoubleKey.h"
#include "vtkInformationDoubleVectorKey.h"
#include "vtkInformationIntegerKey.h"
#include "vtkInformationObjectBaseKey.h"
#include "vtkInformationStringKey.h"
#include "vtkLight.h"
#include "vtkMapper.h"
#include "vtkMath.h"
#include "vtkMatrix4x4.h"
#include "vtkOSPRayActorNode.h"
#include "vtkOSPRayCameraNode.h"
#include "vtkOSPRayLightNode.h"
#include "vtkOSPRayMaterialHelpers.h"
#include "vtkOSPRayMaterialLibrary.h"
#include "vtkOSPRayVolumeNode.h"
#include "vtkObjectFactory.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkTexture.h"
#include "vtkTransform.h"
#include "vtkVolume.h"
#include "vtkVolumeCollection.h"
#include "vtkWeakPointer.h"
#include "RTWrapper/RTWrapper.h"
#include <algorithm>
#include <cmath>
#include <map>
namespace ospray
{
namespace opengl
{
// code borrowed from ospray::modules::opengl to facilitate updating
// and linking
// todo: use ospray's copy instead of this
inline osp::vec3f operator*(const osp::vec3f& a, const osp::vec3f& b)
{
return osp::vec3f{ a.x * b.x, a.y * b.y, a.z * b.z };
}
inline osp::vec3f operator*(const osp::vec3f& a, float b)
{
return osp::vec3f{ a.x * b, a.y * b, a.z * b };
}
inline osp::vec3f operator/(const osp::vec3f& a, float b)
{
return osp::vec3f{ a.x / b, a.y / b, a.z / b };
}
inline osp::vec3f operator*(float b, const osp::vec3f& a)
{
return osp::vec3f{ a.x * b, a.y * b, a.z * b };
}
inline osp::vec3f operator*=(osp::vec3f a, float b)
{
return osp::vec3f{ a.x * b, a.y * b, a.z * b };
}
inline osp::vec3f operator-(const osp::vec3f& a, const osp::vec3f& b)
{
return osp::vec3f{ a.x - b.x, a.y - b.y, a.z - b.z };
}
inline osp::vec3f operator+(const osp::vec3f& a, const osp::vec3f& b)
{
return osp::vec3f{ a.x + b.x, a.y + b.y, a.z + b.z };
}
inline osp::vec3f cross(const osp::vec3f& a, const osp::vec3f& b)
{
return osp::vec3f{ a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x };
}
inline float dot(const osp::vec3f& a, const osp::vec3f& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
inline osp::vec3f normalize(const osp::vec3f& v)
{
return v / sqrtf(dot(v, v));
}
/*! \brief Compute and return OpenGL depth values from the depth component of the given
OSPRay framebuffer, using parameters of the current OpenGL context and assuming a
perspective projection.
This function automatically determines the parameters of the OpenGL perspective
projection and camera direction / up vectors. It assumes these values match those
provided to OSPRay (fovy, aspect, camera direction / up vectors). It then maps the
OSPRay depth buffer and transforms it to OpenGL depth values according to the OpenGL
perspective projection.
The OSPRay frame buffer object must have been constructed with the OSP_FB_DEPTH flag.
*/
OSPTexture getOSPDepthTextureFromOpenGLPerspective(const double& fovy, const double& aspect,
const double& zNear, const double& zFar, const osp::vec3f& _cameraDir,
const osp::vec3f& _cameraUp, const float* glDepthBuffer, float* ospDepthBuffer,
const size_t& glDepthBufferWidth, const size_t& glDepthBufferHeight, RTW::Backend* backend)
{
osp::vec3f cameraDir = (osp::vec3f&)_cameraDir;
osp::vec3f cameraUp = (osp::vec3f&)_cameraUp;
// this should later be done in ISPC...
// transform OpenGL depth to linear depth
for (size_t i = 0; i < glDepthBufferWidth * glDepthBufferHeight; i++)
{
const double z_n = 2.0 * glDepthBuffer[i] - 1.0;
ospDepthBuffer[i] = 2.0 * zNear * zFar / (zFar + zNear - z_n * (zFar - zNear));
if (vtkMath::IsNan(ospDepthBuffer[i]))
{
ospDepthBuffer[i] = FLT_MAX;
}
}
// transform from orthogonal Z depth to ray distance t
osp::vec3f dir_du = normalize(cross(cameraDir, cameraUp));
osp::vec3f dir_dv = normalize(cross(dir_du, cameraDir));
const float imagePlaneSizeY = 2.f * tanf(fovy / 2.f * M_PI / 180.f);
const float imagePlaneSizeX = imagePlaneSizeY * aspect;
dir_du *= imagePlaneSizeX;
dir_dv *= imagePlaneSizeY;
const osp::vec3f dir_00 = cameraDir - .5f * dir_du - .5f * dir_dv;
for (size_t j = 0; j < glDepthBufferHeight; j++)
{
for (size_t i = 0; i < glDepthBufferWidth; i++)
{
const osp::vec3f dir_ij =
normalize(dir_00 + float(i) / float(glDepthBufferWidth - 1) * dir_du +
float(j) / float(glDepthBufferHeight - 1) * dir_dv);
const float t = ospDepthBuffer[j * glDepthBufferWidth + i] / dot(cameraDir, dir_ij);
ospDepthBuffer[j * glDepthBufferWidth + i] = t;
}
}
// nearest texture filtering required for depth textures -- we don't want interpolation of depth
// values...
osp::vec2i texSize = { static_cast<int>(glDepthBufferWidth),
static_cast<int>(glDepthBufferHeight) };
OSPTexture depthTexture = vtkOSPRayMaterialHelpers::NewTexture2D(
backend, (osp::vec2i&)texSize, OSP_TEXTURE_R32F, ospDepthBuffer, OSP_TEXTURE_FILTER_NEAREST);
return depthTexture;
}
}
}
vtkInformationKeyMacro(vtkOSPRayRendererNode, SAMPLES_PER_PIXEL, Integer);
vtkInformationKeyMacro(vtkOSPRayRendererNode, MAX_CONTRIBUTION, Double);
vtkInformationKeyMacro(vtkOSPRayRendererNode, MAX_DEPTH, Integer);
vtkInformationKeyMacro(vtkOSPRayRendererNode, MIN_CONTRIBUTION, Double);
vtkInformationKeyMacro(vtkOSPRayRendererNode, ROULETTE_DEPTH, Integer);
vtkInformationKeyMacro(vtkOSPRayRendererNode, VOLUME_ANISOTROPY, Double);
vtkInformationKeyMacro(vtkOSPRayRendererNode, VARIANCE_THRESHOLD, Double);
vtkInformationKeyMacro(vtkOSPRayRendererNode, MAX_FRAMES, Integer);
vtkInformationKeyMacro(vtkOSPRayRendererNode, AMBIENT_SAMPLES, Integer);
vtkInformationKeyMacro(vtkOSPRayRendererNode, COMPOSITE_ON_GL, Integer);
vtkInformationKeyMacro(vtkOSPRayRendererNode, RENDERER_TYPE, String);
vtkInformationKeyMacro(vtkOSPRayRendererNode, NORTH_POLE, DoubleVector);
vtkInformationKeyMacro(vtkOSPRayRendererNode, EAST_POLE, DoubleVector);
vtkInformationKeyMacro(vtkOSPRayRendererNode, MATERIAL_LIBRARY, ObjectBase);
vtkInformationKeyMacro(vtkOSPRayRendererNode, VIEW_TIME, Double);
vtkInformationKeyMacro(vtkOSPRayRendererNode, TIME_CACHE_SIZE, Integer);
vtkInformationKeyMacro(vtkOSPRayRendererNode, DENOISER_THRESHOLD, Integer);
vtkInformationKeyMacro(vtkOSPRayRendererNode, ENABLE_DENOISER, Integer);
vtkInformationKeyMacro(vtkOSPRayRendererNode, BACKGROUND_MODE, Integer);
class vtkOSPRayRendererNodeInternals
{
// todo: move the rest of the internal data here too
public:
vtkOSPRayRendererNodeInternals(vtkOSPRayRendererNode* _owner)
: Owner(_owner){};
~vtkOSPRayRendererNodeInternals() = default;
bool CanReuseBG(bool forbackplate)
{
bool retval = true;
int index = (forbackplate ? 0 : 1);
vtkRenderer* ren = vtkRenderer::SafeDownCast(this->Owner->GetRenderable());
bool useTexture =
(forbackplate ? ren->GetTexturedBackground() : ren->GetUseImageBasedLighting());
if (this->lUseTexture[index] != useTexture)
{
this->lUseTexture[index] = useTexture;
retval = false;
}
vtkTexture* envTexture =
(forbackplate ? ren->GetBackgroundTexture() : ren->GetEnvironmentTexture());
vtkMTimeType envTextureTime = 0;
if (envTexture)
{
envTextureTime = envTexture->GetMTime();
}
if (this->lTexture[index] != envTexture || envTextureTime > this->lTextureTime[index])
{
this->lTexture[index] = envTexture;
this->lTextureTime[index] = envTextureTime;
retval = false;
}
bool useGradient =
(forbackplate ? ren->GetGradientBackground() : ren->GetGradientEnvironmentalBG());
if (this->lUseGradient[index] != useGradient)
{
this->lUseGradient[index] = useGradient;
retval = false;
}
double* color1 = (forbackplate ? ren->GetBackground() : ren->GetEnvironmentalBG());
double* color2 = (forbackplate ? ren->GetBackground2() : ren->GetEnvironmentalBG2());
if (this->lColor1[index][0] != color1[0] || this->lColor1[index][1] != color1[1] ||
this->lColor1[index][2] != color1[2] || this->lColor2[index][0] != color2[0] ||
this->lColor2[index][1] != color2[1] || this->lColor2[index][2] != color2[2])
{
this->lColor1[index][0] = color1[0];
this->lColor1[index][1] = color1[1];
this->lColor1[index][2] = color1[2];
this->lColor2[index][0] = color2[0];
this->lColor2[index][1] = color2[1];
this->lColor2[index][2] = color2[2];
retval = false;
}
if (!forbackplate)
{
double* up = vtkOSPRayRendererNode::GetNorthPole(ren);
if (!up)
{
up = ren->GetEnvironmentUp();
}
if (this->lup[0] != up[0] || this->lup[1] != up[1] || this->lup[2] != up[2])
{
this->lup[0] = up[0];
this->lup[1] = up[1];
this->lup[2] = up[2];
retval = false;
}
double* east = vtkOSPRayRendererNode::GetEastPole(ren);
if (!east)
{
east = ren->GetEnvironmentRight();
}
if (this->least[0] != east[0] || this->least[1] != east[1] || this->least[2] != east[2])
{
this->least[0] = east[0];
this->least[1] = east[1];
this->least[2] = east[2];
retval = false;
}
}
return retval;
}
bool SetupPathTraceBackground(bool forbackplate, RTW::Backend* backend)
{
vtkRenderer* ren = vtkRenderer::SafeDownCast(this->Owner->GetRenderable());
int bgMode = vtkOSPRayRendererNode::GetBackgroundMode(ren);
bool forpathtracer = true;
if (std::string(this->Owner->GetRendererType(ren)).find(std::string("pathtracer")) ==
std::string::npos)
{
forpathtracer = false;
}
if (!forpathtracer)
{
// scivis is backplate only
if (!forbackplate)
{
return true;
}
bgMode = 0x1; // ignore user setting
}
OSPTexture t2d = nullptr;
bool reuseable = this->CanReuseBG(forbackplate) && (bgMode == this->lBackgroundMode);
if (!reuseable)
{
vtkTexture* text =
(forbackplate ? ren->GetBackgroundTexture() : ren->GetEnvironmentTexture());
if (text && (forbackplate ? ren->GetTexturedBackground() : ren->GetUseImageBasedLighting()))
{
// user provided 2D background texture
vtkImageData* vColorTextureMap = text->GetInput();
// todo: if the imageData is empty, we should download the texture from the GPU
if (vColorTextureMap)
{
t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(
backend, vColorTextureMap, text->GetUseSRGBColorSpace());
}
}
double bgAlpha = ren->GetBackgroundAlpha();
if (t2d == nullptr)
{
// simple color or gradient
std::vector<unsigned char> ochars;
double bg1[3];
if (forbackplate)
{
ren->GetBackground(bg1);
}
else
{
ren->GetEnvironmentalBG(bg1);
bgAlpha = 1.0;
}
if (forpathtracer)
{
for (int i = 0; i < 3; i++)
{
// the final image is gamma corrected so the background has to be converted to linear
// color space
bg1[i] = pow(bg1[i], 2.2);
}
}
int isize = 1;
int jsize = 1;
if (forbackplate ? ren->GetGradientBackground() : ren->GetGradientEnvironmentalBG())
{
double bg2[3];
if (forbackplate)
{
ren->GetBackground2(bg2);
}
else
{
ren->GetEnvironmentalBG2(bg2);
}
if (forpathtracer)
{
for (int i = 0; i < 3; i++)
{
bg2[i] = pow(bg2[i], 2.2);
}
}
isize = 256; // todo: configurable
jsize = 2;
ochars.resize(isize * jsize * 4);
unsigned char* oc = ochars.data();
for (int i = 0; i < isize; i++)
{
double frac = i / static_cast<double>(isize - 1);
*(oc + 0) = (bg1[0] * (1.0 - frac) + bg2[0] * frac) * 255;
*(oc + 1) = (bg1[1] * (1.0 - frac) + bg2[1] * frac) * 255;
*(oc + 2) = (bg1[2] * (1.0 - frac) + bg2[2] * frac) * 255;
*(oc + 3) = bgAlpha * 255;
*(oc + 4) = *(oc + 0);
*(oc + 5) = *(oc + 1);
*(oc + 6) = *(oc + 2);
*(oc + 7) = *(oc + 3);
oc += 8;
}
}
else
{
ochars.resize(4);
ochars[0] = bg1[0] * 255;
ochars[1] = bg1[1] * 255;
ochars[2] = bg1[2] * 255;
ochars[3] = bgAlpha * 255;
}
t2d = vtkOSPRayMaterialHelpers::NewTexture2D(backend, osp::vec2i{ jsize, isize },
(forpathtracer ? OSP_TEXTURE_SRGBA : OSP_TEXTURE_RGBA8), ochars.data(), 0);
}
// now apply the texture we chose above to the right place
if (forbackplate)
{
if (bgMode & 0x1)
{
ospSetObject(this->Owner->GetORenderer(), "map_backplate", t2d);
}
else
{
ospSetObject(this->Owner->GetORenderer(), "map_backplate", nullptr);
}
}
else
{
OSPLight ospLight = ospNewLight("hdri");
ospSetObject(ospLight, "map", t2d);
double* up = vtkOSPRayRendererNode::GetNorthPole(ren);
if (!up)
{
up = ren->GetEnvironmentUp();
}
ospSetVec3f(ospLight, "up", (float)up[0], (float)up[1], (float)up[2]);
double* east = vtkOSPRayRendererNode::GetEastPole(ren);
if (!east)
{
east = ren->GetEnvironmentRight();
}
ospSetVec3f(ospLight, "direction", (float)east[0], (float)east[1], (float)east[2]);
if (bgMode == 0x2)
{
ospSetInt(ospLight, "visible", 1);
}
else
{
ospSetInt(ospLight, "visible", 0); // prevents blending onto backplate in "both" mode
}
ospCommit(ospLight);
this->BGLight = ospLight;
}
} //! reusable
if (!forbackplate && (bgMode & 0x2))
{
this->Owner->AddLight(this->BGLight); // lights cleared every frame, so always add
}
return reuseable;
}
std::map<vtkProp3D*, vtkAbstractMapper3D*> LastMapperFor;
vtkOSPRayRendererNode* Owner;
int lBackgroundMode = 0;
double lColor1[2][3] = { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } };
bool lUseGradient[2] = { false, false };
double lColor2[2][3] = { { 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } };
bool lUseTexture[2] = { false, false };
vtkWeakPointer<vtkTexture> lTexture[2] = { nullptr, nullptr };
vtkMTimeType lTextureTime[2] = { 0, 0 };
double lup[3];
double least[3];
double LastViewPort[2];
double LastParallelScale = 0.0;
double LastFocalDisk = -1.0;
double LastFocalDistance = -1.0;
double LastDTime = 0.0;
OSPLight BGLight{ nullptr };
RTW::Backend* Backend = nullptr;
};
//============================================================================
vtkStandardNewMacro(vtkOSPRayRendererNode);
//------------------------------------------------------------------------------
vtkOSPRayRendererNode::vtkOSPRayRendererNode()
{
this->ColorBufferTex = 0;
this->DepthBufferTex = 0;
this->OWorld = nullptr;
this->ORenderer = nullptr;
this->NumActors = 0;
this->ComputeDepth = true;
this->OFrameBuffer = nullptr;
this->ImageX = this->ImageY = -1;
this->CompositeOnGL = false;
this->Accumulate = true;
this->AccumulateCount = 0;
this->ActorCount = 0;
this->AccumulateTime = 0;
this->AccumulateMatrix = vtkMatrix4x4::New();
this->Internal = new vtkOSPRayRendererNodeInternals(this);
this->PreviousType = "none";
this->Cache = new vtkOSPRayCache<vtkOSPRayCacheItemObject>;
#ifdef VTKOSPRAY_ENABLE_DENOISER
this->DenoiserDevice = oidn::newDevice();
this->DenoiserDevice.commit();
this->DenoiserFilter = this->DenoiserDevice.newFilter("RT");
#endif
}
//------------------------------------------------------------------------------
vtkOSPRayRendererNode::~vtkOSPRayRendererNode()
{
if (this->Internal->Backend != nullptr)
{
RTW::Backend* backend = this->Internal->Backend;
// DDM NO ospRelease(this->OWorld);
ospRelease(this->ORenderer);
ospRelease(this->OFrameBuffer);
// DDM NO ospRelease(this->OCamera);
}
this->AccumulateMatrix->Delete();
delete this->Internal;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetSamplesPerPixel(int value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::SAMPLES_PER_PIXEL(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetSamplesPerPixel(vtkRenderer* renderer)
{
if (!renderer)
{
return 1;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::SAMPLES_PER_PIXEL()))
{
return (info->Get(vtkOSPRayRendererNode::SAMPLES_PER_PIXEL()));
}
return 1;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetMaxContribution(double value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::MAX_CONTRIBUTION(), value);
}
//------------------------------------------------------------------------------
double vtkOSPRayRendererNode::GetMaxContribution(vtkRenderer* renderer)
{
constexpr double DEFAULT_MAX_CONTRIBUTION = 2.0;
if (!renderer)
{
return DEFAULT_MAX_CONTRIBUTION;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::MAX_CONTRIBUTION()))
{
return (info->Get(vtkOSPRayRendererNode::MAX_CONTRIBUTION()));
}
return DEFAULT_MAX_CONTRIBUTION;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetMaxDepth(int value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::MAX_DEPTH(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetMaxDepth(vtkRenderer* renderer)
{
constexpr int DEFAULT_MAX_DEPTH = 20;
if (!renderer)
{
return DEFAULT_MAX_DEPTH;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::MAX_DEPTH()))
{
return (info->Get(vtkOSPRayRendererNode::MAX_DEPTH()));
}
return DEFAULT_MAX_DEPTH;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetMinContribution(double value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::MIN_CONTRIBUTION(), value);
}
//------------------------------------------------------------------------------
double vtkOSPRayRendererNode::GetMinContribution(vtkRenderer* renderer)
{
constexpr double DEFAULT_MIN_CONTRIBUTION = 0.01;
if (!renderer)
{
return DEFAULT_MIN_CONTRIBUTION;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::MIN_CONTRIBUTION()))
{
return (info->Get(vtkOSPRayRendererNode::MIN_CONTRIBUTION()));
}
return DEFAULT_MIN_CONTRIBUTION;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetRouletteDepth(int value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::ROULETTE_DEPTH(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetRouletteDepth(vtkRenderer* renderer)
{
constexpr int DEFAULT_ROULETTE_DEPTH = 5;
if (!renderer)
{
return DEFAULT_ROULETTE_DEPTH;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::ROULETTE_DEPTH()))
{
return (info->Get(vtkOSPRayRendererNode::ROULETTE_DEPTH()));
}
return DEFAULT_ROULETTE_DEPTH;
}
//----------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetVolumeAnisotropy(double value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::VOLUME_ANISOTROPY(), value);
}
//----------------------------------------------------------------------------
double vtkOSPRayRendererNode::GetVolumeAnisotropy(vtkRenderer* renderer)
{
constexpr double DEFAULT_VOLUME_ANISOTROPY = 0.0;
if (!renderer)
{
return DEFAULT_VOLUME_ANISOTROPY;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::VOLUME_ANISOTROPY()))
{
return (info->Get(vtkOSPRayRendererNode::VOLUME_ANISOTROPY()));
}
return DEFAULT_VOLUME_ANISOTROPY;
}
//----------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetVarianceThreshold(double value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::VARIANCE_THRESHOLD(), value);
}
//------------------------------------------------------------------------------
double vtkOSPRayRendererNode::GetVarianceThreshold(vtkRenderer* renderer)
{
constexpr double DEFAULT_VARIANCE_THRESHOLD = 0.3;
if (!renderer)
{
return DEFAULT_VARIANCE_THRESHOLD;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::VARIANCE_THRESHOLD()))
{
return (info->Get(vtkOSPRayRendererNode::VARIANCE_THRESHOLD()));
}
return DEFAULT_VARIANCE_THRESHOLD;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetMaterialLibrary(
vtkOSPRayMaterialLibrary* value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::MATERIAL_LIBRARY(), value);
}
//------------------------------------------------------------------------------
vtkOSPRayMaterialLibrary* vtkOSPRayRendererNode::GetMaterialLibrary(vtkRenderer* renderer)
{
if (!renderer)
{
return nullptr;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::MATERIAL_LIBRARY()))
{
vtkObjectBase* obj = info->Get(vtkOSPRayRendererNode::MATERIAL_LIBRARY());
return (vtkOSPRayMaterialLibrary::SafeDownCast(obj));
}
return nullptr;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetMaxFrames(int value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::MAX_FRAMES(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetMaxFrames(vtkRenderer* renderer)
{
if (!renderer)
{
return 1;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::MAX_FRAMES()))
{
return (info->Get(vtkOSPRayRendererNode::MAX_FRAMES()));
}
return 1;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetRendererType(std::string name, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
#ifdef VTK_ENABLE_OSPRAY
if ("scivis" == name || "OSPRay raycaster" == name)
{
info->Set(vtkOSPRayRendererNode::RENDERER_TYPE(), "scivis");
}
if ("pathtracer" == name || "OSPRay pathtracer" == name)
{
info->Set(vtkOSPRayRendererNode::RENDERER_TYPE(), "pathtracer");
}
#endif
#ifdef VTK_ENABLE_VISRTX
if ("optix pathtracer" == name || "OptiX pathtracer" == name)
{
info->Set(vtkOSPRayRendererNode::RENDERER_TYPE(), "optix pathtracer");
}
#endif
}
//------------------------------------------------------------------------------
std::string vtkOSPRayRendererNode::GetRendererType(vtkRenderer* renderer)
{
if (!renderer)
{
#ifdef VTK_ENABLE_OSPRAY
return std::string("scivis");
#else
return std::string("optix pathtracer");
#endif
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::RENDERER_TYPE()))
{
return (info->Get(vtkOSPRayRendererNode::RENDERER_TYPE()));
}
#ifdef VTK_ENABLE_OSPRAY
return std::string("scivis");
#else
return std::string("optix pathtracer");
#endif
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetAmbientSamples(int value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::AMBIENT_SAMPLES(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetAmbientSamples(vtkRenderer* renderer)
{
if (!renderer)
{
return 0;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::AMBIENT_SAMPLES()))
{
return (info->Get(vtkOSPRayRendererNode::AMBIENT_SAMPLES()));
}
return 0;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetCompositeOnGL(int value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::COMPOSITE_ON_GL(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetCompositeOnGL(vtkRenderer* renderer)
{
if (!renderer)
{
return 0;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::COMPOSITE_ON_GL()))
{
return (info->Get(vtkOSPRayRendererNode::COMPOSITE_ON_GL()));
}
return 0;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetNorthPole(double* value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::NORTH_POLE(), value, 3);
}
//------------------------------------------------------------------------------
double* vtkOSPRayRendererNode::GetNorthPole(vtkRenderer* renderer)
{
if (!renderer)
{
return nullptr;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::NORTH_POLE()))
{
return (info->Get(vtkOSPRayRendererNode::NORTH_POLE()));
}
return nullptr;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetEastPole(double* value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::EAST_POLE(), value, 3);
}
//------------------------------------------------------------------------------
double* vtkOSPRayRendererNode::GetEastPole(vtkRenderer* renderer)
{
if (!renderer)
{
return nullptr;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::EAST_POLE()))
{
return (info->Get(vtkOSPRayRendererNode::EAST_POLE()));
}
return nullptr;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetViewTime(double value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::VIEW_TIME(), value);
}
//------------------------------------------------------------------------------
double vtkOSPRayRendererNode::GetViewTime(vtkRenderer* renderer)
{
if (!renderer)
{
return 0;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::VIEW_TIME()))
{
return (info->Get(vtkOSPRayRendererNode::VIEW_TIME()));
}
return 0;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetTimeCacheSize(int value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::TIME_CACHE_SIZE(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetTimeCacheSize(vtkRenderer* renderer)
{
if (!renderer)
{
return 0;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::TIME_CACHE_SIZE()))
{
return (info->Get(vtkOSPRayRendererNode::TIME_CACHE_SIZE()));
}
return 0;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetDenoiserThreshold(int value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::DENOISER_THRESHOLD(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetDenoiserThreshold(vtkRenderer* renderer)
{
if (!renderer)
{
return 4;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::DENOISER_THRESHOLD()))
{
return (info->Get(vtkOSPRayRendererNode::DENOISER_THRESHOLD()));
}
return 4;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetEnableDenoiser(int value, vtkRenderer* renderer)
{
if (!renderer)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::ENABLE_DENOISER(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetEnableDenoiser(vtkRenderer* renderer)
{
if (!renderer)
{
return 0;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::ENABLE_DENOISER()))
{
return (info->Get(vtkOSPRayRendererNode::ENABLE_DENOISER()));
}
return 0;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::SetBackgroundMode(int value, vtkRenderer* renderer)
{
if (!renderer || value < 0 || value > 3)
{
return;
}
vtkInformation* info = renderer->GetInformation();
info->Set(vtkOSPRayRendererNode::BACKGROUND_MODE(), value);
}
//------------------------------------------------------------------------------
int vtkOSPRayRendererNode::GetBackgroundMode(vtkRenderer* renderer)
{
if (!renderer)
{
return 2;
}
vtkInformation* info = renderer->GetInformation();
if (info && info->Has(vtkOSPRayRendererNode::BACKGROUND_MODE()))
{
return (info->Get(vtkOSPRayRendererNode::BACKGROUND_MODE()));
}
return 2;
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::Traverse(int operation)
{
vtkRenderer* ren = vtkRenderer::SafeDownCast(this->GetRenderable());
if (!ren)
{
return;
}
// do not override other passes
if (operation != render)
{
this->Superclass::Traverse(operation);
return;
}
this->Apply(operation, true);
// camera
// TODO: this repeated traversal to find things of particular types
// is bad, find something smarter
auto const& nodes = this->GetChildren();
for (auto node : nodes)
{
vtkOSPRayCameraNode* child = vtkOSPRayCameraNode::SafeDownCast(node);
if (child)
{
child->Traverse(operation);
this->OCamera = child->GetOCamera();
break;
}
}
RTW::Backend* backend = this->Internal->Backend;
if (backend == nullptr)
{
return;
}
// lights
this->Lights.clear();
bool hasAmbient = false;
for (auto node : nodes)
{
vtkOSPRayLightNode* child = vtkOSPRayLightNode::SafeDownCast(node);
if (child)
{
child->Traverse(operation);
if (child->GetIsAmbient(vtkLight::SafeDownCast(child->GetRenderable())))
{
hasAmbient = true;
}
}
}
if (!hasAmbient && (this->GetAmbientSamples(static_cast<vtkRenderer*>(this->Renderable)) > 0))
{
// hardcode an ambient light for AO since OSP 1.2 stopped doing so.
OSPLight ospAmbient = ospNewLight("ambient");
ospSetString(ospAmbient, "name", "default_ambient");
ospSetVec3f(ospAmbient, "color", 1.f, 1.f, 1.f);
ospSetFloat(
ospAmbient, "intensity", 0.13f * vtkOSPRayLightNode::GetLightScale() * vtkMath::Pi());
ospCommit(ospAmbient);
this->Lights.push_back(ospAmbient);
}
bool bpreused = this->Internal->SetupPathTraceBackground(true, backend);
bool envreused = this->Internal->SetupPathTraceBackground(false, backend);
this->Internal->lBackgroundMode = vtkOSPRayRendererNode::GetBackgroundMode(
static_cast<vtkRenderer*>(this->Renderable)); // save it only once both of the above check
bool bgreused = envreused && bpreused;
// skip every actor/volume when caching is on
double tstep = vtkOSPRayRendererNode::GetViewTime(ren);
bool tCacheHit = this->Cache->Contains(tstep);
// actors
// since we have to spatially sort everything
// let's see if we can avoid that in the common case when
// the objects have not changed. Note we also cache in actornodes
// to reuse already created ospray meshes
vtkMTimeType recent = 0;
int numAct = 0; // catches removed actors
for (auto node : nodes)
{
vtkOSPRayActorNode* child = vtkOSPRayActorNode::SafeDownCast(node);
vtkOSPRayVolumeNode* vchild = vtkOSPRayVolumeNode::SafeDownCast(node);
if (child)
{
numAct++;
recent = std::max(recent, child->GetMTime());
}
if (vchild)
{
numAct++;
recent = std::max(recent, vchild->GetMTime());
}
}
bool enable_cache = true; // turn off to force rebuilds for debugging
if (!tCacheHit && (!enable_cache || (recent > this->RenderTime) || (numAct != this->NumActors)))
{
this->Instances.clear();
this->NumActors = numAct;
for (auto node : nodes)
{
vtkOSPRayActorNode* child = vtkOSPRayActorNode::SafeDownCast(node);
if (child)
{
child->Traverse(operation);
}
vtkOSPRayVolumeNode* vchild = vtkOSPRayVolumeNode::SafeDownCast(node);
if (vchild)
{
vchild->Traverse(operation);
}
}
this->RenderTime = recent;
}
if (!bgreused)
{
// hack to ensure progressive rendering resets when background changes
this->AccumulateTime = 0;
}
this->Apply(operation, false);
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::Invalidate(bool prepass)
{
if (prepass)
{
this->RenderTime = 0;
}
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::Build(bool prepass)
{
if (prepass)
{
vtkRenderer* aren = vtkRenderer::SafeDownCast(this->Renderable);
// make sure we have a camera
if (!aren->IsActiveCameraCreated())
{
aren->ResetCamera();
}
}
this->Superclass::Build(prepass);
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::Render(bool prepass)
{
vtkRenderer* ren = vtkRenderer::SafeDownCast(this->GetRenderable());
if (!ren)
{
return;
}
RTW::Backend* backend = this->Internal->Backend;
if (prepass)
{
OSPRenderer oRenderer = nullptr;
std::string type = this->GetRendererType(static_cast<vtkRenderer*>(this->Renderable));
if (!this->ORenderer || this->PreviousType != type)
{
this->Traverse(invalidate);
this->Internal->Backend = rtwSwitch(type.c_str());
if (this->Internal->Backend == nullptr)
{
return;
}
backend = this->Internal->Backend;
oRenderer = ospNewRenderer(type.c_str());
this->ORenderer = oRenderer;
this->PreviousType = type;
}
else
{
oRenderer = this->ORenderer;
}
ospSetFloat(this->ORenderer, "maxContribution", this->GetMaxContribution(ren));
ospSetFloat(this->ORenderer, "minContribution", this->GetMinContribution(ren));
ospSetFloat(this->ORenderer, "maxPathLength", this->GetMaxDepth(ren));
ospSetFloat(this->ORenderer, "rouletteDepth", this->GetRouletteDepth(ren));
ospSetFloat(this->ORenderer, "varianceThreshold", this->GetVarianceThreshold(ren));
// ospSetInt(oRenderer, "geometryLights", 0); //avoid a crash in ospray 2.1.0
ospCommit(this->ORenderer);
if (ren->GetUseShadows())
{
ospSetInt(oRenderer, "shadowsEnabled", 1);
}
else
{
ospSetInt(oRenderer, "shadowsEnabled", 0);
}
// todo: this can be expensive and should be cached
// also the user might want to control
vtkBoundingBox bbox(ren->ComputeVisiblePropBounds());
if (bbox.IsValid())
{
float diam = static_cast<float>(bbox.GetDiagonalLength());
float logDiam = log(diam);
if (logDiam < 0.f)
{
logDiam = 1.f / (fabs(logDiam));
}
float epsilon = 1e-5 * logDiam;
ospSetFloat(oRenderer, "epsilon", epsilon);
ospSetFloat(oRenderer, "aoDistance", diam * 0.3);
ospSetInt(oRenderer, "autoEpsilon", 0);
}
else
{
ospSetFloat(oRenderer, "epsilon", 0.001f);
}
vtkVolumeCollection* vc = ren->GetVolumes();
if (vc->GetNumberOfItems())
{
ospSetInt(oRenderer, "aoTransparencyEnabled", 1);
}
ospSetInt(oRenderer, "aoSamples", this->GetAmbientSamples(ren));
ospSetInt(oRenderer, "pixelSamples", this->GetSamplesPerPixel(ren));
this->CompositeOnGL = (this->GetCompositeOnGL(ren) != 0);
}
else
{
this->Cache->SetSize(vtkOSPRayRendererNode::GetTimeCacheSize(ren));
double tstep = vtkOSPRayRendererNode::GetViewTime(ren);
auto cached = this->Cache->Get(tstep);
if (cached)
{
this->OWorld = static_cast<OSPWorld>(cached->object);
}
else
{
this->OWorld = ospNewWorld();
// put the model into a group (collection of models)
if (this->Instances.size())
{
if (this->Lights.size())
{
auto data = ospNewSharedData1D(
this->Lights.data(), OSP_LIGHT, static_cast<uint32_t>(this->Lights.size()));
ospCommit(data);
ospSetObject(this->OWorld, "light", data);
ospRelease(data);
}
auto instanceData = ospNewSharedData1D(
this->Instances.data(), OSP_INSTANCE, static_cast<uint32_t>(this->Instances.size()));
ospCommit(instanceData);
ospSetObject(this->OWorld, "instance", instanceData);
ospRelease(instanceData);
this->OInstanceData = instanceData;
}
else
{
ospRemoveParam(this->OWorld, "instance");
}
ospCommit(this->OWorld);
if (this->Cache->HasRoom())
{
auto cacheEntry = std::make_shared<vtkOSPRayCacheItemObject>(backend, this->OWorld);
this->Cache->Set(tstep, std::move(cacheEntry));
}
}
OSPRenderer oRenderer = this->ORenderer;
ospCommit(oRenderer);
osp::vec2i isize = { this->Size[0], this->Size[1] };
if (this->ImageX != this->Size[0] || this->ImageY != this->Size[1])
{
this->ImageX = this->Size[0];
this->ImageY = this->Size[1];
const size_t size = this->ImageX * this->ImageY;
ospRelease(this->OFrameBuffer);
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wextra"
#endif
this->OFrameBuffer = ospNewFrameBuffer(isize, OSP_FB_RGBA32F,
OSP_FB_COLOR | (this->ComputeDepth ? OSP_FB_DEPTH : 0) |
(this->Accumulate ? OSP_FB_ACCUM : 0)
#ifdef VTKOSPRAY_ENABLE_DENOISER
| OSP_FB_NORMAL | OSP_FB_ALBEDO
#endif
);
this->DenoisedBuffer.resize(size);
this->ColorBuffer.resize(size);
this->NormalBuffer.resize(size);
this->AlbedoBuffer.resize(size);
this->DenoiserDirty = true;
ospSetFloat(this->OFrameBuffer, "gamma", 1.0f);
ospCommit(this->OFrameBuffer);
ospFrameBufferClear(this->OFrameBuffer);
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
this->Buffer.resize(this->Size[0] * this->Size[1] * 4);
this->ZBuffer.resize(this->Size[0] * this->Size[1]);
if (this->CompositeOnGL)
{
this->ODepthBuffer.resize(this->Size[0] * this->Size[1]);
}
}
else if (this->Accumulate)
{
// check if something has changed
// if so we clear and start over, otherwise we continue to accumulate
bool canReuse = true;
// TODO: these all need some work as checks are not necessarily fast
// nor sufficient for all cases that matter
// check for stereo and disable so don't get left in right
vtkRenderWindow* rwin = vtkRenderWindow::SafeDownCast(ren->GetVTKWindow());
if (rwin && rwin->GetStereoRender())
{
canReuse = false;
}
double dtime = vtkOSPRayRendererNode::GetViewTime(ren);
if (this->Internal->LastDTime != dtime)
{
this->Internal->LastDTime = dtime;
canReuse = false;
}
// check for tiling, ie typically putting together large images to save high res pictures
double* vp = rwin->GetTileViewport();
if (this->Internal->LastViewPort[0] != vp[0] || this->Internal->LastViewPort[1] != vp[1])
{
canReuse = false;
this->Internal->LastViewPort[0] = vp[0];
this->Internal->LastViewPort[1] = vp[1];
}
// check actors (and time)
vtkMTimeType m = 0;
vtkActorCollection* ac = ren->GetActors();
int nitems = ac->GetNumberOfItems();
if (nitems != this->ActorCount)
{
// TODO: need a hash or something to really check for added/deleted
this->ActorCount = nitems;
this->AccumulateCount = 0;
canReuse = false;
}
if (canReuse)
{
ac->InitTraversal();
vtkActor* nac = ac->GetNextActor();
while (nac)
{
if (nac->GetRedrawMTime() > m)
{
m = nac->GetRedrawMTime();
}
if (this->Internal->LastMapperFor[nac] != nac->GetMapper())
{
// a check to ensure vtkPVLODActor restarts on LOD swap
this->Internal->LastMapperFor[nac] = nac->GetMapper();
canReuse = false;
}
nac = ac->GetNextActor();
}
if (this->AccumulateTime < m)
{
this->AccumulateTime = m;
canReuse = false;
}
}
if (canReuse)
{
m = 0;
vtkVolumeCollection* vc = ren->GetVolumes();
vc->InitTraversal();
vtkVolume* nvol = vc->GetNextVolume();
while (nvol)
{
if (nvol->GetRedrawMTime() > m)
{
m = nvol->GetRedrawMTime();
}
if (this->Internal->LastMapperFor[nvol] != nvol->GetMapper())
{
// a check to ensure vtkPVLODActor restarts on LOD swap
this->Internal->LastMapperFor[nvol] = nvol->GetMapper();
canReuse = false;
}
nvol = vc->GetNextVolume();
};
if (this->AccumulateTime < m)
{
this->AccumulateTime = m;
canReuse = false;
}
}
if (canReuse)
{
// check camera
// Why not cam->mtime?
// cam->mtime is bumped by synch after this in parallel so never reuses
// Why not cam->MVTO->mtime?
// cam set's elements directly, so the mtime doesn't bump with motion
vtkMatrix4x4* camnow = ren->GetActiveCamera()->GetModelViewTransformObject()->GetMatrix();
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (this->AccumulateMatrix->GetElement(i, j) != camnow->GetElement(i, j))
{
this->AccumulateMatrix->DeepCopy(camnow);
canReuse = false;
i = 4;
j = 4;
}
}
}
if (this->Internal->LastParallelScale != ren->GetActiveCamera()->GetParallelScale())
{
this->Internal->LastParallelScale = ren->GetActiveCamera()->GetParallelScale();
canReuse = false;
}
if (this->Internal->LastFocalDisk != ren->GetActiveCamera()->GetFocalDisk())
{
this->Internal->LastFocalDisk = ren->GetActiveCamera()->GetFocalDisk();
canReuse = false;
}
if (this->Internal->LastFocalDistance != ren->GetActiveCamera()->GetFocalDistance())
{
this->Internal->LastFocalDistance = ren->GetActiveCamera()->GetFocalDistance();
canReuse = false;
}
}
if (!canReuse)
{
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wextra"
#endif
ospFrameBufferClear(this->OFrameBuffer);
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
this->AccumulateCount = 0;
}
}
else if (!this->Accumulate)
{
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wextra"
#endif
ospFrameBufferClear(this->OFrameBuffer);
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
}
vtkCamera* cam = vtkRenderer::SafeDownCast(this->Renderable)->GetActiveCamera();
ospSetInt(oRenderer, "backgroundEnabled", ren->GetErase());
if (this->CompositeOnGL && backend->IsSupported(RTW_DEPTH_COMPOSITING))
{
vtkRenderWindow* rwin = vtkRenderWindow::SafeDownCast(ren->GetVTKWindow());
int viewportX, viewportY;
int viewportWidth, viewportHeight;
ren->GetTiledSizeAndOrigin(&viewportWidth, &viewportHeight, &viewportX, &viewportY);
rwin->GetZbufferData(viewportX, viewportY, viewportX + viewportWidth - 1,
viewportY + viewportHeight - 1, this->GetZBuffer());
double zNear, zFar;
double fovy, aspect;
fovy = cam->GetViewAngle();
aspect = double(viewportWidth) / double(viewportHeight);
cam->GetClippingRange(zNear, zFar);
double camUp[3];
double camDir[3];
cam->GetViewUp(camUp);
cam->GetFocalPoint(camDir);
osp::vec3f cameraUp = { static_cast<float>(camUp[0]), static_cast<float>(camUp[1]),
static_cast<float>(camUp[2]) };
osp::vec3f cameraDir = { static_cast<float>(camDir[0]), static_cast<float>(camDir[1]),
static_cast<float>(camDir[2]) };
double cameraPos[3];
cam->GetPosition(cameraPos);
cameraDir.x -= cameraPos[0];
cameraDir.y -= cameraPos[1];
cameraDir.z -= cameraPos[2];
cameraDir = ospray::opengl::normalize(cameraDir);
OSPTexture glDepthTex = ospray::opengl::getOSPDepthTextureFromOpenGLPerspective(fovy, aspect,
zNear, zFar, (osp::vec3f&)cameraDir, (osp::vec3f&)cameraUp, this->GetZBuffer(),
this->ODepthBuffer.data(), viewportWidth, viewportHeight, this->Internal->Backend);
ospSetObject(oRenderer, "map_maxDepth", glDepthTex);
}
else
{
ospSetObject(oRenderer, "map_maxDepth", 0);
}
this->AccumulateCount += this->GetSamplesPerPixel(ren);
bool useDenoiser =
this->GetEnableDenoiser(ren) && (this->AccumulateCount >= this->GetDenoiserThreshold(ren));
ospSetInt(oRenderer, "denoise", useDenoiser ? 1 : 0);
ospCommit(oRenderer);
const bool backendDepthNormalization = backend->IsSupported(RTW_DEPTH_NORMALIZATION);
if (backendDepthNormalization)
{
const double* clipValues = cam->GetClippingRange();
const double clipMin = clipValues[0];
const double clipMax = clipValues[1];
backend->SetDepthNormalizationGL(this->OFrameBuffer, clipMin, clipMax);
}
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wextra"
#endif
ospRenderFrame(this->OFrameBuffer, oRenderer, this->OCamera, this->OWorld);
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
// release data used to store instances and clear world
ospRelease(this->OInstanceData);
this->OInstanceData = nullptr;
// DDM NO ospRelease(this->OWorld);
this->OWorld = nullptr;
// Check if backend can do direct OpenGL display using textures
bool useOpenGLInterop = backend->IsSupported(RTW_OPENGL_INTEROP);
// Only layer 0 can currently display using OpenGL
if (ren->GetLayer() != 0)
useOpenGLInterop = false;
if (useOpenGLInterop)
{
// Check if we actually have an OpenGL window
vtkRenderWindow* rwin = vtkRenderWindow::SafeDownCast(ren->GetVTKWindow());
vtkOpenGLRenderWindow* windowOpenGL = vtkOpenGLRenderWindow::SafeDownCast(rwin);
if (windowOpenGL != nullptr)
{
windowOpenGL->MakeCurrent();
this->ColorBufferTex = backend->GetColorTextureGL(this->OFrameBuffer);
this->DepthBufferTex = backend->GetDepthTextureGL(this->OFrameBuffer);
useOpenGLInterop = (this->ColorBufferTex != 0 && this->DepthBufferTex != 0);
}
else
{
useOpenGLInterop = false;
}
}
if (!useOpenGLInterop)
{
const void* rgba = ospMapFrameBuffer(this->OFrameBuffer, OSP_FB_COLOR);
#ifdef VTKOSPRAY_ENABLE_DENOISER
const osp::vec4f* rgba4f = reinterpret_cast<const osp::vec4f*>(rgba);
this->ColorBuffer.assign(rgba4f, rgba4f + this->Size[0] * this->Size[1]);
if (useDenoiser)
{
this->Denoise();
}
const float* color = reinterpret_cast<const float*>(this->ColorBuffer.data());
this->Buffer.assign(color, color + this->ImageX * this->ImageY * 4);
#else
const float* rgbaf = reinterpret_cast<const float*>(rgba);
this->Buffer.assign(rgbaf, rgbaf + this->Size[0] * this->Size[1] * 4);
#endif
ospUnmapFrameBuffer(rgba, this->OFrameBuffer);
if (this->ComputeDepth)
{
const float* Z =
reinterpret_cast<const float*>(ospMapFrameBuffer(this->OFrameBuffer, OSP_FB_DEPTH));
if (backendDepthNormalization)
{
this->ZBuffer.assign(Z, Z + this->Size[0] * this->Size[1]);
}
else
{
double* clipValues = cam->GetClippingRange();
double clipMin = clipValues[0];
double clipMax = clipValues[1];
double clipDiv = 1.0 / (clipMax - clipMin);
const float* s = Z;
float* d = this->ZBuffer.data();
for (int i = 0; i < (this->Size[0] * this->Size[1]); i++, s++, d++)
{
*d = (*s < clipMin ? 1.0 : (*s - clipMin) * clipDiv);
}
}
ospUnmapFrameBuffer(Z, this->OFrameBuffer);
}
}
}
}
void vtkOSPRayRendererNode::Denoise()
{
#ifdef VTKOSPRAY_ENABLE_DENOISER
RTW::Backend* backend = this->Internal->Backend;
this->DenoisedBuffer = this->ColorBuffer;
if (this->DenoiserDirty)
{
this->DenoiserFilter.setImage("color", (void*)this->ColorBuffer.data(), oidn::Format::Float3,
this->ImageX, this->ImageY, 0, sizeof(osp::vec4f));
this->DenoiserFilter.setImage("normal", (void*)this->NormalBuffer.data(), oidn::Format::Float3,
this->ImageX, this->ImageY, 0, sizeof(osp::vec3f));
this->DenoiserFilter.setImage("albedo", (void*)this->AlbedoBuffer.data(), oidn::Format::Float3,
this->ImageX, this->ImageY, 0, sizeof(osp::vec3f));
this->DenoiserFilter.setImage("output", (void*)this->DenoisedBuffer.data(),
oidn::Format::Float3, this->ImageX, this->ImageY, 0, sizeof(osp::vec4f));
this->DenoiserFilter.commit();
this->DenoiserDirty = false;
}
const auto size = this->ImageX * this->ImageY;
const osp::vec4f* rgba =
static_cast<const osp::vec4f*>(ospMapFrameBuffer(this->OFrameBuffer, OSP_FB_COLOR));
std::copy(rgba, rgba + size, this->ColorBuffer.begin());
ospUnmapFrameBuffer(rgba, this->OFrameBuffer);
const osp::vec3f* normal =
static_cast<const osp::vec3f*>(ospMapFrameBuffer(this->OFrameBuffer, OSP_FB_NORMAL));
std::copy(normal, normal + size, this->NormalBuffer.begin());
ospUnmapFrameBuffer(normal, this->OFrameBuffer);
const osp::vec3f* albedo =
static_cast<const osp::vec3f*>(ospMapFrameBuffer(this->OFrameBuffer, OSP_FB_ALBEDO));
std::copy(albedo, albedo + size, this->AlbedoBuffer.begin());
ospUnmapFrameBuffer(albedo, this->OFrameBuffer);
this->DenoiserFilter.execute();
// Carson: not sure we need two buffers
this->ColorBuffer = this->DenoisedBuffer;
#endif
}
//------------------------------------------------------------------------------
void vtkOSPRayRendererNode::WriteLayer(
unsigned char* buffer, float* Z, int buffx, int buffy, int layer)
{
if (layer == 0)
{
for (int j = 0; j < buffy && j < this->Size[1]; j++)
{
float* iptr = this->Buffer.data() + j * this->Size[0] * 4;
float* zptr = this->ZBuffer.data() + j * this->Size[0];
unsigned char* optr = buffer + j * buffx * 4;
float* ozptr = Z + j * buffx;
for (int i = 0; i < buffx && i < this->Size[0]; i++)
{
*optr++ = static_cast<unsigned char>(vtkMath::ClampValue(*iptr++, 0.f, 1.f) * 255.f);
*optr++ = static_cast<unsigned char>(vtkMath::ClampValue(*iptr++, 0.f, 1.f) * 255.f);
*optr++ = static_cast<unsigned char>(vtkMath::ClampValue(*iptr++, 0.f, 1.f) * 255.f);
*optr++ = static_cast<unsigned char>(vtkMath::ClampValue(*iptr++, 0.f, 1.f) * 255.f);
*ozptr++ = *zptr;
zptr++;
}
}
}
else
{
for (int j = 0; j < buffy && j < this->Size[1]; j++)
{
float* iptr = this->Buffer.data() + j * this->Size[0] * 4;
float* zptr = this->ZBuffer.data() + j * this->Size[0];
unsigned char* optr = buffer + j * buffx * 4;
float* ozptr = Z + j * buffx;
for (int i = 0; i < buffx && i < this->Size[0]; i++)
{
if (*zptr < 1.0)
{
if (this->CompositeOnGL)
{
// ospray is cooperating with GL (osprayvolumemapper)
float A = iptr[3];
for (int h = 0; h < 3; h++)
{
*optr = static_cast<unsigned char>(
(*iptr * 255.f) * (1 - A) + static_cast<float>(*optr) * (A));
optr++;
iptr++;
}
optr++;
iptr++;
}
else
{
// ospray owns all layers in window
*optr++ = static_cast<unsigned char>(vtkMath::ClampValue(*iptr++, 0.f, 1.f) * 255.f);
*optr++ = static_cast<unsigned char>(vtkMath::ClampValue(*iptr++, 0.f, 1.f) * 255.f);
*optr++ = static_cast<unsigned char>(vtkMath::ClampValue(*iptr++, 0.f, 1.f) * 255.f);
*optr++ = static_cast<unsigned char>(vtkMath::ClampValue(*iptr++, 0.f, 1.f) * 255.f);
}
*ozptr = *zptr;
}
else
{
optr += 4;
iptr += 4;
}
ozptr++;
zptr++;
}
}
}
}
//------------------------------------------------------------------------------
vtkRenderer* vtkOSPRayRendererNode::GetRenderer()
{
return vtkRenderer::SafeDownCast(this->GetRenderable());
}
//------------------------------------------------------------------------------
vtkOSPRayRendererNode* vtkOSPRayRendererNode::GetRendererNode(vtkViewNode* self)
{
return static_cast<vtkOSPRayRendererNode*>(self->GetFirstAncestorOfType("vtkOSPRayRendererNode"));
}
//------------------------------------------------------------------------------
RTW::Backend* vtkOSPRayRendererNode::GetBackend()
{
return this->Internal->Backend;
}
|
// Taken from the Boost.Function library
// Copyright Douglas Gregor 2001-2003.
// Copyright 2013 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Use, modification and
// distribution is subject to 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)
// For more information, see http://www.boost.org
// NOTE: Warning caused by assignment of pika::util::function_nonser<float()> to
// pika::util::function_nonser<double()> in test_emptiness. Triggered in
// pika/functional/function.hpp which is included latest by pika/include/util.hpp.
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdouble-promotion"
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdouble-promotion"
#endif
#include <pika/functional/function.hpp>
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#include <pika/modules/testing.hpp>
#include <functional>
#include <string>
#include <utility>
using std::string;
int global_int;
struct write_five_obj
{
void operator()() const
{
global_int = 5;
}
};
struct write_three_obj
{
int operator()() const
{
global_int = 3;
return 7;
}
};
static void write_five()
{
global_int = 5;
}
static void write_three()
{
global_int = 3;
}
struct generate_five_obj
{
int operator()() const
{
return 5;
}
};
struct generate_three_obj
{
int operator()() const
{
return 3;
}
};
static int generate_five()
{
return 5;
}
static int generate_three()
{
return 3;
}
static string identity_str(const string& s)
{
return s;
}
static string string_cat(const string& s1, const string& s2)
{
return s1 + s2;
}
static int sum_ints(int x, int y)
{
return x + y;
}
struct write_const_1_nonconst_2
{
void operator()()
{
global_int = 2;
}
void operator()() const
{
global_int = 1;
}
};
struct add_to_obj
{
add_to_obj(int v)
: value(v)
{
}
int operator()(int x) const
{
return value + x;
}
int value;
};
static void test_zero_args()
{
typedef pika::util::function_nonser<void()> func_void_type;
write_five_obj five;
write_three_obj three;
// Default construction
func_void_type v1;
PIKA_TEST(v1.empty());
// Assignment to an empty function
v1 = five;
PIKA_TEST(!v1.empty());
// Invocation of a function
global_int = 0;
v1();
PIKA_TEST_EQ(global_int, 5);
// reset() method
v1.reset();
PIKA_TEST(v1.empty());
// Assignment to an empty function
v1 = three;
PIKA_TEST(!v1.empty());
// Invocation and self-assignment
global_int = 0;
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wself-assign-overloaded"
#endif
v1 = v1;
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
v1();
PIKA_TEST_EQ(global_int, 3);
// Assignment to a non-empty function
v1 = five;
// Invocation and self-assignment
global_int = 0;
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wself-assign-overloaded"
#endif
v1 = (v1);
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
v1();
PIKA_TEST_EQ(global_int, 5);
// clear
void (*fpv1)() = 0; // NOLINT
v1 = fpv1;
PIKA_TEST(v1.empty());
v1 = write_five;
v1 = nullptr;
PIKA_TEST(v1.empty());
// Assignment to an empty function from a free function
v1 = write_five;
PIKA_TEST(!v1.empty());
// Invocation
global_int = 0;
v1();
PIKA_TEST_EQ(global_int, 5);
// Assignment to a non-empty function from a free function
v1 = write_three;
PIKA_TEST(!v1.empty());
// Invocation
global_int = 0;
v1();
PIKA_TEST_EQ(global_int, 3);
// Assignment
v1 = five;
PIKA_TEST(!v1.empty());
// Invocation
global_int = 0;
v1();
PIKA_TEST_EQ(global_int, 5);
// Assignment to a non-empty function from a free function
v1 = &write_three;
PIKA_TEST(!v1.empty());
// Invocation
global_int = 0;
v1();
PIKA_TEST_EQ(global_int, 3);
// Construction from another function (that is empty)
v1.reset();
func_void_type v2(v1);
PIKA_TEST(v2.empty());
// Assignment to an empty function
v2 = three;
PIKA_TEST(!v2.empty());
// Invocation
global_int = 0;
v2();
PIKA_TEST_EQ(global_int, 3);
// Assignment to a non-empty function
v2 = (five);
// Invocation
global_int = 0;
v2();
PIKA_TEST_EQ(global_int, 5);
v2.reset();
PIKA_TEST(v2.empty());
// Assignment to an empty function from a free function
v2 = (write_five);
PIKA_TEST(!v2.empty());
// Invocation
global_int = 0;
v2();
PIKA_TEST_EQ(global_int, 5);
// Assignment to a non-empty function from a free function
v2 = write_three;
PIKA_TEST(!v2.empty());
// Invocation
global_int = 0;
v2();
PIKA_TEST_EQ(global_int, 3);
// Swapping
v1 = five;
std::swap(v1, v2);
v2();
PIKA_TEST_EQ(global_int, 5);
v1();
PIKA_TEST_EQ(global_int, 3);
std::swap(v1, v2);
v1.reset();
// Assignment
v2 = five;
PIKA_TEST(!v2.empty());
// Invocation
global_int = 0;
v2();
PIKA_TEST_EQ(global_int, 5);
// Assignment to a non-empty function from a free function
v2 = &write_three;
PIKA_TEST(!v2.empty());
// Invocation
global_int = 0;
v2();
PIKA_TEST_EQ(global_int, 3);
// Assignment to a function from an empty function
v2 = v1;
PIKA_TEST(v2.empty());
// Assignment to a function from a function with a functor
v1 = three;
v2 = v1;
PIKA_TEST(!v1.empty());
PIKA_TEST(!v2.empty());
// Invocation
global_int = 0;
v1();
PIKA_TEST_EQ(global_int, 3);
global_int = 0;
v2();
PIKA_TEST_EQ(global_int, 3);
// Assign to a function from a function with a function
v2 = write_five;
v1 = v2;
PIKA_TEST(!v1.empty());
PIKA_TEST(!v2.empty());
global_int = 0;
v1();
PIKA_TEST_EQ(global_int, 5);
global_int = 0;
v2();
PIKA_TEST_EQ(global_int, 5);
// Construct a function given another function containing a function
func_void_type v3(v1);
// Invocation of a function
global_int = 0;
v3();
PIKA_TEST_EQ(global_int, 5);
// reset() method
v3.reset();
PIKA_TEST(!v3);
// Assignment to an empty function
v3 = three;
PIKA_TEST(!v3.empty());
// Invocation
global_int = 0;
v3();
PIKA_TEST_EQ(global_int, 3);
// Assignment to a non-empty function
v3 = five;
// Invocation
global_int = 0;
v3();
PIKA_TEST_EQ(global_int, 5);
// reset()
v3.reset();
PIKA_TEST(v3.empty());
// Assignment to an empty function from a free function
v3 = &write_five;
PIKA_TEST(!v3.empty());
// Invocation
global_int = 0;
v3();
PIKA_TEST_EQ(global_int, 5);
// Assignment to a non-empty function from a free function
v3 = &write_three;
PIKA_TEST(!v3.empty());
// Invocation
global_int = 0;
v3();
PIKA_TEST_EQ(global_int, 3);
// Assignment
v3 = five;
PIKA_TEST(!v3.empty());
// Invocation
global_int = 0;
v3();
PIKA_TEST_EQ(global_int, 5);
// Construction of a function from a function containing a functor
func_void_type v4(v3);
// Invocation of a function
global_int = 0;
v4();
PIKA_TEST_EQ(global_int, 5);
// reset() method
v4.reset();
PIKA_TEST(v4.empty());
// Assignment to an empty function
v4 = three;
PIKA_TEST(!v4.empty());
// Invocation
global_int = 0;
v4();
PIKA_TEST_EQ(global_int, 3);
// Assignment to a non-empty function
v4 = five;
// Invocation
global_int = 0;
v4();
PIKA_TEST_EQ(global_int, 5);
// reset()
v4.reset();
PIKA_TEST(v4.empty());
// Assignment to an empty function from a free function
v4 = &write_five;
PIKA_TEST(!v4.empty());
// Invocation
global_int = 0;
v4();
PIKA_TEST_EQ(global_int, 5);
// Assignment to a non-empty function from a free function
v4 = &write_three;
PIKA_TEST(!v4.empty());
// Invocation
global_int = 0;
v4();
PIKA_TEST_EQ(global_int, 3);
// Assignment
v4 = five;
PIKA_TEST(!v4.empty());
// Invocation
global_int = 0;
v4();
PIKA_TEST_EQ(global_int, 5);
// Construction of a function from a functor
func_void_type v5(five);
// Invocation of a function
global_int = 0;
v5();
PIKA_TEST_EQ(global_int, 5);
// reset() method
v5.reset();
PIKA_TEST(v5.empty());
// Assignment to an empty function
v5 = three;
PIKA_TEST(!v5.empty());
// Invocation
global_int = 0;
v5();
PIKA_TEST_EQ(global_int, 3);
// Assignment to a non-empty function
v5 = five;
// Invocation
global_int = 0;
v5();
PIKA_TEST_EQ(global_int, 5);
// reset()
v5.reset();
PIKA_TEST(v5.empty());
// Assignment to an empty function from a free function
v5 = &write_five;
PIKA_TEST(!v5.empty());
// Invocation
global_int = 0;
v5();
PIKA_TEST_EQ(global_int, 5);
// Assignment to a non-empty function from a free function
v5 = &write_three;
PIKA_TEST(!v5.empty());
// Invocation
global_int = 0;
v5();
PIKA_TEST_EQ(global_int, 3);
// Assignment
v5 = five;
PIKA_TEST(!v5.empty());
// Invocation
global_int = 0;
v5();
PIKA_TEST_EQ(global_int, 5);
// Construction of a function from a function
func_void_type v6(&write_five);
// Invocation of a function
global_int = 0;
v6();
PIKA_TEST_EQ(global_int, 5);
// reset() method
v6.reset();
PIKA_TEST(v6.empty());
// Assignment to an empty function
v6 = three;
PIKA_TEST(!v6.empty());
// Invocation
global_int = 0;
v6();
PIKA_TEST_EQ(global_int, 3);
// Assignment to a non-empty function
v6 = five;
// Invocation
global_int = 0;
v6();
PIKA_TEST_EQ(global_int, 5);
// reset()
v6.reset();
PIKA_TEST(v6.empty());
// Assignment to an empty function from a free function
v6 = &write_five;
PIKA_TEST(!v6.empty());
// Invocation
global_int = 0;
v6();
PIKA_TEST_EQ(global_int, 5);
// Assignment to a non-empty function from a free function
v6 = &write_three;
PIKA_TEST(!v6.empty());
// Invocation
global_int = 0;
v6();
PIKA_TEST_EQ(global_int, 3);
// Assignment
v6 = five;
PIKA_TEST(!v6.empty());
// Invocation
global_int = 0;
v6();
PIKA_TEST_EQ(global_int, 5);
// Const vs. non-const
write_const_1_nonconst_2 one_or_two;
const pika::util::function_nonser<void()> v7(one_or_two);
pika::util::function_nonser<void()> v8(one_or_two);
global_int = 0;
v7();
PIKA_TEST_EQ(global_int, 2);
global_int = 0;
v8();
PIKA_TEST_EQ(global_int, 2);
// Test construction from 0
void (*fpv9)() = 0; // NOLINT
func_void_type v9(fpv9);
PIKA_TEST(v9.empty());
// Test construction from nullptr
func_void_type v9np(nullptr);
PIKA_TEST(v9np.empty());
// Test return values
typedef pika::util::function_nonser<int()> func_int_type;
generate_five_obj gen_five;
generate_three_obj gen_three;
func_int_type i0(gen_five);
PIKA_TEST_EQ(i0(), 5);
i0 = gen_three;
PIKA_TEST_EQ(i0(), 3);
i0 = &generate_five;
PIKA_TEST_EQ(i0(), 5);
i0 = &generate_three;
PIKA_TEST_EQ(i0(), 3);
PIKA_TEST(!i0.empty());
i0.reset();
PIKA_TEST(!i0);
// Test return values with compatible types
typedef pika::util::function_nonser<long()> func_long_type;
func_long_type i1(gen_five);
PIKA_TEST_EQ(i1(), 5);
i1 = gen_three;
PIKA_TEST_EQ(i1(), 3);
i1 = &generate_five;
PIKA_TEST_EQ(i1(), 5);
i1 = &generate_three;
PIKA_TEST_EQ(i1(), 3);
PIKA_TEST(!i1.empty());
i1.reset();
PIKA_TEST(!i1);
}
static void test_one_arg()
{
std::negate<int> neg;
pika::util::function_nonser<int(int)> f1(neg);
PIKA_TEST_EQ(f1(5), -5);
pika::util::function_nonser<string(string)> id(&identity_str);
PIKA_TEST_EQ(id("str"), "str");
pika::util::function_nonser<string(const char*)> id2(&identity_str);
PIKA_TEST_EQ(id2("foo"), "foo");
add_to_obj add_to(5);
pika::util::function_nonser<int(int)> f2(add_to);
PIKA_TEST_EQ(f2(3), 8);
const pika::util::function_nonser<int(int)> cf2(add_to);
PIKA_TEST_EQ(cf2(3), 8);
}
static void test_two_args()
{
pika::util::function_nonser<string(const string&, const string&)> cat(
&string_cat);
PIKA_TEST_EQ(cat("str", "ing"), "string");
pika::util::function_nonser<int(short, short)> sum(&sum_ints);
PIKA_TEST_EQ(sum(2, 3), 5);
}
static void test_emptiness()
{
pika::util::function_nonser<float()> f1;
PIKA_TEST(f1.empty());
pika::util::function_nonser<float()> f2;
f2 = f1;
PIKA_TEST(f2.empty());
pika::util::function_nonser<double()> f3;
f3 = f2;
PIKA_TEST(f3.empty());
}
struct X
{
X(int v)
: value(v)
{
}
int twice() const
{
return 2 * value;
}
int plus(int v)
{
return value + v;
}
int value;
};
static void test_member_functions()
{
pika::util::function_nonser<int(X*)> f1(&X::twice);
X one(1);
X five(5);
PIKA_TEST_EQ(f1(&one), 2);
PIKA_TEST_EQ(f1(&five), 10);
pika::util::function_nonser<int(X*)> f1_2;
f1_2 = &X::twice;
PIKA_TEST_EQ(f1_2(&one), 2);
PIKA_TEST_EQ(f1_2(&five), 10);
pika::util::function_nonser<int(X&, int)> f2(&X::plus);
PIKA_TEST_EQ(f2(one, 3), 4);
PIKA_TEST_EQ(f2(five, 4), 9);
}
struct add_with_throw_on_copy
{
int operator()(int x, int y) const
{
return x + y;
}
add_with_throw_on_copy() {}
add_with_throw_on_copy(const add_with_throw_on_copy&)
{
throw std::runtime_error("But this CAN'T throw");
}
add_with_throw_on_copy& operator=(const add_with_throw_on_copy&)
{
throw std::runtime_error("But this CAN'T throw");
}
};
static void test_ref()
{
add_with_throw_on_copy atc;
try
{
pika::util::function_nonser<int(int, int)> f(std::ref(atc));
PIKA_TEST_EQ(f(1, 3), 4);
}
catch (std::runtime_error const& /*e*/)
{
PIKA_TEST_MSG(false, "Nonthrowing constructor threw an exception");
}
}
static void dummy() {}
static void test_empty_ref()
{
pika::util::function_nonser<void()> f1;
pika::util::function_nonser<void()> f2(std::ref(f1));
try
{
f2();
PIKA_TEST_MSG(
false, "Exception didn't throw for reference to empty function.");
}
catch (std::runtime_error const& /*e*/)
{
}
f1 = dummy;
try
{
f2();
}
catch (std::runtime_error const&)
{
PIKA_TEST_MSG(false, "Error calling referenced function.");
}
}
static void test_exception()
{
pika::util::function_nonser<int(int, int)> f;
try
{
f(5, 4);
PIKA_TEST(false);
}
catch (std::runtime_error const&)
{
// okay
}
}
typedef pika::util::function_nonser<void*(void* reader)> reader_type;
typedef std::pair<int, reader_type> mapped_type;
static void test_implicit()
{
mapped_type m;
m = mapped_type();
}
static void test_call_obj(pika::util::function_nonser<int(int, int)> f)
{
PIKA_TEST(!f.empty());
}
static void test_call_cref(const pika::util::function_nonser<int(int, int)>& f)
{
PIKA_TEST(!f.empty());
}
static void test_call()
{
test_call_obj(std::plus<int>());
test_call_cref(std::plus<int>());
}
struct big_aggregating_structure
{
int disable_small_objects_optimizations[32];
big_aggregating_structure()
{
++global_int;
}
big_aggregating_structure(const big_aggregating_structure&)
{
++global_int;
}
~big_aggregating_structure()
{
--global_int;
}
void operator()()
{
++global_int;
}
void operator()(int)
{
++global_int;
}
};
template <class FunctionT>
static void test_move_semantics()
{
typedef FunctionT f1_type;
big_aggregating_structure obj;
f1_type f1 = obj;
global_int = 0;
f1();
PIKA_TEST(!f1.empty());
PIKA_TEST_EQ(global_int, 1);
// Testing rvalue constructors
f1_type f2(static_cast<f1_type&&>(f1));
PIKA_TEST(f1.empty());
PIKA_TEST(!f2.empty());
PIKA_TEST_EQ(global_int, 1);
f2();
PIKA_TEST_EQ(global_int, 2);
f1_type f3(static_cast<f1_type&&>(f2));
PIKA_TEST(f1.empty());
PIKA_TEST(f2.empty());
PIKA_TEST(!f3.empty());
PIKA_TEST_EQ(global_int, 2);
f3();
PIKA_TEST_EQ(global_int, 3);
// Testing move assignment
f1_type f4;
PIKA_TEST(f4.empty());
f4 = static_cast<f1_type&&>(f3);
PIKA_TEST(f1.empty());
PIKA_TEST(f2.empty());
PIKA_TEST(f3.empty());
PIKA_TEST(!f4.empty());
PIKA_TEST_EQ(global_int, 3);
f4();
PIKA_TEST_EQ(global_int, 4);
// Testing self move assignment
f4 = static_cast<f1_type&&>(f4);
PIKA_TEST(!f4.empty());
PIKA_TEST_EQ(global_int, 4);
// Testing, that no memory leaked when assigning to nonempty function
f4 = obj;
PIKA_TEST(!f4.empty());
PIKA_TEST_EQ(global_int, 4);
f1_type f5 = obj;
PIKA_TEST_EQ(global_int, 5);
f4 = static_cast<f1_type&&>(f5);
PIKA_TEST_EQ(global_int, 4);
}
int main(int, char*[])
{
test_zero_args();
test_one_arg();
test_two_args();
test_emptiness();
test_member_functions();
test_ref();
test_empty_ref();
test_exception();
test_implicit();
test_call();
test_move_semantics<pika::util::function_nonser<void()>>();
return pika::util::report_errors();
}
|
/*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
TextButton::TextButton (const String& name,
const String& toolTip)
: Button (name)
{
setTooltip (toolTip);
}
TextButton::~TextButton()
{
}
void TextButton::paintButton (Graphics& g,
bool isMouseOverButton,
bool isButtonDown)
{
getLookAndFeel().drawButtonBackground (g, *this,
findColour (getToggleState() ? buttonOnColourId
: buttonColourId),
isMouseOverButton,
isButtonDown);
getLookAndFeel().drawButtonText (g, *this,
isMouseOverButton,
isButtonDown);
}
void TextButton::colourChanged()
{
repaint();
}
Font TextButton::getFont()
{
return Font (jmin (15.0f, getHeight() * 0.6f));
}
void TextButton::changeWidthToFitText (const int newHeight)
{
if (newHeight >= 0)
setSize (jmax (1, getWidth()), newHeight);
setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
getHeight());
}
|
#include <vector>
#include <numeric>
#include <iostream>
#include <cassert>
#include "adjacent_difference.h"
int
main(int argc, char** argv)
{
std::vector<value_type> a{1, 5, -2, 4, 0};
std::vector<value_type> result1(a.size());
std::vector<value_type> result2(a.size());
adjacent_difference(a.data(), a.size(), result1.data());
std::adjacent_difference(a.begin(), a.end(), result2.begin());
assert(result1 == result2);
std::cout << "\tsuccessful execution of " << argv[0] << "\n";
return EXIT_SUCCESS;
}
|
/*
* utest_polyline.cpp
*
* Created on: Nov 19, 2020 21:00
* Description:
*
* Copyright (c) 2020 Ruixiang Du (rdu)
*/
#include "gtest/gtest.h"
#include "geometry/polyline.hpp"
using namespace robosw;
struct PolylineTest : testing::Test {
PolylineTest() {
polyline.AddPoint(0, 0);
polyline.AddPoint(0.5, 0.25);
polyline.AddPoint(1.0, 1.0);
polyline.AddPoint(1.5, 1.75);
polyline.AddPoint(2.0, 2);
}
Polyline polyline;
};
TEST_F(PolylineTest, Evaluate) {
ASSERT_TRUE(polyline.GetPoints().size() == 5)
<< "Incorrect number of points in polyline";
}
|
// Copyright (c) 2014 The Sumcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "rpcserver.h"
#include <boost/lexical_cast.hpp>
#include <algorithm>
#include <string>
#include "smessage.h"
#include "init.h"
#include "util.h"
using namespace json_spirit;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
Value smsgenable(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"smsgenable \n"
"Enable secure messaging.");
if (fSecMsgEnabled)
throw std::runtime_error("Secure messaging is already enabled.");
Object result;
result.push_back(Pair("result", (SecureMsgEnable() ? "Enabled secure messaging." : "Failed to enable secure messaging.")));
return result;
}
Value smsgdisable(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"smsgdisable \n"
"Disable secure messaging.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is already disabled.");
Object result;
result.push_back(Pair("result", (SecureMsgDisable() ? "Disabled secure messaging." : "Failed to disable secure messaging.")));
return result;
}
Value smsgoptions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw std::runtime_error(
"smsgoptions [list <with_description>|set <optname> <value>]\n"
"smsgoptions list 1\n"
" list possible options with descriptions.\n"
"List and manage options.");
std::string mode = "list";
if (params.size() > 0)
mode = params[0].get_str();
Object result;
if (mode == "list")
{
bool fDescriptions = false;
if (params.size() > 1)
{
std::string value = params[1].get_str();
fDescriptions = IsStringBoolPositive(value);
};
result.push_back(Pair("option", std::string("newAddressRecv = ") + (smsgOptions.fNewAddressRecv ? "true" : "false")));
if (fDescriptions)
result.push_back(Pair("newAddressRecv", "Enable receiving messages for newly created addresses."));
result.push_back(Pair("option", std::string("newAddressAnon = ") + (smsgOptions.fNewAddressAnon ? "true" : "false")));
if (fDescriptions)
result.push_back(Pair("newAddressAnon", "Enable receiving anonymous messages for newly created addresses."));
result.push_back(Pair("option", std::string("scanIncoming = ") + (smsgOptions.fScanIncoming ? "true" : "false")));
if (fDescriptions)
result.push_back(Pair("scanIncoming", "Scan incoming blocks for public keys."));
result.push_back(Pair("result", "Success."));
} else
if (mode == "set")
{
if (params.size() < 3)
{
result.push_back(Pair("result", "Too few parameters."));
result.push_back(Pair("expected", "set <optname> <value>"));
return result;
};
std::string optname = params[1].get_str();
std::string value = params[2].get_str();
std::transform(optname.begin(), optname.end(), optname.begin(), ::tolower);
bool fValue;
if (optname == "newaddressrecv")
{
if (GetStringBool(value, fValue))
{
smsgOptions.fNewAddressRecv = fValue;
} else
{
result.push_back(Pair("result", "Unknown value."));
return result;
};
result.push_back(Pair("set option", std::string("newAddressRecv = ") + (smsgOptions.fNewAddressRecv ? "true" : "false")));
} else
if (optname == "newaddressanon")
{
if (GetStringBool(value, fValue))
{
smsgOptions.fNewAddressAnon = fValue;
} else
{
result.push_back(Pair("result", "Unknown value."));
return result;
};
result.push_back(Pair("set option", std::string("newAddressAnon = ") + (smsgOptions.fNewAddressAnon ? "true" : "false")));
} else
if (optname == "scanincoming")
{
if (GetStringBool(value, fValue))
{
smsgOptions.fScanIncoming = fValue;
} else
{
result.push_back(Pair("result", "Unknown value."));
return result;
};
result.push_back(Pair("set option", std::string("scanIncoming = ") + (smsgOptions.fScanIncoming ? "true" : "false")));
} else
{
result.push_back(Pair("result", "Option not found."));
return result;
};
} else
{
result.push_back(Pair("result", "Unknown Mode."));
result.push_back(Pair("expected", "smsgoption [list|set <optname> <value>]"));
};
return result;
}
Value smsglocalkeys(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw std::runtime_error(
"smsglocalkeys [whitelist|all|wallet|recv <+/-> <address>|anon <+/-> <address>]\n"
"List and manage keys.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
Object result;
std::string mode = "whitelist";
if (params.size() > 0)
{
mode = params[0].get_str();
};
if (mode == "whitelist"
|| mode == "all")
{
uint32_t nKeys = 0;
int all = mode == "all" ? 1 : 0;
Array keys;
for (std::vector<SecMsgAddress>::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
{
if (!all
&& !it->fReceiveEnabled)
continue;
CBitcoinAddress coinAddress(it->sAddress);
if (!coinAddress.IsValid())
continue;
std::string sPublicKey;
CKeyID keyID;
if (!coinAddress.GetKeyID(keyID))
continue;
CPubKey pubKey;
if (!pwalletMain->GetPubKey(keyID, pubKey))
continue;
if (!pubKey.IsValid()
|| !pubKey.IsCompressed())
{
continue;
};
sPublicKey = EncodeBase58(pubKey.begin(), pubKey.end());
Object objM;
std::string sLabel = pwalletMain->mapAddressBook[keyID];
std::string sInfo;
if (all)
sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off, ");
sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off");
//result.push_back(Pair("key", it->sAddress + " - " + sPublicKey + " " + sInfo + " - " + sLabel));
objM.push_back(Pair("address", it->sAddress));
objM.push_back(Pair("publickey",sPublicKey));
objM.push_back(Pair("receive",(it->fReceiveEnabled ? "1" : "0")));
objM.push_back(Pair("anon",(it->fReceiveAnon ? "1" : "0")));
objM.push_back(Pair("label",sLabel));
keys.push_back(objM);
nKeys++;
};
result.push_back(Pair("keys", keys));
result.push_back(Pair("result", strprintf("%u", nKeys)));
} else
if (mode == "recv")
{
if (params.size() < 3)
{
result.push_back(Pair("result", "Too few parameters."));
result.push_back(Pair("expected", "recv <+/-> <address>"));
return result;
};
std::string op = params[1].get_str();
std::string addr = params[2].get_str();
std::vector<SecMsgAddress>::iterator it;
for (it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
{
if (addr != it->sAddress)
continue;
break;
};
if (it == smsgAddresses.end())
{
result.push_back(Pair("result", "Address not found."));
return result;
};
if (op == "+" || op == "on" || op == "add" || op == "a")
{
it->fReceiveEnabled = true;
} else
if (op == "-" || op == "off" || op == "rem" || op == "r")
{
it->fReceiveEnabled = false;
} else
{
result.push_back(Pair("result", "Unknown operation."));
return result;
};
std::string sInfo;
sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off,");
sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off");
result.push_back(Pair("result", "Success."));
result.push_back(Pair("key", it->sAddress + " " + sInfo));
return result;
} else
if (mode == "anon")
{
if (params.size() < 3)
{
result.push_back(Pair("result", "Too few parameters."));
result.push_back(Pair("expected", "anon <+/-> <address>"));
return result;
};
std::string op = params[1].get_str();
std::string addr = params[2].get_str();
std::vector<SecMsgAddress>::iterator it;
for (it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it)
{
if (addr != it->sAddress)
continue;
break;
};
if (it == smsgAddresses.end())
{
result.push_back(Pair("result", "Address not found."));
return result;
};
if (op == "+" || op == "on" || op == "add" || op == "a")
{
it->fReceiveAnon = true;
} else
if (op == "-" || op == "off" || op == "rem" || op == "r")
{
it->fReceiveAnon = false;
} else
{
result.push_back(Pair("result", "Unknown operation."));
return result;
};
std::string sInfo;
sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off,");
sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off");
result.push_back(Pair("result", "Success."));
result.push_back(Pair("key", it->sAddress + " " + sInfo));
return result;
} else
if (mode == "wallet")
{
uint32_t nKeys = 0;
Array keys;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& entry, pwalletMain->mapAddressBook)
{
if (!IsDestMine(*pwalletMain, entry.first))
continue;
CBitcoinAddress coinAddress(entry.first);
if (!coinAddress.IsValid())
continue;
std::string address;
std::string sPublicKey;
address = coinAddress.ToString();
CKeyID keyID;
if (!coinAddress.GetKeyID(keyID))
continue;
CPubKey pubKey;
if (!pwalletMain->GetPubKey(keyID, pubKey))
continue;
if (!pubKey.IsValid()
|| !pubKey.IsCompressed())
{
continue;
};
sPublicKey = EncodeBase58(pubKey.begin(), pubKey.end());
Object objM;
objM.push_back(Pair("key", address));
objM.push_back(Pair("publickey", sPublicKey));
objM.push_back(Pair("label", entry.second));
keys.push_back(objM);
nKeys++;
};
result.push_back(Pair("keys", keys));
result.push_back(Pair("result", strprintf("%u", nKeys)));
} else
{
result.push_back(Pair("result", "Unknown Mode."));
result.push_back(Pair("expected", "smsglocalkeys [whitelist|all|wallet|recv <+/-> <address>|anon <+/-> <address>]"));
};
return result;
};
Value smsgscanchain(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"smsgscanchain \n"
"Look for public keys in the block chain.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
Object result;
if (!SecureMsgScanBlockChain())
{
result.push_back(Pair("result", "Scan Chain Failed."));
} else
{
result.push_back(Pair("result", "Scan Chain Completed."));
};
return result;
}
Value smsgscanbuckets(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw std::runtime_error(
"smsgscanbuckets \n"
"Force rescan of all messages in the bucket store.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
if (pwalletMain->IsLocked())
throw std::runtime_error("Wallet is locked.");
Object result;
if (!SecureMsgScanBuckets())
{
result.push_back(Pair("result", "Scan Buckets Failed."));
} else
{
result.push_back(Pair("result", "Scan Buckets Completed."));
};
return result;
}
Value smsgaddkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw std::runtime_error(
"smsgaddkey <address> <pubkey>\n"
"Add address, pubkey pair to database.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
std::string addr = params[0].get_str();
std::string pubk = params[1].get_str();
Object result;
int rv = SecureMsgAddAddress(addr, pubk);
if (rv != 0)
{
result.push_back(Pair("result", "Public key not added to db."));
switch (rv)
{
case 2: result.push_back(Pair("reason", "publicKey is invalid.")); break;
case 3: result.push_back(Pair("reason", "publicKey does not match address.")); break;
case 4: result.push_back(Pair("reason", "address is already in db.")); break;
case 5: result.push_back(Pair("reason", "address is invalid.")); break;
default: result.push_back(Pair("reason", "error.")); break;
};
} else
{
result.push_back(Pair("result", "Added public key to db."));
};
return result;
}
Value smsggetpubkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw std::runtime_error(
"smsggetpubkey <address>\n"
"Return the base58 encoded compressed public key for an address.\n"
"Tests localkeys first, then looks in public key db.\n");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
std::string address = params[0].get_str();
std::string publicKey;
Object result;
int rv = SecureMsgGetLocalPublicKey(address, publicKey);
switch (rv)
{
case 0:
result.push_back(Pair("result", "Success."));
result.push_back(Pair("address", address));
result.push_back(Pair("publickey", publicKey));
return result; // success, don't check db
case 2:
case 3:
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Invalid address."));
return result;
case 4:
break; // check db
//case 1:
default:
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Error."));
return result;
};
CBitcoinAddress coinAddress(address);
CKeyID keyID;
if (!coinAddress.GetKeyID(keyID))
{
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Invalid address."));
return result;
};
CPubKey cpkFromDB;
rv = SecureMsgGetStoredKey(keyID, cpkFromDB);
switch (rv)
{
case 0:
if (!cpkFromDB.IsValid()
|| !cpkFromDB.IsCompressed())
{
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Invalid address."));
} else
{
//cpkFromDB.SetCompressedPubKey(); // make sure key is compressed
publicKey = EncodeBase58(cpkFromDB.begin(), cpkFromDB.end());
result.push_back(Pair("result", "Success."));
result.push_back(Pair("address", address));
result.push_back(Pair("publickey", publicKey));
};
break;
case 2:
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Address not found in wallet or db."));
return result;
//case 1:
default:
result.push_back(Pair("result", "Failed."));
result.push_back(Pair("message", "Error, GetStoredKey()."));
return result;
};
return result;
}
Value smsgsend(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw std::runtime_error(
"smsgsend <addrFrom> <addrTo> <message>\n"
"Send an encrypted message from addrFrom to addrTo.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
std::string addrFrom = params[0].get_str();
std::string addrTo = params[1].get_str();
std::string msg = params[2].get_str();
Object result;
std::string sError;
if (SecureMsgSend(addrFrom, addrTo, msg, sError) != 0)
{
result.push_back(Pair("result", "Send failed."));
result.push_back(Pair("error", sError));
} else
result.push_back(Pair("result", "Sent."));
return result;
}
Value smsgsendanon(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw std::runtime_error(
"smsgsendanon <addrTo> <message>\n"
"Send an anonymous encrypted message to addrTo.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
std::string addrFrom = "anon";
std::string addrTo = params[0].get_str();
std::string msg = params[1].get_str();
Object result;
std::string sError;
if (SecureMsgSend(addrFrom, addrTo, msg, sError) != 0)
{
result.push_back(Pair("result", "Send failed."));
result.push_back(Pair("error", sError));
} else
result.push_back(Pair("result", "Sent."));
return result;
}
Value smsginbox(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1) // defaults to read
throw std::runtime_error(
"smsginbox [all|unread|clear]\n"
"Decrypt and display all received messages.\n"
"Warning: clear will delete all messages.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
if (pwalletMain->IsLocked())
throw std::runtime_error("Wallet is locked.");
std::string mode = "unread";
if (params.size() > 0)
{
mode = params[0].get_str();
};
Object result;
std::vector<unsigned char> vchKey;
vchKey.resize(16);
memset(&vchKey[0], 0, 16);
{
LOCK(cs_smsgDB);
SecMsgDB dbInbox;
if (!dbInbox.Open("cr+"))
throw std::runtime_error("Could not open DB.");
uint32_t nMessages = 0;
char cbuf[256];
std::string sPrefix("im");
unsigned char chKey[18];
if (mode == "clear")
{
dbInbox.TxnBegin();
leveldb::Iterator* it = dbInbox.pdb->NewIterator(leveldb::ReadOptions());
while (dbInbox.NextSmesgKey(it, sPrefix, chKey))
{
dbInbox.EraseSmesg(chKey);
nMessages++;
};
delete it;
dbInbox.TxnCommit();
result.push_back(Pair("result", strprintf("Deleted %u messages.", nMessages)));
} else
if (mode == "all"
|| mode == "unread")
{
int fCheckReadStatus = mode == "unread" ? 1 : 0;
SecMsgStored smsgStored;
MessageData msg;
dbInbox.TxnBegin();
leveldb::Iterator* it = dbInbox.pdb->NewIterator(leveldb::ReadOptions());
Array messageList;
while (dbInbox.NextSmesg(it, sPrefix, chKey, smsgStored))
{
if (fCheckReadStatus
&& !(smsgStored.status & SMSG_MASK_UNREAD))
continue;
uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN;
if (SecureMsgDecrypt(false, smsgStored.sAddrTo, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0)
{
Object objM;
objM.push_back(Pair("success", "1"));
objM.push_back(Pair("received", getTimeString(smsgStored.timeReceived, cbuf, sizeof(cbuf))));
objM.push_back(Pair("sent", getTimeString(msg.timestamp, cbuf, sizeof(cbuf))));
objM.push_back(Pair("from", msg.sFromAddress));
objM.push_back(Pair("to", smsgStored.sAddrTo));
objM.push_back(Pair("text", std::string((char*)&msg.vchMessage[0]))); // ugh
messageList.push_back(objM);
} else
{
Object objM;
objM.push_back(Pair("success", "0"));
messageList.push_back(objM);
};
if (fCheckReadStatus)
{
smsgStored.status &= ~SMSG_MASK_UNREAD;
dbInbox.WriteSmesg(chKey, smsgStored);
};
nMessages++;
};
delete it;
dbInbox.TxnCommit();
result.push_back(Pair("messages", messageList));
result.push_back(Pair("result", strprintf("%u", nMessages)));
} else
{
result.push_back(Pair("result", "Unknown Mode."));
result.push_back(Pair("expected", "[all|unread|clear]."));
};
}
return result;
};
Value smsgoutbox(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1) // defaults to read
throw std::runtime_error(
"smsgoutbox [all|clear]\n"
"Decrypt and display all sent messages.\n"
"Warning: clear will delete all sent messages.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
if (pwalletMain->IsLocked())
throw std::runtime_error("Wallet is locked.");
std::string mode = "all";
if (params.size() > 0)
{
mode = params[0].get_str();
}
Object result;
std::string sPrefix("sm");
unsigned char chKey[18];
memset(&chKey[0], 0, 18);
{
LOCK(cs_smsgDB);
SecMsgDB dbOutbox;
if (!dbOutbox.Open("cr+"))
throw std::runtime_error("Could not open DB.");
uint32_t nMessages = 0;
char cbuf[256];
if (mode == "clear")
{
dbOutbox.TxnBegin();
leveldb::Iterator* it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions());
while (dbOutbox.NextSmesgKey(it, sPrefix, chKey))
{
dbOutbox.EraseSmesg(chKey);
nMessages++;
};
delete it;
dbOutbox.TxnCommit();
result.push_back(Pair("result", strprintf("Deleted %u messages.", nMessages)));
} else
if (mode == "all")
{
SecMsgStored smsgStored;
MessageData msg;
leveldb::Iterator* it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions());
Array messageList;
while (dbOutbox.NextSmesg(it, sPrefix, chKey, smsgStored))
{
uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN;
if (SecureMsgDecrypt(false, smsgStored.sAddrOutbox, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0)
{
Object objM;
objM.push_back(Pair("success", "1"));
objM.push_back(Pair("sent", getTimeString(msg.timestamp, cbuf, sizeof(cbuf))));
objM.push_back(Pair("from", msg.sFromAddress));
objM.push_back(Pair("to", smsgStored.sAddrTo));
objM.push_back(Pair("text", std::string((char*)&msg.vchMessage[0]))); // ugh
messageList.push_back(objM);
} else
{
Object objM;
objM.push_back(Pair("success", "0"));
messageList.push_back(objM);
};
nMessages++;
};
delete it;
result.push_back(Pair("messages" ,messageList));
result.push_back(Pair("result", strprintf("%u", nMessages)));
} else
{
result.push_back(Pair("result", "Unknown Mode."));
result.push_back(Pair("expected", "[all|clear]."));
};
}
return result;
};
Value smsgbuckets(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"smsgbuckets [stats|dump]\n"
"Display some statistics.");
if (!fSecMsgEnabled)
throw std::runtime_error("Secure messaging is disabled.");
std::string mode = "stats";
if (params.size() > 0)
{
mode = params[0].get_str();
};
Object result;
char cbuf[256];
if (mode == "stats")
{
uint32_t nBuckets = 0;
uint32_t nMessages = 0;
uint64_t nBytes = 0;
{
LOCK(cs_smsg);
std::map<int64_t, SecMsgBucket>::iterator it;
it = smsgBuckets.begin();
for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it)
{
std::set<SecMsgToken>& tokenSet = it->second.setTokens;
std::string sBucket = boost::lexical_cast<std::string>(it->first);
std::string sFile = sBucket + "_01.dat";
std::string sHash = boost::lexical_cast<std::string>(it->second.hash);
nBuckets++;
nMessages += tokenSet.size();
Object objM;
objM.push_back(Pair("bucket", sBucket));
objM.push_back(Pair("time", getTimeString(it->first, cbuf, sizeof(cbuf))));
objM.push_back(Pair("no. messages", strprintf("%u", tokenSet.size())));
objM.push_back(Pair("hash", sHash));
objM.push_back(Pair("last changed", getTimeString(it->second.timeChanged, cbuf, sizeof(cbuf))));
boost::filesystem::path fullPath = GetDataDir() / "smsgStore" / sFile;
if (!boost::filesystem::exists(fullPath))
{
// -- If there is a file for an empty bucket something is wrong.
if (tokenSet.size() == 0)
objM.push_back(Pair("file size", "Empty bucket."));
else
objM.push_back(Pair("file size, error", "File not found."));
} else
{
try {
uint64_t nFBytes = 0;
nFBytes = boost::filesystem::file_size(fullPath);
nBytes += nFBytes;
objM.push_back(Pair("file size", bytesReadable(nFBytes)));
} catch (const boost::filesystem::filesystem_error& ex)
{
objM.push_back(Pair("file size, error", ex.what()));
};
};
result.push_back(Pair("bucket", objM));
};
}; // LOCK(cs_smsg);
std::string snBuckets = boost::lexical_cast<std::string>(nBuckets);
std::string snMessages = boost::lexical_cast<std::string>(nMessages);
Object objM;
objM.push_back(Pair("buckets", snBuckets));
objM.push_back(Pair("messages", snMessages));
objM.push_back(Pair("size", bytesReadable(nBytes)));
result.push_back(Pair("total", objM));
} else
if (mode == "dump")
{
{
LOCK(cs_smsg);
std::map<int64_t, SecMsgBucket>::iterator it;
it = smsgBuckets.begin();
for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it)
{
std::string sFile = boost::lexical_cast<std::string>(it->first) + "_01.dat";
try {
boost::filesystem::path fullPath = GetDataDir() / "smsgStore" / sFile;
boost::filesystem::remove(fullPath);
} catch (const boost::filesystem::filesystem_error& ex)
{
//objM.push_back(Pair("file size, error", ex.what()));
LogPrintf("Error removing bucket file %s.\n", ex.what());
};
};
smsgBuckets.clear();
}; // LOCK(cs_smsg);
result.push_back(Pair("result", "Removed all buckets."));
} else
{
result.push_back(Pair("result", "Unknown Mode."));
result.push_back(Pair("expected", "[stats|dump]."));
};
return result;
};
|
/* BSD 2-Clause License
Copyright (c) 2016, Doi Yusuke
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LIBICS3_ICS3_BAUDRATE_H
#define LIBICS3_ICS3_BAUDRATE_H
#include <termios.h>
namespace ics
{
class Baudrate
{
public:
using type = uint8_t;
static constexpr Baudrate RATE115200() noexcept;
//static constexpr Baudrate RATE625000() noexcept;
//static constexpr Baudrate RATE1250000() noexcept;
constexpr type get() const noexcept;
constexpr operator type() const noexcept;
constexpr speed_t getSpeed() const noexcept;
private:
constexpr Baudrate(type, speed_t) noexcept; // non explicit, user cannot touch this
const type romdata;
const speed_t baudrate;
};
constexpr Baudrate Baudrate::RATE115200() noexcept
{
return {10, B115200};
}
constexpr Baudrate::type Baudrate::get() const noexcept
{
return romdata;
}
constexpr Baudrate::operator Baudrate::type() const noexcept
{
return get();
}
constexpr speed_t Baudrate::getSpeed() const noexcept
{
return baudrate;
}
constexpr Baudrate::Baudrate(type romdata, speed_t baudrate) noexcept
: romdata {romdata},
baudrate {baudrate}
{
}
}
#endif // LIBICS3_ICS3_BAUDRATE_H
|
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"cupertino_cupertinotextformfieldrow_2", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
|
//=================================================================================================
/*!
// \file src/mathtest/dmatdmatadd/SDaSDa.cpp
// \brief Source file for the SDaSDa dense matrix/dense matrix addition math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. 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.
// 3. Neither the names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/SymmetricMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatadd/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'SDaSDa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
using SDa = blaze::SymmetricMatrix< blaze::DynamicMatrix<TypeA> >;
// Creator type definitions
using CSDa = blazetest::Creator<SDa>;
// Running tests with small matrices
for( size_t i=0UL; i<=9UL; ++i ) {
RUN_DMATDMATADD_OPERATION_TEST( CSDa( i ), CSDa( i ) );
}
// Running tests with large matrices
RUN_DMATDMATADD_OPERATION_TEST( CSDa( 67UL ), CSDa( 67UL ) );
RUN_DMATDMATADD_OPERATION_TEST( CSDa( 128UL ), CSDa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix addition:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
#include <iostream>
#include <vector>
using namespace std;
bool isValid(int n, int i, int j, vector<vector<char>>& grid)
{
if (i >= 1 && j >= 2)
{
if (grid[i - 1][j - 2] == 'K')
{
return false;
}
}
if (i >= 2 && j >= 1)
{
if (grid[i - 2][j - 1] == 'K')
{
return false;
}
}
if (i >= 2 && j <= n - 2)
{
if (grid[i - 2][j + 1] == 'K')
{
return false;
}
}
if (i >= 1 && j <= n - 3)
{
if (grid[i - 1][j + 2] == 'K')
{
return false;
}
}
return true;
}
void nKnight(int n, int i, int j, int curr, vector<vector<vector<char>>>& ans, vector<vector<char>>& grid)
{
if (curr == n)
{
ans.push_back(grid);
return;
}
if (i == n && j == 0)
{
return;
}
if (j == n)
{
return nKnight(n, i + 1, 0, curr, ans, grid);
}
if (grid[i][j] == '0' && curr < n)
{
if (isValid(n, i, j, grid))
{
grid[i][j] = 'K';
nKnight(n, i, j + 1, curr + 1, ans, grid);
grid[i][j] = '0';
}
nKnight(n, i, j + 1, curr, ans, grid);
}
}
int main()
{
int n;
cin >> n;
vector<vector<char>> grid(n, vector<char>(n, '0'));
vector<vector<vector<char>>> ans;
nKnight(n, 0, 0, 0, ans, grid);
for (auto vec : ans)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << vec[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}
|
#include <bits/stdc++.h>
template<typename T> T gcd(T a, T b) {
if(!b) return a;
return gcd(b, a % b);
}
template<typename T> T lcm(T a, T b) {
return a * b / gcd(a, b);
}
template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; }
template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; }
int in() { int x; scanf("%d", &x); return x; }
using namespace std;
typedef long long Int;
typedef unsigned uint;
int N, K;
Int dp[12][20];
Int func(int digit, int len) {
if (len == N) {
return 1;
} else {
Int& ans = dp[digit][len];
if (ans == -1LL) {
ans = 0LL;
for (int i = 0; i < K; i++) {
if ((i == 0 && digit == 0) || (i == 0 && len == 0)) continue;
ans = (ans + func(i, len + 1));
}
}
return ans;
}
}
int main(void) {
scanf("%d%d", &N, &K);
memset(dp, -1LL, sizeof(dp));
printf("%lld\n", func(10, 0));
return 0;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.Runtime.Serialization.ISerializable
#include "System/Runtime/Serialization/ISerializable.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.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: System
namespace System {
// Forward declaring type: RuntimeType
class RuntimeType;
// Forward declaring type: Type
class Type;
}
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
}
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: TypeAttributes
struct TypeAttributes;
// Forward declaring type: RuntimeAssembly
class RuntimeAssembly;
// Forward declaring type: RuntimeModule
class RuntimeModule;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Size: 0x8
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: System.RuntimeTypeHandle
// [ComVisibleAttribute] Offset: D7B3F8
struct RuntimeTypeHandle/*, public System::ValueType, public System::Runtime::Serialization::ISerializable*/ {
public:
// private System.IntPtr value
// Size: 0x8
// Offset: 0x0
System::IntPtr value;
// Field size check
static_assert(sizeof(System::IntPtr) == 0x8);
// Creating value type constructor for type: RuntimeTypeHandle
constexpr RuntimeTypeHandle(System::IntPtr value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Creating interface conversion operator: operator System::Runtime::Serialization::ISerializable
operator System::Runtime::Serialization::ISerializable() noexcept {
return *reinterpret_cast<System::Runtime::Serialization::ISerializable*>(this);
}
// Creating conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept {
return value;
}
// System.Void .ctor(System.IntPtr val)
// Offset: 0xEF9DE4
// template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
// ABORTED: conflicts with another method. RuntimeTypeHandle(System::IntPtr val)
// System.Void .ctor(System.RuntimeType type)
// Offset: 0xEF9DEC
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
RuntimeTypeHandle(System::RuntimeType* type) {
static auto ___internal__logger = ::Logger::get().WithContext("System::RuntimeTypeHandle::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(type)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, type);
}
// private System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0xEF9E08
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
RuntimeTypeHandle(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context) {
static auto ___internal__logger = ::Logger::get().WithContext("System::RuntimeTypeHandle::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(info), ::il2cpp_utils::ExtractType(context)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, info, context);
}
// public System.IntPtr get_Value()
// Offset: 0xEF9E10
System::IntPtr get_Value();
// public System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0xEF9E18
void GetObjectData(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context);
// static System.Reflection.TypeAttributes GetAttributes(System.RuntimeType type)
// Offset: 0x168AAD4
static System::Reflection::TypeAttributes GetAttributes(System::RuntimeType* type);
// static private System.Int32 GetMetadataToken(System.RuntimeType type)
// Offset: 0x1690728
static int GetMetadataToken(System::RuntimeType* type);
// static System.Int32 GetToken(System.RuntimeType type)
// Offset: 0x168D8B4
static int GetToken(System::RuntimeType* type);
// static private System.Type GetGenericTypeDefinition_impl(System.RuntimeType type)
// Offset: 0x169072C
static System::Type* GetGenericTypeDefinition_impl(System::RuntimeType* type);
// static System.Type GetGenericTypeDefinition(System.RuntimeType type)
// Offset: 0x168C124
static System::Type* GetGenericTypeDefinition(System::RuntimeType* type);
// static System.Boolean HasElementType(System.RuntimeType type)
// Offset: 0x168AD48
static bool HasElementType(System::RuntimeType* type);
// static System.Boolean HasInstantiation(System.RuntimeType type)
// Offset: 0x168C12C
static bool HasInstantiation(System::RuntimeType* type);
// static System.Boolean IsArray(System.RuntimeType type)
// Offset: 0x168AED4
static bool IsArray(System::RuntimeType* type);
// static System.Boolean IsByRef(System.RuntimeType type)
// Offset: 0x168AB70
static bool IsByRef(System::RuntimeType* type);
// static System.Boolean IsComObject(System.RuntimeType type)
// Offset: 0x1690730
static bool IsComObject(System::RuntimeType* type);
// static System.Boolean IsInstanceOfType(System.RuntimeType type, System.Object o)
// Offset: 0x168A77C
static bool IsInstanceOfType(System::RuntimeType* type, ::Il2CppObject* o);
// static System.Boolean IsPointer(System.RuntimeType type)
// Offset: 0x168AB80
static bool IsPointer(System::RuntimeType* type);
// static System.Boolean IsPrimitive(System.RuntimeType type)
// Offset: 0x168AB78
static bool IsPrimitive(System::RuntimeType* type);
// static System.Boolean HasReferences(System.RuntimeType type)
// Offset: 0x1690734
static bool HasReferences(System::RuntimeType* type);
// static System.Boolean IsComObject(System.RuntimeType type, System.Boolean isGenericCOM)
// Offset: 0x168AB88
static bool IsComObject(System::RuntimeType* type, bool isGenericCOM);
// static System.Boolean IsContextful(System.RuntimeType type)
// Offset: 0x168AADC
static bool IsContextful(System::RuntimeType* type);
// static System.Boolean IsEquivalentTo(System.RuntimeType rtType1, System.RuntimeType rtType2)
// Offset: 0x168AAB8
static bool IsEquivalentTo(System::RuntimeType* rtType1, System::RuntimeType* rtType2);
// static System.Boolean IsSzArray(System.RuntimeType type)
// Offset: 0x168AE80
static bool IsSzArray(System::RuntimeType* type);
// static System.Boolean IsInterface(System.RuntimeType type)
// Offset: 0x1690738
static bool IsInterface(System::RuntimeType* type);
// static System.Int32 GetArrayRank(System.RuntimeType type)
// Offset: 0x168AF84
static int GetArrayRank(System::RuntimeType* type);
// static System.Reflection.RuntimeAssembly GetAssembly(System.RuntimeType type)
// Offset: 0x168A740
static System::Reflection::RuntimeAssembly* GetAssembly(System::RuntimeType* type);
// static System.RuntimeType GetElementType(System.RuntimeType type)
// Offset: 0x168AF8C
static System::RuntimeType* GetElementType(System::RuntimeType* type);
// static System.Reflection.RuntimeModule GetModule(System.RuntimeType type)
// Offset: 0x168A734
static System::Reflection::RuntimeModule* GetModule(System::RuntimeType* type);
// static System.Boolean IsGenericVariable(System.RuntimeType type)
// Offset: 0x168AAC4
static bool IsGenericVariable(System::RuntimeType* type);
// static System.RuntimeType GetBaseType(System.RuntimeType type)
// Offset: 0x168AAC8
static System::RuntimeType* GetBaseType(System::RuntimeType* type);
// static System.Boolean CanCastTo(System.RuntimeType type, System.RuntimeType target)
// Offset: 0x168A9FC
static bool CanCastTo(System::RuntimeType* type, System::RuntimeType* target);
// static private System.Boolean type_is_assignable_from(System.Type a, System.Type b)
// Offset: 0x169075C
static bool type_is_assignable_from(System::Type* a, System::Type* b);
// static System.Boolean IsGenericTypeDefinition(System.RuntimeType type)
// Offset: 0x168BFC0
static bool IsGenericTypeDefinition(System::RuntimeType* type);
// static System.IntPtr GetGenericParameterInfo(System.RuntimeType type)
// Offset: 0x168FB90
static System::IntPtr GetGenericParameterInfo(System::RuntimeType* type);
// public override System.Boolean Equals(System.Object obj)
// Offset: 0xEF9E20
// Implemented from: System.ValueType
// Base method: System.Boolean ValueType::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public override System.Int32 GetHashCode()
// Offset: 0xEF9E28
// Implemented from: System.ValueType
// Base method: System.Int32 ValueType::GetHashCode()
int GetHashCode();
}; // System.RuntimeTypeHandle
#pragma pack(pop)
static check_size<sizeof(RuntimeTypeHandle), 0 + sizeof(System::IntPtr)> __System_RuntimeTypeHandleSizeCheck;
static_assert(sizeof(RuntimeTypeHandle) == 0x8);
}
DEFINE_IL2CPP_ARG_TYPE(System::RuntimeTypeHandle, "System", "RuntimeTypeHandle");
|
#include <boost/spirit/include/support_attributes_fwd.hpp>
|
struct Path {
int last;
int bitmask;
int cost;
Path() : last(0), bitmask(0), cost(0) {}
void addPoint(int p, int c = 1) {
last = p;
cost += c;
bitmask = bitmask | (1 << p);
}
};
class Solution {
public:
int shortestPathLength(vector<vector<int>> &graph) {
queue<Path> pq;
int n = graph.size();
int mask = (1 << n) - 1;
map<pair<int, int>, int> dist;
for (int i = 0; i < n; i++) {
Path path;
path.addPoint(i, 0);
pq.push(path);
dist[make_pair(1 << i, 0)] = 0;
}
while (pq.size()) {
auto path = pq.front();
pq.pop();
if (path.bitmask == mask)
return path.cost;
int u = path.last;
for (auto v : graph[u]) {
auto path2 = path;
path2.addPoint(v);
auto p = make_pair(path2.bitmask, path2.last);
if (!dist.count(p) || dist[p] > path2.cost) {
pq.push(path2);
dist[make_pair(path2.bitmask, path2.last)] = path.cost;
}
}
}
return 0;
}
};
|
/* -*- C++ -*- */
#include "qtluaprinter.h"
#include <QDialog>
#include <QPrintDialog>
struct Option
{
const char *name;
int value;
};
#define F(t) {#t, (int) QPrinter::t}
static Option pageSizes[] = {
F(A4), F(B5), F(Letter), F(Legal), F(Executive),
F(A0), F(A1), F(A2), F(A3), F(A5), F(A6), F(A7), F(A8), F(A9), F(B0), F(B1),
F(B10), F(B2), F(B3), F(B4), F(B6), F(B7), F(B8), F(B9), F(C5E), F(Comm10E),
F(DLE), F(Folio), F(Ledger), F(Tabloid), F(Custom),
{0} };
static Option outputFormats[] = {
F(NativeFormat), F(PdfFormat), F(PostScriptFormat),
{0} };
static Option printerStates[] = {
F(Idle), F(Active), F(Aborted), F(Error),
{0} };
static const char *
value_to_name(int value, Option *opts)
{
for(; opts->name; opts++)
if (opts->value == value)
return opts->name;
return "unknown";
}
static int
name_to_value(const char *name, Option *opts)
{
for(; opts->name; opts++)
if (! strcmp(name, opts->name))
return opts->value;
return -1;
}
QString
QtLuaPrinter::pageSize() const
{
#if QT_VERSION >= 0x40400
int s = (int)QPrinter::paperSize();
#else
int s = (int)QPrinter::pageSize();
#endif
return QString::fromAscii(value_to_name(s, pageSizes));
}
void
QtLuaPrinter::setPageSize(QString r)
{
int s = name_to_value(r.toLocal8Bit().constData(), pageSizes);
if (s >= 0)
{
custom = false;
if (s != QPrinter::Custom)
QPrinter::setPageSize(QPrinter::PageSize(s));
#if QT_VERSION >= 0x40400
else
custom = true;
if (custom && papSize.isValid())
QPrinter::setPaperSize(papSize, Point);
#endif
}
}
QSizeF
QtLuaPrinter::paperSize() const
{
return papSize;
}
void
QtLuaPrinter::setPaperSize(QSizeF s)
{
papSize = s;
#if QT_VERSION >= 0x40400
if (custom && papSize.isValid())
QPrinter::setPaperSize(papSize, Point);
#endif
}
QString
QtLuaPrinter::outputFormat() const
{
int s = (int) QPrinter::outputFormat();
return QString::fromAscii(value_to_name(s, outputFormats));
}
void
QtLuaPrinter::setOutputFormat(QString r)
{
int s = name_to_value(r.toLocal8Bit().constData(), outputFormats);
if (s >= 0)
QPrinter::setOutputFormat(QPrinter::OutputFormat(s));
}
QString
QtLuaPrinter::printerState() const
{
int s = (int) QPrinter::printerState();
return QString::fromAscii(value_to_name(s, printerStates));
}
bool
QtLuaPrinter::setup(QWidget *parent)
{
QPointer<QPrintDialog> dialog = new QPrintDialog(this, parent);
dialog->setFromTo(fromPage(), toPage());
// options
dialog->addEnabledOption(QPrintDialog::PrintToFile);
dialog->addEnabledOption(QPrintDialog::PrintPageRange);
dialog->addEnabledOption(QPrintDialog::PrintCollateCopies);
// exec
int result = dialog->exec();
delete dialog;
return (result == QDialog::Accepted);
}
QtLuaPrinter::~QtLuaPrinter()
{
emit closing(this);
}
/* -------------------------------------------------------------
Local Variables:
c++-font-lock-extra-types: ("\\sw+_t" "\\(lua_\\)?[A-Z]\\sw*[a-z]\\sw*" "qreal")
End:
------------------------------------------------------------- */
|
//===- TypeUtils.cpp - Helper function for manipulating types -------------===//
//
// 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 "mlir/Quantizer/Support/TypeUtils.h"
#include "mlir/IR/StandardTypes.h"
using namespace mlir;
using namespace mlir::quantizer;
Type mlir::quantizer::getElementOrPrimitiveType(Type t) {
if (auto sType = t.dyn_cast<ShapedType>()) {
return sType.getElementType();
} else {
return t;
}
}
|
/*
===========================================================================
Moka Source Code
Copyright 2019 Stuart Adams. All rights reserved.
https://github.com/stuartdadams/moka
stuartdadams | linkedin.com/in/stuartdadams
This file is part of the Moka Real-Time Physically-Based Rendering Project.
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.
===========================================================================
*/
#pragma once
#include "graphics/buffer/frame_buffer_handle.hpp"
#include "graphics/material/material_parameter.hpp"
#include <asset_importer/texture_importer.hpp>
#include <graphics/buffer/buffer_usage.hpp>
#include <graphics/buffer/index_buffer_handle.hpp>
#include <graphics/buffer/vertex_buffer_handle.hpp>
#include <graphics/buffer/vertex_layout.hpp>
#include <graphics/device/graphics_visitor.hpp>
#include <graphics/program.hpp>
#include <graphics/shader.hpp>
#include <graphics/texture_handle.hpp>
namespace moka
{
class vertex_layout;
class command_list;
/**
* \brief
*/
enum class alpha_mode : uint8_t
{
blend, // The rendered output is combined with the background using the normal painting operation(i.e.the Porter and Duff over operator). This mode is used to simulate geometry such as guaze cloth or animal fur.
mask, // The rendered output is either fully opaque or fully transparent depending on the alpha value and the specified alpha cutoff value. This mode is used to simulate geometry such as tree leaves or wire fences.
opaque // The rendered output is fully opaque and any alpha value is ignored.
};
enum class attribute
{
position,
normal,
tangent,
bitangent,
color0,
color1,
color2,
color3,
indices,
weight,
tex_coord0,
tex_coord1,
tex_coord2,
tex_coord3,
tex_coord4,
tex_coord5,
tex_coord6,
tex_coord7,
extension
};
template <typename T>
struct basic_rectangle
{
T x, y, width, height;
constexpr basic_rectangle(const T x, const T y, const T width, const T height) noexcept
: x{x}, y{y}, width{width}, height{height}
{
}
};
using rectangle = basic_rectangle<int>;
enum class primitive_type : uint8_t
{
points,
lines,
line_loop,
line_strip,
triangles,
triangle_strip,
triangle_fan
};
enum class toggle : uint8_t
{
enable,
disable
};
enum class cull_face : uint8_t
{
front,
back,
front_and_back
};
enum class blend_function_factor : uint8_t
{
zero,
one,
src_color,
one_minus_src_color,
dst_color,
one_minus_dst_color,
src_alpha,
one_minus_src_alpha,
dst_alpha,
one_minus_dst_alpha,
constant_color,
one_minus_constant_color,
constant_alpha,
one_minus_constant_alpha
};
enum class blend_equation : uint8_t
{
func_add,
func_subtract,
func_reverse_subtract,
min,
max
};
enum class face : uint8_t
{
front,
back,
front_and_back
};
struct uniform_data
{
std::string name;
parameter_type type;
size_t count;
size_t buffer_start;
size_t buffer_end;
};
struct texture_binding
{
texture_handle handle;
size_t unit;
};
struct draw_call;
/**
* \brief render_context abstracts the native rendering API.
*/
class graphics_api : public graphics_visitor
{
public:
virtual ~graphics_api() = default;
graphics_api() = default;
graphics_api(const graphics_api& rhs) = default;
graphics_api(graphics_api&& rhs) = default;
graphics_api& operator=(const graphics_api& rhs) = default;
graphics_api& operator=(graphics_api&& rhs) = default;
/**
* \brief Submit a command_list to execute on the device.
* \param commands The command_list you wish to run.
*/
virtual void submit(command_list&& commands) = 0;
/**
* \brief Submit a command_list to execute on the device. The main framebuffer will be swapped after executing, advancing a frame.
* \param commands The command_list you wish to run.
*/
virtual void submit_and_swap(command_list&& commands) = 0;
/**
* \brief Create a new frame buffer.
* \param render_textures An array of render_texture_data.
* \param render_texture_count Size of the render_textures array.
* \return A new frame_buffer_handle representing a frame buffer on the device.
*/
virtual frame_buffer_handle make_frame_buffer(
render_texture_data* render_textures, size_t render_texture_count) = 0;
/**
* \brief Create a shader program from vertex & fragment shaders.
* \param vertex_handle The vertex shader that you want to link to this program.
* \param fragment_handle The fragment shader that you want to link to this program.
* \return A new program_handle representing a program on the device.
*/
virtual program_handle make_program(
const shader_handle& vertex_handle, const shader_handle& fragment_handle) = 0;
/**
* \brief Create a shader from source code.
* \param type The type of shader you want to create.
* \param source The source code of the shader you want to create.
* \return A new shader_handle representing a shader on the device.
*/
virtual shader_handle make_shader(shader_type type, const std::string& source) = 0;
/**
* \brief Create a new vertex buffer.
* \param vertices The host memory buffer that will be used as vertex data.
* \param size The size of the host vertex buffer.
* \param layout The layout of the vertex data.
* \param use A buffer usage hint.
* \return A new vertex_buffer_handle representing an vertex buffer on the device.
*/
virtual vertex_buffer_handle make_vertex_buffer(
const void* vertices, size_t size, vertex_layout&& layout, buffer_usage use) = 0;
/**
* \brief Create a new index buffer.
* \param indices The host memory buffer that will be used as index data.
* \param size The size of the host index buffer.
* \param type The layout of the index data.
* \param use A buffer usage hint.
* \return A new index_buffer_handle representing an index buffer on the device.
*/
virtual index_buffer_handle make_index_buffer(
const void* indices, size_t size, index_type type, buffer_usage use) = 0;
/**
* \brief Create a new texture.
* \param data The host memory buffer that will be used as texture data.
* \param metadata Metadata describing the texture data.
* \param free_host_data If true, free the host memory after uploading to the device. Otherwise allow the calling code to free it.
* \return A new texture_handle representing a texture on the device.
*/
virtual texture_handle make_texture(
const void** data, texture_metadata&& metadata, bool free_host_data) = 0;
/**
* \brief Destroy a frame buffer.
* \param handle The host frame buffer that will be destroyed.
*/
virtual void destroy(frame_buffer_handle handle) = 0;
};
} // namespace moka
|
#include <iostream>
using namespace std;
struct node {
int val;
node *left;
node *right;
};
void print(node *proot) {
if (proot == nullptr) {
return;
}
cout << proot->val << endl;
print(proot->left);
print(proot->right);
}
int count(node *proot) {
if (proot == nullptr) {
return 0;
}
return 1 + count(proot->left) + count(proot->right);
}
int height(node *proot) {
if (proot == nullptr) {
return 0;
}
return 1 + max(height(proot->left), height(proot->right));
}
int leaves(node *proot) {
if (proot == nullptr) {
return 0;
}
if (proot->left == nullptr and proot->right == nullptr) { //lub (proot->left == proot->right)
return 1;
}
return leaves(proot->left) + leaves(proot->right);
}
int at_depth(node *proot, int depth) {
if (proot == nullptr) {
return 0;
}
if (depth == 0) {
return 1;
}
return at_depth(proot->left, depth - 1) + at_depth(proot->right, depth - 1);
}
bool tree_search(node *proot, int n) {
if (proot == nullptr) {
return false;
}
if (proot->val == n) {
return true;
}
return tree_search(proot->left, n) or tree_search(proot->right, n);
}
bool bst_search(node *proot, int n) {
if (proot == nullptr) {
return false;
}
if (proot->val == n) {
return true;
}
return proot->val > n ? bst_search(proot->left, n) : bst_search(proot->right, n);
}
struct word_node {
string w;
int wCount;
word_node *left;
word_node *right;
};
void insert(word_node *&tree, string word) {
if (tree == nullptr) {
tree = new word_node;
tree->w = word;
tree->wCount = 1;
tree->left = nullptr;
tree->right = nullptr;
}
else {
if (tree->w == word) {
tree->wCount;
}
else if (tree->w > word) {
insert(tree->left, word);
}
else {
insert(tree->right, word);
}
}
}
|
#pragma once
#include <vector>
namespace polyvec
{
struct EmptyData
{ };
template <typename EntryData = EmptyData>
class UnionFind
{
struct UFEntry : public EntryData
{
int parent;
};
public:
UnionFind(size_t size)
{
uf.resize(size);
for (int i = 0; i < uf.size(); ++i)
uf[i].parent = i;
}
int getRepresentative(int i)
{
if (uf[i].parent != i)
uf[i].parent = getRepresentative(uf[i].parent);
return uf[i].parent;
}
void merge(int i, int j)
{
uf[getRepresentative(i)].parent = getRepresentative(j);
}
size_t size() const { return uf.size(); }
UFEntry& operator[](int i) { return uf[i]; }
const UFEntry& operator[](int i) const { return uf[i]; }
private:
std::vector<UFEntry> uf;
};
}
|
/******************************************************************************
* Copyright 2018 The Apollo 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 "modules/transform/buffer.h"
#include "absl/strings/str_cat.h"
#include "cyber/cyber.h"
#include "cyber/time/clock.h"
#include "modules/common/adapters/adapter_gflags.h"
using Clock = ::apollo::cyber::Clock;
namespace {
constexpr float kSecondToNanoFactor = 1e9f;
} // namespace
namespace apollo {
namespace transform {
Buffer::Buffer() : BufferCore() { Init(); }
int Buffer::Init() {
const std::string node_name =
absl::StrCat("transform_listener_", Clock::Now().ToNanosecond());
node_ = cyber::CreateNode(node_name);
apollo::cyber::proto::RoleAttributes attr;
attr.set_channel_name("/tf");
message_subscriber_tf_ = node_->CreateReader<TransformStampeds>(
attr, [&](const std::shared_ptr<const TransformStampeds>& msg_evt) {
SubscriptionCallbackImpl(msg_evt, false);
});
apollo::cyber::proto::RoleAttributes attr_static;
attr_static.set_channel_name(FLAGS_tf_static_topic);
attr_static.mutable_qos_profile()->CopyFrom(
apollo::cyber::transport::QosProfileConf::QOS_PROFILE_TF_STATIC);
message_subscriber_tf_static_ = node_->CreateReader<TransformStampeds>(
attr_static, [&](const std::shared_ptr<TransformStampeds>& msg_evt) {
SubscriptionCallbackImpl(msg_evt, true);
});
return cyber::SUCC;
}
void Buffer::SubscriptionCallback(
const std::shared_ptr<const TransformStampeds>& msg_evt) {
SubscriptionCallbackImpl(msg_evt, false);
}
void Buffer::StaticSubscriptionCallback(
const std::shared_ptr<const TransformStampeds>& msg_evt) {
SubscriptionCallbackImpl(msg_evt, true);
}
void Buffer::SubscriptionCallbackImpl(
const std::shared_ptr<const TransformStampeds>& msg_evt, bool is_static) {
cyber::Time now = Clock::Now();
std::string authority =
"cyber_tf"; // msg_evt.getPublisherName(); // lookup the authority
if (now.ToNanosecond() < last_update_.ToNanosecond()) {
AINFO << "Detected jump back in time. Clearing TF buffer.";
clear();
// cache static transform stamped again.
for (auto& msg : static_msgs_) {
setTransform(msg, authority, true);
}
}
last_update_ = now;
for (int i = 0; i < msg_evt->transforms_size(); i++) {
try {
geometry_msgs::TransformStamped trans_stamped;
// header
const auto& header = msg_evt->transforms(i).header();
trans_stamped.header.stamp =
static_cast<uint64_t>(header.timestamp_sec() * kSecondToNanoFactor);
trans_stamped.header.frame_id = header.frame_id();
trans_stamped.header.seq = header.sequence_num();
// child_frame_id
trans_stamped.child_frame_id = msg_evt->transforms(i).child_frame_id();
// translation
const auto& transform = msg_evt->transforms(i).transform();
trans_stamped.transform.translation.x = transform.translation().x();
trans_stamped.transform.translation.y = transform.translation().y();
trans_stamped.transform.translation.z = transform.translation().z();
// rotation
trans_stamped.transform.rotation.x = transform.rotation().qx();
trans_stamped.transform.rotation.y = transform.rotation().qy();
trans_stamped.transform.rotation.z = transform.rotation().qz();
trans_stamped.transform.rotation.w = transform.rotation().qw();
if (is_static) {
static_msgs_.push_back(trans_stamped);
}
setTransform(trans_stamped, authority, is_static);
} catch (tf2::TransformException& ex) {
std::string temp = ex.what();
AERROR << "Failure to set received transform:" << temp.c_str();
}
}
}
bool Buffer::GetLatestStaticTF(const std::string& frame_id,
const std::string& child_frame_id,
TransformStamped* tf) {
for (auto reverse_iter = static_msgs_.rbegin();
reverse_iter != static_msgs_.rend(); ++reverse_iter) {
if ((*reverse_iter).header.frame_id == frame_id &&
(*reverse_iter).child_frame_id == child_frame_id) {
TF2MsgToCyber((*reverse_iter), (*tf));
return true;
}
}
return false;
}
void Buffer::TF2MsgToCyber(
const geometry_msgs::TransformStamped& tf2_trans_stamped,
TransformStamped& trans_stamped) const {
// header
trans_stamped.mutable_header()->set_timestamp_sec(
static_cast<double>(tf2_trans_stamped.header.stamp) / 1e9);
trans_stamped.mutable_header()->set_frame_id(
tf2_trans_stamped.header.frame_id);
// child_frame_id
trans_stamped.set_child_frame_id(tf2_trans_stamped.child_frame_id);
// translation
trans_stamped.mutable_transform()->mutable_translation()->set_x(
tf2_trans_stamped.transform.translation.x);
trans_stamped.mutable_transform()->mutable_translation()->set_y(
tf2_trans_stamped.transform.translation.y);
trans_stamped.mutable_transform()->mutable_translation()->set_z(
tf2_trans_stamped.transform.translation.z);
// rotation
trans_stamped.mutable_transform()->mutable_rotation()->set_qx(
tf2_trans_stamped.transform.rotation.x);
trans_stamped.mutable_transform()->mutable_rotation()->set_qy(
tf2_trans_stamped.transform.rotation.y);
trans_stamped.mutable_transform()->mutable_rotation()->set_qz(
tf2_trans_stamped.transform.rotation.z);
trans_stamped.mutable_transform()->mutable_rotation()->set_qw(
tf2_trans_stamped.transform.rotation.w);
}
TransformStamped Buffer::lookupTransform(const std::string& target_frame,
const std::string& source_frame,
const cyber::Time& time,
const float timeout_second) const {
tf2::Time tf2_time(time.ToNanosecond());
geometry_msgs::TransformStamped tf2_trans_stamped =
lookupTransform(target_frame, source_frame, tf2_time);
TransformStamped trans_stamped;
TF2MsgToCyber(tf2_trans_stamped, trans_stamped);
return trans_stamped;
}
TransformStamped Buffer::lookupTransform(const std::string& target_frame,
const cyber::Time& target_time,
const std::string& source_frame,
const cyber::Time& source_time,
const std::string& fixed_frame,
const float timeout_second) const {
geometry_msgs::TransformStamped tf2_trans_stamped =
lookupTransform(target_frame, target_time.ToNanosecond(), source_frame,
source_time.ToNanosecond(), fixed_frame);
TransformStamped trans_stamped;
TF2MsgToCyber(tf2_trans_stamped, trans_stamped);
return trans_stamped;
}
bool Buffer::canTransform(const std::string& target_frame,
const std::string& source_frame,
const cyber::Time& time, const float timeout_second,
std::string* errstr) const {
uint64_t timeout_ns =
static_cast<uint64_t>(timeout_second * kSecondToNanoFactor);
uint64_t start_time = Clock::Now().ToNanosecond();
while (
Clock::Now().ToNanosecond() < start_time + timeout_ns &&
!canTransform(target_frame, source_frame, time.ToNanosecond(), errstr) &&
!cyber::IsShutdown()) {
std::this_thread::sleep_for(std::chrono::milliseconds(3));
}
bool retval =
canTransform(target_frame, source_frame, time.ToNanosecond(), errstr);
// conditionally_append_timeout_info(errstr, start_time, timeout);
return retval;
}
bool Buffer::canTransform(const std::string& target_frame,
const cyber::Time& target_time,
const std::string& source_frame,
const cyber::Time& source_time,
const std::string& fixed_frame,
const float timeout_second,
std::string* errstr) const {
// poll for transform if timeout is set
uint64_t timeout_ns =
static_cast<uint64_t>(timeout_second * kSecondToNanoFactor);
uint64_t start_time = Clock::Now().ToNanosecond();
while (Clock::Now().ToNanosecond() < start_time + timeout_ns &&
!canTransform(target_frame, target_time.ToNanosecond(), source_frame,
source_time.ToNanosecond(),
fixed_frame) &&
!cyber::IsShutdown()) { // Make sure we haven't been stopped
std::this_thread::sleep_for(std::chrono::milliseconds(3));
}
bool retval =
canTransform(target_frame, target_time.ToNanosecond(), source_frame,
source_time.ToNanosecond(), fixed_frame, errstr);
return retval;
}
} // namespace transform
} // namespace apollo
|
#include "grid.h"
#include "wordlist.h"
#include <unicode/ustream.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <math.h>
#include <vector>
int get_size(icu::UnicodeString s) {
int size = sqrt(s.length());
if (size * size != s.length())
throw std::runtime_error("Invalid number of characters.");
return size;
}
struct State {
WordList::const_iterator w_begin;
WordList::const_iterator w_end;
Grid::Moves::const_iterator m_begin;
Grid::Moves::const_iterator m_end;
int position;
icu::UnicodeString word;
};
class Solver {
private:
const Grid &grid_;
const WordList &word_list_;
const icu::UnicodeString chars_;
public:
Solver(const Grid &grid, const WordList &word_list,
const icu::UnicodeString chars)
: grid_(grid), word_list_(word_list_), chars_(chars) {}
};
std::pair<icu::UnicodeString, std::vector<bool>>
GetCharsAndStars(std::string input) {
icu::UnicodeString utf(icu::UnicodeString::fromUTF8(input));
icu::UnicodeString uppercase(
icu::UnicodeString::fromUTF8("AÁBCDEFGHIÍJKLMNOÓÖŐPQRSTUÚÜŰVXYZ"));
icu::UnicodeString chars;
std::vector<bool> stars(utf.length(), false);
int i = 0;
for (int j = 0; j < utf.length(); ++j)
if (utf[j] == '.')
stars[i] = true;
else {
if (uppercase.indexOf(utf[j]) > -1)
stars[i] = true;
chars += utf[j];
++i;
}
chars.toLower();
return std::make_pair(chars, stars);
}
bool IsStarred(std::vector<bool> already_visited, std::vector<bool> stars) {
for (auto i = 0; i < already_visited.size(); ++i)
if (already_visited[i] && stars[i])
return true;
return false;
}
enum class Printed { yes, no };
int main(int argc, char *argv[]) {
WordList word_list = CreateWordList("freedict_utf8");
if (argc != 2)
throw std::runtime_error(std::string{"usage: "} + argv[0] + " characters");
const auto chars_and_stars = GetCharsAndStars(argv[1]);
const auto &chars = chars_and_stars.first;
const auto &stars = chars_and_stars.second;
const auto size = get_size(chars);
std::cout << "size: " << size << std::endl;
Grid grid(size);
std::vector<State> state;
state.reserve(size * size + 1);
state.push_back(State{word_list.begin(), word_list.end(), grid.All().cbegin(),
grid.All().cend(), 0,
icu::UnicodeString::fromUTF8("")});
std::vector<bool> already_visited(size * size, false);
std::map<icu::UnicodeString, Printed> already_found;
while (state.size() > 0) {
State ¤t_state = state.back();
while ((current_state.m_begin != current_state.m_end) &&
(already_visited[*current_state.m_begin + current_state.position]))
++current_state.m_begin;
if (current_state.m_begin == current_state.m_end) {
// No more possible moves from there
already_visited[current_state.position] = false;
state.pop_back();
if (state.size() > 0)
++state.back().m_begin;
continue;
}
State new_state;
new_state.position = current_state.position + *current_state.m_begin;
already_visited[new_state.position] = true;
new_state.word = current_state.word;
new_state.word.append(chars[new_state.position]);
new_state.w_begin = std::find_if(current_state.w_begin, current_state.w_end,
[new_state](const icu::UnicodeString &s) {
return s.startsWith(new_state.word);
});
new_state.w_end =
std::find_if_not(new_state.w_begin, current_state.w_end,
[new_state](const icu::UnicodeString &s) {
return s.startsWith(new_state.word);
});
new_state.m_begin = grid.PossibleMoves(new_state.position).cbegin();
new_state.m_end = grid.PossibleMoves(new_state.position).cend();
state.push_back(new_state);
if (new_state.word == *new_state.w_begin) {
if (already_found.find(new_state.word) == already_found.cend()) {
const auto starred =
IsStarred(already_visited, stars) && new_state.word.length() > 2;
already_found.insert(
{new_state.word, starred ? Printed::yes : Printed::no});
if (starred)
std::cout << "* " << state[1].position << " " << new_state.word
<< std::endl;
}
}
if (new_state.w_begin == new_state.w_end) {
already_visited[new_state.position] = false;
state.pop_back();
if (state.size() > 0)
++state.back().m_begin;
continue;
}
}
for (auto result : already_found)
if (result.second == Printed::no)
std::cout << result.first << std::endl;
return 0;
}
|
/**
* @file
* @author Aapo Kyrola <akyrola@cs.cmu.edu>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University]
*
* 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.
*
* @section DESCRIPTION
*
* Matrix factorizatino with the Alternative Least Squares (ALS) algorithm.
* This code is based on GraphLab's implementation of ALS by Joey Gonzalez
* and Danny Bickson (CMU). A good explanation of the algorithm is
* given in the following paper:
* Large-Scale Parallel Collaborative Filtering for the Netflix Prize
* Yunhong Zhou, Dennis Wilkinson, Robert Schreiber and Rong Pan
* http://www.springerlink.com/content/j1076u0h14586183/
*
* There are two versions of the ALS in the example applications. This version
* is slower, but works with very low memory. In this implementation, a vertex
* writes its D-dimensional latent factor to its incident edges. See application
* "als_vertices_inmem" for a faster version, which requires more memory.
*
* In the code, we use movie-rating terminology for clarity. This code has been
* tested with the Netflix movie rating challenge, where the task is to predict
* how user rates movies in range from 1 to 5.
*
* This code is has integrated preprocessing, 'sharding', so it is not necessary
* to run sharder prior to running the matrix factorization algorithm. Input
* data must be provided in the Matrix Market format (http://math.nist.gov/MatrixMarket/formats.html).
*
* ALS uses free linear algebra library 'Eigen'. See Readme_Eigen.txt for instructions
* how to obtain it.
*
* At the end of the processing, the two latent factor matrices are written into files in
* the matrix market format.
*
* @section USAGE
*
* bin/example_apps/matrix_factorization/als_edgefactors file <matrix-market-input> niters 5
*
*
*/
#include <string>
#include <algorithm>
#include "graphchi_basic_includes.hpp"
/* ALS-related classes are contained in als.hpp */
#include "als.hpp"
using namespace graphchi;
/**
* Type definitions. Remember to create suitable graph shards using the
* Sharder-program.
*/
typedef latentvec_t VertexDataType;
typedef als_factor_and_weight EdgeDataType; // Edges store the "rating" of user->movie pair
// and the latent factor of their incident vertex.
/**
* GraphChi programs need to subclass GraphChiProgram<vertex-type, edge-type>
* class. The main logic is usually in the update function.
*/
struct ALSEdgeFactorsProgram : public GraphChiProgram<VertexDataType, EdgeDataType> {
// Helper
virtual void set_latent_factor(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, latentvec_t &fact) {
vertex.set_data(fact);
for(int i=0; i < vertex.num_edges(); i++) {
als_factor_and_weight factwght = vertex.edge(i)->get_data();
factwght.factor = fact;
vertex.edge(i)->set_data(factwght); // Note that neighbors override the values they have written to edges.
// This is ok, because vertices are always executed in same order.
}
}
/**
* Vertex update function.
*/
void update(graphchi_vertex<VertexDataType, EdgeDataType> &vertex, graphchi_context &gcontext) {
if (gcontext.iteration == 0) {
/* On first iteration, initialize vertex (and its edges). This is usually required, because
on each run, GraphChi will modify the data files. To start from scratch, it is easiest
do initialize the program in code. Alternatively, you can keep a copy of initial data files. */
latentvec_t latentfac;
latentfac.init();
set_latent_factor(vertex, latentfac);
} else {
mat XtX(NLATENT, NLATENT);
XtX.setZero();
vec Xty(NLATENT);
Xty.setZero();
// Compute XtX and Xty (NOTE: unweighted)
for(int e=0; e < vertex.num_edges(); e++) {
float observation = vertex.edge(e)->get_data().weight;
assert(observation >= 0 && observation <= 5);
latentvec_t nbr_latent = vertex.edge(e)->get_data().factor;
for(int i=0; i<NLATENT; i++) {
Xty(i) += nbr_latent[i] * observation;
for(int j=i; j < NLATENT; j++) {
XtX(j,i) += nbr_latent[i] * nbr_latent[j];
}
}
}
// Symmetrize
for(int i=0; i <NLATENT; i++)
for(int j=i + 1; j< NLATENT; j++) XtX(i,j) = XtX(j,i);
// Diagonal
for(int i=0; i < NLATENT; i++) XtX(i,i) += (LAMBDA) * vertex.num_edges();
// Solve the least squares problem with eigen using Cholesky decomposition
vec veclatent = XtX.ldlt().solve(Xty);
// Convert to plain doubles (this is useful because now the output data by GraphCHI
// is plain binary double matrix that can be read, for example, by Matlab).
latentvec_t newlatent;
for(int i=0; i < NLATENT; i++) newlatent[i] = veclatent[i];
double sqerror = 0;
bool compute_rmse = (gcontext.iteration == gcontext.num_iterations-1 && vertex.num_outedges() == 0);
if (compute_rmse) { // Compute RMSE only on "right side" of bipartite graph
for(int e=0; e < vertex.num_edges(); e++) {
// Compute RMSE
float observation = vertex.edge(e)->get_data().weight;
latentvec_t nbr_latent = vertex.edge(e)->get_data().factor;
double prediction = nbr_latent.dot(newlatent);
sqerror += (prediction - observation) * (prediction - observation);
}
rmselock.lock();
rmse += sqerror;
rmselock.unlock();
if (vertex.id() % 5000 == 1) {
logstream(LOG_DEBUG) << "Computed RMSE for : " << vertex.id() << std::endl;
}
}
set_latent_factor(vertex, newlatent);
if (vertex.id() % 100000 == 1) {
std::cout << gcontext.iteration << ": " << vertex.id() << std::endl;
}
}
/* Hack: we need to count ourselves the number of vertices on left
and right side of the bipartite graph.
TODO: maybe there should be specialized support for bipartite graphs in GraphChi?
*/
if (vertex.num_outedges() > 0) {
// Left side on the bipartite graph
max_left_vertex = std::max(vertex.id(), max_left_vertex);
} else {
max_right_vertex = std::max(vertex.id(), max_right_vertex);
}
}
/**
* Called before an iteration starts.
*/
void before_iteration(int iteration, graphchi_context &gcontext) {
}
/**
* Called after an iteration has finished.
*/
void after_iteration(int iteration, graphchi_context &gcontext) {
}
/**
* Called before an execution interval is started.
*/
void before_exec_interval(vid_t window_st, vid_t window_en, graphchi_context &gcontext) {
}
/**
* Called after an execution interval has finished.
*/
void after_exec_interval(vid_t window_st, vid_t window_en, graphchi_context &gcontext) {
}
};
int main(int argc, const char ** argv) {
/* GraphChi initialization will read the command line
arguments and the configuration file. */
graphchi_init(argc, argv);
/* Metrics object for keeping track of performance counters
and other information. Currently required. */
metrics m("als-edgefactors");
/* Basic arguments for application. NOTE: File will be automatically 'sharded'. */
std::string filename = get_option_string("file"); // Base filename
int niters = get_option_int("niters", 6); // Number of iterations
bool scheduler = false; // Selective scheduling not supported for now.
/* Preprocess data if needed, or discover preprocess files */
int nshards = convert_matrixmarket_for_ALS<als_factor_and_weight>(filename);
/* Run */
ALSEdgeFactorsProgram program;
graphchi_engine<VertexDataType, EdgeDataType> engine(filename, nshards, scheduler, m);
engine.run(program, niters);
/* Report result (train RMSE) */
double trainRMSE = sqrt(rmse / (1.0 * engine.num_edges()));
m.set("train_rmse", trainRMSE);
m.set("latent_dimension", NLATENT);
std::cout << "Latent factor dimension: " << NLATENT << " - train RMSE: " << trainRMSE << std::endl;
/* Output latent factor matrices in matrix-market format */
vid_t numvertices = engine.num_vertices();
assert(numvertices == max_right_vertex + 1); // Sanity check
output_als_result(filename, numvertices, max_left_vertex);
/* Report execution metrics */
metrics_report(m);
return 0;
}
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "key.h"
#include "keystore.h"
#include "validation.h"
#include "policy/policy.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "test/test_arc.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet_ismine.h"
#endif
#include <vector>
#include <boost/test/unit_test.hpp>
using namespace std;
// Helpers:
static std::vector<unsigned char>
Serialize(const CScript& s)
{
std::vector<unsigned char> sSerialized(s.begin(), s.end());
return sSerialized;
}
static bool
Verify(const CScript& scriptSig, const CScript& scriptPubKey, bool fStrict, ScriptError& err)
{
// Create dummy to/from transactions:
CMutableTransaction txFrom;
txFrom.vout.resize(1);
txFrom.vout[0].scriptPubKey = scriptPubKey;
CMutableTransaction txTo;
txTo.vin.resize(1);
txTo.vout.resize(1);
txTo.vin[0].prevout.n = 0;
txTo.vin[0].prevout.hash = txFrom.GetHash();
txTo.vin[0].scriptSig = scriptSig;
txTo.vout[0].nValue = 1;
return VerifyScript(scriptSig, scriptPubKey, fStrict ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, MutableTransactionSignatureChecker(&txTo, 0), &err);
}
BOOST_FIXTURE_TEST_SUITE(script_P2SH_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(sign)
{
LOCK(cs_main);
// Pay-to-script-hash looks like this:
// scriptSig: <sig> <sig...> <serialized_script>
// scriptPubKey: HASH160 <hash> EQUAL
// Test SignSignature() (and therefore the version of Solver() that signs transactions)
CBasicKeyStore keystore;
CKey key[4];
for (int i = 0; i < 4; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
}
// 8 Scripts: checking all combinations of
// different keys, straight/P2SH, pubkey/pubkeyhash
CScript standardScripts[4];
standardScripts[0] << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG;
standardScripts[1] = GetScriptForDestination(key[1].GetPubKey().GetID());
standardScripts[2] << ToByteVector(key[1].GetPubKey()) << OP_CHECKSIG;
standardScripts[3] = GetScriptForDestination(key[2].GetPubKey().GetID());
CScript evalScripts[4];
for (int i = 0; i < 4; i++)
{
keystore.AddCScript(standardScripts[i]);
evalScripts[i] = GetScriptForDestination(CScriptID(standardScripts[i]));
}
CMutableTransaction txFrom; // Funding transaction:
string reason;
txFrom.vout.resize(8);
for (int i = 0; i < 4; i++)
{
txFrom.vout[i].scriptPubKey = evalScripts[i];
txFrom.vout[i].nValue = COIN;
txFrom.vout[i+4].scriptPubKey = standardScripts[i];
txFrom.vout[i+4].nValue = COIN;
}
BOOST_CHECK(IsStandardTx(txFrom, reason));
CMutableTransaction txTo[8]; // Spending transactions
for (int i = 0; i < 8; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1;
#ifdef ENABLE_WALLET
BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i));
#endif
}
for (int i = 0; i < 8; i++)
{
BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i));
}
// All of the above should be OK, and the txTos have valid signatures
// Check to make sure signature verification fails if we use the wrong ScriptSig:
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
{
CScript sigSave = txTo[i].vin[0].scriptSig;
txTo[i].vin[0].scriptSig = txTo[j].vin[0].scriptSig;
const CTxOut& output = txFrom.vout[txTo[i].vin[0].prevout.n];
bool sigOK = CScriptCheck(output.scriptPubKey, output.nValue, txTo[i], 0, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, false)();
if (i == j)
BOOST_CHECK_MESSAGE(sigOK, strprintf("VerifySignature %d %d", i, j));
else
BOOST_CHECK_MESSAGE(!sigOK, strprintf("VerifySignature %d %d", i, j));
txTo[i].vin[0].scriptSig = sigSave;
}
}
BOOST_AUTO_TEST_CASE(norecurse)
{
ScriptError err;
// Make sure only the outer pay-to-script-hash does the
// extra-validation thing:
CScript invalidAsScript;
invalidAsScript << OP_INVALIDOPCODE << OP_INVALIDOPCODE;
CScript p2sh = GetScriptForDestination(CScriptID(invalidAsScript));
CScript scriptSig;
scriptSig << Serialize(invalidAsScript);
// Should not verify, because it will try to execute OP_INVALIDOPCODE
BOOST_CHECK(!Verify(scriptSig, p2sh, true, err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_BAD_OPCODE, ScriptErrorString(err));
// Try to recur, and verification should succeed because
// the inner HASH160 <> EQUAL should only check the hash:
CScript p2sh2 = GetScriptForDestination(CScriptID(p2sh));
CScript scriptSig2;
scriptSig2 << Serialize(invalidAsScript) << Serialize(p2sh);
BOOST_CHECK(Verify(scriptSig2, p2sh2, true, err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
BOOST_AUTO_TEST_CASE(set)
{
LOCK(cs_main);
// Test the CScript::Set* methods
CBasicKeyStore keystore;
CKey key[4];
std::vector<CPubKey> keys;
for (int i = 0; i < 4; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
keys.push_back(key[i].GetPubKey());
}
CScript inner[4];
inner[0] = GetScriptForDestination(key[0].GetPubKey().GetID());
inner[1] = GetScriptForMultisig(2, std::vector<CPubKey>(keys.begin(), keys.begin()+2));
inner[2] = GetScriptForMultisig(1, std::vector<CPubKey>(keys.begin(), keys.begin()+2));
inner[3] = GetScriptForMultisig(2, std::vector<CPubKey>(keys.begin(), keys.begin()+3));
CScript outer[4];
for (int i = 0; i < 4; i++)
{
outer[i] = GetScriptForDestination(CScriptID(inner[i]));
keystore.AddCScript(inner[i]);
}
CMutableTransaction txFrom; // Funding transaction:
string reason;
txFrom.vout.resize(4);
for (int i = 0; i < 4; i++)
{
txFrom.vout[i].scriptPubKey = outer[i];
txFrom.vout[i].nValue = CENT;
}
BOOST_CHECK(IsStandardTx(txFrom, reason));
CMutableTransaction txTo[4]; // Spending transactions
for (int i = 0; i < 4; i++)
{
txTo[i].vin.resize(1);
txTo[i].vout.resize(1);
txTo[i].vin[0].prevout.n = i;
txTo[i].vin[0].prevout.hash = txFrom.GetHash();
txTo[i].vout[0].nValue = 1*CENT;
txTo[i].vout[0].scriptPubKey = inner[i];
#ifdef ENABLE_WALLET
BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i));
#endif
}
for (int i = 0; i < 4; i++)
{
BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i));
BOOST_CHECK_MESSAGE(IsStandardTx(txTo[i], reason), strprintf("txTo[%d].IsStandard", i));
}
}
BOOST_AUTO_TEST_CASE(is)
{
// Test CScript::IsPayToScriptHash()
uint160 dummy;
CScript p2sh;
p2sh << OP_HASH160 << ToByteVector(dummy) << OP_EQUAL;
BOOST_CHECK(p2sh.IsPayToScriptHash());
// Not considered pay-to-script-hash if using one of the OP_PUSHDATA opcodes:
static const unsigned char direct[] = { OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL };
BOOST_CHECK(CScript(direct, direct+sizeof(direct)).IsPayToScriptHash());
static const unsigned char pushdata1[] = { OP_HASH160, OP_PUSHDATA1, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL };
BOOST_CHECK(!CScript(pushdata1, pushdata1+sizeof(pushdata1)).IsPayToScriptHash());
static const unsigned char pushdata2[] = { OP_HASH160, OP_PUSHDATA2, 20,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL };
BOOST_CHECK(!CScript(pushdata2, pushdata2+sizeof(pushdata2)).IsPayToScriptHash());
static const unsigned char pushdata4[] = { OP_HASH160, OP_PUSHDATA4, 20,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL };
BOOST_CHECK(!CScript(pushdata4, pushdata4+sizeof(pushdata4)).IsPayToScriptHash());
CScript not_p2sh;
BOOST_CHECK(!not_p2sh.IsPayToScriptHash());
not_p2sh.clear(); not_p2sh << OP_HASH160 << ToByteVector(dummy) << ToByteVector(dummy) << OP_EQUAL;
BOOST_CHECK(!not_p2sh.IsPayToScriptHash());
not_p2sh.clear(); not_p2sh << OP_NOP << ToByteVector(dummy) << OP_EQUAL;
BOOST_CHECK(!not_p2sh.IsPayToScriptHash());
not_p2sh.clear(); not_p2sh << OP_HASH160 << ToByteVector(dummy) << OP_CHECKSIG;
BOOST_CHECK(!not_p2sh.IsPayToScriptHash());
}
BOOST_AUTO_TEST_CASE(switchover)
{
// Test switch over code
CScript notValid;
ScriptError err;
notValid << OP_11 << OP_12 << OP_EQUALVERIFY;
CScript scriptSig;
scriptSig << Serialize(notValid);
CScript fund = GetScriptForDestination(CScriptID(notValid));
// Validation should succeed under old rules (hash is correct):
BOOST_CHECK(Verify(scriptSig, fund, false, err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
// Fail under new:
BOOST_CHECK(!Verify(scriptSig, fund, true, err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EQUALVERIFY, ScriptErrorString(err));
}
BOOST_AUTO_TEST_CASE(AreInputsStandard)
{
LOCK(cs_main);
CCoinsView coinsDummy;
CCoinsViewCache coins(&coinsDummy);
CBasicKeyStore keystore;
CKey key[6];
vector<CPubKey> keys;
for (int i = 0; i < 6; i++)
{
key[i].MakeNewKey(true);
keystore.AddKey(key[i]);
}
for (int i = 0; i < 3; i++)
keys.push_back(key[i].GetPubKey());
CMutableTransaction txFrom;
txFrom.vout.resize(7);
// First three are standard:
CScript pay1 = GetScriptForDestination(key[0].GetPubKey().GetID());
keystore.AddCScript(pay1);
CScript pay1of3 = GetScriptForMultisig(1, keys);
txFrom.vout[0].scriptPubKey = GetScriptForDestination(CScriptID(pay1)); // P2SH (OP_CHECKSIG)
txFrom.vout[0].nValue = 1000;
txFrom.vout[1].scriptPubKey = pay1; // ordinary OP_CHECKSIG
txFrom.vout[1].nValue = 2000;
txFrom.vout[2].scriptPubKey = pay1of3; // ordinary OP_CHECKMULTISIG
txFrom.vout[2].nValue = 3000;
// vout[3] is complicated 1-of-3 AND 2-of-3
// ... that is OK if wrapped in P2SH:
CScript oneAndTwo;
oneAndTwo << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()) << ToByteVector(key[2].GetPubKey());
oneAndTwo << OP_3 << OP_CHECKMULTISIGVERIFY;
oneAndTwo << OP_2 << ToByteVector(key[3].GetPubKey()) << ToByteVector(key[4].GetPubKey()) << ToByteVector(key[5].GetPubKey());
oneAndTwo << OP_3 << OP_CHECKMULTISIG;
keystore.AddCScript(oneAndTwo);
txFrom.vout[3].scriptPubKey = GetScriptForDestination(CScriptID(oneAndTwo));
txFrom.vout[3].nValue = 4000;
// vout[4] is max sigops:
CScript fifteenSigops; fifteenSigops << OP_1;
for (unsigned i = 0; i < MAX_P2SH_SIGOPS; i++)
fifteenSigops << ToByteVector(key[i%3].GetPubKey());
fifteenSigops << OP_15 << OP_CHECKMULTISIG;
keystore.AddCScript(fifteenSigops);
txFrom.vout[4].scriptPubKey = GetScriptForDestination(CScriptID(fifteenSigops));
txFrom.vout[4].nValue = 5000;
// vout[5/6] are non-standard because they exceed MAX_P2SH_SIGOPS
CScript sixteenSigops; sixteenSigops << OP_16 << OP_CHECKMULTISIG;
keystore.AddCScript(sixteenSigops);
txFrom.vout[5].scriptPubKey = GetScriptForDestination(CScriptID(fifteenSigops));
txFrom.vout[5].nValue = 5000;
CScript twentySigops; twentySigops << OP_CHECKMULTISIG;
keystore.AddCScript(twentySigops);
txFrom.vout[6].scriptPubKey = GetScriptForDestination(CScriptID(twentySigops));
txFrom.vout[6].nValue = 6000;
AddCoins(coins, txFrom, 0);
CMutableTransaction txTo;
txTo.vout.resize(1);
txTo.vout[0].scriptPubKey = GetScriptForDestination(key[1].GetPubKey().GetID());
txTo.vin.resize(5);
for (int i = 0; i < 5; i++)
{
txTo.vin[i].prevout.n = i;
txTo.vin[i].prevout.hash = txFrom.GetHash();
}
BOOST_CHECK(SignSignature(keystore, txFrom, txTo, 0));
BOOST_CHECK(SignSignature(keystore, txFrom, txTo, 1));
BOOST_CHECK(SignSignature(keystore, txFrom, txTo, 2));
// SignSignature doesn't know how to sign these. We're
// not testing validating signatures, so just create
// dummy signatures that DO include the correct P2SH scripts:
txTo.vin[3].scriptSig << OP_11 << OP_11 << vector<unsigned char>(oneAndTwo.begin(), oneAndTwo.end());
txTo.vin[4].scriptSig << vector<unsigned char>(fifteenSigops.begin(), fifteenSigops.end());
BOOST_CHECK(::AreInputsStandard(txTo, coins));
// 22 P2SH sigops for all inputs (1 for vin[0], 6 for vin[3], 15 for vin[4]
BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txTo, coins), 22U);
CMutableTransaction txToNonStd1;
txToNonStd1.vout.resize(1);
txToNonStd1.vout[0].scriptPubKey = GetScriptForDestination(key[1].GetPubKey().GetID());
txToNonStd1.vout[0].nValue = 1000;
txToNonStd1.vin.resize(1);
txToNonStd1.vin[0].prevout.n = 5;
txToNonStd1.vin[0].prevout.hash = txFrom.GetHash();
txToNonStd1.vin[0].scriptSig << vector<unsigned char>(sixteenSigops.begin(), sixteenSigops.end());
BOOST_CHECK(!::AreInputsStandard(txToNonStd1, coins));
BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd1, coins), 16U);
CMutableTransaction txToNonStd2;
txToNonStd2.vout.resize(1);
txToNonStd2.vout[0].scriptPubKey = GetScriptForDestination(key[1].GetPubKey().GetID());
txToNonStd2.vout[0].nValue = 1000;
txToNonStd2.vin.resize(1);
txToNonStd2.vin[0].prevout.n = 6;
txToNonStd2.vin[0].prevout.hash = txFrom.GetHash();
txToNonStd2.vin[0].scriptSig << vector<unsigned char>(twentySigops.begin(), twentySigops.end());
BOOST_CHECK(!::AreInputsStandard(txToNonStd2, coins));
BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd2, coins), 20U);
}
BOOST_AUTO_TEST_SUITE_END()
|
#include<iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
cout << a + b;
}
|
#include"localization_ekf/localization_ekf.h"
kalman_filter::kalman_filter()
{
param=new EKF_param();
pose_state={0,0,0};
input_state={0,0,0};
param->F_x=identity;
param->F_u=identity;
param->Q={{abs(input_state[0]),0,0},{0,abs(input_state[1]),0},{0,0,abs(input_state[2])}};
param->P=float(0.01)*(mat<float,3,3>)identity;
// for(int i=0;i<ScanNb;i++)
// {
// param->R[i].R_=float(0.01)*(mat<float,2,2>)identity;
// param->H[i].H_={{0,0},{0,0},{0,0}};
// }
param->R=float(0.01)*(mat<float,2,2>)identity;
param->H={{0,0},{0,0},{0,0}};
param->g=0.01;
param->K_gain={{0,0,0},{0,0,0}};
}
void kalman_filter::setRobotPose(std::vector<float> pose)
{
for(int i=0;i<pose.size();i++)
pose_state[i]=pose[i];
}
void kalman_filter::setRobotInput(std::vector<float> input)
{
for(int i=0;i<input.size();i++)
input_state[i]=input[i];
}
vec<float,3>kalman_filter::transitionFunction(vec<float,3>prev_state,vec<float,3>curr_input)
{
//process model function is defines here
//prev_state(x_t-1,y_t-1,theta_t-1),curr_input(del_x,del_y,del_theta_fromIMU)
return prev_state+curr_input;
}
void kalman_filter:: measurementFunction(vec<float,2>map)
{
Z_j={map[0]-pose_state[2],map[1]-(pose_state[0]*cos(map[0])+pose_state[1]*sin(map[0]))};
param->H={{0,-cos(map[0])},{0,-sin(map[0])},{-1,0}};
}
void kalman_filter::state_prediction()
{
pose_state=transitionFunction(pose_state,input_state);
param->Q={{abs(input_state[0]),0,0},{0,abs(input_state[0]),0},{0,0,abs(input_state[0])}};
param->P=mul(param->F_x,mul(param->P,transpose(param->F_x)))+mul(param->F_u,mul(param->Q,transpose(param->F_u)));
}
void kalman_filter::set_obser_meas_state(std::vector<std::vector<float>>laserScan)
{
scan.reserve(laserScan.size());
scan=laserScan;
}
void kalman_filter::state_update()
{
for(int i=0;i<scan[0].size();i++)
{
mat<float,2,1> v=vec<float,2>{scan[i][0],scan[i][1]}-Z_j;
mat<float,2,2>innov_cov=mul(param->H,mul(param->P,transpose(param->H)))+param->R;
if((mul(transpose(v),mul(inverse(innov_cov),v)))<=(mat<float,1,1>)param->g)
{
param->K_gain=mul(param->P,mul(transpose(param->H),inverse(innov_cov)));
mat<float,3,1> del_pose=mul(param->K_gain,v);
pose_state=pose_state+vec<float,3>{del_pose.row(0)[0],del_pose.row(0)[1],del_pose.row(0)[2]};
param->P=param->P-mul(param->K_gain,mul(innov_cov,transpose(param->K_gain)));
}
}
}
std::vector<float>kalman_filter::get_robotPose()
{
std::vector<float>pose(3);
for(int i=0;i<3;i++)
pose[i]=pose_state[i];
return pose;
}
|
/*
* 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/foas/model/ListInstanceResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Foas;
using namespace AlibabaCloud::Foas::Model;
ListInstanceResult::ListInstanceResult() :
ServiceResult()
{}
ListInstanceResult::ListInstanceResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListInstanceResult::~ListInstanceResult()
{}
void ListInstanceResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allInstancesNode = value["Instances"]["Instance"];
for (auto valueInstancesInstance : allInstancesNode)
{
Instance instancesObject;
if(!valueInstancesInstance["Id"].isNull())
instancesObject.id = std::stol(valueInstancesInstance["Id"].asString());
if(!valueInstancesInstance["ProjectName"].isNull())
instancesObject.projectName = valueInstancesInstance["ProjectName"].asString();
if(!valueInstancesInstance["JobName"].isNull())
instancesObject.jobName = valueInstancesInstance["JobName"].asString();
if(!valueInstancesInstance["ActualState"].isNull())
instancesObject.actualState = valueInstancesInstance["ActualState"].asString();
if(!valueInstancesInstance["ExpectState"].isNull())
instancesObject.expectState = valueInstancesInstance["ExpectState"].asString();
if(!valueInstancesInstance["JobType"].isNull())
instancesObject.jobType = valueInstancesInstance["JobType"].asString();
if(!valueInstancesInstance["ApiType"].isNull())
instancesObject.apiType = valueInstancesInstance["ApiType"].asString();
if(!valueInstancesInstance["Code"].isNull())
instancesObject.code = valueInstancesInstance["Code"].asString();
if(!valueInstancesInstance["Properties"].isNull())
instancesObject.properties = valueInstancesInstance["Properties"].asString();
if(!valueInstancesInstance["Packages"].isNull())
instancesObject.packages = valueInstancesInstance["Packages"].asString();
if(!valueInstancesInstance["Starter"].isNull())
instancesObject.starter = valueInstancesInstance["Starter"].asString();
if(!valueInstancesInstance["StartTime"].isNull())
instancesObject.startTime = std::stol(valueInstancesInstance["StartTime"].asString());
if(!valueInstancesInstance["LastErrorTime"].isNull())
instancesObject.lastErrorTime = std::stol(valueInstancesInstance["LastErrorTime"].asString());
if(!valueInstancesInstance["LastErrorMessage"].isNull())
instancesObject.lastErrorMessage = valueInstancesInstance["LastErrorMessage"].asString();
if(!valueInstancesInstance["LastOperator"].isNull())
instancesObject.lastOperator = valueInstancesInstance["LastOperator"].asString();
if(!valueInstancesInstance["LastOperateTime"].isNull())
instancesObject.lastOperateTime = std::stol(valueInstancesInstance["LastOperateTime"].asString());
if(!valueInstancesInstance["PlanJson"].isNull())
instancesObject.planJson = valueInstancesInstance["PlanJson"].asString();
if(!valueInstancesInstance["EngineVersion"].isNull())
instancesObject.engineVersion = valueInstancesInstance["EngineVersion"].asString();
if(!valueInstancesInstance["EngineJobHandler"].isNull())
instancesObject.engineJobHandler = valueInstancesInstance["EngineJobHandler"].asString();
if(!valueInstancesInstance["InputDelay"].isNull())
instancesObject.inputDelay = std::stol(valueInstancesInstance["InputDelay"].asString());
if(!valueInstancesInstance["ClusterId"].isNull())
instancesObject.clusterId = valueInstancesInstance["ClusterId"].asString();
if(!valueInstancesInstance["QueueName"].isNull())
instancesObject.queueName = valueInstancesInstance["QueueName"].asString();
if(!valueInstancesInstance["EndTime"].isNull())
instancesObject.endTime = std::stol(valueInstancesInstance["EndTime"].asString());
instances_.push_back(instancesObject);
}
if(!value["PageIndex"].isNull())
pageIndex_ = std::stoi(value["PageIndex"].asString());
if(!value["PageSize"].isNull())
pageSize_ = std::stoi(value["PageSize"].asString());
if(!value["TotalPage"].isNull())
totalPage_ = std::stoi(value["TotalPage"].asString());
if(!value["TotalCount"].isNull())
totalCount_ = std::stol(value["TotalCount"].asString());
}
std::vector<ListInstanceResult::Instance> ListInstanceResult::getInstances()const
{
return instances_;
}
long ListInstanceResult::getTotalCount()const
{
return totalCount_;
}
int ListInstanceResult::getPageSize()const
{
return pageSize_;
}
int ListInstanceResult::getTotalPage()const
{
return totalPage_;
}
int ListInstanceResult::getPageIndex()const
{
return pageIndex_;
}
|
#include <iostream>
#include <sstream>
#include <string>
#include <slhaea.h>
using namespace std;
using namespace SLHAea;
int main()
{
double alpha_em = 127.934;
double G_mu = 1.16637e-05;
double alpha_s = 0.1172;
double m_Z = 91.1876;
double m_b = 4.25;
double m_t = 174.3;
double m_tau = 1.777;
Coll out1;
string block = "SMINPUTS";
out1[block][""] << "BLOCK" << block;
out1[block][""] << 1 << alpha_em << "# alpha_em";
out1[block][""] << 2 << G_mu << "# G_mu";
out1[block][""] << 3 << alpha_s << "# alpha_s";
out1[block][""] << 4 << m_Z << "# m_Z";
out1[block][""] << 5 << m_b << "# m_b";
out1[block][""] << 6 << m_t << "# m_t";
out1[block][""] << 7 << m_tau << "# m_tau";
stringstream ss;
ss.precision(8);
ss.setf(ios_base::scientific);
ss << "BLOCK SMINPUTS\n"
<< " 1 " << alpha_em << " # alpha_em\n"
<< " 2 " << G_mu << " # G_mu\n"
<< " 3 " << alpha_s << " # alpha_s\n"
<< " 4 " << m_Z << " # m_Z\n"
<< " 5 " << m_b << " # m_b\n"
<< " 6 " << m_t << " # m_t\n"
<< " 7 " << m_tau << " # m_tau\n";
Coll out2(ss);
cout << out1;
cout << out2;
}
|
// Copyright (c) 2014-2018 Sebastien Rombauts (sebastien.rombauts@gmail.com)
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)
#include "GitSourceControlState.h"
#define LOCTEXT_NAMESPACE "GitSourceControl.State"
int32 FGitSourceControlState::GetHistorySize() const
{
return History.Num();
}
TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetHistoryItem( int32 HistoryIndex ) const
{
check(History.IsValidIndex(HistoryIndex));
return History[HistoryIndex];
}
TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision( int32 RevisionNumber ) const
{
for(const auto& Revision : History)
{
if(Revision->GetRevisionNumber() == RevisionNumber)
{
return Revision;
}
}
return nullptr;
}
TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision(const FString& InRevision) const
{
for(const auto& Revision : History)
{
if(Revision->GetRevision() == InRevision)
{
return Revision;
}
}
return nullptr;
}
TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetBaseRevForMerge() const
{
for(const auto& Revision : History)
{
// look for the the SHA1 id of the file, not the commit id (revision)
if(Revision->FileHash == PendingMergeBaseFileHash)
{
return Revision;
}
}
return nullptr;
}
// @todo add Slate icons for git specific states (NotAtHead vs Conflicted...)
FName FGitSourceControlState::GetIconName() const
{
if(LockState == ELockState::Locked)
{
return FName("Subversion.CheckedOut");
}
else if(LockState == ELockState::LockedOther)
{
return FName("Subversion.CheckedOutByOtherUser");
}
else if (!IsCurrent())
{
return FName("Subversion.NotAtHeadRevision");
}
switch(WorkingCopyState)
{
case EWorkingCopyState::Modified:
if(bUsingGitLfsLocking)
{
return FName("Subversion.NotInDepot");
}
else
{
return FName("Subversion.CheckedOut");
}
case EWorkingCopyState::Added:
return FName("Subversion.OpenForAdd");
case EWorkingCopyState::Renamed:
case EWorkingCopyState::Copied:
return FName("Subversion.Branched");
case EWorkingCopyState::Deleted: // Deleted & Missing files does not show in Content Browser
case EWorkingCopyState::Missing:
return FName("Subversion.MarkedForDelete");
case EWorkingCopyState::Conflicted:
return FName("Subversion.NotAtHeadRevision");
case EWorkingCopyState::NotControlled:
return FName("Subversion.NotInDepot");
case EWorkingCopyState::Unknown:
case EWorkingCopyState::Unchanged: // Unchanged is the same as "Pristine" (not checked out) for Perforce, ie no icon
case EWorkingCopyState::Ignored:
default:
return NAME_None;
}
return NAME_None;
}
FName FGitSourceControlState::GetSmallIconName() const
{
if(LockState == ELockState::Locked)
{
return FName("Subversion.CheckedOut_Small");
}
else if(LockState == ELockState::LockedOther)
{
return FName("Subversion.CheckedOutByOtherUser_Small");
}
else if (!IsCurrent())
{
return FName("Subversion.NotAtHeadRevision_Small");
}
switch(WorkingCopyState)
{
case EWorkingCopyState::Modified:
if(bUsingGitLfsLocking)
{
return FName("Subversion.NotInDepot_Small");
}
else
{
return FName("Subversion.CheckedOut_Small");
}
case EWorkingCopyState::Added:
return FName("Subversion.OpenForAdd_Small");
case EWorkingCopyState::Renamed:
case EWorkingCopyState::Copied:
return FName("Subversion.Branched_Small");
case EWorkingCopyState::Deleted: // Deleted & Missing files can appear in the Submit to Source Control window
case EWorkingCopyState::Missing:
return FName("Subversion.MarkedForDelete_Small");
case EWorkingCopyState::Conflicted:
return FName("Subversion.NotAtHeadRevision_Small");
case EWorkingCopyState::NotControlled:
return FName("Subversion.NotInDepot_Small");
case EWorkingCopyState::Unknown:
case EWorkingCopyState::Unchanged: // Unchanged is the same as "Pristine" (not checked out) for Perforce, ie no icon
case EWorkingCopyState::Ignored:
default:
return NAME_None;
}
return NAME_None;
}
FText FGitSourceControlState::GetDisplayName() const
{
if(LockState == ELockState::Locked)
{
return LOCTEXT("Locked", "Locked For Editing");
}
else if(LockState == ELockState::LockedOther)
{
return FText::Format( LOCTEXT("LockedOther", "Locked by "), FText::FromString(LockUser) );
}
else if (!IsCurrent())
{
return LOCTEXT("NotCurrent", "Not current");
}
switch(WorkingCopyState)
{
case EWorkingCopyState::Unknown:
return LOCTEXT("Unknown", "Unknown");
case EWorkingCopyState::Unchanged:
return LOCTEXT("Unchanged", "Unchanged");
case EWorkingCopyState::Added:
return LOCTEXT("Added", "Added");
case EWorkingCopyState::Deleted:
return LOCTEXT("Deleted", "Deleted");
case EWorkingCopyState::Modified:
return LOCTEXT("Modified", "Modified");
case EWorkingCopyState::Renamed:
return LOCTEXT("Renamed", "Renamed");
case EWorkingCopyState::Copied:
return LOCTEXT("Copied", "Copied");
case EWorkingCopyState::Conflicted:
return LOCTEXT("ContentsConflict", "Contents Conflict");
case EWorkingCopyState::Ignored:
return LOCTEXT("Ignored", "Ignored");
case EWorkingCopyState::NotControlled:
return LOCTEXT("NotControlled", "Not Under Source Control");
case EWorkingCopyState::Missing:
return LOCTEXT("Missing", "Missing");
}
return FText();
}
FText FGitSourceControlState::GetDisplayTooltip() const
{
if(LockState == ELockState::Locked)
{
return LOCTEXT("Locked_Tooltip", "Locked for editing by current user");
}
else if(LockState == ELockState::LockedOther)
{
return FText::Format( LOCTEXT("LockedOther_Tooltip", "Locked for editing by: {0}"), FText::FromString(LockUser) );
}
else if (!IsCurrent())
{
return LOCTEXT("NotCurrent_Tooltip", "The file(s) are not at the head revision");
}
switch(WorkingCopyState)
{
case EWorkingCopyState::Unknown:
return LOCTEXT("Unknown_Tooltip", "Unknown source control state");
case EWorkingCopyState::Unchanged:
return LOCTEXT("Pristine_Tooltip", "There are no modifications");
case EWorkingCopyState::Added:
return LOCTEXT("Added_Tooltip", "Item is scheduled for addition");
case EWorkingCopyState::Deleted:
return LOCTEXT("Deleted_Tooltip", "Item is scheduled for deletion");
case EWorkingCopyState::Modified:
return LOCTEXT("Modified_Tooltip", "Item has been modified");
case EWorkingCopyState::Renamed:
return LOCTEXT("Renamed_Tooltip", "Item has been renamed");
case EWorkingCopyState::Copied:
return LOCTEXT("Copied_Tooltip", "Item has been copied");
case EWorkingCopyState::Conflicted:
return LOCTEXT("ContentsConflict_Tooltip", "The contents of the item conflict with updates received from the repository.");
case EWorkingCopyState::Ignored:
return LOCTEXT("Ignored_Tooltip", "Item is being ignored.");
case EWorkingCopyState::NotControlled:
return LOCTEXT("NotControlled_Tooltip", "Item is not under version control.");
case EWorkingCopyState::Missing:
return LOCTEXT("Missing_Tooltip", "Item is missing (e.g., you moved or deleted it without using Git). This also indicates that a directory is incomplete (a checkout or update was interrupted).");
}
return FText();
}
const FString& FGitSourceControlState::GetFilename() const
{
return LocalFilename;
}
const FDateTime& FGitSourceControlState::GetTimeStamp() const
{
return TimeStamp;
}
// Deleted and Missing assets cannot appear in the Content Browser, but the do in the Submit files to Source Control window!
bool FGitSourceControlState::CanCheckIn() const
{
if(bUsingGitLfsLocking)
{
return ( ( (LockState == ELockState::Locked) && !IsConflicted() ) || (WorkingCopyState == EWorkingCopyState::Added) ) && IsCurrent();
}
else
{
return (WorkingCopyState == EWorkingCopyState::Added
|| WorkingCopyState == EWorkingCopyState::Deleted
|| WorkingCopyState == EWorkingCopyState::Missing
|| WorkingCopyState == EWorkingCopyState::Modified
|| WorkingCopyState == EWorkingCopyState::Renamed) && IsCurrent();
}
}
bool FGitSourceControlState::CanCheckout() const
{
if(bUsingGitLfsLocking)
{
// We don't want to allow checkout if the file is out-of-date, as modifying an out-of-date binary file will most likely result in a merge conflict
return (WorkingCopyState == EWorkingCopyState::Unchanged || WorkingCopyState == EWorkingCopyState::Modified) && LockState == ELockState::NotLocked && IsCurrent();
}
else
{
return false; // With Git all tracked files in the working copy are always already checked-out (as opposed to Perforce)
}
}
bool FGitSourceControlState::IsCheckedOut() const
{
if (bUsingGitLfsLocking)
{
return LockState == ELockState::Locked;
}
else
{
return IsSourceControlled(); // With Git all tracked files in the working copy are always checked-out (as opposed to Perforce)
}
}
bool FGitSourceControlState::IsCheckedOutOther(FString* Who) const
{
if (Who != NULL)
{
*Who = LockUser;
}
return LockState == ELockState::LockedOther;
}
bool FGitSourceControlState::IsCurrent() const
{
return !bNewerVersionOnServer;
}
bool FGitSourceControlState::IsSourceControlled() const
{
return WorkingCopyState != EWorkingCopyState::NotControlled && WorkingCopyState != EWorkingCopyState::Ignored && WorkingCopyState != EWorkingCopyState::Unknown;
}
bool FGitSourceControlState::IsAdded() const
{
return WorkingCopyState == EWorkingCopyState::Added;
}
bool FGitSourceControlState::IsDeleted() const
{
return WorkingCopyState == EWorkingCopyState::Deleted || WorkingCopyState == EWorkingCopyState::Missing;
}
bool FGitSourceControlState::IsIgnored() const
{
return WorkingCopyState == EWorkingCopyState::Ignored;
}
bool FGitSourceControlState::CanEdit() const
{
return IsCurrent(); // With Git all files in the working copy are always editable (as opposed to Perforce)
}
bool FGitSourceControlState::CanDelete() const
{
return !IsCheckedOutOther() && IsSourceControlled() && IsCurrent();
}
bool FGitSourceControlState::IsUnknown() const
{
return WorkingCopyState == EWorkingCopyState::Unknown;
}
bool FGitSourceControlState::IsModified() const
{
// Warning: for Perforce, a checked-out file is locked for modification (whereas with Git all tracked files are checked-out),
// so for a clean "check-in" (commit) checked-out files unmodified should be removed from the changeset (the index)
// http://stackoverflow.com/questions/12357971/what-does-revert-unchanged-files-mean-in-perforce
//
// Thus, before check-in UE4 Editor call RevertUnchangedFiles() in PromptForCheckin() and CheckinFiles().
//
// So here we must take care to enumerate all states that need to be commited,
// all other will be discarded :
// - Unknown
// - Unchanged
// - NotControlled
// - Ignored
return WorkingCopyState == EWorkingCopyState::Added
|| WorkingCopyState == EWorkingCopyState::Deleted
|| WorkingCopyState == EWorkingCopyState::Modified
|| WorkingCopyState == EWorkingCopyState::Renamed
|| WorkingCopyState == EWorkingCopyState::Copied
|| WorkingCopyState == EWorkingCopyState::Missing
|| WorkingCopyState == EWorkingCopyState::Conflicted;
}
bool FGitSourceControlState::CanAdd() const
{
return WorkingCopyState == EWorkingCopyState::NotControlled;
}
bool FGitSourceControlState::IsConflicted() const
{
return WorkingCopyState == EWorkingCopyState::Conflicted;
}
bool FGitSourceControlState::CanRevert() const
{
return CanCheckIn();
}
#undef LOCTEXT_NAMESPACE
|
#pragma once
#include "track.hpp"
#include "transform.hpp"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.