hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d650b090cb4856c74d69fb505b2db3d6f0828e50 | 10,342 | cpp | C++ | src/Layer_Manager.cpp | meredityman/LayerDev | e9a9aa608b6355a1acb34b1e596cd732e998e940 | [
"MIT"
] | 3 | 2020-04-03T11:40:09.000Z | 2020-04-08T04:34:37.000Z | src/Layer_Manager.cpp | meredityman/LayerDev | e9a9aa608b6355a1acb34b1e596cd732e998e940 | [
"MIT"
] | null | null | null | src/Layer_Manager.cpp | meredityman/LayerDev | e9a9aa608b6355a1acb34b1e596cd732e998e940 | [
"MIT"
] | 2 | 2020-03-26T15:47:35.000Z | 2020-04-08T04:34:39.000Z | #include "Layer_Manager.h"
#include "Layers/layer.h"
#include "Preset_layers.h"
#include "GUI/LayerGui.h"
#include "Utils/LayerUtils.h"
using RESOURCE_TYPE = ProjectResource::RESOURCE_TYPE ;
Layer_Manager::Layer_Manager()
{
layer_types = Layer_base::getLayerNames();
gui = new LayerGui();
canvas.setup();
addListeners();
ofDisableArbTex();
}
Layer_Manager::~Layer_Manager()
{
removeListeners();
if (gui != nullptr) delete(gui);
}
shared_ptr<Layer_base> Layer_Manager::add_layer(string name, bool _activate)
{
if (std::find(layer_types.begin(), layer_types.end(), name) == layer_types.end()) {
ofLogWarning(__FUNCTION__) << name << " is not an available layer type";
}
auto layer = Layer_base::create(name, this);
layer->setup(canvas.getWidth(), canvas.getHeight());
layers.push_back(layer);
if (_activate) {
setActiveLayer(layer);
}
return layer;
}
vector<string> Layer_Manager::get_layer_names()
{
return layer_types;
}
void Layer_Manager::setKeyLayer(shared_ptr<Layer_base> _layer) {
auto layer_itr = findLayer(_layer);
if (layer_itr != layers.end()) {
keyLayer = _layer;
}
}
void Layer_Manager::redrawAll()
{
for (auto & layer : layers) {
layer->redraw();
}
}
void Layer_Manager::onMouseMoved(ofMouseEventArgs & _args) {
auto args = canvas.transformMouseEventArgs(_args);
mousePosition = glm::vec2(args.x, args.y);
if (!b_mouseOverGui) canvasMouseMoved.notify(this, args);
}
void Layer_Manager::onMouseDragged(ofMouseEventArgs & _args) {
auto args = canvas.transformMouseEventArgs(_args);
mousePosition = glm::vec2(args.x, args.y);
if (!b_mouseOverGui) canvasMouseDragged.notify(this, args);
}
void Layer_Manager::onMousePressed(ofMouseEventArgs & _args) {
auto args = canvas.transformMouseEventArgs(_args);
mousePosition = glm::vec2(args.x, args.y);
if (!b_mouseOverGui) canvasMousePressed.notify(this, args);
}
void Layer_Manager::onMouseReleased(ofMouseEventArgs & _args) {
auto args = canvas.transformMouseEventArgs(_args);
mousePosition = glm::vec2(args.x, args.y);
if (!b_mouseOverGui) canvasMouseReleased.notify(this, _args);
}
void Layer_Manager::onMouseScrolled(ofMouseEventArgs & _args) {
auto args = canvas.transformMouseEventArgs(_args);
mousePosition = glm::vec2(args.x, args.y);
if (!b_mouseOverGui) canvasMouseScrolled.notify(this, args);
}
void Layer_Manager::onMouseEntered(ofMouseEventArgs & _args) {
auto args = canvas.transformMouseEventArgs(_args);
mousePosition = glm::vec2(args.x, args.y);
if (!b_mouseOverGui) canvasMouseEntered.notify(this, args);
}
void Layer_Manager::onMouseExited(ofMouseEventArgs & _args) {
auto args = canvas.transformMouseEventArgs(_args);
mousePosition = glm::vec2(args.x, args.y);
if (!b_mouseOverGui) canvasMouseExited.notify(this, args);
}
void Layer_Manager::onKeyPressed(ofKeyEventArgs & _args)
{
switch (_args.key) {
case 'o':
b_drawOverlay = !b_drawOverlay;
break;
}
canvasKeyPressed.notify(_args);
}
void Layer_Manager::onKeyReleased(ofKeyEventArgs & _args)
{
canvasKeyReleased.notify(_args);
}
void Layer_Manager::onProjectLoaded(bool & _val)
{
if (!_val) return;
presetLayers = Presets::getPresetLayers(this);
auto potraitLayerFunc = presetLayers.find("Portrait");
if (potraitLayerFunc != presetLayers.end()) {
(potraitLayerFunc->second)(true);
}
}
void Layer_Manager::addListeners()
{
ofAddListener(canvas.canvasResized , this, &Layer_Manager::onCanvasResized);
ofAddListener(canvas.backgroundChanged , this, &Layer_Manager::onBackgroundChanged);
ofAddListener(ofEvents().mouseMoved , this, &Layer_Manager::onMouseMoved );
ofAddListener(ofEvents().mouseDragged , this, &Layer_Manager::onMouseDragged );
ofAddListener(ofEvents().mousePressed , this, &Layer_Manager::onMousePressed );
ofAddListener(ofEvents().mouseReleased , this, &Layer_Manager::onMouseReleased);
ofAddListener(ofEvents().mouseScrolled , this, &Layer_Manager::onMouseScrolled);
ofAddListener(ofEvents().mouseEntered , this, &Layer_Manager::onMouseEntered );
ofAddListener(ofEvents().mouseExited , this, &Layer_Manager::onMouseExited );
ofAddListener(ofEvents().keyPressed , this, &Layer_Manager::onKeyPressed );
ofAddListener(ofEvents().keyReleased , this, &Layer_Manager::onKeyReleased );
ofAddListener(projectManager().onLoaded, this, &Layer_Manager::onProjectLoaded);
}
void Layer_Manager::removeListeners()
{
ofRemoveListener(canvas.canvasResized , this, &Layer_Manager::onCanvasResized);
ofRemoveListener(canvas.backgroundChanged , this, &Layer_Manager::onBackgroundChanged);
ofRemoveListener(ofEvents().mouseMoved , this, &Layer_Manager::onMouseMoved );
ofRemoveListener(ofEvents().mouseDragged , this, &Layer_Manager::onMouseDragged );
ofRemoveListener(ofEvents().mousePressed , this, &Layer_Manager::onMousePressed );
ofRemoveListener(ofEvents().mouseReleased , this, &Layer_Manager::onMouseReleased);
ofRemoveListener(ofEvents().mouseScrolled , this, &Layer_Manager::onMouseScrolled);
ofRemoveListener(ofEvents().mouseEntered , this, &Layer_Manager::onMouseEntered );
ofRemoveListener(ofEvents().mouseExited , this, &Layer_Manager::onMouseExited );
ofRemoveListener(projectManager().onLoaded, this, &Layer_Manager::onProjectLoaded);
}
void Layer_Manager::onCanvasResized(glm::vec2 & _size)
{
for (auto & layer : layers) {
layer->resize(_size.x, _size.y);
}
}
void Layer_Manager::onBackgroundChanged(bool & _var)
{
redrawAll();
}
void Layer_Manager::setActiveLayer(shared_ptr<Layer_base> _layer)
{
if(active_layer != nullptr) active_layer->deactivate();
if (active_layer != _layer) {
active_layer = _layer;
active_layer->activate();
}
else {
active_layer = nullptr;
}
}
deque<shared_ptr<Layer_base>>::iterator Layer_Manager::findLayer(shared_ptr<Layer_base> _layer)
{
for (auto layer = layers.begin(); layer < layers.end(); layer++) {
if (*layer == _layer) return layer;
}
return layers.end();
}
void Layer_Manager::delete_layer(shared_ptr<Layer_base> _layer)
{
auto layer_itr = findLayer(_layer);
if (layer_itr != layers.end()) {
layers.erase(layer_itr);
if (active_layer == _layer) active_layer = nullptr;
}
}
void Layer_Manager::move_layer(shared_ptr<Layer_base> _layer, DIRECTION _dir)
{
if (layers.size() <= 1) return;
auto layer_itr = findLayer(_layer);
if (layer_itr != layers.end()) {
auto layer_itr = findLayer(_layer);
if (_dir == UP) {
auto next = layer_itr + 1;
if (next < layers.end()) {
std::iter_swap(layer_itr, next);
}
}
else if (_dir == DOWN) {
if ( layer_itr != layers.begin() ) {
auto next = layer_itr - 1;
std::iter_swap(layer_itr, next);
}
}
_layer->redraw();
}
}
void Layer_Manager::draw() const
{
bool needsRedraw = false;
for (auto & layer : layers) {
needsRedraw |= layer->needsRedraw();
}
ofEnableBlendMode(ofBlendMode::OF_BLENDMODE_ALPHA);
if (needsRedraw) {
canvas.clearContent();
bool forceRedraw = false;
for (auto & layer : layers) {
auto s_layer = dynamic_pointer_cast<Static_base>(layer);
if (s_layer) {
forceRedraw |= s_layer->draw(canvas.getFbo());
}
else {
auto f_layer = dynamic_pointer_cast<Filter_base>(layer);
if (f_layer) {
forceRedraw |= f_layer->draw(canvas.getFbo(), forceRedraw);
}
}
}
}
else if (layers.size() == 0) {
canvas.clearContent();
}
if (ofGetKeyPressed(' ')) {
layerVisualiser.draw(getLayers());
}
else {
canvas.clearOverlay();
if (active_layer != nullptr && b_drawOverlay) {
active_layer->drawOverlay(canvas.getOverlayFbo());
}
canvas.draw();
}
drawFancyCursor();
}
void Layer_Manager::drawFancyCursor() const
{
ofPushStyle();
string str = "x " + ofToString(mousePosition.x) + "\ny " + ofToString(mousePosition.y) + "\n";
if (active_layer != nullptr) {
str += active_layer->getCursorData();
}
ofSetColor(ofColor::white);
ofDrawBitmapString(str, ofGetMouseX() + 30, ofGetMouseY() + 30);
ofPopStyle();
}
void Layer_Manager::drawGui()
{
gui->draw(this);
b_mouseOverGui = gui->mouseOverGui();
}
void Layer_Manager::update()
{
for (auto & layer : layers) {
layer->update();
}
}
void Layer_Manager::saveAs() const
{
string newPath;
if (LayerUtils::saveImageDialogue(newPath)) {
savePath = newPath;
LayerUtils::saveImage(savePath, canvas.getPixels());
}
}
void Layer_Manager::save() const
{
if (savePath == "") {
saveAs();
}
else {
LayerUtils::saveImage(savePath, canvas.getPixels());
}
}
void Layer_Manager::exportLayers() const
{
string newPath;
if (LayerUtils::saveFolderDialogue(newPath)) {
ProjectManager & projectManager = ProjectManager::getInstance();
string name;
if (projectManager.isLoaded()) name = projectManager.getName() + "_" + ofGetTimestampString();
else name = "output_" + ofGetTimestampString();
string folderPath = ofFilePath::join(newPath, name);
ofDirectory dir(folderPath);
if (!dir.exists()) dir.create();
string imageName = name + "_Beauty.png";
string imagePath = ofFilePath::join(folderPath, imageName);
LayerUtils::saveImage(imagePath, canvas.getPixels());
int index = 0;
for (auto & layer : layers) {
if (layer->isEnabled()) {
string layerName = name + "_L" + ofToString(index++) + ".png";
string layerPath = ofFilePath::join(folderPath, layerName);
layer->saveLayer(layerPath);
}
}
}
}
| 28.490358 | 102 | 0.649584 | [
"vector"
] |
d652273fc167f64598d93896e9a300f6f58c5e69 | 5,589 | cpp | C++ | src/utils/process/ProcessApp.cpp | veprbl/libepecur | 83167ac6220e69887c03b556f1a7ffc518cbb227 | [
"Unlicense"
] | 1 | 2021-06-25T13:41:19.000Z | 2021-06-25T13:41:19.000Z | src/utils/process/ProcessApp.cpp | veprbl/libepecur | 83167ac6220e69887c03b556f1a7ffc518cbb227 | [
"Unlicense"
] | null | null | null | src/utils/process/ProcessApp.cpp | veprbl/libepecur | 83167ac6220e69887c03b556f1a7ffc518cbb227 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <TFile.h>
#include <TSystem.h>
#include <TTree.h>
#include <epecur/geometry.hpp>
#include <epecur/git-rev-export.hpp>
#include "Process2ndPass.hpp"
#include "ProcessApp.hpp"
#include "ProcessMain.hpp"
namespace po = boost::program_options;
using namespace std;
string geometry_filepath;
string input_filepath;
string output_filepath;
double central_momentum;
void ParseCommandLine( int argc, char* argv[] )
{
po::options_description cmdline_options;
po::options_description visible("Allowed options");
visible.add_options()
("help,h", "produce this output")
("geometry-file,g", po::value<string>(), "specify geometry description file")
("output-file,o", po::value<string>(), "output filepath")
("central-momentum,m", po::value<double>(), "central momentum")
;
cmdline_options.add(visible);
po::positional_options_description p;
p.add("input-file", 1);
po::options_description hidden("Hidden options");
hidden.add_options()
("input-file", po::value< vector<string> >(), "input file")
;
cmdline_options.add(hidden);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(cmdline_options).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help") || !vm.count("input-file") || !vm.count("geometry-file") || !vm.count("output-file"))
{
cerr << "Usage: " << argv[0] << " input-file -g geometry-file -o output-file" << endl;
cerr << endl;
cerr << visible << endl;
exit(1);
}
input_filepath = vm["input-file"].as< vector<string> >()[0];
output_filepath = vm["output-file"].as<string>();
geometry_filepath = vm["geometry-file"].as<string>();
if (vm.count("central-momentum"))
{
central_momentum = vm["central-momentum"].as<double>();
}
else
{
cerr << "Please specify central momentum option" << endl;
cerr << visible << endl;
exit(1);
}
if (output_filepath == input_filepath)
{
cerr << "Output filename is identical to input filename." << endl;
exit(1);
}
}
map<string, string> get_info_hash( TTree *info )
{
map<string, string> result;
TBranch *key_br = info->GetBranch("key");
TBranch *value_br = info->GetBranch("value");
void *key_adr = key_br->GetAddress();
void *value_adr = value_br->GetAddress();
char key[MAX_VALUE_LEN];
char value[MAX_VALUE_LEN];
key_br->SetAddress(key);
value_br->SetAddress(value);
int count = info->GetEntries();
for(int i = 0; i < count; i++)
{
info->GetEntry(i);
result[key] = value;
}
key_br->SetAddress(key_adr);
value_br->SetAddress(value_adr);
return result;
}
void add_info_value( TTree *info, string key, string value )
{
info->GetBranch("key")->SetAddress((void*)key.c_str());
info->GetBranch("value")->SetAddress((void*)value.c_str());
info->Fill();
}
bool is_same_size_tree(TTree *tree, Long_t *prev_entries, bool *first)
{
Long_t entries;
TObjArray *ar = tree->GetListOfBranches();
for(Long_t i = 0; i < ar->GetEntries(); i++)
{
TBranch *br = (TBranch*)(*ar)[i];
entries = br->GetEntries();
if ((!*first) && (entries != *prev_entries))
{
return false;
}
*prev_entries = entries;
*first = false;
}
return true;
}
int main( int argc, char* argv[] )
{
ParseCommandLine(argc, argv);
ifstream file(geometry_filepath.c_str(), ios::in);
if (!file.is_open())
{
throw "Couldn't open geometry file!";
}
Geometry geom(file);
TFile input_file(input_filepath.c_str());
TTree *info = (TTree*)input_file.FindObjectAny("info");
TTree *events = (TTree*)input_file.FindObjectAny("events");
TTree *cycle_efficiency = (TTree*)input_file.FindObjectAny("cycle_efficiency");
// Now check that all branches in all tress have the same count of entries
Long_t prev_entries;
bool first = true;
bool result = true;
result &= is_same_size_tree(events, &prev_entries, &first);
result &= is_same_size_tree(cycle_efficiency, &prev_entries, &first);
if (!result)
{
throw "Unbalanced input tree";
}
if (!info)
{
throw "Missing info tree!";
}
info->Scan("key:value", "", "colsize=30");
map<string, string> info_hash = get_info_hash(info);
string file_commit_id = info_hash["GIT_COMMIT_ID"];
if (file_commit_id != GIT_COMMIT_ID)
{
cerr << endl
<< "Warning: Commit id mismatch"
<< endl
<< "File created by: "
<< file_commit_id
<< endl
<< "Current software is: "
<< GIT_COMMIT_ID
<< endl;
}
string original_filename =
gSystem->BaseName(info_hash["INPUT_FILE"].c_str());
cerr << "original_filename\t" << original_filename << endl;
try
{
TFile output_file(output_filepath.c_str(), "RECREATE");
TTree *events_new;
TTree *efficiency_tree;
TTree *info_new = info->CloneTree();
add_info_value(info_new, "PROCESS_GIT_COMMIT_ID", GIT_COMMIT_ID);
intersection_set_t s;
events_new = Process(events, cycle_efficiency, geom, central_momentum, &s);
efficiency_tree = Process2ndPass(events_new);
// Now check that all branches in all tress have the same count of entries
Long_t prev_entries;
bool first = true;
bool result = true;
result &= is_same_size_tree(events_new, &prev_entries, &first);
result &= is_same_size_tree(efficiency_tree, &prev_entries, &first);
if (!result)
{
throw "Unbalanced output tree";
}
output_file.Write();
}
catch(const char *e)
{
cerr << "Exception: " << e << endl;
cerr << "Removing output file \"" << output_filepath << "\"." << endl;
gSystem->Unlink(output_filepath.c_str());
return EXIT_FAILURE;
}
return 0;
}
| 23.987124 | 107 | 0.679728 | [
"geometry",
"vector"
] |
d65fbe45bef126120fdfb5241d6167b171970009 | 1,528 | hpp | C++ | include/Source.hpp | Buerner/ssrface | 226afe2badb432cfef21f40cbce05c2c026d3e19 | [
"MIT"
] | null | null | null | include/Source.hpp | Buerner/ssrface | 226afe2badb432cfef21f40cbce05c2c026d3e19 | [
"MIT"
] | null | null | null | include/Source.hpp | Buerner/ssrface | 226afe2badb432cfef21f40cbce05c2c026d3e19 | [
"MIT"
] | null | null | null | //
// Source.hpp
// SSRconnector
//
// Created by Martin Bürner on 09.06.16.
// Copyright © 2016 Martin Bürner. All rights reserved.
//
#ifndef Source_hpp
#define Source_hpp
#include <string>
#include <map>
#include <math.h>
namespace ssrface {
enum param_idcs {
name,
id,
x,
y,
orientation,
model,
mute,
volume,
fixed,
n_params
};
const std::map<std::string, param_idcs> param_map =
{
{ "name", param_idcs::name },
{ "id", param_idcs::id },
{ "x", param_idcs::x },
{ "y", param_idcs::y },
{ "azimuth", param_idcs::orientation },
{ "model", param_idcs::model },
{ "mute", param_idcs::mute },
{ "volume", param_idcs::volume },
{ "fixed", param_idcs::fixed }
};
/**
@struct Source
@brief This struct stores all the attributes of a source object in the SoundScape Renderer.
*/
struct Source {
unsigned short id;
std::string name{"Bob"};
float x = 0.f;
float y = 0.f;
float orientation = 0.f;
std::string model = "point";
bool mute = false;
float volume = 1.f;
bool fixed = false;
float distance_to( Source* src )
{
return sqrtf( powf(x - src->x, 2.f) + powf(y - src->y, 2.f) );
}
float angle_to( Source* src )
{
float delta_x = src->x - x;
float delta_y = src->y - y * M_PI;
return atanf( delta_y / delta_x ) - orientation;
}
void print();
};
} // Namespace ssrface
#endif /* Source_hpp */
| 19.1 | 92 | 0.560209 | [
"object",
"model"
] |
d664fcfb2f5bb236ed8348fbdf01af23db3bf919 | 447 | cpp | C++ | Dataset/Leetcode/train/22/657.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/22/657.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/22/657.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
//如果使用char str[]则需要记录一个cur
void print_kuohao(vector<string>&res, string str, int l, int r, int n){
if(l == n && r == n){res.push_back(str); return;}
if(l < n)print_kuohao(res, str + '(', l + 1, r, n);
if(r < l)print_kuohao(res, str + ')', l, r + 1, n);
}
vector<string> XXX(int n) {
vector<string> res;
print_kuohao(res, "", 0, 0, n);
return res;
}
};
| 27.9375 | 75 | 0.519016 | [
"vector"
] |
69943b56a590e25ffb86a5b58e2ced95d42e44a8 | 1,791 | cc | C++ | feeder/data_iterator_test.cc | disktnk/chainer-compiler | 5cfd027b40ea6e4abf73eb42be70b4fba74d1cde | [
"MIT"
] | 116 | 2019-01-25T03:54:44.000Z | 2022-03-08T00:11:14.000Z | feeder/data_iterator_test.cc | disktnk/chainer-compiler | 5cfd027b40ea6e4abf73eb42be70b4fba74d1cde | [
"MIT"
] | 431 | 2019-01-25T10:18:44.000Z | 2020-06-17T05:28:55.000Z | feeder/data_iterator_test.cc | disktnk/chainer-compiler | 5cfd027b40ea6e4abf73eb42be70b4fba74d1cde | [
"MIT"
] | 26 | 2019-01-25T07:21:09.000Z | 2021-11-26T04:24:35.000Z | #include <cstring>
#include <memory>
#include <gtest/gtest.h>
#include <chainerx/array.h>
#include <chainerx/context.h>
#include <chainerx/routines/creation.h>
#include <chainerx/routines/manipulation.h>
#include <feeder/data_iterator.h>
namespace {
class MyDataIterator : public DataIterator {
public:
explicit MyDataIterator(int end = 999) : DataIterator(3), end_(end) {
}
std::vector<chainerx::Array> GetNextImpl() override {
if (counter_ == end_) return {};
std::shared_ptr<void> data(new char[sizeof(counter_)], std::default_delete<char[]>());
std::memcpy(data.get(), &counter_, sizeof(counter_));
chainerx::Array array = chainerx::FromContiguousHostData({}, chainerx::Dtype::kInt32, data);
counter_++;
return {array};
}
private:
int counter_ = 42;
int end_;
};
TEST(TestDataIterator, Basic) {
chainerx::Context ctx;
chainerx::SetGlobalDefaultContext(&ctx);
MyDataIterator iter;
iter.Start();
EXPECT_EQ(42, int64_t(chainerx::AsScalar(iter.GetNext()[0])));
EXPECT_EQ(43, int64_t(chainerx::AsScalar(iter.GetNext()[0])));
EXPECT_EQ(44, int64_t(chainerx::AsScalar(iter.GetNext()[0])));
EXPECT_EQ(45, int64_t(chainerx::AsScalar(iter.GetNext()[0])));
EXPECT_EQ(46, int64_t(chainerx::AsScalar(iter.GetNext()[0])));
iter.Terminate();
}
TEST(TestDataIterator, Finish) {
chainerx::Context ctx;
chainerx::SetGlobalDefaultContext(&ctx);
MyDataIterator iter(45);
iter.Start();
EXPECT_EQ(42, int64_t(chainerx::AsScalar(iter.GetNext()[0])));
EXPECT_EQ(43, int64_t(chainerx::AsScalar(iter.GetNext()[0])));
EXPECT_EQ(44, int64_t(chainerx::AsScalar(iter.GetNext()[0])));
EXPECT_TRUE(iter.GetNext().empty());
iter.Terminate();
}
} // namespace
| 28.887097 | 100 | 0.673925 | [
"vector"
] |
6994e328cfad2e661587da915f00a518953c312a | 10,653 | cpp | C++ | main.cpp | ryskina/romanization-decipherment | 7c9a64e574b54671988017e442e20585b1a6559a | [
"MIT"
] | 3 | 2020-06-29T19:28:41.000Z | 2021-02-10T02:49:38.000Z | main.cpp | ryskina/romanization-decipherment | 7c9a64e574b54671988017e442e20585b1a6559a | [
"MIT"
] | null | null | null | main.cpp | ryskina/romanization-decipherment | 7c9a64e574b54671988017e442e20585b1a6559a | [
"MIT"
] | null | null | null | /*
* main.cpp
*
* Created on: Oct 24, 2019
* Author: Maria Ryskina
*/
#include <list>
#include <ctime>
#include <math.h>
#include <dirent.h>
#include <getopt.h>
#include <sys/stat.h>
#include <fst/fstlib.h>
#include <ngram/ngram.h>
#include "data_utils.h"
#include "fst_utils.h"
#include "base_fst.h"
#include "emission.h"
#include "lm.h"
#include "model.h"
using namespace fst;
// Default hyperparameter settings
int seed = 0;
int batch_size = 10;
int upgrade_lm_every = 100;
int upgrade_lm_by = 1;
int max_delay = 2;
float freeze_at = -1; // no freezing
std::string dataset;
std::string prior = "uniform";
bool run_supervised = false;
bool no_epsilons = false;
bool no_test = false;
bool no_save = false;
/*
* Argument parsing functions
*/
void PrintHelp() {
std::cout <<
"USAGE (unsupervised):\n"
" ./decipher --dataset {ru|ar} [--seed S] [--batch-size B] [--upgrade-lm-every E] [--upgrade-lm-by U]"
" [--prior {phonetic|visual|combined}] [--freeze-at F] [--no-epsilons] [--no-test] [--no-save]\n"
"USAGE (supervised):\n"
" ./decipher --dataset {ru|ar} --supervised [--seed S] [--batch-size B] [--no-test] [--no-save]\n\n"
"OPTIONS:\n"
"--dataset {ru|ar}: Dataset (Russian or Arabic; mandatory parameter)\n"
"--seed S: Set random seed to S (int; default 0)\n"
"--batch-size B: Mini-batch size for stepwise EM training "
"(unsupervised only; int; default 10)\n"
"--upgrade-lm-every E: Increasing language model order after processing every E batches "
"(unsupervised only; int; default 100)\n"
"--upgrade-lm-by U: Increasing language model order by U each time "
"(unsupervised only; int; default 1)\n"
"--prior {phonetic|visual|combined}: Prior on emission parameters "
"(unsupervised training only; default = uniform)\n"
"--freeze-at F: Train with freezing insertion and deletion probabilities at F "
"for the first E batches (unsupervised only; float; "
"no freezing by default)\n"
"--supervised: Train a supervised model on validation data\n"
"--no-epsilons: Turn off insertions and deletions (unsupervised only)\n"
"--no-test: Turn off testing\n"
"--no-save: Turn off model saving\n"
"--help: Display help\n";
exit(1);
}
void ProcessArgs(int argc, char* argv[]) {
const char* const short_opts = "d:n:b:e:u:p:f:srtvh";
const option long_opts[] = {
{"dataset", required_argument, nullptr, 'd'},
{"seed", required_argument, nullptr, 'n'},
{"batch-size", required_argument, nullptr, 'b'},
{"upgrade-lm-every", required_argument, nullptr, 'e'},
{"upgrade-lm-by", required_argument, nullptr, 'u'},
{"prior", required_argument, nullptr, 'p'},
{"freeze-at", required_argument, nullptr, 'f'},
{"supervised", no_argument, nullptr, 's'},
{"no-epsilons", no_argument, nullptr, 'r'},
{"no-test", no_argument, nullptr, 't'},
{"no-save", no_argument, nullptr, 'v'},
{"help", no_argument, nullptr, 'h'},
{nullptr, no_argument, nullptr, 0}
};
while (true) {
const auto opt = getopt_long(argc, argv, short_opts, long_opts, nullptr);
if (-1 == opt)
break;
switch (opt)
{
case 'd':
dataset = std::string(optarg);
if (dataset != "ru" && dataset != "ar") {
std::cout << "Error: Unknown dataset option: " << dataset << std::endl;
PrintHelp();
break;
}
std::cout << "Dataset: " << dataset << std::endl;
break;
case 'n':
seed = std::stoi(optarg);
break;
case 'b':
batch_size = std::stoi(optarg);
break;
case 'e':
upgrade_lm_every = std::stoi(optarg);
break;
case 'u':
upgrade_lm_by = std::stoi(optarg);
break;
case 'p':
prior = std::string(optarg);
if (prior != "phonetic" && prior != "visual" && prior != "combined") {
std::cout << "Error: Unknown prior option: " << prior << std::endl;
PrintHelp();
break;
}
break;
case 'f':
freeze_at = std::stof(optarg);
break;
case 's':
run_supervised = true;
break;
case 'r':
no_epsilons = true;
break;
case 't':
no_test = true;
break;
case 'v':
no_save = true;
break;
case 'h': // -h or --help
case '?': // Unrecognized option
default:
PrintHelp();
break;
}
}
if (dataset.empty()) {
std::cout << "Error: No dataset specified\n";
PrintHelp();
} else {
if (dataset == "ar") max_delay = 5;
std::cout << "Maximum emission model delay: " << max_delay << std::endl;
}
if (run_supervised) {
std::cout << "Training a supervised model\n";
} else {
std::cout << "Training an unsupervised model with " << prior << " prior\n";
std::cout << "Mini-batch size: " << batch_size << std::endl;
std::cout << "Language model order will be increased every " << upgrade_lm_every << " batches\n";
std::cout << "Language model order will be increased by " << upgrade_lm_by << " each time\n";
if (freeze_at > 0) {
std::cout << "Insertion and deletion probabilities frozen at " << exp(-freeze_at) <<
" (" << freeze_at << " in negative log space) for the first " <<
upgrade_lm_every << " batches\n";
}
}
std::cout << "Seed: " << seed << std::endl;
}
int main(int argc, char* argv[]) {
ProcessArgs(argc, argv);
std::string data_dir = "./data/" + dataset;
mkdir("./output/", 0777);
std::string output_dir = "./output/" + dataset;
if (run_supervised) {
output_dir = output_dir + "_sup_seed-" + std::to_string(seed);
} else {
output_dir = output_dir + "_uns_" + prior + "_seed-" + std::to_string(seed) +
"_upgrade-lm-every-" + std::to_string(upgrade_lm_every) +
"-by-" + std::to_string(upgrade_lm_by);
if (no_epsilons) {
output_dir += "_no-epsilons";
}
if (freeze_at >= 0) {
output_dir += "_freeze-" + std::to_string(freeze_at);
}
}
mkdir(output_dir.c_str(), 0777);
std::cout << "Saving models and output files to " << output_dir << std::endl;
Indexer origIndexer = Indexer(data_dir + "/alphabet_orig.txt");
Indexer latinIndexer = Indexer(data_dir + "/alphabet_latin.txt");
IndexedStrings trainData(&latinIndexer, &origIndexer);
DataUtils::readAndIndex(data_dir + "/data_train.txt", &trainData);
std::cout << "\nLoaded " << trainData.latinIndices.size() << " training sentences\n";
IndexedStrings devData(&latinIndexer, &origIndexer);
DataUtils::readAndIndex(data_dir + "/data_dev.txt", &devData);
std::cout << "Loaded " << devData.latinIndices.size() << " validation sentence pairs\n";
IndexedStrings testData(&latinIndexer, &origIndexer);
if (!no_test) {
DataUtils::readAndIndex(data_dir + "/data_test.txt", &testData);
std::cout << "Loaded " << testData.latinIndices.size() << " test sentence pairs\n";
} else {
std::cout << "Testing turned off\n";
}
IndexedStrings lmTrainData(&latinIndexer, &origIndexer);
DataUtils::readAndIndex(data_dir + "/data_lm.txt", &lmTrainData);
std::cout << "Loaded " << lmTrainData.latinIndices.size() << " monolingual LM training sentences\n";
if (!latinIndexer.locked) latinIndexer.lock();
if (!origIndexer.locked) origIndexer.lock();
if (run_supervised) {
std::cout << "\nTraining the language model of the original orthography...\n";
VectorFst<StdArc> lmFst = trainLmOpenGRM(lmTrainData, origIndexer.getSize(), 6, output_dir, no_save);
std::cout << "Done\n";
std::cout << "\nTraining the emission model on validation data...\n";
EmissionTropicalSemiring tropicalEm = trainEmission(devData, max_delay, origIndexer.getSize(),
latinIndexer.getSize(), seed, output_dir, no_save);
std::cout << "Done\n";
Model model(lmFst, tropicalEm);
if (!no_save) {
std::string model_outfile = output_dir + "/model.fst";
std::cout << "\nComposing and saving the base lattice to: " << model_outfile << std::endl;
VectorFst<StdArc> allStatesLattice;
lmPhiCompose<StdArc>(model.lmStd, model.emStd, &allStatesLattice);
allStatesLattice.Write(model_outfile);
}
if (!no_test) {
std::cout << "\nTesting...\n";
std::string prediction_file = output_dir + "/prediction.txt";
std::cout << "Writing predictions to " << prediction_file << std::endl;
float cer = model.test(testData, PHI_MATCH, true, prediction_file);
std::cout << "CER: " << cer << std::endl;
} else {
// Printing the emission parameters
model.emStd.printProbsWithLabels(model.emStd.logProbs, &origIndexer,
&latinIndexer, model.emStd.orig_epsilon, model.emStd.latin_epsilon);
}
} else {
std::vector<std::vector<int>> monolingualTrain = trainData.latinIndices;
std::sort(monolingualTrain.begin(), monolingualTrain.end(),
[](const std::vector<int> &a, const std::vector<int> &b){ return a.size() < b.size(); });
std::cout << "\nTraining the language models of the original orthography...\n";
std::vector<VectorFst<StdArc>> lmFstArray;
// While insertion/deletion probabilities are kept frozen,
// the language model disallows epsilons (insertions) to keep the model locally normalized
for (int order = 2; order <= 6; order++) lmFstArray.push_back(
trainLmOpenGRM(lmTrainData, origIndexer.getSize(), order, output_dir, no_save,
no_epsilons || (freeze_at >= 0 && order == 2)));
std::vector<std::pair<int, int>> priorMappings;
if (prior != "uniform") {
std::string priorFname = data_dir + "/prior_" + prior + ".txt";
priorMappings = DataUtils::readPrior(priorFname, &latinIndexer, &origIndexer);
std::cout << "Initializing with the " << prior << " prior\n";
}
Trainer trainer(lmFstArray, max_delay, &origIndexer, &latinIndexer, seed, priorMappings,
no_epsilons, freeze_at);
trainer.train(monolingualTrain, devData, testData, output_dir, batch_size, upgrade_lm_every,
upgrade_lm_by, PHI_MATCH, true, no_save);
}
return 0;
}
| 35.51 | 109 | 0.59495 | [
"vector",
"model"
] |
69a23c505f4053460ece96efcad4833b97a8201e | 9,504 | cpp | C++ | ROS_Eploration/agv_exploration/src/AgvExplorer.cpp | WarOfDevil/AGV | 3891570995f639081d7865098c19efbed27e33f9 | [
"MIT"
] | null | null | null | ROS_Eploration/agv_exploration/src/AgvExplorer.cpp | WarOfDevil/AGV | 3891570995f639081d7865098c19efbed27e33f9 | [
"MIT"
] | null | null | null | ROS_Eploration/agv_exploration/src/AgvExplorer.cpp | WarOfDevil/AGV | 3891570995f639081d7865098c19efbed27e33f9 | [
"MIT"
] | null | null | null | #include <agv_exploration/AgvExplorer.h>
#include <actionlib/client/simple_action_client.h>
#include <nav2d_navigator/GetFirstMapAction.h>
#include <nav2d_navigator/GetFirstMapGoal.h>
#include <nav2d_navigator/ExploreAction.h>
#include <nav2d_navigator/ExploreGoal.h>
#include <nav2d_operator/cmd.h>
#include <actionlib_msgs/GoalStatusArray.h>
#include <tf/transform_listener.h>
#include <agv_exploration/StartExplorationGoal.h>
using namespace agv_exploration;
using namespace actionlib;
using namespace tf;
using namespace nav2d_navigator;
using namespace nav2d_operator;
using namespace ros;
/**
* Constructor.
* @param n The ROS node handle.
*/
AgvExplorer::AgvExplorer(NodeHandle n)
{
// Get parameters from parameters server.
n.param("wait_for_server_duration", this->waitForServerDuration_, WAIT_FOR_SERVER_DURATION);
n.param(
"wait_for_get_first_map_duration",
this->waitForGetFirstMapDuration_,
WAIT_FOR_GET_FIRST_MAP_DURATION);
n.param(
"unstuck_after_not_moving_for_seconds",
this->unstuckAfterNotMovingForSeconds_,
UNSTUCK_AFTER_NOT_MOVING_FOR_SECONDS);
n.param(
"try_unstuck_seconds_per_direction",
this->tryUnstuckSecondsPerDirection_,
TRY_UNSTUCK_SECONDS_PER_DIRECTION);
n.param("max_retries", this->maxRetries_, MAX_RETRIES);
this->cmdPublisher_ = n.advertise<cmd>("cmd", 1000);
this->listener_ = new TransformListener();
this->startExplorationServer_ =
new SimpleActionServer<StartExplorationAction>(n, "AgvStartExploration", false);
this->startExplorationServer_->registerGoalCallback(boost::bind(&AgvExplorer::goalCallback, this));
this->startExplorationServer_->start();
spin();
}
/**
* Destructor.
*/
AgvExplorer::~AgvExplorer()
{
this->startExplorationServer_->shutdown();
delete this->listener_;
delete this->startExplorationServer_;
}
/**
* Gets the initial map. Will make the AGV move forward and then do a 360 degrees rotation.
*/
void AgvExplorer::getFirstMap()
{
SimpleActionClient<GetFirstMapAction> getFirstMapClient("GetFirstMap", true);
ROS_INFO("Waiting for Nav2d GetFirstMap server");
getFirstMapClient.waitForServer(Duration(this->waitForServerDuration_));
GetFirstMapGoal getFirstMapGoal;
ROS_INFO("Started mapping");
getFirstMapClient.sendGoalAndWait(getFirstMapGoal, Duration(this->waitForGetFirstMapDuration_));
getFirstMapClient.cancelAllGoals();
ROS_INFO("Mapping completed");
}
/**
* Starts exploration of the environment. The function handles stuck issues and returns when the exploration is
* completed.
*/
void AgvExplorer::startExploration()
{
SimpleActionClient<ExploreAction> *exploreClient = new SimpleActionClient<ExploreAction>("Explore", true);
ROS_INFO("Waiting for Nav2d Explore server");
exploreClient->waitForServer(Duration(this->waitForServerDuration_));
ExploreGoal exploreGoal;
ROS_INFO("Started exploration");
exploreClient->sendGoal(exploreGoal);
Duration d(this->unstuckAfterNotMovingForSeconds_);
StampedTransform previousAgvTransform, currentAgvTransform = getAgvTransform();
short restartingAttemptCounter = 1;
// Wait initially.
d.sleep();
do
{
// Check if the exploration goal should be preempted and stop exploration.
if (this->startExplorationServer_->isPreemptRequested())
{
exploreClient->cancelAllGoals();
this->startExplorationServer_->setPreempted();
ROS_WARN("Exploration cancelled.");
break;
}
// Aborted or preempted state can occur when the exploration crashes because of not being able to find
// path to the goal or because of the robot being stuck.
SimpleClientGoalState currentActionState = exploreClient->getState();
if (currentActionState == SimpleClientGoalState::ABORTED ||
currentActionState == SimpleClientGoalState::PREEMPTED)
{
if (restartingAttemptCounter > this->maxRetries_)
{
ROS_ERROR(
"Exploration crashed critically. Unable to recover after %d retries.", this->maxRetries_);
this->startExplorationServer_->setAborted();
break;
}
tryUnstuck();
// If the exploration was aborted, restart it.
ROS_WARN("Exploration was aborted. Restarting %d time...", restartingAttemptCounter);
exploreClient = new SimpleActionClient<ExploreAction>("/Explore", true);
exploreClient->sendGoal(exploreGoal);
// Increment restart counter.
restartingAttemptCounter++;
}
else
{
// If the restart was successful, then reset the counter.
restartingAttemptCounter = 1;
}
// The AGV can also get stuck without the exploration being aborted or preempted, therefore we check
// again here.
currentAgvTransform = getAgvTransform();
if (!hasAgvMoved(previousAgvTransform, currentAgvTransform))
{
ROS_WARN("AGV is stuck");
tryUnstuck();
}
// Set the current transform, pose and yaw as previous and then wait.
previousAgvTransform = currentAgvTransform;
d.sleep();
} while (exploreClient->getState() != SimpleClientGoalState::SUCCEEDED);
if (this->startExplorationServer_->isActive())
{
// Set succeeded only when the exploration was not cancelled.
ROS_INFO("Exploration completed");
this->startExplorationServer_->setSucceeded();
}
delete exploreClient;
}
/**
* Gets the current AGV transform used to determine its position and orientation.
* @return A StampedTransform representing the AGV's current position and orientation.
*/
StampedTransform AgvExplorer::getAgvTransform()
{
StampedTransform transform;
try
{
// Get the latest available transform.
this->listener_->lookupTransform("map", "base_link", Time(0), transform);
}
catch (TransformException &ex)
{
ROS_ERROR("%s", ex.what());
}
return transform;
}
/**
* Tries to unstuck the AGV by moving in different direction for specified by tryUnstuckSecondsPerDirection amount of
* seconds.
* @param unstuckType The unstuck direction to which the AGV should move.
*/
void AgvExplorer::tryUnstuck(short unstuckType)
{
StampedTransform previousAgvTransform = getAgvTransform();
cmd cmd;
ros::Duration d(this->tryUnstuckSecondsPerDirection_);
// Turn [-1.0 .. 1.0]: -1(rotate left); 0(straight); 1(rotate right)
// Velocity [-1.0 .. 1.0]: -1(full speed back); 0(stop); 1(full speed ahead)
// Mode: 0(Avoid obstacles); 1(Stop at obstacles)
switch (unstuckType)
{
case UNSTUCK_FORWARD:
cmd.Mode = 0;
cmd.Turn = 0;
cmd.Velocity = 1;
ROS_INFO("Trying to unstuck by moving forward...");
break;
case UNSTUCK_BACKWARDS:
cmd.Mode = 0;
cmd.Turn = 0;
cmd.Velocity = -1;
ROS_INFO("Trying to unstuck by moving backwards...");
break;
case UNSTUCK_LEFT:
cmd.Mode = 0;
cmd.Turn = -1;
cmd.Velocity = 1;
ROS_INFO("Trying to unstuck by moving left...");
break;
case UNSTUCK_RIGHT:
cmd.Mode = 0;
cmd.Turn = 1;
cmd.Velocity = 1;
ROS_INFO("Trying to unstuck by moving right...");
break;
}
// Move for 1 second in the specified direction and then stop.
this->cmdPublisher_.publish(cmd);
d.sleep();
cmd.Velocity = 0;
this->cmdPublisher_.publish(cmd);
// If the AGV has not changed its position or orientation it means that unstucking in the current direction was not
// successful. We increase the unstuck type if it is less than the maximum allowed value and retry.
if (!hasAgvMoved(previousAgvTransform, getAgvTransform()) && unstuckType < UNSTUCK_RIGHT)
{
tryUnstuck(++unstuckType);
}
}
/**
* Executed on receiving a new goal.
*/
void AgvExplorer::goalCallback()
{
this->startExplorationServer_->acceptNewGoal();
ROS_INFO("Goal accepted.");
this->getFirstMap();
// Run the exploration loop on a separate thread so it does not block the communication with the
// exploration server.
boost::thread t1(boost::bind(&AgvExplorer::startExploration, this));
}
/**
* Checks whether the AGV has changed its position or orientation. By using the previous and current AGV
* transformations.
* @param previousAgvTransform The last AGV transformation.
* @param currentAgvTransform The current AGV transformation.
* @return True if the AGV has changed its position or orientation, otherwise false.
*/
bool AgvExplorer::hasAgvMoved(StampedTransform previousAgvTransform, StampedTransform currentAgvTransform)
{
Vector3 previousAgvPose, currentAgvPose;
double previousAgvYaw, currentAgvYaw;
previousAgvPose = previousAgvTransform.getOrigin();
currentAgvPose = currentAgvTransform.getOrigin();
previousAgvYaw = getYaw(previousAgvTransform.getRotation());
currentAgvYaw = getYaw(currentAgvTransform.getRotation());
// If X, Y and Yaw of the AGV are the same, then it has not moved.
return !(previousAgvPose.getX() == currentAgvPose.getX() &&
previousAgvPose.getY() == currentAgvPose.getY() &&
previousAgvYaw == currentAgvYaw);
} | 34.18705 | 119 | 0.688763 | [
"transform"
] |
69a3bc5be6c5a59d85e475a9ab6a9647ba616cee | 8,561 | cpp | C++ | com/win32com/src/extensions/PyIPropertySetStorage.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | 3 | 2020-06-18T16:57:44.000Z | 2020-07-21T17:52:06.000Z | com/win32com/src/extensions/PyIPropertySetStorage.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | null | null | null | com/win32com/src/extensions/PyIPropertySetStorage.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | null | null | null | // This file implements the IPropertySetStorage Interface and Gateway for Python.
// Generated by makegw.py
#include "stdafx.h"
#include "PythonCOM.h"
#include "PythonCOMServer.h"
#ifndef NO_PYCOM_IPROPERTYSETSTORAGE
#include "PyIPropertySetStorage.h"
// @doc - This file contains autoduck documentation
// ---------------------------------------------------
//
// Interface Implementation
PyIPropertySetStorage::PyIPropertySetStorage(IUnknown *pdisp) : PyIUnknown(pdisp) { ob_type = &type; }
PyIPropertySetStorage::~PyIPropertySetStorage() {}
/* static */ IPropertySetStorage *PyIPropertySetStorage::GetI(PyObject *self)
{
return (IPropertySetStorage *)PyIUnknown::GetI(self);
}
// @pymethod <o PyIPropertyStorage>|PyIPropertySetStorage|Create|Creates a new property set in the storage object
PyObject *PyIPropertySetStorage::Create(PyObject *self, PyObject *args)
{
IPropertySetStorage *pIPSS = GetI(self);
if (pIPSS == NULL)
return NULL;
FMTID rfmtid;
PyObject *obrfmtid;
CLSID pclsid;
PyObject *obpclsid;
// @pyparm <o PyIID>|fmtid||GUID identifying a property set, pythoncom.FMTID_*
// @pyparm <o PyIID>|clsid||CLSID of property set handler, usually same as fmtid
// @pyparm int|Flags||Specifies behaviour of property set, storagecon.PROPSETFLAG_*
// @pyparm int|Mode||Access mode, combination of storagecon.STGM_* flags
DWORD grfFlags;
DWORD grfMode;
IPropertyStorage *ppprstg;
if (!PyArg_ParseTuple(args, "OOll:Create", &obrfmtid, &obpclsid, &grfFlags, &grfMode))
return NULL;
BOOL bPythonIsHappy = TRUE;
if (bPythonIsHappy && !PyWinObject_AsIID(obrfmtid, &rfmtid))
bPythonIsHappy = FALSE;
if (bPythonIsHappy && !PyWinObject_AsIID(obpclsid, &pclsid))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
HRESULT hr;
PY_INTERFACE_PRECALL;
hr = pIPSS->Create(rfmtid, &pclsid, grfFlags, grfMode, &ppprstg);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr, pIPSS, IID_IPropertySetStorage);
return PyCom_PyObjectFromIUnknown(ppprstg, IID_IPropertyStorage, FALSE);
}
// @pymethod <o PyIPropertyStorage>|PyIPropertySetStorage|Open|Opens an existing property set
PyObject *PyIPropertySetStorage::Open(PyObject *self, PyObject *args)
{
IPropertySetStorage *pIPSS = GetI(self);
if (pIPSS == NULL)
return NULL;
FMTID rfmtid;
PyObject *obrfmtid;
// @pyparm <o PyIID>|fmtid||GUID of a property set, pythoncom.FMTID_*
// @pyparm int|Mode|STGM_READ \| STGM_SHARE_EXCLUSIVE|Access mode, combination of storagecon.STGM_* flags
DWORD grfMode = STGM_READ | STGM_SHARE_EXCLUSIVE;
IPropertyStorage *ppprstg;
if (!PyArg_ParseTuple(args, "O|l:Open", &obrfmtid, &grfMode))
return NULL;
if (!PyWinObject_AsIID(obrfmtid, &rfmtid))
return NULL;
HRESULT hr;
PY_INTERFACE_PRECALL;
hr = pIPSS->Open(rfmtid, grfMode, &ppprstg);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr, pIPSS, IID_IPropertySetStorage);
return PyCom_PyObjectFromIUnknown(ppprstg, IID_IPropertyStorage, FALSE);
}
// @pymethod |PyIPropertySetStorage|Delete|Removes a property set from this storage object
PyObject *PyIPropertySetStorage::Delete(PyObject *self, PyObject *args)
{
IPropertySetStorage *pIPSS = GetI(self);
if (pIPSS == NULL)
return NULL;
FMTID rfmtid;
PyObject *obrfmtid;
// @pyparm <o PyIID>|fmtid||GUID of a property set, pythoncom.FMTID_*
if (!PyArg_ParseTuple(args, "O:Delete", &obrfmtid))
return NULL;
if (!PyWinObject_AsIID(obrfmtid, &rfmtid))
return NULL;
HRESULT hr;
PY_INTERFACE_PRECALL;
hr = pIPSS->Delete(rfmtid);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr, pIPSS, IID_IPropertySetStorage);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod <o PyIEnumSTATPROPSETSTG>|PyIPropertySetStorage|Enum|Creates an iterator to enumerate contained property
// sets
PyObject *PyIPropertySetStorage::Enum(PyObject *self, PyObject *args)
{
IPropertySetStorage *pIPSS = GetI(self);
if (pIPSS == NULL)
return NULL;
IEnumSTATPROPSETSTG *ppenum;
if (!PyArg_ParseTuple(args, ":Enum"))
return NULL;
HRESULT hr;
PY_INTERFACE_PRECALL;
hr = pIPSS->Enum(&ppenum);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr, pIPSS, IID_IPropertySetStorage);
return PyCom_PyObjectFromIUnknown(ppenum, IID_IEnumSTATPROPSETSTG, FALSE);
}
// @object PyIPropertySetStorage|Container for a collection of property sets.
// Can be iterated over to enumerate property sets.
static struct PyMethodDef PyIPropertySetStorage_methods[] = {
{"Create", PyIPropertySetStorage::Create, 1}, // @pymeth Create|Creates a new property set in the storage object
{"Open", PyIPropertySetStorage::Open, 1}, // @pymeth Open|Opens an existing property set
{"Delete", PyIPropertySetStorage::Delete, 1}, // @pymeth Delete|Removes a property set from this storage object
{"Enum", PyIPropertySetStorage::Enum, 1}, // @pymeth Enum|Creates an iterator to enumerate contained property sets
{NULL}};
PyComEnumProviderTypeObject PyIPropertySetStorage::type("PyIPropertySetStorage", &PyIUnknown::type,
sizeof(PyIPropertySetStorage), PyIPropertySetStorage_methods,
GET_PYCOM_CTOR(PyIPropertySetStorage), "Enum");
// ---------------------------------------------------
//
// Gateway Implementation
STDMETHODIMP PyGPropertySetStorage::Create(
/* [in] */ REFFMTID rfmtid,
/* [unique][in] */ const CLSID *pclsid,
/* [in] */ DWORD grfFlags,
/* [in] */ DWORD grfMode,
/* [out] */ IPropertyStorage **ppprstg)
{
PY_GATEWAY_METHOD;
if (ppprstg == NULL)
return E_POINTER;
HRESULT hr;
PyObject *result;
{
TmpPyObject obclsid;
if (pclsid) {
obclsid = PyWinObject_FromIID(*pclsid);
if (obclsid == NULL)
return MAKE_PYCOM_GATEWAY_FAILURE_CODE("Create");
}
else {
Py_INCREF(Py_None);
obclsid = Py_None;
}
TmpPyObject obfmtid = PyWinObject_FromIID(rfmtid);
if (obfmtid == NULL)
return MAKE_PYCOM_GATEWAY_FAILURE_CODE("Create");
hr = InvokeViaPolicy("Create", &result, "OOkk", obfmtid, obclsid, grfFlags, grfMode);
}
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
if (!PyCom_InterfaceFromPyInstanceOrObject(result, IID_IPropertyStorage, (void **)ppprstg, FALSE))
hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("Create");
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGPropertySetStorage::Open(
/* [in] */ REFFMTID rfmtid,
/* [in] */ DWORD grfMode,
/* [out] */ IPropertyStorage **ppprstg)
{
PY_GATEWAY_METHOD;
TmpPyObject obfmtid = PyWinObject_FromIID(rfmtid);
if (obfmtid == NULL)
return MAKE_PYCOM_GATEWAY_FAILURE_CODE("Open");
if (ppprstg == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("Open", &result, "Ok", obfmtid, grfMode);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
if (!PyCom_InterfaceFromPyInstanceOrObject(result, IID_IPropertyStorage, (void **)ppprstg, FALSE))
hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("Open");
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGPropertySetStorage::Delete(
/* [in] */ REFFMTID rfmtid)
{
PY_GATEWAY_METHOD;
PyObject *obrfmtid = PyWinObject_FromIID(rfmtid);
if (obrfmtid == NULL)
return MAKE_PYCOM_GATEWAY_FAILURE_CODE("Delete");
HRESULT hr = InvokeViaPolicy("Delete", NULL, "O", obrfmtid);
Py_DECREF(obrfmtid);
return hr;
}
STDMETHODIMP PyGPropertySetStorage::Enum(
/* [out] */ IEnumSTATPROPSETSTG **ppenum)
{
PY_GATEWAY_METHOD;
if (ppenum == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("Enum", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
if (!PyCom_InterfaceFromPyInstanceOrObject(result, IID_IEnumSTATPROPSETSTG, (void **)ppenum, FALSE))
hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("Enum");
Py_DECREF(result);
return hr;
}
#endif // NO_PYCOM_IPROPERTYSETSTORAGE
| 35.820084 | 119 | 0.678776 | [
"object"
] |
69a827ad08b7b6279356f0d1c4e0dc6cde69676c | 1,109 | hpp | C++ | Loader.hpp | SpectreVert/ykz | 2922ec2178b0d53483d143888f945c7046f9f623 | [
"MIT"
] | null | null | null | Loader.hpp | SpectreVert/ykz | 2922ec2178b0d53483d143888f945c7046f9f623 | [
"MIT"
] | null | null | null | Loader.hpp | SpectreVert/ykz | 2922ec2178b0d53483d143888f945c7046f9f623 | [
"MIT"
] | null | null | null | /*
* Created by Costa Bushnaq
*
* 03-05-2021 @ 22:05:28
*
* see LICENSE
*/
#ifndef _LOADER_HPP
#define _LOADER_HPP
#include "generic/IModule.hpp"
#include <map>
#include <memory>
#include <functional>
#include <string>
#include <string_view>
#include <vector>
#include <dlfcn.h>
namespace ykz {
class Loader {
struct ModuleInstance {
using ConstructorType = IModule*();
virtual ~ModuleInstance() = default;
std::unique_ptr<ModuleInstance> static load_instance(std::string const&);
void static dtor(void*);
std::shared_ptr<void> binary;
std::shared_ptr<IModule> module;
std::function<ConstructorType> ctor;
};
std::map<std::string, std::unique_ptr<ModuleInstance>> m_modules;
public:
std::string_view constexpr static k_suffix = ".so";
virtual ~Loader() = default;
Loader() = default;
std::size_t load_from_path(std::string const&);
std::size_t unload_all();
bool unload(std::string const&);
std::vector<std::string> loaded_modules() const;
std::weak_ptr<IModule> instance(std::string const&) const;
}; // class Loader
} // namespace ykz
#endif /* _LOADER_HPP */
| 18.79661 | 75 | 0.707845 | [
"vector"
] |
69ab74cc1b8b76e2d582885ef10851d6e53c1d2e | 393 | cpp | C++ | collection/cp/bcw_codebook-master/codes/Geometry/Intersection_of_two_circles/Intersection_of_two_circles.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | 1 | 2019-03-24T13:12:01.000Z | 2019-03-24T13:12:01.000Z | collection/cp/bcw_codebook-master/codes/Geometry/Intersection_of_two_circles/Intersection_of_two_circles.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | collection/cp/bcw_codebook-master/codes/Geometry/Intersection_of_two_circles/Intersection_of_two_circles.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | using ld = double;
vector<pdd> interCircle(pdd o1, double r1, pdd o2, double r2) {
ld d2 = (o1 - o2) * (o1 - o2);
ld d = sqrt(d2);
if (d < abs(r1-r2)) return {};
if (d > r1+r2) return {};
pdd u = 0.5*(o1+o2) + ((r2*r2-r1*r1)/(2*d2))*(o1-o2);
double A = sqrt((r1+r2+d) * (r1-r2+d) * (r1+r2-d) * (-r1+r2+d));
pdd v = A / (2*d2) * pdd(o1.S-o2.S, -o1.F+o2.F);
return {u+v, u-v};
}
| 32.75 | 66 | 0.503817 | [
"vector"
] |
69abd6059e225336d7d9af57274e530f7f599f96 | 1,802 | cxx | C++ | tests/getri.cxx | evaleev/scalapackpp | bf17a7246af38d34523bd0099b01d9961d06d311 | [
"BSD-3-Clause"
] | 2 | 2021-11-30T15:04:15.000Z | 2021-11-30T18:41:58.000Z | tests/getri.cxx | evaleev/scalapackpp | bf17a7246af38d34523bd0099b01d9961d06d311 | [
"BSD-3-Clause"
] | 5 | 2020-02-12T19:29:45.000Z | 2021-05-28T16:13:48.000Z | tests/getri.cxx | evaleev/scalapackpp | bf17a7246af38d34523bd0099b01d9961d06d311 | [
"BSD-3-Clause"
] | 2 | 2020-02-12T03:44:12.000Z | 2021-11-30T13:54:03.000Z | /**
* This file is a part of scalapackpp (see LICENSE)
*
* Copyright (c) 2019-2020 David Williams-Young
* All rights reserved
*/
#include "ut.hpp"
#include <scalapackpp/block_cyclic.hpp>
#include <scalapackpp/pblas/gemm.hpp>
#include <scalapackpp/factorizations/getrf.hpp>
#include <scalapackpp/matrix_inverse/getri.hpp>
SCALAPACKPP_TEST_CASE( "Getri", "[getri]" ) {
using namespace scalapackpp;
blacspp::Grid grid = blacspp::Grid::square_grid( MPI_COMM_WORLD );
blacspp::mpi_info mpi( MPI_COMM_WORLD );
int64_t M = 100, mb = 4;
std::default_random_engine gen(mpi.rank());
std::normal_distribution<detail::real_t<TestType>> dist( 0., 1. );
BlockCyclicMatrix<TestType> A( grid, M, M, mb, mb );
std::generate( A.begin(), A.end(), [&](){ return dist(gen); } );
for( auto i = 0; i < M; ++i )
if( A.dist().i_own( i, i ) ) {
auto [ row_idx, col_idx ] = A.dist().local_indx(i, i);
A.data()[ row_idx + col_idx * A.m_local() ] += 10.;
}
auto A_inv( A );
std::vector<int64_t> IPIV( A.m_local() + A.dist().mb() );
auto info = pgetrf( A_inv, IPIV.data() );
REQUIRE( info == 0 );
info = pgetri( A_inv, IPIV.data() );
REQUIRE( info == 0 );
// Check correctness
BlockCyclicMatrix<TestType> I_approx( grid, M, M, mb, mb );
pgemm(
Op::NoTrans, Op::NoTrans,
1., A, A_inv, 0., I_approx
);
auto tol = 10*M*M*std::numeric_limits<detail::real_t<TestType>>::epsilon();
const detail::real_t<TestType> one = 1.;
for( auto i = 0; i < M; ++i )
for( auto j = 0; j < M; ++j )
if( A.dist().i_own( i, j ) ) {
auto [ I, J ] = A.dist().local_indx( i, j );
auto x = std::real( I_approx.data()[ I + J * A.m_local() ] );
if( i == j ) CHECK( x == Approx( one ).epsilon(tol) );
else CHECK( std::abs(x) < tol );
}
}
| 25.742857 | 77 | 0.602109 | [
"vector"
] |
69ad677e996945ff08c4e40d9f7c25659bb5952d | 114,774 | cpp | C++ | FPSLighting/Dependencies/DIRECTX/Samples/C++/Misc/DxDiagReport/dxdiaginfo.cpp | billionare/FPSLighting | c7d646f51cf4dee360dcc7c8e2fd2821b421b418 | [
"MIT"
] | null | null | null | FPSLighting/Dependencies/DIRECTX/Samples/C++/Misc/DxDiagReport/dxdiaginfo.cpp | billionare/FPSLighting | c7d646f51cf4dee360dcc7c8e2fd2821b421b418 | [
"MIT"
] | null | null | null | FPSLighting/Dependencies/DIRECTX/Samples/C++/Misc/DxDiagReport/dxdiaginfo.cpp | billionare/FPSLighting | c7d646f51cf4dee360dcc7c8e2fd2821b421b418 | [
"MIT"
] | null | null | null | //----------------------------------------------------------------------------
// File: dxdiaginfo.cpp
//
// Desc: Sample app to read info from dxdiagn.dll
//
// Copyright (c) Microsoft Corp. All rights reserved.
//-----------------------------------------------------------------------------
#define STRICT
#define INITGUID
#include <windows.h>
#pragma warning( disable : 4996 ) // disable deprecated warning
#include <strsafe.h>
#pragma warning( default : 4996 )
#include <initguid.h>
#include <wchar.h>
#pragma warning( push, 3 )
#pragma warning(disable:4995 4786 4788)
#include <vector>
#pragma warning( pop )
using namespace std;
#include "dxdiaginfo.h"
#include "resource.h"
//-----------------------------------------------------------------------------
// Defines, and constants
//-----------------------------------------------------------------------------
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } }
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
#define SAFE_BSTR_FREE(x) if(x) { SysFreeString( x ); x = NULL; }
#define EXPAND(x) x, sizeof(x)/sizeof(TCHAR)
//-----------------------------------------------------------------------------
// Name: CDxDiagInfo()
// Desc: Constuct class
//-----------------------------------------------------------------------------
CDxDiagInfo::CDxDiagInfo()
{
m_pDxDiagProvider = NULL;
m_pDxDiagRoot = NULL;
m_pSysInfo = NULL;
m_pFileInfo = NULL;
m_pMusicInfo = NULL;
m_pInputInfo = NULL;
m_pNetInfo = NULL;
m_pShowInfo = NULL;
}
//-----------------------------------------------------------------------------
// Name: ~CDxDiagInfo()
// Desc: Cleanup
//-----------------------------------------------------------------------------
CDxDiagInfo::~CDxDiagInfo()
{
SAFE_RELEASE( m_pDxDiagRoot );
SAFE_RELEASE( m_pDxDiagProvider );
SAFE_DELETE( m_pSysInfo );
DestroySystemDevice( m_vSystemDevices );
DestroyFileList( m_pFileInfo );
DestroyDisplayInfo( m_vDisplayInfo );
DestroyInputInfo( m_pInputInfo );
DestroyMusicInfo( m_pMusicInfo );
DestroyNetworkInfo( m_pNetInfo );
DestroySoundInfo( m_vSoundInfos );
DestroySoundCaptureInfo( m_vSoundCaptureInfos );
DestroyShowInfo( m_pShowInfo );
if( m_bCleanupCOM )
CoUninitialize();
}
//-----------------------------------------------------------------------------
// Name: Init()
// Desc: Connect to dxdiagn.dll and init it
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::Init( BOOL bAllowWHQLChecks )
{
HRESULT hr;
hr = CoInitialize( NULL );
m_bCleanupCOM = SUCCEEDED( hr );
hr = CoCreateInstance( CLSID_DxDiagProvider,
NULL,
CLSCTX_INPROC_SERVER,
IID_IDxDiagProvider,
( LPVOID* )&m_pDxDiagProvider );
if( FAILED( hr ) )
goto LCleanup;
if( m_pDxDiagProvider == NULL )
{
hr = E_POINTER;
goto LCleanup;
}
// Fill out a DXDIAG_INIT_PARAMS struct and pass it to IDxDiagContainer::Initialize
// Passing in TRUE for bAllowWHQLChecks, allows dxdiag to check if drivers are
// digital signed as logo'd by WHQL which may connect via internet to update
// WHQL certificates.
DXDIAG_INIT_PARAMS dxDiagInitParam;
ZeroMemory( &dxDiagInitParam, sizeof( DXDIAG_INIT_PARAMS ) );
dxDiagInitParam.dwSize = sizeof( DXDIAG_INIT_PARAMS );
dxDiagInitParam.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION;
dxDiagInitParam.bAllowWHQLChecks = bAllowWHQLChecks;
dxDiagInitParam.pReserved = NULL;
hr = m_pDxDiagProvider->Initialize( &dxDiagInitParam );
if( FAILED( hr ) )
goto LCleanup;
hr = m_pDxDiagProvider->GetRootContainer( &m_pDxDiagRoot );
if( FAILED( hr ) )
goto LCleanup;
LCleanup:
return hr;
}
//-----------------------------------------------------------------------------
// Name: QueryDxDiagViaDll()
// Desc: Query dxdiagn.dll for all its information
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::QueryDxDiagViaDll()
{
if( NULL == m_pDxDiagProvider )
return E_INVALIDARG;
// Any of these might fail, but if they do we
// can still process the others
GetSystemInfo( &m_pSysInfo );
GetSystemDevices( m_vSystemDevices );
GetDirectXFilesInfo( &m_pFileInfo );
GetDisplayInfo( m_vDisplayInfo );
GetSoundInfo( m_vSoundInfos, m_vSoundCaptureInfos );
GetMusicInfo( &m_pMusicInfo );
GetInputInfo( &m_pInputInfo );
GetNetworkInfo( &m_pNetInfo );
GetShowInfo( &m_pShowInfo );
GetLogicalDiskInfo( m_vLogicalDiskList );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: GetSystemInfo()
// Desc: Get the system info from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetSystemInfo( SysInfo** ppSysInfo )
{
HRESULT hr;
IDxDiagContainer* pObject = NULL;
DWORD nCurCount = 0;
if( NULL == m_pDxDiagProvider )
return E_INVALIDARG;
int i;
SysInfo* pSysInfo = new SysInfo;
if( NULL == pSysInfo )
return E_OUTOFMEMORY;
ZeroMemory( pSysInfo, sizeof( SysInfo ) );
*ppSysInfo = pSysInfo;
// Get the IDxDiagContainer object called "DxDiag_SystemInfo".
// This call may take some time while dxdiag gathers the info.
hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_SystemInfo", &pObject );
if( FAILED( hr ) || pObject == NULL )
{
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetUIntValue( pObject, L"dwOSMajorVersion", &pSysInfo->m_dwOSMajorVersion ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwOSMinorVersion", &pSysInfo->m_dwOSMinorVersion ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwOSBuildNumber", &pSysInfo->m_dwOSBuildNumber ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwOSPlatformID", &pSysInfo->m_dwOSPlatformID ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwDirectXVersionMajor", &pSysInfo->m_dwDirectXVersionMajor ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwDirectXVersionMinor", &pSysInfo->m_dwDirectXVersionMinor ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDirectXVersionLetter", EXPAND(pSysInfo->m_szDirectXVersionLetter) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDebug", &pSysInfo->m_bDebug ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bNECPC98", &pSysInfo->m_bNECPC98 ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetInt64Value( pObject, L"ullPhysicalMemory", &pSysInfo->m_ullPhysicalMemory ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetInt64Value( pObject, L"ullUsedPageFile", &pSysInfo->m_ullUsedPageFile ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetInt64Value( pObject, L"ullAvailPageFile", &pSysInfo->m_ullAvailPageFile ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bNetMeetingRunning", &pSysInfo->m_bNetMeetingRunning ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject,
L"bIsD3D8DebugRuntimeAvailable", &pSysInfo->m_bIsD3D8DebugRuntimeAvailable ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bIsD3DDebugRuntime", &pSysInfo->m_bIsD3DDebugRuntime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject,
L"bIsDInput8DebugRuntimeAvailable",
&pSysInfo->m_bIsDInput8DebugRuntimeAvailable ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bIsDInput8DebugRuntime", &pSysInfo->m_bIsDInput8DebugRuntime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject,
L"bIsDMusicDebugRuntimeAvailable", &pSysInfo->m_bIsDMusicDebugRuntimeAvailable ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bIsDMusicDebugRuntime", &pSysInfo->m_bIsDMusicDebugRuntime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bIsDDrawDebugRuntime", &pSysInfo->m_bIsDDrawDebugRuntime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bIsDPlayDebugRuntime", &pSysInfo->m_bIsDPlayDebugRuntime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bIsDSoundDebugRuntime", &pSysInfo->m_bIsDSoundDebugRuntime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"nD3DDebugLevel", &pSysInfo->m_nD3DDebugLevel ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"nDDrawDebugLevel", &pSysInfo->m_nDDrawDebugLevel ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"nDIDebugLevel", &pSysInfo->m_nDIDebugLevel ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"nDMusicDebugLevel", &pSysInfo->m_nDMusicDebugLevel ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"nDPlayDebugLevel", &pSysInfo->m_nDPlayDebugLevel ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"nDSoundDebugLevel", &pSysInfo->m_nDSoundDebugLevel ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"nDShowDebugLevel", &pSysInfo->m_nDShowDebugLevel ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szWindowsDir", EXPAND(pSysInfo->m_szWindowsDir) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szBuildLab", EXPAND(pSysInfo->m_szBuildLab) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDxDiagVersion", EXPAND(pSysInfo->m_szDxDiagVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szSetupParamEnglish", EXPAND(pSysInfo->m_szSetupParamEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szProcessorEnglish", EXPAND(pSysInfo->m_szProcessorEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szSystemManufacturerEnglish",
EXPAND(pSysInfo->m_szSystemManufacturerEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szSystemModelEnglish", EXPAND(pSysInfo->m_szSystemModelEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szBIOSEnglish", EXPAND(pSysInfo->m_szBIOSEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szPhysicalMemoryEnglish", EXPAND(pSysInfo->m_szPhysicalMemoryEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szCSDVersion", EXPAND(pSysInfo->m_szCSDVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDirectXVersionEnglish", EXPAND(pSysInfo->m_szDirectXVersionEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDirectXVersionLongEnglish",
EXPAND(pSysInfo->m_szDirectXVersionLongEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szMachineNameLocalized", EXPAND(pSysInfo->m_szMachineNameLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szOSLocalized", EXPAND(pSysInfo->m_szOSLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szOSExLocalized", EXPAND(pSysInfo->m_szOSExLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szOSExLongLocalized", EXPAND(pSysInfo->m_szOSExLongLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLanguagesLocalized", EXPAND(pSysInfo->m_szLanguagesLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szPageFileLocalized", EXPAND(pSysInfo->m_szPageFileLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTimeLocalized", EXPAND(pSysInfo->m_szTimeLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szMachineNameEnglish", EXPAND(pSysInfo->m_szMachineNameEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szOSEnglish", EXPAND(pSysInfo->m_szOSEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szOSExEnglish", EXPAND(pSysInfo->m_szOSExEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szOSExLongEnglish", EXPAND(pSysInfo->m_szOSExLongEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLanguagesEnglish", EXPAND(pSysInfo->m_szLanguagesEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szPageFileEnglish", EXPAND(pSysInfo->m_szPageFileEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTimeEnglish", EXPAND(pSysInfo->m_szTimeEnglish) ) ) )
goto LCleanup; nCurCount++;
// Get the extended cpuid for args 0x80000008 through 0x80000018.
// pSysInfo->m_ExtFuncBitmasks[0] will contain extended cpuid info from arg 0x80000009
// pSysInfo->m_ExtFuncBitmasks[15] will contain extended cpuid info from arg 0x80000018
for( i = 0; i < 16; i++ )
{
WCHAR strName[256];
WCHAR strName2[256];
StringCchPrintfW( strName, 256, L"ExtendedCPUFunctionBitmasks_0x800000%0.2x_bits", i + 0x09 );
StringCchCopyW( strName2, 256, strName ); StringCchCatW( strName2, 256, L"0_31" );
if( FAILED( hr = GetUIntValue( pObject, strName2, &pSysInfo->m_ExtFuncBitmasks[i].dwBits0_31 ) ) )
goto LCleanup; nCurCount++;
StringCchCopyW( strName2, 256, strName ); StringCchCatW( strName2, 256, L"32_63" );
if( FAILED( hr = GetUIntValue( pObject, strName2, &pSysInfo->m_ExtFuncBitmasks[i].dwBits32_63 ) ) )
goto LCleanup; nCurCount++;
StringCchCopyW( strName2, 256, strName ); StringCchCatW( strName2, 256, L"64_95" );
if( FAILED( hr = GetUIntValue( pObject, strName2, &pSysInfo->m_ExtFuncBitmasks[i].dwBits64_95 ) ) )
goto LCleanup; nCurCount++;
StringCchCopyW( strName2, 256, strName ); StringCchCatW( strName2, 256, L"96_127" );
if( FAILED( hr = GetUIntValue( pObject, strName2, &pSysInfo->m_ExtFuncBitmasks[i].dwBits96_127 ) ) )
goto LCleanup; nCurCount++;
}
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
// normal clients should't do this
if( FAILED( hr = pObject->GetNumberOfProps( &pSysInfo->m_nElementCount ) ) )
return hr;
if( pSysInfo->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pSysInfo recorded") );
#endif
LCleanup:
SAFE_RELEASE( pObject );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetSystemDevices()
// Desc: Get the system devices info from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetSystemDevices( vector <SystemDevice*>& vSystemDevices )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
if( NULL == m_pDxDiagProvider )
return E_INVALIDARG;
// Get the IDxDiagContainer object called "DxDiag_SystemDevices".
// This call may take some time while dxdiag gathers the info.
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_SystemDevices", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
SystemDevice* pSystemDevice = new SystemDevice;
if( pSystemDevice == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pSystemDevice, sizeof( SystemDevice ) );
// Add pSystemDevice to vSystemDevices
vSystemDevices.push_back( pSystemDevice );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szDescription", EXPAND(pSystemDevice->m_szDescription) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDeviceID", EXPAND(pSystemDevice->m_szDeviceID) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GatherSystemDeviceDriverList( pObject, pSystemDevice->m_vDriverList ) ) )
goto LCleanup;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pSystemDevice->m_nElementCount ) ) )
return hr;
if( pSystemDevice->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pSystemDevice recorded") );
#endif
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetLogicalDiskInfo()
// Desc: Get the logical disk info from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetLogicalDiskInfo( vector <LogicalDisk*>& vLogicalDisks )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
if( NULL == m_pDxDiagProvider )
return E_INVALIDARG;
// Get the IDxDiagContainer object called "DxDiag_LogicalDisks".
// This call may take some time while dxdiag gathers the info.
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_LogicalDisks", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
LogicalDisk* pLogicalDisk = new LogicalDisk;
if( pLogicalDisk == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pLogicalDisk, sizeof( LogicalDisk ) );
// Add pLogicalDisk to vLogicalDisks
vLogicalDisks.push_back( pLogicalDisk );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szDriveLetter", EXPAND(pLogicalDisk->m_szDriveLetter) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szFreeSpace", EXPAND(pLogicalDisk->m_szFreeSpace) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szMaxSpace", EXPAND(pLogicalDisk->m_szMaxSpace) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szFileSystem", EXPAND(pLogicalDisk->m_szFileSystem) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szModel", EXPAND(pLogicalDisk->m_szModel) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szPNPDeviceID", EXPAND(pLogicalDisk->m_szPNPDeviceID) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwHardDriveIndex", &pLogicalDisk->m_dwHardDriveIndex ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GatherSystemDeviceDriverList( pObject, pLogicalDisk->m_vDriverList ) ) )
goto LCleanup;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pLogicalDisk->m_nElementCount ) ) )
return hr;
if( pLogicalDisk->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pLogicalDisk recorded") );
#endif
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GatherSystemDeviceDriverList()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GatherSystemDeviceDriverList( IDxDiagContainer* pParent, vector <FileNode*>& vDriverList )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
if( FAILED( hr = pParent->GetChildContainer( L"Drivers", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
FileNode* pFileNode = new FileNode;
if( pFileNode == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pFileNode, sizeof( FileNode ) );
// Add pFileNode to vDriverList
vDriverList.push_back( pFileNode );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GatherFileNodeInst( pFileNode, pObject ) ) )
goto LCleanup;
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GatherFileNodeInst()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GatherFileNodeInst( FileNode* pFileNode, IDxDiagContainer* pObject )
{
HRESULT hr;
DWORD nCurCount = 0;
if( FAILED( hr = GetStringValue( pObject, L"szPath", EXPAND(pFileNode->m_szPath) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szName", EXPAND(pFileNode->m_szName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVersion", EXPAND(pFileNode->m_szVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLanguageEnglish", EXPAND(pFileNode->m_szLanguageEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLanguageLocalized", EXPAND(pFileNode->m_szLanguageLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFileTimeLow", &pFileNode->m_FileTime.dwLowDateTime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFileTimeHigh", &pFileNode->m_FileTime.dwHighDateTime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDatestampEnglish", EXPAND(pFileNode->m_szDatestampEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDatestampLocalized", EXPAND(pFileNode->m_szDatestampLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szAttributes", EXPAND(pFileNode->m_szAttributes) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"lNumBytes", &pFileNode->m_lNumBytes ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bExists", &pFileNode->m_bExists ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bBeta", &pFileNode->m_bBeta ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDebug", &pFileNode->m_bDebug ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bObsolete", &pFileNode->m_bObsolete ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bProblem", &pFileNode->m_bProblem ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pFileNode->m_nElementCount ) ) )
goto LCleanup;
if( pFileNode->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pFileNode recorded") );
#endif
LCleanup:
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetDirectXFilesInfo()
// Desc: Get the DirectX file info from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetDirectXFilesInfo( FileInfo** ppFileInfo )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
FileInfo* pFileInfo = new FileInfo;
if( pFileInfo == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pFileInfo, sizeof( FileInfo ) );
*ppFileInfo = pFileInfo;
// Get the IDxDiagContainer object called "DxDiag_DirectXFiles".
// This call may take some time while dxdiag gathers the info.
hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectXFiles", &pObject );
if( FAILED( hr ) || pObject == NULL )
{
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szDXFileNotesLocalized", EXPAND(pFileInfo->m_szDXFileNotesLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDXFileNotesEnglish", EXPAND(pFileInfo->m_szDXFileNotesEnglish) ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pFileInfo->m_nElementCount ) ) )
return hr;
if( pFileInfo->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pFileInfo recorded") );
#endif
SAFE_RELEASE( pObject );
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectXFiles", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
FileNode* pFileNode = new FileNode;
if( pFileNode == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pFileNode, sizeof( FileNode ) );
// Add pFileNode to pFileInfo->m_vDxComponentsFiles
pFileInfo->m_vDxComponentsFiles.push_back( pFileNode );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szName", EXPAND(pFileNode->m_szName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVersion", EXPAND(pFileNode->m_szVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLanguageEnglish", EXPAND(pFileNode->m_szLanguageEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLanguageLocalized", EXPAND(pFileNode->m_szLanguageLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFileTimeLow", &pFileNode->m_FileTime.dwLowDateTime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFileTimeHigh", &pFileNode->m_FileTime.dwHighDateTime ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDatestampEnglish", EXPAND(pFileNode->m_szDatestampEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDatestampLocalized", EXPAND(pFileNode->m_szDatestampLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szAttributes", EXPAND(pFileNode->m_szAttributes) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"lNumBytes", &pFileNode->m_lNumBytes ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bExists", &pFileNode->m_bExists ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bBeta", &pFileNode->m_bBeta ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDebug", &pFileNode->m_bDebug ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bObsolete", &pFileNode->m_bObsolete ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bProblem", &pFileNode->m_bProblem ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pFileNode->m_nElementCount ) ) )
return hr;
if( pFileNode->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pFileNode recorded") );
#endif
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetDisplayInfo()
// Desc: Get the display info from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetDisplayInfo( vector <DisplayInfo*>& vDisplayInfo )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
// Get the IDxDiagContainer object called "DxDiag_DisplayDevices".
// This call may take some time while dxdiag gathers the info.
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DisplayDevices", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
DisplayInfo* pDisplayInfo = new DisplayInfo;
if( pDisplayInfo == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pDisplayInfo, sizeof( DisplayInfo ) );
// Add pDisplayInfo to vDisplayInfo
vDisplayInfo.push_back( pDisplayInfo );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szDeviceName", EXPAND(pDisplayInfo->m_szDeviceName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDescription", EXPAND(pDisplayInfo->m_szDescription) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szKeyDeviceID", EXPAND(pDisplayInfo->m_szKeyDeviceID) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szKeyDeviceKey", EXPAND(pDisplayInfo->m_szKeyDeviceKey) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szManufacturer", EXPAND(pDisplayInfo->m_szManufacturer) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szChipType", EXPAND(pDisplayInfo->m_szChipType) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDACType", EXPAND(pDisplayInfo->m_szDACType) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szRevision", EXPAND(pDisplayInfo->m_szRevision) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDisplayMemoryLocalized",
EXPAND(pDisplayInfo->m_szDisplayMemoryLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDisplayMemoryEnglish",
EXPAND(pDisplayInfo->m_szDisplayMemoryEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDisplayModeLocalized",
EXPAND(pDisplayInfo->m_szDisplayModeLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDisplayModeEnglish", EXPAND(pDisplayInfo->m_szDisplayModeEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwWidth", &pDisplayInfo->m_dwWidth ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwHeight", &pDisplayInfo->m_dwHeight ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwBpp", &pDisplayInfo->m_dwBpp ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwRefreshRate", &pDisplayInfo->m_dwRefreshRate ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szMonitorName", EXPAND(pDisplayInfo->m_szMonitorName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szMonitorMaxRes", EXPAND(pDisplayInfo->m_szMonitorMaxRes) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverName", EXPAND(pDisplayInfo->m_szDriverName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverVersion", EXPAND(pDisplayInfo->m_szDriverVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverAttributes", EXPAND(pDisplayInfo->m_szDriverAttributes) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverLanguageEnglish",
EXPAND(pDisplayInfo->m_szDriverLanguageEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverLanguageLocalized",
EXPAND(pDisplayInfo->m_szDriverLanguageLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverDateEnglish", EXPAND(pDisplayInfo->m_szDriverDateEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverDateLocalized",
EXPAND(pDisplayInfo->m_szDriverDateLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"lDriverSize", &pDisplayInfo->m_lDriverSize ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szMiniVdd", EXPAND(pDisplayInfo->m_szMiniVdd) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szMiniVddDateLocalized",
EXPAND(pDisplayInfo->m_szMiniVddDateLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szMiniVddDateEnglish", EXPAND(pDisplayInfo->m_szMiniVddDateEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"lMiniVddSize", &pDisplayInfo->m_lMiniVddSize ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVdd", EXPAND(pDisplayInfo->m_szVdd) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bCanRenderWindow", &pDisplayInfo->m_bCanRenderWindow ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverBeta", &pDisplayInfo->m_bDriverBeta ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverDebug", &pDisplayInfo->m_bDriverDebug ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverSigned", &pDisplayInfo->m_bDriverSigned ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverSignedValid", &pDisplayInfo->m_bDriverSignedValid ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDeviceIdentifier", EXPAND(pDisplayInfo->m_szDeviceIdentifier) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverSignDate", EXPAND(pDisplayInfo->m_szDriverSignDate) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwDDIVersion", &pDisplayInfo->m_dwDDIVersion ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDDIVersionEnglish", EXPAND(pDisplayInfo->m_szDDIVersionEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDDIVersionLocalized",
EXPAND(pDisplayInfo->m_szDDIVersionLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"iAdapter", &pDisplayInfo->m_iAdapter ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVendorId", EXPAND(pDisplayInfo->m_szVendorId) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDeviceId", EXPAND(pDisplayInfo->m_szDeviceId) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szSubSysId", EXPAND(pDisplayInfo->m_szSubSysId) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szRevisionId", EXPAND(pDisplayInfo->m_szRevisionId) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwWHQLLevel", &pDisplayInfo->m_dwWHQLLevel ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bNoHardware", &pDisplayInfo->m_bNoHardware ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject,
L"bDDAccelerationEnabled", &pDisplayInfo->m_bDDAccelerationEnabled ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"b3DAccelerationExists", &pDisplayInfo->m_b3DAccelerationExists ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject,
L"b3DAccelerationEnabled", &pDisplayInfo->m_b3DAccelerationEnabled ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bAGPEnabled", &pDisplayInfo->m_bAGPEnabled ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bAGPExists", &pDisplayInfo->m_bAGPExists ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bAGPExistenceValid", &pDisplayInfo->m_bAGPExistenceValid ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDXVAModes", EXPAND(pDisplayInfo->m_szDXVAModes) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDDStatusLocalized", EXPAND(pDisplayInfo->m_szDDStatusLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDDStatusEnglish", EXPAND(pDisplayInfo->m_szDDStatusEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szD3DStatusLocalized", EXPAND(pDisplayInfo->m_szD3DStatusLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szD3DStatusEnglish", EXPAND(pDisplayInfo->m_szD3DStatusEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szAGPStatusLocalized", EXPAND(pDisplayInfo->m_szAGPStatusLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szAGPStatusEnglish", EXPAND(pDisplayInfo->m_szAGPStatusEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szNotesLocalized", EXPAND(pDisplayInfo->m_szNotesLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szNotesEnglish", EXPAND(pDisplayInfo->m_szNotesEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szRegHelpText", EXPAND(pDisplayInfo->m_szRegHelpText) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultDDLocalized",
EXPAND(pDisplayInfo->m_szTestResultDDLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultDDEnglish",
EXPAND(pDisplayInfo->m_szTestResultDDEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultD3D7Localized",
EXPAND(pDisplayInfo->m_szTestResultD3D7Localized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultD3D7English",
EXPAND(pDisplayInfo->m_szTestResultD3D7English) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultD3D8Localized",
EXPAND(pDisplayInfo->m_szTestResultD3D8Localized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultD3D8English",
EXPAND(pDisplayInfo->m_szTestResultD3D8English) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultD3D9Localized",
EXPAND(pDisplayInfo->m_szTestResultD3D9Localized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultD3D9English",
EXPAND(pDisplayInfo->m_szTestResultD3D9English) ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pDisplayInfo->m_nElementCount ) ) )
return hr;
if( pDisplayInfo->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pDisplayInfo recorded") );
#endif
GatherDXVA_DeinterlaceCaps( pObject, pDisplayInfo->m_vDXVACaps );
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GatherDXVA_DeinterlaceCaps
// Desc:
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GatherDXVA_DeinterlaceCaps( IDxDiagContainer* pParent,
vector <DxDiag_DXVA_DeinterlaceCaps*>& vDXVACaps )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
if( FAILED( hr = pParent->GetChildContainer( L"DXVADeinterlaceCaps", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
DxDiag_DXVA_DeinterlaceCaps* pDXVANode = new DxDiag_DXVA_DeinterlaceCaps;
if( pDXVANode == NULL )
return E_OUTOFMEMORY;
// Add pDXVANode to vDXVACaps
vDXVACaps.push_back( pDXVANode );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szD3DInputFormat", EXPAND(pDXVANode->szD3DInputFormat) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szD3DOutputFormat", EXPAND(pDXVANode->szD3DOutputFormat) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szGuid", EXPAND(pDXVANode->szGuid) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szCaps", EXPAND(pDXVANode->szCaps) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwNumPreviousOutputFrames", &pDXVANode->dwNumPreviousOutputFrames ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwNumForwardRefSamples", &pDXVANode->dwNumForwardRefSamples ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwNumBackwardRefSamples", &pDXVANode->dwNumBackwardRefSamples ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pDXVANode->m_nElementCount ) ) )
goto LCleanup;
if( pDXVANode->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pDXVANode recorded") );
#endif
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetSoundInfo()
// Desc: Get the sound info from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetSoundInfo( vector <SoundInfo*>& vSoundInfos, vector <SoundCaptureInfo*>& vSoundCaptureInfos )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
// Get the IDxDiagContainer object called "DxDiag_DirectSound.DxDiag_SoundDevices".
// This call may take some time while dxdiag gathers the info.
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectSound.DxDiag_SoundDevices", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
SoundInfo* pSoundInfo = new SoundInfo;
if( pSoundInfo == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pSoundInfo, sizeof( SoundInfo ) );
// Add pSoundInfo to vSoundInfos
vSoundInfos.push_back( pSoundInfo );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetUIntValue( pObject, L"dwDevnode", &pSoundInfo->m_dwDevnode ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szGuidDeviceID", EXPAND(pSoundInfo->m_szGuidDeviceID) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szHardwareID", EXPAND(pSoundInfo->m_szHardwareID) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szRegKey", EXPAND(pSoundInfo->m_szRegKey) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szManufacturerID", EXPAND(pSoundInfo->m_szManufacturerID) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szProductID", EXPAND(pSoundInfo->m_szProductID) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDescription", EXPAND(pSoundInfo->m_szDescription) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverName", EXPAND(pSoundInfo->m_szDriverName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverPath", EXPAND(pSoundInfo->m_szDriverPath) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverVersion", EXPAND(pSoundInfo->m_szDriverVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverLanguageEnglish",
EXPAND(pSoundInfo->m_szDriverLanguageEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverLanguageLocalized",
EXPAND(pSoundInfo->m_szDriverLanguageLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverAttributes", EXPAND(pSoundInfo->m_szDriverAttributes) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverDateEnglish", EXPAND(pSoundInfo->m_szDriverDateEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverDateLocalized", EXPAND(pSoundInfo->m_szDriverDateLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szOtherDrivers", EXPAND(pSoundInfo->m_szOtherDrivers) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szProvider", EXPAND(pSoundInfo->m_szProvider) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szType", EXPAND(pSoundInfo->m_szType) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"lNumBytes", &pSoundInfo->m_lNumBytes ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverBeta", &pSoundInfo->m_bDriverBeta ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverDebug", &pSoundInfo->m_bDriverDebug ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverSigned", &pSoundInfo->m_bDriverSigned ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverSignedValid", &pSoundInfo->m_bDriverSignedValid ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"lAccelerationLevel", &pSoundInfo->m_lAccelerationLevel ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDefaultSoundPlayback", &pSoundInfo->m_bDefaultSoundPlayback ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDefaultVoicePlayback", &pSoundInfo->m_bDefaultVoicePlayback ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bVoiceManager", &pSoundInfo->m_bVoiceManager ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bEAX20Listener", &pSoundInfo->m_bEAX20Listener ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bEAX20Source", &pSoundInfo->m_bEAX20Source ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bI3DL2Listener", &pSoundInfo->m_bI3DL2Listener ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bI3DL2Source", &pSoundInfo->m_bI3DL2Source ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bZoomFX", &pSoundInfo->m_bZoomFX ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFlags", &pSoundInfo->m_dwFlags ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwMinSecondarySampleRate", &pSoundInfo->m_dwMinSecondarySampleRate ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwMaxSecondarySampleRate", &pSoundInfo->m_dwMaxSecondarySampleRate ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwPrimaryBuffers", &pSoundInfo->m_dwPrimaryBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwMaxHwMixingAllBuffers", &pSoundInfo->m_dwMaxHwMixingAllBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwMaxHwMixingStaticBuffers", &pSoundInfo->m_dwMaxHwMixingStaticBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwMaxHwMixingStreamingBuffers",
&pSoundInfo->m_dwMaxHwMixingStreamingBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwFreeHwMixingAllBuffers", &pSoundInfo->m_dwFreeHwMixingAllBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwFreeHwMixingStaticBuffers", &pSoundInfo->m_dwFreeHwMixingStaticBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwFreeHwMixingStreamingBuffers",
&pSoundInfo->m_dwFreeHwMixingStreamingBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwMaxHw3DAllBuffers", &pSoundInfo->m_dwMaxHw3DAllBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwMaxHw3DStaticBuffers", &pSoundInfo->m_dwMaxHw3DStaticBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwMaxHw3DStreamingBuffers", &pSoundInfo->m_dwMaxHw3DStreamingBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFreeHw3DAllBuffers", &pSoundInfo->m_dwFreeHw3DAllBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwFreeHw3DStaticBuffers", &pSoundInfo->m_dwFreeHw3DStaticBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwFreeHw3DStreamingBuffers", &pSoundInfo->m_dwFreeHw3DStreamingBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwTotalHwMemBytes", &pSoundInfo->m_dwTotalHwMemBytes ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFreeHwMemBytes", &pSoundInfo->m_dwFreeHwMemBytes ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwMaxContigFreeHwMemBytes", &pSoundInfo->m_dwMaxContigFreeHwMemBytes ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwUnlockTransferRateHwBuffers",
&pSoundInfo->m_dwUnlockTransferRateHwBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject,
L"dwPlayCpuOverheadSwBuffers", &pSoundInfo->m_dwPlayCpuOverheadSwBuffers ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szNotesLocalized", EXPAND(pSoundInfo->m_szNotesLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szNotesEnglish", EXPAND(pSoundInfo->m_szNotesEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szRegHelpText", EXPAND(pSoundInfo->m_szRegHelpText) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultLocalized", EXPAND(pSoundInfo->m_szTestResultLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultEnglish", EXPAND(pSoundInfo->m_szTestResultEnglish) ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pSoundInfo->m_nElementCount ) ) )
return hr;
if( pSoundInfo->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pSoundInfo recorded") );
#endif
SAFE_RELEASE( pObject );
}
SAFE_RELEASE( pContainer );
// Get the IDxDiagContainer object called "DxDiag_DirectSound.DxDiag_SoundCaptureDevices".
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectSound.DxDiag_SoundCaptureDevices",
&pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
SoundCaptureInfo* pSoundCaptureInfo = new SoundCaptureInfo;
if( pSoundCaptureInfo == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pSoundCaptureInfo, sizeof( SoundCaptureInfo ) );
// Add pSoundCaptureInfo to vSoundCaptureInfos
vSoundCaptureInfos.push_back( pSoundCaptureInfo );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szDescription", EXPAND(pSoundCaptureInfo->m_szDescription) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szGuidDeviceID", EXPAND(pSoundCaptureInfo->m_szGuidDeviceID) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverName", EXPAND(pSoundCaptureInfo->m_szDriverName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverPath", EXPAND(pSoundCaptureInfo->m_szDriverPath) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverVersion", EXPAND(pSoundCaptureInfo->m_szDriverVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverLanguageEnglish",
EXPAND(pSoundCaptureInfo->m_szDriverLanguageEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverLanguageLocalized",
EXPAND(pSoundCaptureInfo->m_szDriverLanguageLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverAttributes",
EXPAND(pSoundCaptureInfo->m_szDriverAttributes) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverDateEnglish",
EXPAND(pSoundCaptureInfo->m_szDriverDateEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDriverDateLocalized",
EXPAND(pSoundCaptureInfo->m_szDriverDateLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"lNumBytes", &pSoundCaptureInfo->m_lNumBytes ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverBeta", &pSoundCaptureInfo->m_bDriverBeta ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDriverDebug", &pSoundCaptureInfo->m_bDriverDebug ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject,
L"bDefaultSoundRecording", &pSoundCaptureInfo->m_bDefaultSoundRecording ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject,
L"bDefaultVoiceRecording", &pSoundCaptureInfo->m_bDefaultVoiceRecording ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFlags", &pSoundCaptureInfo->m_dwFlags ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFormats", &pSoundCaptureInfo->m_dwFormats ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pSoundCaptureInfo->m_nElementCount ) ) )
return hr;
if( pSoundCaptureInfo->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pSoundCaptureInfo recorded") );
#endif
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetMusicInfo()
// Desc: Get the music info from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetMusicInfo( MusicInfo** ppMusicInfo )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
MusicInfo* pMusicInfo = NULL;
pMusicInfo = new MusicInfo;
if( NULL == pMusicInfo )
return E_OUTOFMEMORY;
ZeroMemory( pMusicInfo, sizeof( MusicInfo ) );
*ppMusicInfo = pMusicInfo;
// Get the IDxDiagContainer object called "DxDiag_DirectMusic".
// This call may take some time while dxdiag gathers the info.
hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectMusic", &pObject );
if( FAILED( hr ) || pObject == NULL )
{
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetBoolValue( pObject, L"bDMusicInstalled", &pMusicInfo->m_bDMusicInstalled ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szGMFilePath", EXPAND(pMusicInfo->m_szGMFilePath) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szGMFileVersion", EXPAND(pMusicInfo->m_szGMFileVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bAccelerationEnabled", &pMusicInfo->m_bAccelerationEnabled ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bAccelerationExists", &pMusicInfo->m_bAccelerationExists ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szNotesLocalized", EXPAND(pMusicInfo->m_szNotesLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szNotesEnglish", EXPAND(pMusicInfo->m_szNotesEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szRegHelpText", EXPAND(pMusicInfo->m_szRegHelpText) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultLocalized", EXPAND(pMusicInfo->m_szTestResultLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultEnglish", EXPAND(pMusicInfo->m_szTestResultEnglish) ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pMusicInfo->m_nElementCount ) ) )
return hr;
if( pMusicInfo->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pMusicInfo recorded") );
#endif
SAFE_RELEASE( pObject );
// Get the number of "DxDiag_DirectMusic.DxDiag_DirectMusicPorts" objects in the dll
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectMusic.DxDiag_DirectMusicPorts", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
MusicPort* pMusicPort = new MusicPort;
if( pMusicPort == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pMusicPort, sizeof( MusicPort ) );
// Add pMusicPort to pMusicInfo->m_vMusicPorts
pMusicInfo->m_vMusicPorts.push_back( pMusicPort );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szGuid", EXPAND(pMusicPort->m_szGuid) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bSoftware", &pMusicPort->m_bSoftware ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bKernelMode", &pMusicPort->m_bKernelMode ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bUsesDLS", &pMusicPort->m_bUsesDLS ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bExternal", &pMusicPort->m_bExternal ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwMaxAudioChannels", &pMusicPort->m_dwMaxAudioChannels ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwMaxChannelGroups", &pMusicPort->m_dwMaxChannelGroups ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bDefaultPort", &pMusicPort->m_bDefaultPort ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bOutputPort", &pMusicPort->m_bOutputPort ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDescription", EXPAND(pMusicPort->m_szDescription) ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pMusicPort->m_nElementCount ) ) )
return hr;
if( pMusicPort->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pMusicPort recorded") );
#endif
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetInputInfo()
// Desc: Get the input info from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetInputInfo( InputInfo** ppInputInfo )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pChild = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
InputInfo* pInputInfo = NULL;
pInputInfo = new InputInfo;
if( NULL == pInputInfo )
return E_OUTOFMEMORY;
ZeroMemory( pInputInfo, sizeof( InputInfo ) );
*ppInputInfo = pInputInfo;
// Get the IDxDiagContainer object called "DxDiag_DirectInput".
// This call may take some time while dxdiag gathers the info.
hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectInput", &pObject );
if( FAILED( hr ) || pObject == NULL )
{
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetBoolValue( pObject, L"bPollFlags", &pInputInfo->m_bPollFlags ) ) )
return hr; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szInputNotesLocalized", EXPAND(pInputInfo->m_szInputNotesLocalized) ) ) )
return hr; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szInputNotesEnglish", EXPAND(pInputInfo->m_szInputNotesEnglish) ) ) )
return hr; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szRegHelpText", EXPAND(pInputInfo->m_szRegHelpText) ) ) )
return hr; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pInputInfo->m_nElementCount ) ) )
return hr;
if( pInputInfo->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pInputInfo recorded") );
#endif
SAFE_RELEASE( pObject );
// Get the number of "DxDiag_DirectInput.DxDiag_DirectInputDevices" objects in the dll
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectInput.DxDiag_DirectInputDevices",
&pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
InputDeviceInfo* pInputDevice = new InputDeviceInfo;
if( pInputDevice == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pInputDevice, sizeof( InputDeviceInfo ) );
// Add pInputDevice to pInputInfo->m_vDirectInputDevices
pInputInfo->m_vDirectInputDevices.push_back( pInputDevice );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szInstanceName", EXPAND(pInputDevice->m_szInstanceName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bAttached", &pInputDevice->m_bAttached ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwVendorID", &pInputDevice->m_dwVendorID ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwProductID", &pInputDevice->m_dwProductID ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwJoystickID", &pInputDevice->m_dwJoystickID ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwDevType", &pInputDevice->m_dwDevType ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szFFDriverName", EXPAND(pInputDevice->m_szFFDriverName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szFFDriverDateEnglish",
EXPAND(pInputDevice->m_szFFDriverDateEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szFFDriverVersion", EXPAND(pInputDevice->m_szFFDriverVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetIntValue( pObject, L"lFFDriverSize", &pInputDevice->m_lFFDriverSize ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pInputDevice->m_nElementCount ) ) )
return hr;
if( pInputDevice->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pInputDevice recorded") );
#endif
SAFE_RELEASE( pObject );
}
SAFE_RELEASE( pContainer );
// Get "DxDiag_DirectInput.DxDiag_DirectInputGameports" tree
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectInput.DxDiag_DirectInputGameports",
&pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
InputRelatedDeviceInfo* pInputRelatedDevice = new InputRelatedDeviceInfo;
if( pInputRelatedDevice == NULL )
return E_OUTOFMEMORY;
m_pInputInfo->m_vGamePortDevices.push_back( pInputRelatedDevice );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pChild );
if( FAILED( hr ) || pChild == NULL )
{
if( pChild == NULL )
hr = E_FAIL;
goto LCleanup;
}
GatherInputRelatedDeviceInst( pInputRelatedDevice, pChild );
SAFE_RELEASE( pChild );
}
SAFE_RELEASE( pContainer );
// Get "DxDiag_DirectInput.DxDiag_DirectInputUSBRoot" tree
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectInput.DxDiag_DirectInputUSBRoot",
&pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
InputRelatedDeviceInfo* pInputRelatedDevice = new InputRelatedDeviceInfo;
if( pInputRelatedDevice == NULL )
return E_OUTOFMEMORY;
m_pInputInfo->m_vUsbRoot.push_back( pInputRelatedDevice );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pChild );
if( FAILED( hr ) || pChild == NULL )
{
if( pChild == NULL )
hr = E_FAIL;
goto LCleanup;
}
GatherInputRelatedDeviceInst( pInputRelatedDevice, pChild );
SAFE_RELEASE( pChild );
}
SAFE_RELEASE( pContainer );
// Get "DxDiag_DirectInput.DxDiag_DirectInputPS2Devices" tree
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectInput.DxDiag_DirectInputPS2Devices",
&pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
InputRelatedDeviceInfo* pInputRelatedDevice = new InputRelatedDeviceInfo;
if( pInputRelatedDevice == NULL )
return E_OUTOFMEMORY;
m_pInputInfo->m_vPS2Devices.push_back( pInputRelatedDevice );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pChild );
if( FAILED( hr ) || pChild == NULL )
{
if( pChild == NULL )
hr = E_FAIL;
goto LCleanup;
}
GatherInputRelatedDeviceInst( pInputRelatedDevice, pChild );
SAFE_RELEASE( pChild );
}
SAFE_RELEASE( pContainer );
LCleanup:
SAFE_RELEASE( pContainer );
SAFE_RELEASE( pChild );
SAFE_RELEASE( pObject );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GatherInputRelatedDeviceInst()
// Desc: Get the InputRelatedDeviceInfo tree from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GatherInputRelatedDeviceInst( InputRelatedDeviceInfo* pInputRelatedDevice,
IDxDiagContainer* pContainer )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pChild = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
nCurCount = 0;
if( FAILED( hr = GetUIntValue( pContainer, L"dwVendorID", &pInputRelatedDevice->m_dwVendorID ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pContainer, L"dwProductID", &pInputRelatedDevice->m_dwProductID ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pContainer, L"szDescription", EXPAND(pInputRelatedDevice->m_szDescription) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pContainer, L"szLocation", EXPAND(pInputRelatedDevice->m_szLocation) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pContainer, L"szMatchingDeviceId",
EXPAND(pInputRelatedDevice->m_szMatchingDeviceId) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pContainer, L"szUpperFilters", EXPAND(pInputRelatedDevice->m_szUpperFilters) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pContainer, L"szService", EXPAND(pInputRelatedDevice->m_szService) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pContainer, L"szLowerFilters", EXPAND(pInputRelatedDevice->m_szLowerFilters) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pContainer, L"szOEMData", EXPAND(pInputRelatedDevice->m_szOEMData) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pContainer, L"szFlags1", EXPAND(pInputRelatedDevice->m_szFlags1) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pContainer, L"szFlags2", EXPAND(pInputRelatedDevice->m_szFlags2) ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pContainer->GetNumberOfProps( &pInputRelatedDevice->m_nElementCount ) ) )
goto LCleanup;
if( pInputRelatedDevice->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pInputRelatedDevice recorded") );
#endif
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pChild );
if( FAILED( hr ) || pChild == NULL )
{
if( pChild == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( wcscmp( wszContainer, L"Drivers" ) == 0 )
{
if( FAILED( hr = GatherInputRelatedDeviceInstDrivers( pInputRelatedDevice, pChild ) ) )
goto LCleanup;
}
else
{
InputRelatedDeviceInfo* pChildInputRelatedDevice = new InputRelatedDeviceInfo;
if( pChildInputRelatedDevice == NULL )
{
hr = E_OUTOFMEMORY;
goto LCleanup;
}
pInputRelatedDevice->m_vChildren.push_back( pChildInputRelatedDevice );
if( FAILED( hr = GatherInputRelatedDeviceInst( pChildInputRelatedDevice, pChild ) ) )
goto LCleanup;
}
SAFE_RELEASE( pChild );
}
LCleanup:
SAFE_RELEASE( pChild );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GatherInputRelatedDeviceInstDrivers()
// Desc: Get the driver list and store it in a InputRelatedDeviceInfo node
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GatherInputRelatedDeviceInstDrivers( InputRelatedDeviceInfo* pInputRelatedDevice,
IDxDiagContainer* pChild )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pDriverChild = NULL;
DWORD nChildInstanceCount = 0;
if( FAILED( hr = pChild->GetNumberOfChildContainers( &nChildInstanceCount ) ) )
goto LCleanup;
DWORD nFileItem;
for( nFileItem = 0; nFileItem < nChildInstanceCount; nFileItem++ )
{
hr = pChild->EnumChildContainerNames( nFileItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pChild->GetChildContainer( wszContainer, &pDriverChild );
if( FAILED( hr ) || pDriverChild == NULL )
{
if( pDriverChild == NULL )
hr = E_FAIL;
goto LCleanup;
}
FileNode* pFileNode = new FileNode;
if( pFileNode == NULL )
return E_OUTOFMEMORY;
pInputRelatedDevice->m_vDriverList.push_back( pFileNode );
if( FAILED( hr = GatherFileNodeInst( pFileNode, pDriverChild ) ) )
goto LCleanup;
SAFE_RELEASE( pDriverChild );
}
LCleanup:
SAFE_RELEASE( pDriverChild );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetNetworkInfo()
// Desc: Get the network info from the dll
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetNetworkInfo( NetInfo** ppNetInfo )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
NetInfo* pNetInfo = NULL;
pNetInfo = new NetInfo;
if( NULL == pNetInfo )
return E_OUTOFMEMORY;
ZeroMemory( pNetInfo, sizeof( NetInfo ) );
*ppNetInfo = pNetInfo;
// Get the IDxDiagContainer object called "DxDiag_DirectPlay".
// This call may take some time while dxdiag gathers the info.
hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectPlay", &pObject );
if( FAILED( hr ) || pObject == NULL )
{
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szNetworkNotesLocalized", EXPAND(pNetInfo->m_szNetworkNotesLocalized) ) ) )
return hr; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szNetworkNotesEnglish", EXPAND(pNetInfo->m_szNetworkNotesEnglish) ) ) )
return hr; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szRegHelpText", EXPAND(m_pNetInfo->m_szRegHelpText) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultLocalized", EXPAND(pNetInfo->m_szTestResultLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szTestResultEnglish", EXPAND(pNetInfo->m_szTestResultEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVoiceWizardFullDuplexTestLocalized",
EXPAND(m_pNetInfo->m_szVoiceWizardFullDuplexTestLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVoiceWizardHalfDuplexTestLocalized",
EXPAND(m_pNetInfo->m_szVoiceWizardHalfDuplexTestLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVoiceWizardMicTestLocalized",
EXPAND(m_pNetInfo->m_szVoiceWizardMicTestLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVoiceWizardFullDuplexTestEnglish",
EXPAND(m_pNetInfo->m_szVoiceWizardFullDuplexTestEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVoiceWizardHalfDuplexTestEnglish",
EXPAND(m_pNetInfo->m_szVoiceWizardHalfDuplexTestEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVoiceWizardMicTestEnglish",
EXPAND(m_pNetInfo->m_szVoiceWizardMicTestEnglish) ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pNetInfo->m_nElementCount ) ) )
return hr;
if( pNetInfo->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pNetInfo recorded") );
#endif
SAFE_RELEASE( pObject );
// Get the number of "DxDiag_DirectPlay.DxDiag_DirectPlayApps" objects in the dll
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectPlay.DxDiag_DirectPlayApps", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
NetApp* pNetApp = new NetApp;
if( pNetApp == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pNetApp, sizeof( NetApp ) );
// Add pNetApp to pNetInfo->m_vNetApps
pNetInfo->m_vNetApps.push_back( pNetApp );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szName", EXPAND(pNetApp->m_szName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szGuid", EXPAND(pNetApp->m_szGuid) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szExeFile", EXPAND(pNetApp->m_szExeFile) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szExePath", EXPAND(pNetApp->m_szExePath) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szExeVersionLocalized", EXPAND(pNetApp->m_szExeVersionLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szExeVersionEnglish", EXPAND(pNetApp->m_szExeVersionEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLauncherFile", EXPAND(pNetApp->m_szLauncherFile) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLauncherPath", EXPAND(pNetApp->m_szLauncherPath) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLauncherVersionLocalized",
EXPAND(pNetApp->m_szLauncherVersionLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szLauncherVersionEnglish",
EXPAND(pNetApp->m_szLauncherVersionEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bRegistryOK", &pNetApp->m_bRegistryOK ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bProblem", &pNetApp->m_bProblem ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bFileMissing", &pNetApp->m_bFileMissing ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwDXVer", &pNetApp->m_dwDXVer ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pNetApp->m_nElementCount ) ) )
return hr;
if( pNetApp->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pNetApp recorded") );
#endif
SAFE_RELEASE( pObject );
}
SAFE_RELEASE( pContainer );
// Get the number of "DxDiag_DirectPlaySP" objects in the dll
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectPlay.DxDiag_DirectPlaySPs", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
NetSP* pNetSP = new NetSP;
if( pNetSP == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pNetSP, sizeof( NetSP ) );
// Add pNetSP to pNetInfo->m_vNetSPs
pNetInfo->m_vNetSPs.push_back( pNetSP );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szNameLocalized", EXPAND(pNetSP->m_szNameLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szNameEnglish", EXPAND(pNetSP->m_szNameEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szGuid", EXPAND(pNetSP->m_szGuid) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szFile", EXPAND(pNetSP->m_szFile) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szPath", EXPAND(pNetSP->m_szPath) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVersionLocalized", EXPAND(pNetSP->m_szVersionLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVersionEnglish", EXPAND(pNetSP->m_szVersionEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bRegistryOK", &pNetSP->m_bRegistryOK ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bProblem", &pNetSP->m_bProblem ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bFileMissing", &pNetSP->m_bFileMissing ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetBoolValue( pObject, L"bInstalled", &pNetSP->m_bInstalled ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwDXVer", &pNetSP->m_dwDXVer ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pNetSP->m_nElementCount ) ) )
return hr;
if( pNetSP->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pNetSP recorded") );
#endif
SAFE_RELEASE( pObject );
}
SAFE_RELEASE( pContainer );
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectPlay.DxDiag_DirectPlayAdapters",
&pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
NetAdapter* pNetAdapter = new NetAdapter;
if( pNetAdapter == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pNetAdapter, sizeof( NetAdapter ) );
// Add pNetAdapter to m_pNetInfo->m_vNetAdapters
m_pNetInfo->m_vNetAdapters.push_back( pNetAdapter );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szAdapterName", EXPAND(pNetAdapter->m_szAdapterName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szSPNameEnglish", EXPAND(pNetAdapter->m_szSPNameEnglish) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szSPNameLocalized", EXPAND(pNetAdapter->m_szSPNameLocalized) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szGuid", EXPAND(pNetAdapter->m_szGuid) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFlags", &pNetAdapter->m_dwFlags ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pNetAdapter->m_nElementCount ) ) )
return hr;
if( pNetAdapter->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pNetAdapter recorded") );
#endif
SAFE_RELEASE( pObject );
}
SAFE_RELEASE( pContainer );
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectPlay.DxDiag_DirectPlayVoiceCodecs",
&pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
NetVoiceCodec* pNetVoiceCodec = new NetVoiceCodec;
if( pNetVoiceCodec == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pNetVoiceCodec, sizeof( NetVoiceCodec ) );
// Add pNetVoiceCodec to m_pNetInfo->m_vNetVoiceCodecs
m_pNetInfo->m_vNetVoiceCodecs.push_back( pNetVoiceCodec );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szName", EXPAND(pNetVoiceCodec->m_szName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szGuid", EXPAND(pNetVoiceCodec->m_szGuid) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szDescription", EXPAND(pNetVoiceCodec->m_szDescription) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwFlags", &pNetVoiceCodec->m_dwFlags ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwMaxBitsPerSecond", &pNetVoiceCodec->m_dwMaxBitsPerSecond ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pNetVoiceCodec->m_nElementCount ) ) )
return hr;
if( pNetVoiceCodec->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pNetVoiceCodec recorded") );
#endif
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetShowInfo()
// Desc:
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetShowInfo( ShowInfo** ppShowInfo )
{
HRESULT hr;
WCHAR wszContainer[256];
IDxDiagContainer* pContainer = NULL;
IDxDiagContainer* pObject = NULL;
DWORD nInstanceCount = 0;
DWORD nItem = 0;
DWORD nCurCount = 0;
ShowInfo* pShowInfo = NULL;
pShowInfo = new ShowInfo;
if( NULL == pShowInfo )
return E_OUTOFMEMORY;
ZeroMemory( pShowInfo, sizeof( ShowInfo ) );
*ppShowInfo = pShowInfo;
// Get the IDxDiagContainer object called "DxDiag_DirectShowFilters".
// This call may take some time while dxdiag gathers the info.
if( FAILED( hr = m_pDxDiagRoot->GetChildContainer( L"DxDiag_DirectShowFilters", &pContainer ) ) )
goto LCleanup;
if( FAILED( hr = pContainer->GetNumberOfChildContainers( &nInstanceCount ) ) )
goto LCleanup;
for( nItem = 0; nItem < nInstanceCount; nItem++ )
{
nCurCount = 0;
ShowFilterInfo* pShowFilter = new ShowFilterInfo;
if( pShowFilter == NULL )
return E_OUTOFMEMORY;
ZeroMemory( pShowFilter, sizeof( ShowFilterInfo ) );
// Add pShowFilter to pShowInfo->m_vShowFilters
pShowInfo->m_vShowFilters.push_back( pShowFilter );
hr = pContainer->EnumChildContainerNames( nItem, wszContainer, 256 );
if( FAILED( hr ) )
goto LCleanup;
hr = pContainer->GetChildContainer( wszContainer, &pObject );
if( FAILED( hr ) || pObject == NULL )
{
if( pObject == NULL )
hr = E_FAIL;
goto LCleanup;
}
if( FAILED( hr = GetStringValue( pObject, L"szName", EXPAND(pShowFilter->m_szName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szVersion", EXPAND(pShowFilter->m_szVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"ClsidFilter", EXPAND(pShowFilter->m_ClsidFilter) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szFileName", EXPAND(pShowFilter->m_szFileName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szFileVersion", EXPAND(pShowFilter->m_szFileVersion) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"szCatName", EXPAND(pShowFilter->m_szCatName) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetStringValue( pObject, L"ClsidCat", EXPAND(pShowFilter->m_ClsidCat) ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwInputs", &pShowFilter->m_dwInputs ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwOutputs", &pShowFilter->m_dwOutputs ) ) )
goto LCleanup; nCurCount++;
if( FAILED( hr = GetUIntValue( pObject, L"dwMerit", &pShowFilter->m_dwMerit ) ) )
goto LCleanup; nCurCount++;
#ifdef _DEBUG
// debug check to make sure we got all the info from the object
if( FAILED( hr = pObject->GetNumberOfProps( &pShowFilter->m_nElementCount ) ) )
return hr;
if( pShowFilter->m_nElementCount != nCurCount )
OutputDebugString( TEXT("Not all elements in pShowFilter recorded") );
#endif
SAFE_RELEASE( pObject );
}
LCleanup:
SAFE_RELEASE( pObject );
SAFE_RELEASE( pContainer );
return hr;
}
//-----------------------------------------------------------------------------
// Name: GetStringValue()
// Desc: Get a string value from a IDxDiagContainer object
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetStringValue( IDxDiagContainer* pObject, WCHAR* wstrName, TCHAR* strValue, int nStrLen )
{
HRESULT hr;
VARIANT var;
VariantInit( &var );
if( FAILED( hr = pObject->GetProp( wstrName, &var ) ) )
return hr;
if( var.vt != VT_BSTR )
return E_INVALIDARG;
#ifdef _UNICODE
wcsncpy( strValue, var.bstrVal, nStrLen-1 );
#else
wcstombs( strValue, var.bstrVal, nStrLen );
#endif
strValue[nStrLen - 1] = TEXT( '\0' );
VariantClear( &var );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: GetUIntValue()
// Desc: Get a UINT value from a IDxDiagContainer object
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetUIntValue( IDxDiagContainer* pObject, WCHAR* wstrName, DWORD* pdwValue )
{
HRESULT hr;
VARIANT var;
VariantInit( &var );
if( FAILED( hr = pObject->GetProp( wstrName, &var ) ) )
return hr;
if( var.vt != VT_UI4 )
return E_INVALIDARG;
*pdwValue = var.ulVal;
VariantClear( &var );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: GetIntValue()
// Desc: Get a INT value from a IDxDiagContainer object
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetIntValue( IDxDiagContainer* pObject, WCHAR* wstrName, LONG* pnValue )
{
HRESULT hr;
VARIANT var;
VariantInit( &var );
if( FAILED( hr = pObject->GetProp( wstrName, &var ) ) )
return hr;
if( var.vt != VT_I4 )
return E_INVALIDARG;
*pnValue = var.lVal;
VariantClear( &var );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: GetBoolValue()
// Desc: Get a BOOL value from a IDxDiagContainer object
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetBoolValue( IDxDiagContainer* pObject, WCHAR* wstrName, BOOL* pbValue )
{
HRESULT hr;
VARIANT var;
VariantInit( &var );
if( FAILED( hr = pObject->GetProp( wstrName, &var ) ) )
return hr;
if( var.vt != VT_BOOL )
return E_INVALIDARG;
*pbValue = ( var.boolVal != 0 );
VariantClear( &var );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: GetInt64Value()
// Desc: Get a ULONGLONG value from a IDxDiagContainer object
//-----------------------------------------------------------------------------
HRESULT CDxDiagInfo::GetInt64Value( IDxDiagContainer* pObject, WCHAR* wstrName, ULONGLONG* pullValue )
{
HRESULT hr;
VARIANT var;
VariantInit( &var );
if( FAILED( hr = pObject->GetProp( wstrName, &var ) ) )
return hr;
// 64-bit values are stored as strings in BSTRs
if( var.vt != VT_BSTR )
return E_INVALIDARG;
*pullValue = _wtoi64( var.bstrVal );
VariantClear( &var );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: DestroySystemDevice()
// Desc:
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DestroySystemDevice( vector <SystemDevice*>& vSystemDevices )
{
SystemDevice* pSystemDevice;
vector <SystemDevice*>::iterator iter;
for( iter = vSystemDevices.begin(); iter != vSystemDevices.end(); iter++ )
{
pSystemDevice = *iter;
SAFE_DELETE( pSystemDevice );
}
vSystemDevices.clear();
}
//-----------------------------------------------------------------------------
// Name: DestroyFileList()
// Desc: Cleanup the file list
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DestroyFileList( FileInfo* pFileInfo )
{
if( pFileInfo )
{
FileNode* pFileNode;
vector <FileNode*>::iterator iter;
for( iter = pFileInfo->m_vDxComponentsFiles.begin(); iter != pFileInfo->m_vDxComponentsFiles.end(); iter++ )
{
pFileNode = *iter;
SAFE_DELETE( pFileNode );
}
pFileInfo->m_vDxComponentsFiles.clear();
SAFE_DELETE( pFileInfo );
}
}
//-----------------------------------------------------------------------------
// Name: DestroyDisplayInfo()
// Desc: Cleanup the display info
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DestroyDisplayInfo( vector <DisplayInfo*>& vDisplayInfo )
{
DisplayInfo* pDisplayInfo;
vector <DisplayInfo*>::iterator iter;
for( iter = vDisplayInfo.begin(); iter != vDisplayInfo.end(); iter++ )
{
pDisplayInfo = *iter;
DxDiag_DXVA_DeinterlaceCaps* pDXVANode;
vector <DxDiag_DXVA_DeinterlaceCaps*>::iterator iterDXVA;
for( iterDXVA = pDisplayInfo->m_vDXVACaps.begin(); iterDXVA != pDisplayInfo->m_vDXVACaps.end(); iterDXVA++ )
{
pDXVANode = *iterDXVA;
SAFE_DELETE( pDXVANode );
}
pDisplayInfo->m_vDXVACaps.clear();
SAFE_DELETE( pDisplayInfo );
}
vDisplayInfo.clear();
}
//-----------------------------------------------------------------------------
// Name: DestroyInputInfo()
// Desc: Cleanup the input info
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DestroyInputInfo( InputInfo* pInputInfo )
{
if( pInputInfo )
{
InputDeviceInfo* pInputDeviceInfoDelete;
vector <InputDeviceInfo*>::iterator iter;
for( iter = pInputInfo->m_vDirectInputDevices.begin(); iter != pInputInfo->m_vDirectInputDevices.end();
iter++ )
{
pInputDeviceInfoDelete = *iter;
SAFE_DELETE( pInputDeviceInfoDelete );
}
pInputInfo->m_vDirectInputDevices.clear();
DeleteInputTree( pInputInfo->m_vGamePortDevices );
DeleteInputTree( pInputInfo->m_vUsbRoot );
DeleteInputTree( pInputInfo->m_vPS2Devices );
SAFE_DELETE( pInputInfo );
}
}
//-----------------------------------------------------------------------------
// Name: DeleteInputTree
// Desc:
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DeleteInputTree( vector <InputRelatedDeviceInfo*>& vDeviceList )
{
InputRelatedDeviceInfo* pInputNode;
vector <InputRelatedDeviceInfo*>::iterator iter;
for( iter = vDeviceList.begin(); iter != vDeviceList.end(); iter++ )
{
pInputNode = *iter;
if( !pInputNode->m_vChildren.empty() )
DeleteInputTree( pInputNode->m_vChildren );
DeleteFileList( pInputNode->m_vDriverList );
SAFE_DELETE( pInputNode );
}
vDeviceList.clear();
}
//-----------------------------------------------------------------------------
// Name: DeleteFileList()
// Desc:
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DeleteFileList( vector <FileNode*>& vDriverList )
{
FileNode* pFileNodeDelete;
vector <FileNode*>::iterator iter;
for( iter = vDriverList.begin(); iter != vDriverList.end(); iter++ )
{
pFileNodeDelete = *iter;
SAFE_DELETE( pFileNodeDelete );
}
vDriverList.clear();
}
//-----------------------------------------------------------------------------
// Name: DestroyMusicInfo()
// Desc: Cleanup the music info
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DestroyMusicInfo( MusicInfo* pMusicInfo )
{
if( pMusicInfo )
{
MusicPort* pMusicPort;
vector <MusicPort*>::iterator iter;
for( iter = pMusicInfo->m_vMusicPorts.begin(); iter != pMusicInfo->m_vMusicPorts.end(); iter++ )
{
pMusicPort = *iter;
SAFE_DELETE( pMusicPort );
}
pMusicInfo->m_vMusicPorts.clear();
SAFE_DELETE( pMusicInfo );
}
}
//-----------------------------------------------------------------------------
// Name: DestroyNetworkInfo()
// Desc: Cleanup the network info
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DestroyNetworkInfo( NetInfo* pNetInfo )
{
if( pNetInfo )
{
NetApp* pNetApp;
vector <NetApp*>::iterator iterNetApp;
for( iterNetApp = pNetInfo->m_vNetApps.begin(); iterNetApp != pNetInfo->m_vNetApps.end(); iterNetApp++ )
{
pNetApp = *iterNetApp;
SAFE_DELETE( pNetApp );
}
pNetInfo->m_vNetApps.clear();
NetSP* pNetSP;
vector <NetSP*>::iterator iterNetSP;
for( iterNetSP = pNetInfo->m_vNetSPs.begin(); iterNetSP != pNetInfo->m_vNetSPs.end(); iterNetSP++ )
{
pNetSP = *iterNetSP;
SAFE_DELETE( pNetSP );
}
pNetInfo->m_vNetSPs.clear();
NetAdapter* pNetAdapter;
vector <NetAdapter*>::iterator iterNetAdapter;
for( iterNetAdapter = pNetInfo->m_vNetAdapters.begin(); iterNetAdapter != pNetInfo->m_vNetAdapters.end();
iterNetAdapter++ )
{
pNetAdapter = *iterNetAdapter;
SAFE_DELETE( pNetAdapter );
}
pNetInfo->m_vNetAdapters.clear();
NetVoiceCodec* pNetVoiceCodec;
vector <NetVoiceCodec*>::iterator iterNetCodec;
for( iterNetCodec = pNetInfo->m_vNetVoiceCodecs.begin(); iterNetCodec != pNetInfo->m_vNetVoiceCodecs.end();
iterNetCodec++ )
{
pNetVoiceCodec = *iterNetCodec;
SAFE_DELETE( pNetVoiceCodec );
}
pNetInfo->m_vNetVoiceCodecs.clear();
SAFE_DELETE( pNetInfo );
}
}
//-----------------------------------------------------------------------------
// Name: DestroySoundInfo()
// Desc: Cleanup the sound info
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DestroySoundInfo( vector <SoundInfo*>& vSoundInfos )
{
SoundInfo* pSoundInfo;
vector <SoundInfo*>::iterator iter;
for( iter = vSoundInfos.begin(); iter != vSoundInfos.end(); iter++ )
{
pSoundInfo = *iter;
SAFE_DELETE( pSoundInfo );
}
vSoundInfos.clear();
}
//-----------------------------------------------------------------------------
// Name: DestroySoundCaptureInfo()
// Desc: Cleanup the sound info
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DestroySoundCaptureInfo( vector <SoundCaptureInfo*>& vSoundCaptureInfos )
{
SoundCaptureInfo* pSoundCaptureInfo;
vector <SoundCaptureInfo*>::iterator iter;
for( iter = vSoundCaptureInfos.begin(); iter != vSoundCaptureInfos.end(); iter++ )
{
pSoundCaptureInfo = *iter;
SAFE_DELETE( pSoundCaptureInfo );
}
vSoundCaptureInfos.clear();
}
//-----------------------------------------------------------------------------
// Name: DestroySoundInfo()
// Desc: Cleanup the show info
//-----------------------------------------------------------------------------
VOID CDxDiagInfo::DestroyShowInfo( ShowInfo* pShowInfo )
{
ShowFilterInfo* pShowFilterInfo;
vector <ShowFilterInfo*>::iterator iter;
for( iter = pShowInfo->m_vShowFilters.begin(); iter != pShowInfo->m_vShowFilters.end(); iter++ )
{
pShowFilterInfo = *iter;
SAFE_DELETE( pShowFilterInfo );
}
pShowInfo->m_vShowFilters.clear();
SAFE_DELETE( pShowInfo );
}
| 42.938272 | 125 | 0.598515 | [
"object",
"vector"
] |
69b5455ce56f55523fe6f93218561d75e911207d | 5,231 | hpp | C++ | include/CDHMM.hpp | tim-krebs/CDHMM | 7ab9ae5e7a470b213c471a9369ed1748308d0846 | [
"MIT"
] | null | null | null | include/CDHMM.hpp | tim-krebs/CDHMM | 7ab9ae5e7a470b213c471a9369ed1748308d0846 | [
"MIT"
] | null | null | null | include/CDHMM.hpp | tim-krebs/CDHMM | 7ab9ae5e7a470b213c471a9369ed1748308d0846 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include <map>
#include "GMM.hpp"
class CDHMM
{
private:
/* data */
int number_states;
int number_gaussians;
int dimension_feature;
std::string type_covariance;
std::string type_model;
public:
// Constructor/Destructor
CDHMM(int number_states, std::string type_model, std::string type_covariance, int dimension_feature, int number_gaussians);
~CDHMM();
// Initital Probability pi
std::vector<double> initial_probability;
// Transition Probability A
std::vector<std::vector<double> > state_transition_probability;
// Observation Probability B
std::vector<std::vector<double> > state_observation_probability;
// Create Vector of mixture models for discrete Observation B
std::vector<GMM> v_GMM;
// Inititale Wahrscheinlichkeit berechenen!!!! pi = 1 0 0 0 0 0 0...
void Initialize(int dimension_feature, int number_gaussians, int number_data, std::vector<std::vector<double> > &data);
double Forward_Algorithm(int length_data, std::vector<int> &state, std::vector<std::vector<double> > &alpha, std::vector<double> &likelihood);
double Backward_Algorithm(int length_data, std::vector<int> &state, std::vector<std::vector<double> > &beta, std::vector<double> &likelihood);
double Baum_Welch_Algorithm();
};
/**
* @brief Construct a new CDHMM::CDHMM object
*
* @param number_states (int) Number of states of the HMM
* @param type_model (string) Type of the model. Curretnly only avalable for linear hmm
* @param type_covariance (string) linear or full. Currently only diagonal available
* @param dimension_feature (int) Dimension of the feature vector. Default is 12
* @param number_gaussians (int) observations per state
*/
CDHMM::CDHMM(int number_states, std::string type_model, std::string type_covariance, int dimension_feature, int number_gaussians)
{
this->number_states = number_states;
this->number_gaussians = number_gaussians;
this->dimension_feature = dimension_feature;
this->type_covariance = type_covariance;
this->type_model = type_model;
v_GMM.resize(number_states);
for(int i = 0; i < number_states; i++)
{
v_GMM[i] = GMM(type_covariance, dimension_feature, number_gaussians);
}
}
CDHMM::~CDHMM()
{
}
/**
* @brief
*
* @param dimension_feature
* @param number_gaussians
* @param number_data
* @param data
*/
void CDHMM::Initialize(int dimension_feature, int number_gaussians, int number_data, std::vector<std::vector<double> > &data)
{
// Initital Probability pi
for(int i = 0; i < number_states; i++)
{
if(i == 0) initial_probability.push_back(1);
initial_probability.push_back(0);
}
for(int i = 0; i < number_states; i++)
{
std::cout << initial_probability[i] << " ";
}
//Initialize the transition prob matrix A
state_transition_probability.resize(number_states);
for (int i = 0; i < number_states; i++)
{
state_transition_probability[i].resize(number_states);
for (int j = 0; j < number_states; j++)
{
// for linear model
if (i == j)
{
state_transition_probability[i][j] = 0.7;
state_transition_probability[i][j+1] = 0.3;
}
}
}
state_transition_probability[0][0] = 0.0;
state_transition_probability[0][1] = 1.0;
state_transition_probability[number_states-1][number_states-1] = 0.0;
//Initialize the observation matrix B
// Calculate the continious observations first
Kmeans kmeans = Kmeans(data[0].size(), number_gaussians);
kmeans.Initialize(data.size(), data);
while (kmeans.Cluster(data.size(), data));
for(int i = 0; i < this->number_states; i++)
{
for(int j = 0; j < number_gaussians; j++)
{
for(int k = 0; k < data[0].size(); k++)
{
v_GMM[i].diagonal_covariance[j][k] = 1;
v_GMM[i].mean[j][k] = kmeans.centroid[j][k];
}
v_GMM[i].weight[j] = 1.0 / number_gaussians;
}
}
data.clear();
}
// Woking on
double CDHMM::Forward_Algorithm(int length_event, std::vector<int> &state, std::vector<std::vector<double> > &alpha, std::vector<double> &likelihood)
{
double log_likelihood = 0;
for(int i = 0; i < length_event; i++)
{
double tmp = 0;
if(i == 0)
{
for(int j = 0; j < state.size(); j++)
{
int k = state[j];
tmp += (alpha[i][j] = (j == 0) * initial_probability[k] * likelihood[i * number_states * k]);
}
}
else
{
for(int j = 0; j < state.size(); j++)
{
double tmp = 0;
}
}
}
return -log_likelihood;
}
double CDHMM::Backward_Algorithm(int length_event, std::vector<int> &state, std::vector<std::vector<double> > &beta, std::vector<double> &likelihood)
{
double log_likelihood = 0;
return -log_likelihood;
}
double CDHMM::Baum_Welch_Algorithm()
{
double likelihood =0;
return likelihood;
}
| 28.429348 | 149 | 0.622634 | [
"object",
"vector",
"model"
] |
69b54a5d57b2088a3f77fed625982c090d81ad11 | 2,783 | cpp | C++ | src/cli/main.cpp | Thinkaboutmin/C-Veia | b31454261389c716cca039eb8787909b6d32efc7 | [
"MIT"
] | null | null | null | src/cli/main.cpp | Thinkaboutmin/C-Veia | b31454261389c716cca039eb8787909b6d32efc7 | [
"MIT"
] | null | null | null | src/cli/main.cpp | Thinkaboutmin/C-Veia | b31454261389c716cca039eb8787909b6d32efc7 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include <locale>
#include "cli_tic_tac_toe.h"
#include "menu.h"
#include "../lib/player/ai.h"
#include "../lib/player/ai_min_max.h"
#include "../lib/player/ai_min_max_pruned.h"
#include "human_player.h"
#include "string_table.h"
#include "screen.h"
using namespace tic_tac_toe;
int main(int argc, char ** argv) {
// Define the locale so that wide characters are interpreted as UTF-8
std::setlocale(LC_ALL, "");
// Start by giving the option of modifying the game.
MenuFinishOption option = MenuFinishOption::MODIFY_GAME;
Screen screen(std::wcin, std::wcout);
Menu menu(screen);
CliTicTacToe * game = nullptr;
do {
if (option == MenuFinishOption::MODIFY_GAME) {
if (game != nullptr) {
// Clear last tic tac toe game.
CliTicTacToe * tmp = game;
game = nullptr;
delete tmp;
}
MenuOption option = menu.askForMode();
switch(option) {
case MenuOption::DEFAULT:
case MenuOption::TOTAL:
default: {
auto * player_1 = new HumanPlayer{L"X", screen};
auto * player_2 = new AI<std::wstring>{L"O"};
auto * table = new StringTable{3, 3};
game = new CliTicTacToe(screen, {player_1, player_2}, table);
break;
}
case MenuOption::CUSTOMIZED: {
menu.customizationMenu();
std::vector<Player<std::wstring> *> players = menu.getPlayers();
StringTable * table = menu.getTable();
game = new CliTicTacToe(screen, players, table);
for (const auto player : game->getPlayers()) {
player->injectJudge(game);
}
break;
}
}
} else {
game->resetGame();
}
GameStatus status;
do {
screen.clearScreen();
status = game->showBoard().playerPlay().isThereAWinner();
} while(status == GameStatus::ONGOING);
screen.clearScreen();
game->showBoard();
switch (status) {
case GameStatus::DRAW:
std::wcout << L"Nobody won!";
break;
case GameStatus::WIN:
std::wcout << L"Player " << game->getWinner()->getPlayerSymbol() << " won!";
break;
case GameStatus::ONGOING:
default:
break;
}
option = menu.clearScreenEndGame().playAgain();
} while(option != MenuFinishOption::EXIT);
delete game;
return 0;
}
| 31.988506 | 92 | 0.513115 | [
"vector"
] |
69b936f34b215d812179cf3cc38aa3d212f0afa4 | 475 | hpp | C++ | src/physics/WorldParser.hpp | hhebb/physics2d | 58be79626831a0316b9648779786406fa1a7d900 | [
"MIT"
] | null | null | null | src/physics/WorldParser.hpp | hhebb/physics2d | 58be79626831a0316b9648779786406fa1a7d900 | [
"MIT"
] | null | null | null | src/physics/WorldParser.hpp | hhebb/physics2d | 58be79626831a0316b9648779786406fa1a7d900 | [
"MIT"
] | null | null | null | # ifndef WORLD_PARSER
# define WORLD_PARSER
# include <jsoncpp/json/json.h>
# include <fstream>
# include <iostream>
# include <sstream>
# include "../Definition.hpp"
using namespace std;
class WorldParser
{
public:
string testName;
vector<POLY_DATA> polys;
vector<Vector2> positions;
vector<SCALAR> rotations;
vector<BodyType> bTypes;
vector<int> layers;
void Parse(string path);
vector<string> Split(string str, char delim);
};
# endif | 17.592593 | 49 | 0.698947 | [
"vector"
] |
69cece2c6656296b3897a9099d9b09132b6a754d | 2,391 | hpp | C++ | IO/src/decklink/include/decklink_discovery.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 182 | 2019-04-19T12:38:30.000Z | 2022-03-20T16:48:20.000Z | IO/src/decklink/include/decklink_discovery.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 107 | 2019-04-23T10:49:35.000Z | 2022-03-02T18:12:28.000Z | IO/src/decklink/include/decklink_discovery.hpp | tlalexander/stitchEm | cdff821ad2c500703e6cb237ec61139fce7bf11c | [
"MIT"
] | 59 | 2019-06-04T11:27:25.000Z | 2022-03-17T23:49:49.000Z | // Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#ifndef DECKLINK_DISCOVERY_HPP_
#define DECKLINK_DISCOVERY_HPP_
#include "libvideostitch/plugin.hpp"
#if defined(_WIN32)
#include "DeckLinkAPI_h.h"
#else
#include "DeckLinkAPI.h"
#include "DeckLinkAPIModes.h"
#endif
#include <vector>
#include <string>
#include <memory>
namespace VideoStitch {
namespace Plugin {
class DeckLinkDiscovery : public VSDiscoveryPlugin {
struct Device {
Device() : deckLinkDevice(nullptr), supportedDisplayModes(), supportedPixelFormats() {
pluginDevice.type = Plugin::DiscoveryDevice::UNKNOWN;
}
virtual ~Device();
Plugin::DiscoveryDevice pluginDevice;
std::shared_ptr<IDeckLink> deckLinkDevice;
std::vector<DisplayMode> supportedDisplayModes;
std::vector<PixelFormat> supportedPixelFormats;
};
public:
static std::shared_ptr<Device> createDevice(std::shared_ptr<IDeckLink> deckLinkDevice,
const std::string& deviceIdName,
const std::string& deviceDisplayableName);
static DeckLinkDiscovery* create();
virtual ~DeckLinkDiscovery() {}
virtual std::string name() const;
virtual std::string readableName() const;
virtual std::vector<Plugin::DiscoveryDevice> inputDevices();
virtual std::vector<Plugin::DiscoveryDevice> outputDevices();
virtual std::vector<std::string> cards() const;
virtual void registerAutoDetectionCallback(AutoDetection&);
virtual std::vector<DisplayMode> supportedDisplayModes(const Plugin::DiscoveryDevice&);
DisplayMode currentDisplayMode(const Plugin::DiscoveryDevice&) {
return DisplayMode(); // TODO
}
virtual std::vector<PixelFormat> supportedPixelFormat(const Plugin::DiscoveryDevice&);
virtual std::vector<int> supportedNbChannels(const Plugin::DiscoveryDevice& device);
virtual std::vector<Audio::SamplingRate> supportedSamplingRates(const Plugin::DiscoveryDevice& device);
virtual std::vector<Audio::SamplingDepth> supportedSampleFormats(const Plugin::DiscoveryDevice& device);
private:
DeckLinkDiscovery(const std::vector<std::string>& cards, const std::vector<std::shared_ptr<Device>>& devices);
std::vector<std::string> m_cards;
std::vector<std::shared_ptr<Device>> m_devices;
};
} // namespace Plugin
} // namespace VideoStitch
#endif // DECKLINK_DISCOVERY_HPP_
| 33.676056 | 112 | 0.736512 | [
"vector"
] |
69d0150716d69bed5d398185e4750093347f968e | 634 | cpp | C++ | 216.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 8 | 2018-10-31T11:00:19.000Z | 2020-07-31T05:25:06.000Z | 216.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | null | null | null | 216.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 2 | 2018-05-31T11:29:22.000Z | 2019-09-11T06:34:40.000Z | class Solution {
public:
vector<vector<int>> ans;
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> t;
helper(k,n,t);
return ans;
}
void helper(int k, int n, vector<int> x){
if(k==0 && n==0){
ans.push_back(x);
return;
}else if(k==0 || n==0) return;
int nn=0;
for(int i=1;i<k;i++) nn+=i;
int maxf=min(9,(n-nn)/k),minf=0;
if(x.size()!=0) minf=x.back();
for(int i=minf+1;i<=maxf;i++){
x.push_back(i);
helper(k-1,n-i,x);
x.erase(x.end()-1,x.end());
}
}
};
| 25.36 | 55 | 0.44795 | [
"vector"
] |
69d4ba245e798c63808834e5fdbe6e634238f4dd | 1,265 | cpp | C++ | listener/router.cpp | olafurw/server2 | 28cfc7c07ef5e87951af8f5326b54e3434391765 | [
"MIT"
] | null | null | null | listener/router.cpp | olafurw/server2 | 28cfc7c07ef5e87951af8f5326b54e3434391765 | [
"MIT"
] | null | null | null | listener/router.cpp | olafurw/server2 | 28cfc7c07ef5e87951af8f5326b54e3434391765 | [
"MIT"
] | null | null | null | #include "router.hpp"
#include "static_file.hpp"
#include <iostream>
router::router()
{
m_has_data = false;
}
void router::start()
{
std::cout << "[Router] Starting" << std::endl;
m_config = std::unique_ptr<config_storage>(new config_storage(
"/home/olafurw/server/config/routes"
));
std::vector<request_parser> work;
std::cout << "[Router] Started" << std::endl;
while(true)
{
{
std::unique_lock<std::mutex> lock(m_mutex);
m_cv.wait(lock, [&]{ return m_has_data; });
work.swap(m_work);
m_has_data = false;
}
for(auto&& request : work)
{
config c = m_config->get(request.get_path());
static_file sf("/home/olafurw/server/www/" + c.path);
m_cb(request.get_socket(), sf.m_data);
}
work.clear();
}
}
void router::data_callback(std::function<void(const int, std::string)> cb)
{
m_cb = cb;
}
void router::on_request(request_parser&& r)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_has_data = true;
m_work.emplace_back(r);
m_cv.notify_all();
}
router::~router()
{
} | 19.166667 | 74 | 0.531225 | [
"vector"
] |
69d6b18d94822640ae60c58829f8622c84b43cf2 | 83,791 | cpp | C++ | audioserver/src/audsrv-main.cpp | rdkcmf/rdk-audioserver | 4a6dcf24161427676359205280c12853e991e6ab | [
"Apache-2.0"
] | null | null | null | audioserver/src/audsrv-main.cpp | rdkcmf/rdk-audioserver | 4a6dcf24161427676359205280c12853e991e6ab | [
"Apache-2.0"
] | null | null | null | audioserver/src/audsrv-main.cpp | rdkcmf/rdk-audioserver | 4a6dcf24161427676359205280c12853e991e6ab | [
"Apache-2.0"
] | null | null | null | /*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2017 RDK Management
*
* 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.
*/
/**
* @defgroup audioserver
* @{
* @defgroup audsrv
* @{
**/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/un.h>
#include "audsrv-logger.h"
#include "audsrv-protocol.h"
#include "audsrv-conn.h"
#include "audioserver-soc.h"
#include <vector>
#define FILE_LOCK_SUFFIX ".lock"
#define FILE_LOCK_SUFFIX_LEN (5)
#define FILE_LOCK_FLAGS (O_CREAT|O_CLOEXEC)
#define FILE_LOCK_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP)
#define AUDSRV_MAX_MSG (1024)
#define AUDSRV_MAX_CAPTURE_DATA_SIZE (30*1024)
#define AUDSRV_SENDBUFFSIZE (80*1024)
#define LEVEL_DENOMINATOR (1000000)
typedef struct _AudsrvContext AudsrvContext;
typedef struct _AudsrvClient
{
AudsrvContext *ctx;
int fdSocket;
struct ucred ucred;
AudsrvConn *conn;
pthread_t threadId;
pthread_mutex_t mutex;
bool clientStarted;
bool clientReady;
bool clientAbort;
bool stopRequested;
AudSrvCaptureParameters captureParams;
AudSrvSocClient soc;
unsigned sessionType;
char sessionName[AUDSRV_MAX_SESSION_NAME_LEN+1];
} AudsrvClient;
typedef struct _AudsrvContext
{
char *serverName;
struct sockaddr_un addr;
char lockName[sizeof(addr.sun_path)+FILE_LOCK_SUFFIX_LEN];
int fdLock;
int fdSocket;
AudSrvSoc soc;
pthread_mutex_t mutex;
std::vector<AudsrvClient*> clients;
std::vector<AudsrvClient*> clientsSessionEvent;
} AudsrvContext;
static AudsrvContext* audsrv_create_server_context( const char *name );
static void audsrv_destroy_server_context( AudsrvContext* ctx );
static bool audsrv_create_server_socket( AudsrvContext *ctx );
static AudsrvClient* audsrv_create_client( AudsrvContext *ctx, int fd );
static void audsrv_destroy_client( AudsrvContext *ctx, AudsrvClient *client );
static void* audsrv_client_thread( void *arg );
static int audsrv_process_message( AudsrvClient *client );
static int audsrv_process_init( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_audioinfo( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_basetime( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_play( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_stop( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_pause( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_unpause( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_flush( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_audiosync( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_audiodata( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_audiodatahandle( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_mute( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_unmute( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_volume( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_enable_session_event( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_disable_session_event( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_enableeos( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_disableeos( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_startcapture( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_stopcapture( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_enumsessions( AudsrvClient *client, unsigned msglen, unsigned version );
static int audsrv_process_getstatus( AudsrvClient *client, unsigned msglen, unsigned version );
static void audsrv_eos_callback( void *userData );
static void audsrv_first_audio_callback( void *userData );
static void audsrv_pts_error_callback( void *userData, unsigned count );
static void audsrv_underflow_callback( void *userData, unsigned count, unsigned bufferedBytes, unsigned queuedFrames );
static void audsrv_capture_callback( void *userData, AudSrvCaptureParameters *params, unsigned char *data, int datalen );
static void audsrv_distribute_session_event( AudsrvContext *ctx, int event, AudsrvClient *clientSubject );
static void audsrv_send_session_event( AudsrvClient *client, int event, AudsrvClient *clientSubject );
static bool audsrv_send_eos_detected( AudsrvClient *client );
static bool audsrv_send_first_audio( AudsrvClient *client );
static bool audsrv_send_pts_error( AudsrvClient *client, unsigned count );
static bool audsrv_send_underflow( AudsrvClient *client, unsigned count, unsigned bufferedBytes, unsigned queuedFrames );
static bool audsrv_send_capture_params( AudsrvClient *client );
static bool audsrv_send_capture_data( AudsrvClient *client, unsigned char *data, int datalen );
static bool audsrv_send_capture_done( AudsrvClient *client );
static bool audsrv_send_enum_session_results( AudsrvClient *client, unsigned long long token, int sessionCount, unsigned char *data, int datalen );
static bool audsrv_send_getstatus_results( AudsrvClient *client, unsigned long long token, AudSrvSessionStatus *status );
static bool g_running= false;
static long long getCurrentTimeMicro()
{
struct timeval tv;
long long utcCurrentTimeMicro;
gettimeofday(&tv,0);
utcCurrentTimeMicro= tv.tv_sec*1000000LL+tv.tv_usec;
return utcCurrentTimeMicro;
}
static void signalHandler(int signum)
{
printf("signalHandler: signum %d\n", signum);
g_running= false;
}
static AudsrvContext* audsrv_create_server_context( const char *name )
{
AudsrvContext *ctx= 0;
ctx= (AudsrvContext*)calloc( 1, sizeof(AudsrvContext) );
TRACE1("audsrv_create_server_context: ctx %p", ctx);
if ( ctx )
{
ctx->fdLock= -1;
ctx->fdSocket= -1;
ctx->serverName= strdup( name );
pthread_mutex_init( &ctx->mutex, 0 );
ctx->clients= std::vector<AudsrvClient*>();
ctx->clientsSessionEvent= std::vector<AudsrvClient*>();
if ( !ctx->serverName )
{
ERROR("audsrv_create_server_context: unable to duplicate server name");
goto error;
}
ctx->soc= AudioServerSocOpen();
if ( !ctx->soc )
{
ERROR("audsrv_create_server_context: unable to open audioserver-soc");
goto error;
}
return ctx;
}
error:
audsrv_destroy_server_context( ctx );
return 0;
}
static void audsrv_destroy_server_context( AudsrvContext* ctx )
{
TRACE1("audsrv_destroy_server_context: ctx %p", ctx);
if ( ctx )
{
pthread_mutex_lock( &ctx->mutex );
while( ctx->clients.size() > 0 )
{
AudsrvClient *client= ctx->clients.back();
audsrv_destroy_client( ctx, client );
ctx->clients.pop_back();
}
while( ctx->clientsSessionEvent.size() > 0 )
{
ctx->clientsSessionEvent.pop_back();
}
if ( ctx->fdSocket >= 0 )
{
close(ctx->fdSocket);
ctx->fdSocket= -1;
}
if ( ctx->addr.sun_path )
{
(void)unlink( ctx->addr.sun_path );
ctx->addr.sun_path[0]= '\0';
}
if ( ctx->fdLock >= 0 )
{
close(ctx->fdLock);
ctx->fdLock= -1;
}
if ( ctx->lockName )
{
(void)unlink( ctx->lockName );
ctx->lockName[0]= '\0';
}
if ( ctx->serverName )
{
free( ctx->serverName );
ctx->serverName= 0;
}
if ( ctx->soc )
{
AudioServerSocClose( ctx->soc );
ctx->soc= 0;
}
pthread_mutex_unlock( &ctx->mutex );
pthread_mutex_destroy( &ctx->mutex );
free( ctx );
}
}
static bool audsrv_create_server_socket( AudsrvContext *ctx )
{
bool result= false;
const char *workDir;
int pathSize, maxPathSize;
socklen_t addrSize;
int rc;
workDir= getenv("XDG_RUNTIME_DIR");
if ( !workDir )
{
ERROR("XDG_RUNTIME_DIR is not set");
goto exit;
}
ctx->addr.sun_family= AF_LOCAL;
maxPathSize= (int)sizeof(ctx->addr.sun_path);
pathSize= snprintf(ctx->addr.sun_path,
maxPathSize,
"%s/%s",
workDir,
ctx->serverName) + 1;
if ( pathSize < 0 )
{
ERROR("error formulating socket name");
goto exit;
}
if ( pathSize > maxPathSize )
{
ERROR("full socket name length (%d) exceeds allowed length of %d bytes", pathSize, maxPathSize );
goto exit;
}
TRACE1("full socket name (%s)", ctx->addr.sun_path );
snprintf( ctx->lockName,
sizeof(ctx->lockName),
"%s%s",
ctx->addr.sun_path,
FILE_LOCK_SUFFIX);
ctx->fdLock= open(ctx->lockName, FILE_LOCK_FLAGS, FILE_LOCK_MODE );
if ( ctx->fdLock < 0 )
{
ERROR("unable to create lock file (%s) errno %d", ctx->lockName, errno );
}
rc= flock(ctx->fdLock, LOCK_EX|LOCK_NB);
if ( rc < 0 )
{
ERROR("unable to lock: check if another server is running with the name %s", ctx->serverName );
goto exit;
}
// We've got the lock, delete any existing socket file
(void)unlink(ctx->addr.sun_path);
ctx->fdSocket= socket( PF_LOCAL, SOCK_STREAM|SOCK_CLOEXEC, 0 );
if ( ctx->fdSocket < 0 )
{
ERROR("unable to open socket: errno %d", errno );
goto exit;
}
addrSize= offsetof(struct sockaddr_un, sun_path) + pathSize;
rc= bind(ctx->fdSocket, (struct sockaddr *)&ctx->addr, addrSize );
if ( rc < 0 )
{
ERROR("bind failed for socket: errno %d", errno );
goto exit;
}
rc= listen(ctx->fdSocket, 1);
if ( rc < 0 )
{
ERROR("listen failed for socket: errno %d", errno );
goto exit;
}
result= true;
exit:
if ( !result )
{
if ( ctx->fdSocket >= 0 )
{
close(ctx->fdSocket);
ctx->fdSocket= -1;
}
if ( ctx->addr.sun_path )
{
(void)unlink( ctx->addr.sun_path );
ctx->addr.sun_path[0]= '\0';
}
if ( ctx->fdLock >= 0 )
{
close(ctx->fdLock);
ctx->fdLock= -1;
}
if ( ctx->lockName )
{
(void)unlink( ctx->lockName );
ctx->lockName[0]= '\0';
}
}
return result;
}
static void showUsage()
{
printf("usage:\n");
printf(" audioserver [options]\n" );
printf("where [options] are:\n" );
printf(" --name <server name> : audio server name to use\n" );
printf(" --help : show usage\n" );
printf(" -? : show usage\n" );
printf("\n" );}
int main( int argc, const char **argv )
{
int nRC= 0;
int len;
bool error= false;
const char *serverName= "audsrv0";
AudsrvContext *ctx= 0;
printf( "audioserver\n");
for( int i= 1; i < argc; ++i )
{
len= strlen(argv[i]);
if ( (len == 6) && !strncmp( (const char*)argv[i], "--name", len) )
{
if ( i < argc-1 )
{
++i;
serverName= argv[i];
}
else
{
error= true;
printf("--name option missing name\n" );
}
}
else
if ( ((len == 2) &&
!strncmp( (const char*)argv[i], "-?", len)) ||
((len == 6) &&
!strncmp( (const char*)argv[i], "--help", len)) )
{
showUsage();
goto exit;
}
else
{
printf("ignoring unrecognized argument (%s)\n", argv[i] );
}
}
if ( !error )
{
struct sigaction sigint;
sigint.sa_handler= signalHandler;
sigemptyset(&sigint.sa_mask);
sigint.sa_flags= SA_RESETHAND;
sigaction(SIGINT, &sigint, NULL);
sigaction(SIGTERM, &sigint, NULL);
char *env= getenv( "AUDSRV_DEBUG" );
if ( env )
{
int level= atoi( env );
audsrv_set_log_level( level );
}
INFO("using server name: %s", serverName);
ctx= audsrv_create_server_context( serverName );
if ( !ctx )
{
ERROR("unable allocate server context");
goto exit;
}
if ( audsrv_create_server_socket( ctx ) )
{
g_running= true;
while( g_running )
{
int fd;
struct sockaddr_un addr;
socklen_t addrLen= sizeof(addr);
INFO("listening for connections...");
fd= accept4( ctx->fdSocket, (struct sockaddr *)&addr, &addrLen, SOCK_CLOEXEC );
if ( fd >= 0 )
{
INFO("received connection on fd %d", fd);
if ( g_running )
{
AudsrvClient *client= audsrv_create_client( ctx, fd );
if ( client )
{
INFO("created client %p for fd %d", client, fd);
pthread_mutex_lock( &ctx->mutex );
ctx->clients.push_back( client );
pthread_mutex_unlock( &ctx->mutex );
}
else
{
ERROR("unable to create client for fd %d", fd);
}
}
else
{
close( fd );
}
}
}
}
}
exit:
if ( ctx )
{
audsrv_destroy_server_context( ctx );
}
return nRC;
}
static AudsrvClient* audsrv_create_client( AudsrvContext *ctx, int fd )
{
AudsrvClient *client= 0;
int rc;
bool error= true;
socklen_t optlen;
client= (AudsrvClient*)calloc( 1, sizeof(AudsrvClient) );
if ( client )
{
pthread_mutex_init( &client->mutex, 0 );
client->ctx= ctx;
client->fdSocket= fd;
client->captureParams.version= (unsigned)-1;
optlen= sizeof(struct ucred);
rc= getsockopt( client->fdSocket, SOL_SOCKET, SO_PEERCRED,
&client->ucred, &optlen );
if ( rc < 0 )
{
ERROR("unable to get client credentials from socket: errno %d", errno );
}
else
{
client->conn= audsrv_conn_init( client->fdSocket, AUDSRV_MAX_MSG, AUDSRV_SENDBUFFSIZE );
if ( !client->conn )
{
ERROR("unable to initialize connection");
}
else
{
rc= pthread_create( &client->threadId, NULL, audsrv_client_thread, client );
if ( !rc )
{
bool ready, abort;
INFO("client %p pid %d connected", client, client->ucred.pid);
for( int i= 0; i < 500; ++i )
{
pthread_mutex_lock( &client->mutex );
ready= client->clientReady;
abort= client->clientAbort;
pthread_mutex_unlock( &client->mutex );
if ( ready )
{
TRACE1("client %p ready", client);
break;
}
if ( abort )
{
TRACE1("client %p aborting", client);
break;
}
usleep( 10000 );
}
if ( ready )
{
error= false;
}
else
{
ERROR("client thread failed to become ready");
}
}
else
{
ERROR("error creating thread for client %p fd %d", client, fd );
}
}
}
}
else
{
ERROR("unable to allocate new client");
}
if ( error )
{
pthread_mutex_lock( &ctx->mutex );
audsrv_destroy_client( ctx, client );
pthread_mutex_unlock( &ctx->mutex );
client= 0;
}
return client;
}
static void audsrv_destroy_client( AudsrvContext *ctx, AudsrvClient *client )
{
if ( client )
{
if ( client->fdSocket >= 0 )
{
TRACE1("audsrv_destroy_client: shutting down socket fd %d for client %p", client->fdSocket, client );
shutdown( client->fdSocket, SHUT_RDWR );
}
if ( client->clientStarted )
{
client->stopRequested= true;
pthread_mutex_unlock( &ctx->mutex );
TRACE1("audsrv_destroy_client: requested stop, calling join for client %p", client);
pthread_join( client->threadId, NULL );
TRACE1("audsrv_destroy_client: join complete for client %p", client);
pthread_mutex_lock( &ctx->mutex );
}
if ( client->soc )
{
AudioServerSocCloseClient( client->soc );
client->soc= 0;
}
if ( client->conn )
{
audsrv_conn_term( client->conn );
client->conn= 0;
}
if ( client->fdSocket >= 0 )
{
TRACE1("audsrv_destroy_client: closing fd %d for client %p", client->fdSocket, client );
close( client->fdSocket );
client->fdSocket= -1;
}
pthread_mutex_destroy( &client->mutex );
free( client );
}
}
static void* audsrv_client_thread( void *arg )
{
AudsrvClient *client= (AudsrvClient*)arg;
TRACE1( "audsrv_client_thread: enter: client %p fd %d pid %d", client, client->fdSocket, client->ucred.pid );
client->clientStarted= true;
pthread_mutex_lock( &client->mutex );
client->clientReady= true;
pthread_mutex_unlock( &client->mutex );
while( !client->stopRequested && !client->clientAbort )
{
int consumed;
int len= audsrv_conn_recv( client->conn );
if ( client->conn->peerDisconnected && !client->stopRequested )
{
INFO("audsrv_client_thread: client %p pid %d disconnected", client, client->ucred.pid);
}
if ( client->conn->count >= AUDSRV_MSG_HDR_LEN )
{
TRACE2("audsrv_client_thread: client %p received %d bytes", client, client->conn->count );
do
{
consumed= audsrv_process_message( client );
}
while( consumed > 0 );
}
else if ( client->conn->peerDisconnected )
{
break;
}
}
if ( client->soc )
{
AudioServerSocCloseClient( client->soc );
client->soc= 0;
}
else if ( client->sessionType != AUDSRV_SESSION_Observer )
{
ERROR("audsrv_client_thread: enter: client %p fd %d pid %d: unable to open soc client, aborting", client, client->fdSocket, client->ucred.pid );
}
exit:
TRACE1( "audsrv_client_thread: exit: client %p fd %d", client, client->fdSocket );
if ( !client->stopRequested && client->conn->peerDisconnected )
{
AudsrvContext *ctx= client->ctx;
pthread_mutex_lock( &ctx->mutex );
for( std::vector<AudsrvClient*>::iterator it= ctx->clientsSessionEvent.begin();
it != ctx->clientsSessionEvent.end();
++it )
{
if ( client == (*it) )
{
ctx->clientsSessionEvent.erase( it );
break;
}
}
pthread_mutex_unlock( &ctx->mutex );
audsrv_distribute_session_event( client->ctx, AUDSRV_SESSIONEVENT_Removed, client );
pthread_mutex_lock( &ctx->mutex );
for( std::vector<AudsrvClient*>::iterator it= ctx->clients.begin();
it != ctx->clients.end();
++it )
{
if ( client == (*it) )
{
ctx->clients.erase( it );
audsrv_destroy_client( ctx, client );
break;
}
}
pthread_mutex_unlock( &ctx->mutex );
}
client->clientStarted= false;
return NULL;
}
static int audsrv_process_message( AudsrvClient *client )
{
int consumed= 0;
int avail= client->conn->count;
unsigned msglen, msgid, version;
if ( avail < AUDSRV_MSG_HDR_LEN )
{
goto exit;
}
msglen= audsrv_conn_peek_u32( client->conn );
TRACE2("audsrv_process_message: peeked msglen %d", msglen);
if ( msglen+AUDSRV_MSG_HDR_LEN > client->conn->count )
{
goto exit;
}
audsrv_conn_skip( client->conn, 4 );
msgid= audsrv_conn_get_u32( client->conn );
version= audsrv_conn_get_u32( client->conn );
TRACE2("audsrv_process_message: msglen %d msgid %d version %d", msglen, msgid, version);
consumed += AUDSRV_MSG_HDR_LEN;
switch( msgid )
{
case AUDSRV_MSG_Init:
consumed += audsrv_process_init( client, msglen, version );
break;
case AUDSRV_MSG_AudioInfo:
consumed += audsrv_process_audioinfo( client, msglen, version );
break;
case AUDSRV_MSG_Play:
consumed += audsrv_process_play( client, msglen, version );
break;
case AUDSRV_MSG_Basetime:
consumed += audsrv_process_basetime( client, msglen, version );
break;
case AUDSRV_MSG_Stop:
consumed += audsrv_process_stop( client, msglen, version );
break;
case AUDSRV_MSG_Pause:
consumed += audsrv_process_pause( client, msglen, version );
break;
case AUDSRV_MSG_UnPause:
consumed += audsrv_process_unpause( client, msglen, version );
break;
case AUDSRV_MSG_Flush:
consumed += audsrv_process_flush( client, msglen, version );
break;
case AUDSRV_MSG_AudioSync:
consumed += audsrv_process_audiosync( client, msglen, version );
break;
case AUDSRV_MSG_AudioData:
consumed += audsrv_process_audiodata( client, msglen, version );
break;
case AUDSRV_MSG_AudioDataHandle:
consumed += audsrv_process_audiodatahandle( client, msglen, version );
break;
case AUDSRV_MSG_Mute:
consumed += audsrv_process_mute( client, msglen, version );
break;
case AUDSRV_MSG_UnMute:
consumed += audsrv_process_unmute( client, msglen, version );
break;
case AUDSRV_MSG_Volume:
consumed += audsrv_process_volume( client, msglen, version );
break;
case AUDSRV_MSG_EnableSessionEvent:
consumed += audsrv_process_enable_session_event( client, msglen, version );
break;
case AUDSRV_MSG_DisableSessionEvent:
consumed += audsrv_process_disable_session_event( client, msglen, version );
break;
case AUDSRV_MSG_EnableEOS:
consumed += audsrv_process_enableeos( client, msglen, version );
break;
case AUDSRV_MSG_DisableEOS:
consumed += audsrv_process_disableeos( client, msglen, version );
break;
case AUDSRV_MSG_StartCapture:
consumed += audsrv_process_startcapture( client, msglen, version );
break;
case AUDSRV_MSG_StopCapture:
consumed += audsrv_process_stopcapture( client, msglen, version );
break;
case AUDSRV_MSG_EnumSessions:
consumed += audsrv_process_enumsessions( client, msglen, version );
break;
case AUDSRV_MSG_GetStatus:
consumed += audsrv_process_getstatus( client, msglen, version );
break;
case AUDSRV_MSG_EOSDetected:
case AUDSRV_MSG_FirstAudio:
case AUDSRV_MSG_PtsError:
case AUDSRV_MSG_Underflow:
case AUDSRV_MSG_CaptureParameters:
case AUDSRV_MSG_CaptureData:
case AUDSRV_MSG_CaptureDone:
case AUDSRV_MSG_EnumSessionsResults:
case AUDSRV_MSG_GetStatusResults:
case AUDSRV_MSG_SessionEvent:
ERROR("ignoring msg %d inappropriate for server to receive", msgid);
audsrv_conn_skip( client->conn, msglen );
consumed += msglen;
break;
default:
INFO("ignoring unknown command %d len %d", msgid, msglen );
audsrv_conn_skip( client->conn, msglen );
consumed += msglen;
break;
}
exit:
return consumed;
}
static int audsrv_process_init( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: init version %d", version);
if ( version <= AUDSRV_MSG_Init_Version )
{
unsigned len, type, value;
unsigned sessionType;
bool isPrivate;
char name[AUDSRV_MAX_SESSION_NAME_LEN+1];
char *sessionName= 0;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for init arg 1 (sessionType)", AUDSRV_TYPE_U16, type );
goto exit;
}
value= audsrv_conn_get_u16( client->conn );
switch( value )
{
case AUDSRV_SESSION_Primary:
case AUDSRV_SESSION_Secondary:
case AUDSRV_SESSION_Effect:
case AUDSRV_SESSION_Capture:
sessionType= (AUDSRV_SESSIONTYPE)value;
break;
default:
WARNING("unknown sesson type: using secondary");
sessionType= AUDSRV_SESSION_Secondary;
break;
}
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for init arg 2 (isPrivate)", AUDSRV_TYPE_U16, type );
goto exit;
}
value= audsrv_conn_get_u16( client->conn );
isPrivate= (value ? true : false);
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_String )
{
ERROR("expecting type %d (string) not type %d for init arg 3 (sessionName)", AUDSRV_TYPE_String, type );
goto exit;
}
if ( len > AUDSRV_MAX_SESSION_NAME_LEN )
{
ERROR("sessionName too long (%d) for init", len );
goto exit;
}
if ( len )
{
audsrv_conn_get_string( client->conn, name );
sessionName= name;
}
INFO("sessionType %d sessionName (%s) isPrivate %d", sessionType, sessionName, isPrivate);
client->soc= AudioServerSocOpenClient( client->ctx->soc, sessionType, isPrivate, sessionName );
if ( !client->soc )
{
ERROR("AudioServerSocOpenClient failed: sessionType %u", sessionType);
goto exit;
}
client->sessionType= sessionType;
if ( sessionName )
{
int len= strlen(sessionName);
strncpy( client->sessionName, sessionName, len );
client->sessionName[len]= 0;
}
audsrv_distribute_session_event( client->ctx, AUDSRV_SESSIONEVENT_Added, client );
AudioServerSocSetFirstAudioFrameCallback( client->soc, audsrv_first_audio_callback, client );
AudioServerSocSetPTSErrorCallback( client->soc, audsrv_pts_error_callback, client );
AudioServerSocSetUnderflowCallback( client->soc, audsrv_underflow_callback, client );
}
exit:
return msglen;
}
static int audsrv_process_audioinfo( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: audioinfo version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_AudioInfo_Version )
{
AudSrvAudioInfo audioInfo;
unsigned len, type;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_String )
{
ERROR("expecting type %d (string) not type %d for audioinfo arg 1 (mimeType)", AUDSRV_TYPE_String, type );
goto exit;
}
if ( len > AUDSRV_MAX_MIME_LEN )
{
ERROR("mimetype too long (%d) for audioinfo", len );
goto exit;
}
audsrv_conn_get_string( client->conn, audioInfo.mimeType );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for audioinfo arg 2 (codec)", AUDSRV_TYPE_U16, type );
goto exit;
}
audioInfo.codec= audsrv_conn_get_u16( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for audioinfo arg 3 (pid)", AUDSRV_TYPE_U16, type );
goto exit;
}
audioInfo.pid= audsrv_conn_get_u16( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U32 )
{
ERROR("expecting type %d (U32) not type %d for audioinfo arg 4 (ptsOffset)", AUDSRV_TYPE_U32, type );
goto exit;
}
audioInfo.ptsOffset= audsrv_conn_get_u32( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U64 )
{
ERROR("expecting type %d (U64) not type %d for audioinfo arg 5 (dataId)", AUDSRV_TYPE_U64, type );
goto exit;
}
audioInfo.dataId= audsrv_conn_get_u64( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U64 )
{
ERROR("expecting type %d (U64) not type %d for audioinfo arg 6 (timingId)", AUDSRV_TYPE_U64, type );
goto exit;
}
audioInfo.timingId= audsrv_conn_get_u64( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U64 )
{
ERROR("expecting type %d (U64) not type %d for audioinfo arg 7 (privateId)", AUDSRV_TYPE_U64, type );
goto exit;
}
audioInfo.privateId= audsrv_conn_get_u64( client->conn );
TRACE1("audioInfo: codec %d pid 0x%X ptsOffset:%u mimeType(%s) timingId %llX dataId %llX privateId %llX",
audioInfo.codec, audioInfo.pid, audioInfo.ptsOffset, audioInfo.mimeType, audioInfo.timingId, audioInfo.dataId, audioInfo.privateId );
if ( !AudioServerSocSetAudioInfo( client->soc, &audioInfo ) )
{
ERROR("AudioServerSocSetAudioInfo failed");
}
}
}
else
{
ERROR("msg: audioInfo: no soc");
}
exit:
return msglen;
}
static int audsrv_process_basetime( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: basetime version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_Basetime_Version )
{
unsigned len, type;
unsigned long long basetime;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U64 )
{
ERROR("expecting type %d (U64) not type %d for basetime arg 1 (basetime)", AUDSRV_TYPE_U64, type );
goto exit;
}
basetime= audsrv_conn_get_u64( client->conn );
TRACE1("msg: basetime basetime %lld", basetime );
if ( !AudioServerSocBasetime( client->soc, basetime ) )
{
ERROR("AudioServerSocBasetime failed");
}
}
}
else
{
ERROR("msg: basetime: no soc");
}
exit:
return msglen;
}
static int audsrv_process_play( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: play version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_Play_Version )
{
if ( !AudioServerSocPlay( client->soc ) )
{
ERROR("AudioServerSocPlay failed");
}
}
}
else
{
ERROR("msg: play: no soc");
}
return msglen;
}
static int audsrv_process_stop( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: stop version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_Stop_Version )
{
if ( !AudioServerSocStop( client->soc ) )
{
ERROR("AudioServerSocStop failed");
}
}
}
else
{
ERROR("msg: stop: no soc");
}
return msglen;
}
static int audsrv_process_pause( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: pause version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_Pause_Version )
{
if ( !AudioServerSocPause( client->soc, true ) )
{
ERROR("AudioServerSocPause TRUE failed");
}
}
}
else
{
ERROR("msg: pause: no soc");
}
return msglen;
}
static int audsrv_process_unpause( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: unpause version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_UnPause_Version )
{
if ( !AudioServerSocPause( client->soc, false ) )
{
ERROR("AudioServerSocPause FALSE failed");
}
}
}
else
{
ERROR("msg: unpause: no soc");
}
return msglen;
}
static int audsrv_process_flush( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: flush version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_Flush_Version )
{
if ( !AudioServerSocFlush( client->soc ) )
{
ERROR("AudioServerSocFlush failed");
}
}
}
else
{
ERROR("msg: flush: no soc");
}
return msglen;
}
static int audsrv_process_audiosync( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: audiosync version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_AudioSync_Version )
{
unsigned len, type;
long long thenMicros, nowMicros, diff, diff45KHz;
unsigned long long stc;
unsigned adjustedStc;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U64 )
{
ERROR("expecting type %d (U64) not type %d for audiosync arg 1 (nowMicros)", AUDSRV_TYPE_U64, type );
goto exit;
}
thenMicros= (long long)audsrv_conn_get_u64( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U64 )
{
ERROR("expecting type %d (U64) not type %d for audiosync arg 2 (stc)", AUDSRV_TYPE_U64, type );
goto exit;
}
stc= audsrv_conn_get_u64( client->conn );
nowMicros= getCurrentTimeMicro();
diff= nowMicros-thenMicros;
diff45KHz= ((diff * 45000) / 1000000);
adjustedStc= stc + diff45KHz;
TRACE1("msg: audiosync stc %lld then %lld now %lld diff %lld diff45 %lld stcadj %u",
stc, thenMicros, nowMicros, diff, diff45KHz, adjustedStc);
if ( !AudioServerSocAudioSync( client->soc, adjustedStc ) )
{
ERROR("AudioServerSocAudioSync failed");
}
}
}
else
{
ERROR("msg: audiosync: no soc");
}
exit:
return msglen;
}
static int audsrv_process_audiodata( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE3("msg: audiodata version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_AudioData_Version )
{
unsigned len, type, datalen;
unsigned char *data;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_Buffer )
{
ERROR("expecting type %d (buffer) not type %d for audiodata arg 1 (data)", AUDSRV_TYPE_Buffer, type );
goto exit;
}
audsrv_conn_get_buffer( client->conn, len, &data, &datalen );
if ( data && datalen )
{
if ( !AudioServerSocAudioData( client->soc, data, datalen ) )
{
ERROR("AudioServerSocData failed");
}
len -= datalen;
}
if ( len )
{
audsrv_conn_get_buffer( client->conn, len, &data, &datalen );
if ( data && datalen )
{
if ( !AudioServerSocAudioData( client->soc, data, datalen ) )
{
ERROR("AudioServerSocData failed");
}
}
}
}
}
else
{
ERROR("msg: audiodata: no soc");
}
exit:
return msglen;
}
static int audsrv_process_audiodatahandle( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE3("msg: audiodatahandle version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_AudioDataHandle_Version )
{
unsigned len, type;
unsigned long long dataHandle;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U64 )
{
ERROR("expecting type %d (U64) not type %d for audiodatahandle arg 1 (dataHandle)", AUDSRV_TYPE_U64, type );
goto exit;
}
dataHandle= audsrv_conn_get_u64( client->conn );
if ( !AudioServerSocAudioDataHandle( client->soc, dataHandle ) )
{
ERROR("AudioServerSocDataHandle failed" );
}
}
}
else
{
ERROR("msg: audiodata: no soc");
}
exit:
return msglen;
}
static int audsrv_process_mute( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: mute version %d", version);
if ( version <= AUDSRV_MSG_Mute_Version )
{
unsigned len, type;
unsigned global;
char name[AUDSRV_MAX_SESSION_NAME_LEN+1];
char *sessionName= 0;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for audio mute arg 1 (global)", AUDSRV_TYPE_U16, type );
goto exit;
}
global= audsrv_conn_get_u16( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_String )
{
ERROR("expecting type %d (string) not type %d for audio mute arg 2 (sessionName)", AUDSRV_TYPE_String, type );
goto exit;
}
if ( len > AUDSRV_MAX_SESSION_NAME_LEN )
{
ERROR("sessionName too long (%d) for audio mute", len );
goto exit;
}
if ( len )
{
audsrv_conn_get_string( client->conn, name );
sessionName= name;
}
if ( global )
{
AudsrvContext *ctx= client->ctx;
if ( !AudioServerSocGlobalMute( ctx->soc, true ) )
{
ERROR("AudioServerSocMute TRUE failed");
}
}
else
{
if ( sessionName )
{
TRACE1("msg: mute sessionName (%s)", sessionName);
AudsrvContext *ctx= client->ctx;
pthread_mutex_lock( &ctx->mutex );
for( std::vector<AudsrvClient*>::iterator it= ctx->clients.begin();
it != ctx->clients.end();
++it )
{
AudsrvClient *clientIter= (*it);
pthread_mutex_lock( &clientIter->mutex );
if ( !strcmp( sessionName, clientIter->sessionName ) )
{
if ( clientIter->soc )
{
if ( !AudioServerSocMute( clientIter->soc, true ) )
{
ERROR("AudioServerSocMute TRUE failed");
}
}
else
{
ERROR("msg: mute: no soc");
}
}
pthread_mutex_unlock( &clientIter->mutex );
}
pthread_mutex_unlock( &ctx->mutex );
}
else
{
if ( client->soc )
{
if ( !AudioServerSocMute( client->soc, true ) )
{
ERROR("AudioServerSocMute TRUE failed");
}
}
else
{
ERROR("msg: mute: no soc");
}
}
}
}
exit:
return msglen;
}
static int audsrv_process_unmute( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: unmute version %d", version);
if ( version <= AUDSRV_MSG_UnMute_Version )
{
unsigned len, type;
unsigned global;
char name[AUDSRV_MAX_SESSION_NAME_LEN+1];
char *sessionName= 0;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for audio unmute arg 1 (global)", AUDSRV_TYPE_U16, type );
goto exit;
}
global= audsrv_conn_get_u16( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_String )
{
ERROR("expecting type %d (string) not type %d for audio unmute arg 2 (sessionName)", AUDSRV_TYPE_String, type );
goto exit;
}
if ( len > AUDSRV_MAX_SESSION_NAME_LEN )
{
ERROR("sessionName too long (%d) for audio unmute", len );
goto exit;
}
if ( len )
{
audsrv_conn_get_string( client->conn, name );
sessionName= name;
}
if ( global )
{
AudsrvContext *ctx= client->ctx;
if ( !AudioServerSocGlobalMute( ctx->soc, false ) )
{
ERROR("AudioServerSocGlobalMute FALSE failed");
}
}
else
{
if ( sessionName )
{
TRACE1("msg: unmute sessionName (%s)", sessionName);
AudsrvContext *ctx= client->ctx;
pthread_mutex_lock( &ctx->mutex );
for( std::vector<AudsrvClient*>::iterator it= ctx->clients.begin();
it != ctx->clients.end();
++it )
{
AudsrvClient *clientIter= (*it);
pthread_mutex_lock( &clientIter->mutex );
if ( !strcmp( sessionName, clientIter->sessionName ) )
{
if ( clientIter->soc )
{
if ( !AudioServerSocMute( clientIter->soc, false ) )
{
ERROR("AudioServerSocMute FALSE failed");
}
}
else
{
ERROR("msg: unmute: no soc");
}
}
pthread_mutex_unlock( &clientIter->mutex );
}
pthread_mutex_unlock( &ctx->mutex );
}
else
{
if ( client->soc )
{
if ( !AudioServerSocMute( client->soc, false ) )
{
ERROR("AudioServerSocMute FALSE failed");
}
}
else
{
ERROR("msg: unmute: no soc");
}
}
}
}
exit:
return msglen;
}
static int audsrv_process_volume( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: volume version %d", version);
if ( version <= AUDSRV_MSG_Volume_Version )
{
unsigned len, type;
unsigned numerator, denominator;
float volume= 1.0;
unsigned global;
char name[AUDSRV_MAX_SESSION_NAME_LEN+1];
char *sessionName= 0;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U32 )
{
ERROR("expecting type %d (U32) not type %d for volume arg 1 (numerator)", AUDSRV_TYPE_U32, type );
goto exit;
}
numerator= audsrv_conn_get_u32( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U32 )
{
ERROR("expecting type %d (U32) not type %d for volume arg 2 (denominator)", AUDSRV_TYPE_U32, type );
goto exit;
}
denominator= audsrv_conn_get_u32( client->conn );
if ( denominator == 0 )
{
ERROR("volume denominator is 0 - setting volume to 1.0");
}
else
{
volume= (float)numerator/(float)denominator;
TRACE1("msg: volume (%u/%u) = %f", numerator, denominator, volume );
}
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for audio volume arg 3 (global)", AUDSRV_TYPE_U16, type );
goto exit;
}
global= audsrv_conn_get_u16( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_String )
{
ERROR("expecting type %d (string) not type %d for audio volume arg 4 (sessionName)", AUDSRV_TYPE_String, type );
goto exit;
}
if ( len > AUDSRV_MAX_SESSION_NAME_LEN )
{
ERROR("sessionName too long (%d) for audio volume", len );
goto exit;
}
if ( len )
{
audsrv_conn_get_string( client->conn, name );
sessionName= name;
}
if ( global )
{
AudsrvContext *ctx= client->ctx;
AudioServerSocGlobalVolume( ctx->soc, volume );
}
else
{
if ( sessionName )
{
TRACE1("msg: volume sessionName (%s)", sessionName);
AudsrvContext *ctx= client->ctx;
pthread_mutex_lock( &ctx->mutex );
for( std::vector<AudsrvClient*>::iterator it= ctx->clients.begin();
it != ctx->clients.end();
++it )
{
AudsrvClient *clientIter= (*it);
pthread_mutex_lock( &clientIter->mutex );
if ( !strcmp( sessionName, clientIter->sessionName ) )
{
if ( clientIter->soc )
{
if ( !AudioServerSocVolume( clientIter->soc, volume ) )
{
ERROR("AudioServerSocVolume failed");
}
}
else
{
ERROR("msg: volume: no soc");
}
}
pthread_mutex_unlock( &clientIter->mutex );
}
pthread_mutex_unlock( &ctx->mutex );
}
else
{
if ( client->soc )
{
if ( !AudioServerSocVolume( client->soc, volume ) )
{
ERROR("AudioServerSocVolume failed");
}
}
else
{
ERROR("msg: volume: no soc");
}
}
}
}
exit:
return msglen;
}
static int audsrv_process_enable_session_event( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: enableSessionEvent version %d", version);
if ( version <= AUDSRV_MSG_EnableSessionEvent_Version )
{
if ( client )
{
AudsrvContext *ctx= client->ctx;
if ( ctx )
{
pthread_mutex_lock( &ctx->mutex );
ctx->clientsSessionEvent.push_back( client );
pthread_mutex_unlock( &ctx->mutex );
}
}
}
return msglen;
}
static int audsrv_process_disable_session_event( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: disableSessionEvent version %d", version);
if ( version <= AUDSRV_MSG_DisableSessionEvent_Version )
{
if ( client )
{
AudsrvContext *ctx= client->ctx;
if ( ctx )
{
pthread_mutex_lock( &ctx->mutex );
for( std::vector<AudsrvClient*>::iterator it= ctx->clientsSessionEvent.begin();
it != ctx->clientsSessionEvent.end();
++it )
{
if ( client == (*it) )
{
ctx->clientsSessionEvent.erase( it );
break;
}
}
pthread_mutex_unlock( &ctx->mutex );
}
}
}
return msglen;
}
static int audsrv_process_enableeos( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: enableeos version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_EnableEOS_Version )
{
AudioServerSocEnableEOSDetection( client->soc, audsrv_eos_callback, client );
}
}
else
{
ERROR("msg: enableeos: no soc");
}
return msglen;
}
static int audsrv_process_disableeos( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: disableeos version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_DisableEOS_Version )
{
AudioServerSocDisableEOSDetection( client->soc );
}
}
else
{
ERROR("msg: disableeos: no soc");
}
return msglen;
}
static int audsrv_process_startcapture( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: startcapture version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_StartCapture_Version )
{
unsigned len, type, value;
char name[AUDSRV_MAX_SESSION_NAME_LEN+1];
char *sessionName= 0;
AudSrvCaptureParameters captureParams;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for audio start capture arg 1 (numChannels)", AUDSRV_TYPE_U16, type );
goto exit;
}
captureParams.numChannels = audsrv_conn_get_u16( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for audio start capture arg 3 (bitsPerSample)", AUDSRV_TYPE_U16, type );
goto exit;
}
captureParams.bitsPerSample = audsrv_conn_get_u16( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U16 )
{
ERROR("expecting type %d (U16) not type %d for audio start capture arg 3 (threshold)", AUDSRV_TYPE_U16, type );
goto exit;
}
captureParams.threshold = audsrv_conn_get_u16( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U32 )
{
ERROR("expecting type %d (U32) not type %d for audio start capture arg 1 (sampleRate)", AUDSRV_TYPE_U32, type );
goto exit;
}
captureParams.sampleRate = audsrv_conn_get_u32( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U32 )
{
ERROR("expecting type %d (U32) not type %d for audio start capture arg 1 (outputDelay)", AUDSRV_TYPE_U32, type );
goto exit;
}
captureParams.outputDelay = audsrv_conn_get_u32( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U32 )
{
ERROR("expecting type %d (U32) not type %d for audio start capture arg 1 (fifoSize)", AUDSRV_TYPE_U32, type );
goto exit;
}
captureParams.fifoSize = audsrv_conn_get_u32( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_String )
{
ERROR("expecting type %d (string) not type %d for init arg 1 (sessionName)", AUDSRV_TYPE_String, type );
goto exit;
}
if ( len > AUDSRV_MAX_SESSION_NAME_LEN )
{
ERROR("sessionName too long (%d) for init", len );
goto exit;
}
if ( len )
{
audsrv_conn_get_string( client->conn, name );
sessionName= name;
}
INFO("capture sessionName (%s)", sessionName);
AudioServerSocSetCaptureCallback( client->soc, sessionName, audsrv_capture_callback, &captureParams, client );
}
}
else
{
ERROR("msg: startcapture: no soc");
}
exit:
return msglen;
}
static int audsrv_process_stopcapture( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: stopcapture version %d", version);
if ( client->soc )
{
if ( version <= AUDSRV_MSG_StartCapture_Version )
{
AudioServerSocSetCaptureCallback( client->soc, NULL, NULL, NULL, 0 );
audsrv_send_capture_done( client );
}
}
else
{
ERROR("msg: stopcapture: no soc");
}
return msglen;
}
static int audsrv_process_enumsessions( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: enumsessions version %d", version);
if ( version <= AUDSRV_MSG_EnumSessions_Version )
{
unsigned long long token;
int sessionCount= 0;
int infoSize= 0;
int namelen;
const char *name;
unsigned char *enumInfo= 0;
unsigned len, type;
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U64 )
{
ERROR("expecting type %d (U64) not type %d for enum sessions arg 1 (token)", AUDSRV_TYPE_U64, type );
goto exit;
}
token= audsrv_conn_get_u64( client->conn );
AudsrvContext *ctx= client->ctx;
pthread_mutex_lock( &ctx->mutex );
sessionCount= 0;
for( std::vector<AudsrvClient*>::iterator it= ctx->clients.begin();
it != ctx->clients.end();
++it )
{
AudsrvClient *clientIter= (*it);
pthread_mutex_lock( &clientIter->mutex );
if ( clientIter->sessionType != AUDSRV_SESSION_Observer )
{
++sessionCount;
infoSize += (AUDSRV_MSG_TYPE_HDR_LEN+AUDSRV_MSG_U32_LEN); //client pid
infoSize += (AUDSRV_MSG_TYPE_HDR_LEN+AUDSRV_MSG_U16_LEN); //client session type
namelen= strlen(clientIter->sessionName);
name= namelen ? clientIter->sessionName : "no-name";
infoSize += AUDSRV_MSG_TYPE_HDR_LEN+AUDSRV_MSG_STRING_LEN(name);
}
pthread_mutex_unlock( &clientIter->mutex );
}
enumInfo= (unsigned char *)malloc( infoSize );
if ( enumInfo )
{
unsigned char *p= enumInfo;
for( std::vector<AudsrvClient*>::iterator it= ctx->clients.begin();
it != ctx->clients.end();
++it )
{
AudsrvClient *clientIter= (*it);
pthread_mutex_lock( &clientIter->mutex );
if ( clientIter->sessionType != AUDSRV_SESSION_Observer )
{
TRACE1("client pid %d type %d name(%s)", clientIter->ucred.pid, clientIter->sessionType, name );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U32_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, clientIter->ucred.pid );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, clientIter->sessionType );
namelen= strlen(clientIter->sessionName);
name= namelen ? clientIter->sessionName : "no-name";
p += audsrv_conn_put_u32( p, AUDSRV_MSG_STRING_LEN(name) );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_String );
p += audsrv_conn_put_string( p, name );
}
pthread_mutex_unlock( &clientIter->mutex );
}
}
else
{
ERROR("No memory for enum session response");
}
audsrv_send_enum_session_results( client, token, sessionCount, enumInfo, infoSize );
if ( enumInfo )
{
free( enumInfo );
}
pthread_mutex_unlock( &ctx->mutex );
}
exit:
return msglen;
}
static int audsrv_process_getstatus( AudsrvClient *client, unsigned msglen, unsigned version )
{
TRACE1("msg: getstatus version %d", version);
if ( version <= AUDSRV_MSG_GetStatus_Version )
{
unsigned long long token;
unsigned len, type;
char name[AUDSRV_MAX_SESSION_NAME_LEN+1];
char *sessionName= 0;
bool haveStatus= false;
AudSrvSessionStatus status, *pStatus= 0;
AudsrvContext *ctx= client->ctx;
pStatus= &status;
memset( &status, 0, sizeof(status) );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_U64 )
{
ERROR("expecting type %d (U64) not type %d for getstatus arg 1 (token)", AUDSRV_TYPE_U64, type );
goto exit;
}
token= audsrv_conn_get_u64( client->conn );
len= audsrv_conn_get_u32( client->conn );
type= audsrv_conn_get_u32( client->conn );
if ( type != AUDSRV_TYPE_String )
{
ERROR("expecting type %d (string) not type %d for getstatus arg 2 (sessionName)", AUDSRV_TYPE_String, type );
goto exit;
}
if ( len > AUDSRV_MAX_SESSION_NAME_LEN )
{
ERROR("sessionName too long (%d) for audio getstatus", len );
goto exit;
}
if ( len )
{
audsrv_conn_get_string( client->conn, name );
sessionName= name;
}
if ( sessionName )
{
TRACE1("msg: getstatus sessionName (%s)", sessionName);
pthread_mutex_lock( &ctx->mutex );
for( std::vector<AudsrvClient*>::iterator it= ctx->clients.begin();
it != ctx->clients.end();
++it )
{
AudsrvClient *clientIter= (*it);
pthread_mutex_lock( &clientIter->mutex );
if ( !strcmp( sessionName, clientIter->sessionName ) )
{
if ( clientIter->soc )
{
if ( AudioServerSocGetStatus( ctx->soc, clientIter->soc, &status ) )
{
status.ready= true;
}
haveStatus= true;
}
else
{
ERROR("msg: getstatus: no soc");
}
}
pthread_mutex_unlock( &clientIter->mutex );
}
pthread_mutex_unlock( &ctx->mutex );
}
else
{
if ( client->soc )
{
if ( AudioServerSocGetStatus( ctx->soc, client->soc, &status ) )
{
status.ready= true;
}
haveStatus= true;
}
else
{
if ( !AudioServerSocGetStatus( ctx->soc, 0, &status ) )
{
ERROR("msg: getstatus: failed to get global status");
}
}
}
if ( haveStatus )
{
if ( sessionName )
{
strcpy( status.sessionName, sessionName );
}
else
{
strcpy( status.sessionName, client->sessionName );
}
}
audsrv_send_getstatus_results( client, token, pStatus );
}
exit:
return msglen;
}
static void audsrv_eos_callback( void *userData )
{
AudsrvClient *client= (AudsrvClient*)userData;
if ( client )
{
TRACE1("audsrv_eos_callback: client %p", client);
audsrv_send_eos_detected( client );
}
}
static void audsrv_first_audio_callback( void *userData )
{
AudsrvClient *client= (AudsrvClient*)userData;
if ( client )
{
TRACE1("audsrv_first_audio_callback: client %p", client);
audsrv_send_first_audio( client );
}
}
static void audsrv_pts_error_callback( void *userData, unsigned count )
{
AudsrvClient *client= (AudsrvClient*)userData;
if ( client )
{
TRACE1("audsrv_pts_error_callback: client %p count %u", client, count);
audsrv_send_pts_error( client, count );
}
}
static void audsrv_underflow_callback( void *userData, unsigned count, unsigned bufferedBytes, unsigned queuedFrames )
{
AudsrvClient *client= (AudsrvClient*)userData;
if ( client )
{
TRACE1("audsrv_underflow_callback: client %p count %u bufferedBytes %u queuedFrames %u",
client, count, bufferedBytes, queuedFrames);
audsrv_send_underflow( client, count, bufferedBytes, queuedFrames );
}
}
static void audsrv_capture_callback( void *userData, AudSrvCaptureParameters *params, unsigned char *data, int datalen )
{
AudsrvClient *client= (AudsrvClient*)userData;
if ( client )
{
TRACE1("audsrv_capture_callback: client %p data %p datalen %u", client, data, datalen);
if ( params->version != client->captureParams.version )
{
client->captureParams= *params;
audsrv_send_capture_params( client );
}
while( datalen > 0 )
{
int sendlen= datalen;
if (sendlen > AUDSRV_MAX_CAPTURE_DATA_SIZE)
{
sendlen= AUDSRV_MAX_CAPTURE_DATA_SIZE;
}
audsrv_send_capture_data( client, data, sendlen );
data += sendlen;
datalen -= sendlen;
}
}
}
static void audsrv_distribute_session_event( AudsrvContext *ctx, int event, AudsrvClient *clientSubject )
{
TRACE1("audsrv_distribute_session_event: event %d clientSubject %p", clientSubject );
if ( ctx )
{
pthread_mutex_lock( &ctx->mutex );
for( std::vector<AudsrvClient*>::iterator it= ctx->clientsSessionEvent.begin();
it != ctx->clientsSessionEvent.end();
++it )
{
AudsrvClient *clientIter= (*it);
audsrv_send_session_event( clientIter, event, clientSubject );
}
pthread_mutex_unlock( &ctx->mutex );
}
}
static void audsrv_send_session_event( AudsrvClient *client, int event, AudsrvClient *clientSubject )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen, namelen;
int sendLen;
const char *name;
TRACE1("audsrv_send_session_event: client %p", client );
if ( client )
{
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN+AUDSRV_MSG_U16_LEN); //event
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN+AUDSRV_MSG_U32_LEN); //client pid
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN+AUDSRV_MSG_U16_LEN); //client session type
namelen= strlen(clientSubject->sessionName);
name= namelen ? clientSubject->sessionName : "no-name";
paramLen += AUDSRV_MSG_TYPE_HDR_LEN+AUDSRV_MSG_STRING_LEN(name);
msgLen= AUDSRV_MSG_HDR_LEN + paramLen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("session event msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_SessionEvent );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_SessionEvent_Version );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u32( p, event );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U32_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, clientSubject->ucred.pid );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, clientSubject->sessionType );
namelen= strlen(clientSubject->sessionName);
name= namelen ? clientSubject->sessionName : "no-name";
p += audsrv_conn_put_u32( p, AUDSRV_MSG_STRING_LEN(name) );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_String );
p += audsrv_conn_put_string( p, name );
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, NULL, 0 );
result= (sendLen == msgLen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_session_event: client %p result %d", client, result );
}
static bool audsrv_send_eos_detected( AudsrvClient *client )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen;
int sendLen;
TRACE1("audsrv_send_eos_detected: client %p", client );
if ( client )
{
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
msgLen= AUDSRV_MSG_HDR_LEN + paramLen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("eos detected msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_EOSDetected );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_EOSDetected_Version );
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, NULL, 0 );
result= (sendLen == msgLen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_eos_detected: client %p result %d", client, result );
return result;
}
static bool audsrv_send_first_audio( AudsrvClient *client )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen;
int sendLen;
TRACE1("audsrv_send_first_audio: client %p", client );
if ( client )
{
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
msgLen= AUDSRV_MSG_HDR_LEN + paramLen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("first audio msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_FirstAudio );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_FirstAudio_Version );
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, NULL, 0 );
result= (sendLen == msgLen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_first_audio: client %p result %d", client, result );
return result;
}
static bool audsrv_send_pts_error( AudsrvClient *client, unsigned count )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen;
int sendLen;
TRACE1("audsrv_send_pts_error: client %p count %u", client, count );
if ( client )
{
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // count
msgLen= AUDSRV_MSG_HDR_LEN + paramLen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("pts error msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_PtsError );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_PtsError_Version );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U32_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, count );
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, NULL, 0 );
result= (sendLen == msgLen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_pts_error: client %p result %d", client, result );
return result;
}
static bool audsrv_send_underflow( AudsrvClient *client, unsigned count, unsigned bufferedBytes, unsigned queuedFrames )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen;
int sendLen;
TRACE1("audsrv_send_underflow: client %p count %u bufferedBytes %u queuedFrames %u", client, count, bufferedBytes, queuedFrames );
if ( client )
{
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // count
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // bufferedBytes
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // queuedFrames
msgLen= AUDSRV_MSG_HDR_LEN + paramLen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("underflow msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_Underflow );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_Underflow_Version );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U32_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, count );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U32_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, bufferedBytes );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U32_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, queuedFrames );
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, NULL, 0 );
result= (sendLen == msgLen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_underflow: client %p result %d", client, result );
return result;
}
static bool audsrv_send_capture_params( AudsrvClient *client )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen;
int sendLen;
TRACE1("audsrv_send_capture_params: client %p version %u numchan %u bits %u rate %u",
client, client->captureParams.version, client->captureParams.numChannels,
client->captureParams.bitsPerSample, client->captureParams.sampleRate );
if ( client )
{
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // version
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // numChannels
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // bitsPerSample
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // sampleRate
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // outputDelay
msgLen= AUDSRV_MSG_HDR_LEN + paramLen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("captureParameters msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_CaptureParameters );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_CaptureParameters_Version );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U32_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, client->captureParams.version );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, client->captureParams.numChannels );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, client->captureParams.bitsPerSample );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U32_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, client->captureParams.sampleRate );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U32_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, client->captureParams.outputDelay );
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, NULL, 0 );
result= (sendLen == msgLen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_capture_params: client %p result %d", client, result );
return result;
}
static bool audsrv_send_capture_data( AudsrvClient *client, unsigned char *data, int datalen )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen;
int sendLen;
TRACE1("audsrv_send_capture_data: client %p data %p len %d", client, data, datalen );
if ( client )
{
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + datalen); // buffer
// Don't include payload data length since it doesn't occupy space
// in our work buffer
msgLen= AUDSRV_MSG_HDR_LEN + paramLen - datalen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("captureData msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_CaptureData );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_CaptureData_Version );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_BUFFER_LEN(datalen) );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_Buffer );
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, data, datalen );
result= (sendLen == msgLen+datalen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_capture_data: client %p result %d", client, result );
return result;
}
static bool audsrv_send_capture_done( AudsrvClient *client )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen;
int sendLen;
TRACE1("audsrv_send_capture_done: client %p", client );
if ( client )
{
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
msgLen= AUDSRV_MSG_HDR_LEN + paramLen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("capture done msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_CaptureDone );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_CaptureDone_Version );
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, NULL, 0 );
result= (sendLen == msgLen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_capture_done: client %p result %d", client, result );
return result;
}
static bool audsrv_send_enum_session_results( AudsrvClient *client, unsigned long long token, int sessionCount, unsigned char *data, int datalen )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen;
int sendLen;
int enumResult;
TRACE1("audsrv_send_enum_session_results: client %p token:%llx data %p len %d", client, token, data, datalen );
if ( client )
{
enumResult= (data && datalen) ? 0 : 1;
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U64_LEN); // token
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // enumResult
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // sessionCount
paramLen += datalen; // parameter set comprising enum results
// Don't include payload data length since it doesn't occupy space
// in our work buffer
msgLen= AUDSRV_MSG_HDR_LEN + paramLen - datalen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("enum session results msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_EnumSessionsResults );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_EnumSessionsResults_Version );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U64_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U64 );
p += audsrv_conn_put_u64( p, token );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, enumResult );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, sessionCount );
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, data, datalen );
result= (sendLen == msgLen+datalen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_enum_session_results: client %p result %d", client, result );
return result;
}
static bool audsrv_send_getstatus_results( AudsrvClient *client, unsigned long long token, AudSrvSessionStatus *status )
{
bool result= false;
unsigned char *p;
int msgLen, paramLen, nameLen= 0;
int sendLen;
int getStatusResult;
TRACE1("audsrv_send_getstatus_results: client %p", client );
if ( client )
{
getStatusResult= (status->ready ? 0 : 1);
pthread_mutex_lock( &client->mutex );
p= client->conn->sendbuff;
paramLen= 0;
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U64_LEN); // token
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // getStatusResult
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // global muted
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // global volume num
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // global volume denom
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // ready
if ( getStatusResult == 0 )
{
nameLen= AUDSRV_MSG_STRING_LEN(status->sessionName);
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // playing
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // paused
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U16_LEN); // muted
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // volume num
paramLen += (AUDSRV_MSG_TYPE_HDR_LEN + AUDSRV_MSG_U32_LEN); // volume denom
paramLen += AUDSRV_MSG_TYPE_HDR_LEN+nameLen;
}
msgLen= AUDSRV_MSG_HDR_LEN + paramLen;
if ( msgLen > AUDSRV_MAX_MSG )
{
ERROR("getstatus results msg too large");
pthread_mutex_unlock( &client->mutex );
goto exit;
}
p += audsrv_conn_put_u32( p, paramLen );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_GetStatusResults );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_GetStatusResults_Version );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U64_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U64 );
p += audsrv_conn_put_u64( p, token );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, getStatusResult );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, status->globalMuted );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, status->globalVolume*LEVEL_DENOMINATOR );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, LEVEL_DENOMINATOR );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, status->ready );
if ( status )
{
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, status->playing );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, status->paused );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U16 );
p += audsrv_conn_put_u16( p, status->muted );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, status->volume*LEVEL_DENOMINATOR );
p += audsrv_conn_put_u32( p, AUDSRV_MSG_U16_LEN );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_U32 );
p += audsrv_conn_put_u32( p, LEVEL_DENOMINATOR );
p += audsrv_conn_put_u32( p, nameLen );
p += audsrv_conn_put_u32( p, AUDSRV_TYPE_String );
if ( nameLen )
{
p += audsrv_conn_put_string( p, status->sessionName );
}
}
sendLen= audsrv_conn_send( client->conn, client->conn->sendbuff, msgLen, NULL, 0 );
result= (sendLen == msgLen);
pthread_mutex_unlock( &client->mutex );
}
exit:
TRACE1("audsrv_send_getstatus_results: client %p result %d", client, result );
return result;
}
/** @} */
/** @} */
| 29.390039 | 150 | 0.589455 | [
"vector"
] |
69de799dc102c839958521258f84ab387c829398 | 5,381 | cpp | C++ | android/android/os/Bundle.cpp | djangw/androidpp | 7d78de900873184bf7bed231fabb3f4280c4edfd | [
"BSD-3-Clause"
] | null | null | null | android/android/os/Bundle.cpp | djangw/androidpp | 7d78de900873184bf7bed231fabb3f4280c4edfd | [
"BSD-3-Clause"
] | null | null | null | android/android/os/Bundle.cpp | djangw/androidpp | 7d78de900873184bf7bed231fabb3f4280c4edfd | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2016 NAVER Corp. 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 ``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 "Bundle.h"
#include <android/os/BundlePrivate.h>
#include <android/os/ParcelablePrivate.h>
namespace android {
namespace os {
Bundle::Bundle()
: m_private(std::make_shared<BundlePrivate>())
{
}
Bundle::Bundle(const Bundle& o)
: m_private(o.m_private)
{
}
Bundle::Bundle(Bundle&& o)
: m_private(std::move(o.m_private))
{
}
Bundle& Bundle::operator=(const Bundle& other)
{
m_private = other.m_private;
return *this;
}
Bundle& Bundle::operator=(Bundle&& other)
{
m_private = std::move(other.m_private);
return *this;
}
int8_t Bundle::getByte(StringRef key)
{
return m_private->getValue(key).b;
}
int8_t Bundle::getByte(StringRef key, int8_t defaultValue)
{
if (!m_private->findKey(key))
return defaultValue;
return getByte(key);
}
wchar_t Bundle::getChar(StringRef key)
{
return m_private->getValue(key).c;
}
wchar_t Bundle::getChar(StringRef key, wchar_t defaultValue)
{
if (!m_private->findKey(key))
return defaultValue;
return getChar(key);
}
CharSequence Bundle::getCharSequence(StringRef key)
{
return m_private->getCharSequence(key);
}
CharSequence Bundle::getCharSequence(StringRef key, const CharSequence& defaultValue)
{
if (!m_private->findKey(key))
return defaultValue;
return getCharSequence(key);
}
float Bundle::getFloat(StringRef key)
{
return m_private->getValue(key).f;
}
float Bundle::getFloat(StringRef key, float defaultValue)
{
if (!m_private->findKey(key))
return defaultValue;
return getFloat(key);
}
int32_t Bundle::getInt(StringRef key)
{
return m_private->getValue(key).i;
}
int32_t Bundle::getInt(StringRef key, int32_t defaultValue)
{
if (!m_private->findKey(key))
return defaultValue;
return getInt(key);
}
int16_t Bundle::getShort(StringRef key)
{
return m_private->getValue(key).s;
}
int16_t Bundle::getShort(StringRef key, short defaultValue)
{
if (!m_private->findKey(key))
return defaultValue;
return getShort(key);
}
void Bundle::putByte(StringRef key, int8_t value)
{
m_private->putValue(key, BundleValue(value));
}
void Bundle::putChar(StringRef key, wchar_t value)
{
m_private->putValue(key, BundleValue(value));
}
void Bundle::putCharSequence(StringRef key, const CharSequence& value)
{
m_private->putCharSequence(key, value);
}
void Bundle::putFloat(StringRef key, float value)
{
m_private->putValue(key, BundleValue(value));
}
void Bundle::putInt(StringRef key, int32_t value)
{
m_private->putValue(key, BundleValue(value));
}
void Bundle::putShort(StringRef key, int16_t value)
{
m_private->putValue(key, BundleValue(value));
}
std::shared_ptr<Parcelable> Bundle::getParcelable(StringRef key)
{
return m_private->getParcelable(key);
}
void Bundle::putParcelable(StringRef key, std::passed_ptr<Parcelable> value)
{
m_private->putParcelable(key, value);
}
void Bundle::readFromParcel(Parcel& parcel)
{
m_private->readFromParcel(parcel);
}
void Bundle::clear()
{
m_private->clear();
}
void Bundle::remove(StringRef key)
{
m_private->remove(key);
}
bool Bundle::containsKey(StringRef key)
{
return m_private->findKey(key);
}
class BundleCreator final : public ParcelableCreator {
public:
std::shared_ptr<Parcelable> createFromParcel(Parcel& source) override
{
auto result = std::make_shared<Bundle>();
result->readFromParcel(source);
return result;
}
std::vector<std::shared_ptr<Parcelable>> newArray(int32_t size) override
{
return {};
}
BundleCreator()
: ParcelableCreator(this, L"android.os", L"Bundle.CREATOR")
{
}
};
const std::lazy_ptr<Parcelable::Creator> Bundle::CREATOR([] { return new BundleCreator; });
int32_t Bundle::describeContents()
{
return 0;
}
void Bundle::writeToParcel(Parcel& dest, int32_t flags) const
{
ParcelableCreator::writeToParcel(*this, dest);
m_private->writeToParcel(dest, flags);
}
} // namespace os
} // namespace android
| 22.995726 | 91 | 0.715295 | [
"vector"
] |
69df8175b5d87060dc4777c8dfb2f3eaa9a9354a | 15,905 | cc | C++ | test/unstable_log_test.cc | Myicefrog/libraft | 30946643e59a97b83396b0a632219081cc3df565 | [
"MIT"
] | 1 | 2021-09-06T11:59:41.000Z | 2021-09-06T11:59:41.000Z | test/unstable_log_test.cc | Myicefrog/libraft | 30946643e59a97b83396b0a632219081cc3df565 | [
"MIT"
] | null | null | null | test/unstable_log_test.cc | Myicefrog/libraft | 30946643e59a97b83396b0a632219081cc3df565 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include "libraft.h"
#include "util.h"
#include "unstable_log.h"
#include "default_logger.h"
TEST(unstableLogTests, TestUnstableMaybeFirstIndex) {
struct tmp {
EntryVec entries;
uint64_t offset;
Snapshot *snapshot;
bool wok;
uint64_t windex;
tmp(EntryVec ens, uint64_t off, Snapshot *snap, bool w, uint64_t index)
: entries(ens), offset(off), snapshot(snap), wok(w), windex(index) {
}
};
vector<tmp> tests;
// no snapshot
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
tmp t(entries, 5, NULL, false, 0);
tests.push_back(t);
}
{
EntryVec entries;
tmp t(entries, 0, NULL, false, 0);
tests.push_back(t);
}
// has snapshot
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, true, 5);
tests.push_back(t);
}
{
EntryVec entries;
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, true, 5);
tests.push_back(t);
}
int i;
for (i = 0;i < tests.size(); ++i) {
unstableLog unstable;
unstable.entries_ = tests[i].entries;
unstable.offset_ = tests[i].offset;
unstable.snapshot_ = tests[i].snapshot;
unstable.logger_ = NULL;
uint64_t index;
bool ok = unstable.maybeFirstIndex(&index);
EXPECT_EQ(tests[i].wok, ok);
}
}
TEST(unstableLogTests, TestMaybeLastIndex) {
struct tmp {
EntryVec entries;
uint64_t offset;
Snapshot *snapshot;
bool wok;
uint64_t windex;
tmp(EntryVec ens, uint64_t off, Snapshot *snap, bool w, uint64_t index)
: entries(ens), offset(off), snapshot(snap), wok(w), windex(index) {
}
};
vector<tmp> tests;
// last in entries
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
tmp t(entries, 5, NULL, true, 5);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, true, 5);
tests.push_back(t);
}
// last in entries
{
EntryVec entries;
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, true, 4);
tests.push_back(t);
}
// empty unstable
{
EntryVec entries;
tmp t(entries, 0, NULL, false, 0);
tests.push_back(t);
}
int i;
for (i = 0;i < tests.size(); ++i) {
unstableLog unstable;
unstable.entries_ = tests[i].entries;
unstable.offset_ = tests[i].offset;
unstable.snapshot_ = tests[i].snapshot;
unstable.logger_ = NULL;
uint64_t index;
bool ok = unstable.maybeLastIndex(&index);
EXPECT_EQ(tests[i].wok, ok);
}
}
TEST(unstableLogTests, TestUnstableMaybeTerm) {
struct tmp {
EntryVec entries;
uint64_t offset;
Snapshot *snapshot;
uint64_t index;
bool wok;
uint64_t wterm;
tmp(EntryVec ens, uint64_t off, Snapshot *snap, uint64_t i, bool w, uint64_t t)
: entries(ens), offset(off), snapshot(snap), index(i), wok(w), wterm(t) {
}
};
vector<tmp> tests;
// term from entries
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
tmp t(entries, 5, NULL, 5, true, 1);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
tmp t(entries, 5, NULL, 6, false, 0);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
tmp t(entries, 5, NULL, 4, false, 0);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, 5, true, 1);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, 6, false, 0);
tests.push_back(t);
}
// term from snapshot
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, 4, true, 1);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, 3, false, 0);
tests.push_back(t);
}
{
EntryVec entries;
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, 5, false, 0);
tests.push_back(t);
}
{
EntryVec entries;
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
tmp t(entries, 5, snapshot, 4, true, 1);
tests.push_back(t);
}
{
EntryVec entries;
tmp t(entries, 0, NULL, 5, false, 0);
tests.push_back(t);
}
int i;
for (i = 0;i < tests.size(); ++i) {
unstableLog unstable;
unstable.entries_ = tests[i].entries;
unstable.offset_ = tests[i].offset;
unstable.snapshot_ = tests[i].snapshot;
unstable.logger_ = NULL;
uint64_t term;
bool ok = unstable.maybeTerm(tests[i].index, &term);
EXPECT_EQ(tests[i].wok, ok) << "i: " << i << ", index: " << tests[i].index;
EXPECT_EQ(tests[i].wterm, term);
}
}
TEST(unstableLogTests, TestUnstableRestore) {
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
unstableLog unstable;
unstable.entries_ = entries;
unstable.offset_ = 5;
unstable.snapshot_ = snapshot;
unstable.logger_ = NULL;
Snapshot s;
{
SnapshotMetadata *meta = s.mutable_metadata();
meta->set_index(6);
meta->set_term(2);
unstable.restore(s);
}
EXPECT_EQ(unstable.offset_, s.metadata().index() + 1);
EXPECT_EQ(unstable.entries_.size(), 0);
EXPECT_EQ(true, isDeepEqualSnapshot(unstable.snapshot_, &s));
}
TEST(unstableLogTests, TestUnstableStableTo) {
struct tmp {
EntryVec entries;
uint64_t offset;
Snapshot *snapshot;
uint64_t index, term;
uint64_t woffset;
int wlen;
tmp(EntryVec ens, uint64_t off, Snapshot *snap, uint64_t index, uint64_t term, uint64_t wo, int wl)
: entries(ens), offset(off), snapshot(snap), index(index), term(term), woffset(wo), wlen(wl) {
}
};
vector<tmp> tests;
{
EntryVec entries;
tmp t(entries, 0, NULL, 5, 1, 0, 0);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
// stable to the first entry
tmp t(entries, 5, NULL, 5, 1, 6, 0);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
entry.set_index(6);
entry.set_term(1);
entries.push_back(entry);
// stable to the first entry
tmp t(entries, 5, NULL, 5, 1, 6, 1);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(6);
entry.set_term(2);
EntryVec entries;
entries.push_back(entry);
// stable to the first entry and term mismatch
tmp t(entries, 6, NULL, 6, 1, 6, 1);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
// stable to old entry
tmp t(entries, 5, NULL, 4, 1, 5, 1);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
// stable to old entry
tmp t(entries, 5, NULL, 4, 2, 5, 1);
tests.push_back(t);
}
// with snapshot
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
// stable to the first entry
tmp t(entries, 5, snapshot, 5, 1, 6, 0);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
entry.set_index(6);
entry.set_term(1);
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(1);
// stable to the first entry
tmp t(entries, 5, snapshot, 5, 1, 6, 1);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(6);
entry.set_term(2);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(5);
meta->set_term(1);
// stable to the first entry and term mismatch
tmp t(entries, 6, snapshot, 6, 1, 6, 1);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(1);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(5);
meta->set_term(1);
// stable to snapshot
tmp t(entries, 5, snapshot, 4, 1, 5, 1);
tests.push_back(t);
}
{
Entry entry;
entry.set_index(5);
entry.set_term(2);
EntryVec entries;
entries.push_back(entry);
Snapshot *snapshot = new Snapshot();
SnapshotMetadata *meta = snapshot->mutable_metadata();
meta->set_index(4);
meta->set_term(2);
// stable to snapshot
tmp t(entries, 5, snapshot, 4, 1, 5, 1);
tests.push_back(t);
}
int i;
for (i = 0;i < tests.size(); ++i) {
unstableLog unstable;
unstable.entries_ = tests[i].entries;
unstable.offset_ = tests[i].offset;
unstable.snapshot_ = tests[i].snapshot;
unstable.logger_ = NULL;
unstable.stableTo(tests[i].index, tests[i].term);
EXPECT_EQ(unstable.offset_, tests[i].woffset) << "i: " << i << ", woffset: " << tests[i].woffset;
EXPECT_EQ(unstable.entries_.size(), tests[i].wlen);
}
}
TEST(unstableLogTests, TestUnstableTruncateAndAppend) {
struct tmp {
EntryVec entries;
uint64_t offset;
Snapshot *snapshot;
EntryVec toappend;
uint64_t woffset;
EntryVec wentries;
tmp(EntryVec ens, uint64_t off, Snapshot *snap, EntryVec append, uint64_t wo, EntryVec wents)
: entries(ens), offset(off), snapshot(snap), toappend(append), woffset(wo), wentries(wents) {
}
};
vector<tmp> tests;
// append to the end
{
Entry entry;
EntryVec entries, append, wents;
entry.set_index(5);
entry.set_term(1);
entries.push_back(entry);
entry.set_index(6);
entry.set_term(1);
append.push_back(entry);
entry.set_index(7);
entry.set_term(1);
append.push_back(entry);
entry.set_index(5);
entry.set_term(1);
wents.push_back(entry);
entry.set_index(6);
entry.set_term(1);
wents.push_back(entry);
entry.set_index(7);
entry.set_term(1);
wents.push_back(entry);
tmp t(entries, 5, NULL, append, 5, wents);
tests.push_back(t);
}
// replace the unstable entries
{
Entry entry;
EntryVec entries, append, wents;
entry.set_index(5);
entry.set_term(1);
entries.push_back(entry);
entry.set_index(5);
entry.set_term(2);
append.push_back(entry);
entry.set_index(6);
entry.set_term(2);
append.push_back(entry);
entry.set_index(5);
entry.set_term(2);
wents.push_back(entry);
entry.set_index(6);
entry.set_term(2);
wents.push_back(entry);
tmp t(entries, 5, NULL, append, 5, wents);
tests.push_back(t);
}
{
Entry entry;
EntryVec entries, append, wents;
entry.set_index(5);
entry.set_term(1);
entries.push_back(entry);
entry.set_index(4);
entry.set_term(2);
append.push_back(entry);
entry.set_index(5);
entry.set_term(2);
append.push_back(entry);
entry.set_index(6);
entry.set_term(2);
append.push_back(entry);
entry.set_index(4);
entry.set_term(2);
wents.push_back(entry);
entry.set_index(5);
entry.set_term(2);
wents.push_back(entry);
entry.set_index(6);
entry.set_term(2);
wents.push_back(entry);
tmp t(entries, 5, NULL, append, 4, wents);
tests.push_back(t);
}
// truncate the existing entries and append
{
Entry entry;
EntryVec entries, append, wents;
entry.set_index(5);
entry.set_term(1);
entries.push_back(entry);
entry.set_index(6);
entry.set_term(1);
entries.push_back(entry);
entry.set_index(7);
entry.set_term(1);
entries.push_back(entry);
entry.set_index(6);
entry.set_term(2);
append.push_back(entry);
entry.set_index(5);
entry.set_term(1);
wents.push_back(entry);
entry.set_index(6);
entry.set_term(2);
wents.push_back(entry);
tmp t(entries, 5, NULL, append, 5, wents);
tests.push_back(t);
}
{
Entry entry;
EntryVec entries, append, wents;
entry.set_index(5);
entry.set_term(1);
entries.push_back(entry);
entry.set_index(6);
entry.set_term(1);
entries.push_back(entry);
entry.set_index(7);
entry.set_term(1);
entries.push_back(entry);
entry.set_index(7);
entry.set_term(2);
append.push_back(entry);
entry.set_index(8);
entry.set_term(2);
append.push_back(entry);
entry.set_index(5);
entry.set_term(1);
wents.push_back(entry);
entry.set_index(6);
entry.set_term(1);
wents.push_back(entry);
entry.set_index(7);
entry.set_term(2);
wents.push_back(entry);
entry.set_index(8);
entry.set_term(2);
wents.push_back(entry);
tmp t(entries, 5, NULL, append, 5, wents);
tests.push_back(t);
}
int i;
for (i = 0;i < tests.size(); ++i) {
unstableLog unstable;
unstable.entries_ = tests[i].entries;
unstable.offset_ = tests[i].offset;
unstable.snapshot_ = tests[i].snapshot;
unstable.logger_ = &kDefaultLogger;
unstable.truncateAndAppend(tests[i].toappend);
EXPECT_EQ(unstable.offset_, tests[i].woffset) << "i: " << i << ", woffset: " << tests[i].woffset;
EXPECT_EQ(true, isDeepEqualEntries(unstable.entries_, tests[i].wentries)) << "i: " << i;
}
}
| 23.218978 | 103 | 0.627036 | [
"vector"
] |
69e82dfbb06b7fbaebb9e6e8e25af2c23da39c38 | 2,722 | cpp | C++ | tcob/src/gfx/Quad.cpp | TobiasBohnen/tcob | 53092b3c8e657f1ff5e48ce961659edf7cb1cb05 | [
"MIT"
] | 2 | 2021-08-18T19:14:35.000Z | 2021-12-01T14:14:49.000Z | tcob/src/gfx/Quad.cpp | TobiasBohnen/tcob | 53092b3c8e657f1ff5e48ce961659edf7cb1cb05 | [
"MIT"
] | null | null | null | tcob/src/gfx/Quad.cpp | TobiasBohnen/tcob | 53092b3c8e657f1ff5e48ce961659edf7cb1cb05 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Tobias Bohnen
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include <tcob/gfx/Quad.hpp>
#include <tcob/gfx/Texture.hpp>
namespace tcob::gfx {
static_assert(sizeof(Quad) == sizeof(Vertex) * 4);
void Quad::set_color(const Color& color)
{
const std::array<u8, 4> col { color.R, color.G, color.B, color.A };
TopRight.Color = col;
BottomRight.Color = col;
BottomLeft.Color = col;
TopLeft.Color = col;
}
void Quad::set_texcoords(const TextureRegion& region, bool flipHorizontally, bool flipVertically)
{
const RectF rect { region.UVRect };
const f32 level { static_cast<f32>(region.Level) };
vec3 tr { rect.get_right(), rect.Top, level };
vec3 br { rect.get_right(), rect.get_bottom(), level };
vec3 bl { rect.Left, rect.get_bottom(), level };
vec3 tl { rect.Left, rect.Top, level };
if (flipHorizontally) {
std::swap(tl, tr);
std::swap(bl, br);
}
if (flipVertically) {
std::swap(tl, bl);
std::swap(tr, br);
}
TopRight.TexCoords = tr;
BottomRight.TexCoords = br;
BottomLeft.TexCoords = bl;
TopLeft.TexCoords = tl;
}
void Quad::scroll_texcoords(const PointF& offset)
{
const f32 left { TopLeft.TexCoords[0] + offset.X };
const f32 top { TopLeft.TexCoords[1] + offset.Y };
const f32 right { BottomRight.TexCoords[0] + offset.X };
const f32 bottom { BottomRight.TexCoords[1] + offset.Y };
const RectF rect { left, top, right - left, bottom - top };
const f32 level { TopRight.TexCoords[2] };
TopRight.TexCoords = { rect.get_right(), rect.Top, level };
BottomRight.TexCoords = { rect.get_right(), rect.get_bottom(), level };
BottomLeft.TexCoords = { rect.Left, rect.get_bottom(), level };
TopLeft.TexCoords = { rect.Left, rect.Top, level };
}
void Quad::set_position(const RectF& rect, const Transform& trans)
{
const PointF tr { trans * rect.get_top_right() };
const PointF br { trans * rect.get_bottom_right() };
const PointF bl { trans * rect.get_bottom_left() };
const PointF tl { trans * rect.get_top_left() };
TopRight.Position = { tr.X, tr.Y };
BottomRight.Position = { br.X, br.Y };
BottomLeft.Position = { bl.X, bl.Y };
TopLeft.Position = { tl.X, tl.Y };
}
void Quad::set_position(const RectF& rect)
{
const PointF tr { rect.get_top_right() };
const PointF br { rect.get_bottom_right() };
const PointF bl { rect.get_bottom_left() };
const PointF tl { rect.get_top_left() };
TopRight.Position = { tr.X, tr.Y };
BottomRight.Position = { br.X, br.Y };
BottomLeft.Position = { bl.X, bl.Y };
TopLeft.Position = { tl.X, tl.Y };
}
} | 30.931818 | 97 | 0.642175 | [
"transform"
] |
69e82e364cdf9e16a25c400b4a651be1f498149f | 1,659 | cpp | C++ | UniEngine/src/TransformManager.cpp | edisonlee0212/UniEngine-deprecated | 4b899980c280ac501c3b5fa2746cf1e71cfedd28 | [
"MIT"
] | null | null | null | UniEngine/src/TransformManager.cpp | edisonlee0212/UniEngine-deprecated | 4b899980c280ac501c3b5fa2746cf1e71cfedd28 | [
"MIT"
] | null | null | null | UniEngine/src/TransformManager.cpp | edisonlee0212/UniEngine-deprecated | 4b899980c280ac501c3b5fa2746cf1e71cfedd28 | [
"MIT"
] | 1 | 2021-09-06T08:07:37.000Z | 2021-09-06T08:07:37.000Z | #include "pch.h"
#include "TransformManager.h"
#include "UniEngine.h"
#include "EditorManager.h"
#include "SerializationManager.h"
using namespace UniEngine;
void UniEngine::TransformManager::Init()
{
GetInstance().m_transformQuery = EntityManager::CreateEntityQuery();
EntityManager::SetEntityQueryAllFilters(GetInstance().m_transformQuery, Transform(), GlobalTransform());
}
void UniEngine::TransformManager::LateUpdate()
{
EntityManager::ForEach<Transform, GlobalTransform>(JobManager::PrimaryWorkers(), GetInstance().m_transformQuery, [](int i, Entity entity, Transform& ltp, GlobalTransform& ltw)
{
if (EntityManager::IsEntityStatic(entity) || !EntityManager::GetParent(entity).IsNull()) return;
ltw.m_value = ltp.m_value;
CalculateLtwRecursive(ltw, entity);
}, false
);
if (!Application::IsPlaying())
{
PhysicsSimulationManager::UploadTransforms();
}
}
void UniEngine::TransformManager::CalculateLtwRecursive(const GlobalTransform& pltw, Entity entity)
{
if(EntityManager::IsEntityStatic(entity)) return;
for (const auto& i : EntityManager::GetChildren(entity)) {
auto ltp = EntityManager::GetComponentData<Transform>(i);
GlobalTransform ltw;
ltw.m_value = pltw.m_value * ltp.m_value;
EntityManager::SetComponentData<GlobalTransform>(i, ltw);
//auto* ltp = static_cast<Transform*>(static_cast<void*>(EntityManager::GetComponentDataPointer(entity, typeid(Transform).hash_code())));
//auto* ltw = static_cast<GlobalTransform*>(static_cast<void*>(EntityManager::GetComponentDataPointer(entity, typeid(GlobalTransform).hash_code())));
//ltw->Value = pltw->Value * ltp->Value;
CalculateLtwRecursive(ltw, i);
}
}
| 37.704545 | 176 | 0.762508 | [
"transform"
] |
69f0623a0b42339354ee01201b9db4bf2e377461 | 1,035 | cpp | C++ | cpp-leetcode/leetcode139-word-break_dp1.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 45 | 2021-07-25T00:45:43.000Z | 2022-03-24T05:10:43.000Z | cpp-leetcode/leetcode139-word-break_dp1.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | null | null | null | cpp-leetcode/leetcode139-word-break_dp1.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 15 | 2021-07-25T00:40:52.000Z | 2021-12-27T06:25:31.000Z | #include<vector>
#include<algorithm>
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
/** 题意: 1 <= s.length <= 300, 故不需要判空 */
const int len = s.size();
bool dp[len + 1];
dp[0] = true;
fill(dp + 1, dp + len + 1, false);
for (int i = 0; i < len; i++) /* 双指针i和j */
{
for (int j = i + 1; j <= len; j++)
{
string subs = s.substr(i, j - i); /* 对于字符串s中[i:j]范围内的子串subs, 都去判断一下dp[i]是不是true以及subs在不在数组wordDict中。 */
if (find(wordDict.begin(), wordDict.end(), subs) != wordDict.end() && dp[i])
dp[j] = true;
}
}
return dp[len];
}
};
// Test
int main()
{
Solution sol;
string s = "applepenapple";
vector<string> wordDict = {"apple", "pen"};
// 预期输出: true
auto res = sol.wordBreak(s, wordDict);
cout << (res == true ? "true" : "false");
return 0;
}
| 25.875 | 119 | 0.495652 | [
"vector"
] |
69fb1696e104ef9dec327fbdbbf36177e8858183 | 1,871 | cpp | C++ | libraries/hostsfile/tests/hostsfile.cpp | Smjert/osquery-extensions | 6b83eb4156cb162adc8db24390f49ff6ac2841d8 | [
"Apache-2.0"
] | 194 | 2017-12-14T14:00:34.000Z | 2022-03-21T23:56:06.000Z | libraries/hostsfile/tests/hostsfile.cpp | Smjert/osquery-extensions | 6b83eb4156cb162adc8db24390f49ff6ac2841d8 | [
"Apache-2.0"
] | 49 | 2017-12-09T16:32:37.000Z | 2021-12-14T22:15:06.000Z | libraries/hostsfile/tests/hostsfile.cpp | Smjert/osquery-extensions | 6b83eb4156cb162adc8db24390f49ff6ac2841d8 | [
"Apache-2.0"
] | 27 | 2017-12-14T23:48:39.000Z | 2022-02-25T01:54:45.000Z | /*
* Copyright (c) 2018 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "hostsfile.h"
#include <sstream>
#include <gtest/gtest.h>
namespace trailofbits {
TEST(HostsFileTests, ParseHostsFileLine) {
std::vector<std::string> test_input = {
"# test",
"1.2.3.4 temp # this is a comment!",
"5.6.7.8 test1 test2 test3 test4",
"",
"9.10.11.12\t\ttest5"};
std::vector<std::string> expected_output = {
"1.2.3.4: temp",
"5.6.7.8: test1, test2, test3, test4",
"9.10.11.12: test5"};
std::vector<std::string> actual_output;
for (const auto& line : test_input) {
std::string address;
std::set<std::string> domain_list;
if (HostsFile::ParseHostsFileLine(address, domain_list, line)) {
std::stringstream stream;
stream << address << ": ";
for (auto it = domain_list.begin(); it != domain_list.end(); it++) {
const auto& domain = *it;
stream << domain;
if (std::next(it, 1) != domain_list.end()) {
stream << ", ";
}
}
actual_output.push_back(stream.str());
}
}
EXPECT_EQ(expected_output.size(), actual_output.size());
for (auto i = 0U; i < expected_output.size(); i++) {
EXPECT_EQ(expected_output.at(i), actual_output.at(i));
}
}
} // namespace trailofbits
| 27.925373 | 75 | 0.628541 | [
"vector"
] |
69fbbc172ca3188f47f20c66b2b6ad752da4ca1c | 3,905 | cpp | C++ | src/AdventOfCode2019/Day10-MonitoringStation/test_Day10-MonitoringStation.cpp | dbartok/advent-of-code-cpp | c8c2df7a21980f8f3e42128f7bc5df8288f18490 | [
"MIT"
] | null | null | null | src/AdventOfCode2019/Day10-MonitoringStation/test_Day10-MonitoringStation.cpp | dbartok/advent-of-code-cpp | c8c2df7a21980f8f3e42128f7bc5df8288f18490 | [
"MIT"
] | null | null | null | src/AdventOfCode2019/Day10-MonitoringStation/test_Day10-MonitoringStation.cpp | dbartok/advent-of-code-cpp | c8c2df7a21980f8f3e42128f7bc5df8288f18490 | [
"MIT"
] | null | null | null | #include "Day10-MonitoringStation.h"
#include <AdventOfCodeCommon/UnittestExtraDefinitions.h>
#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>
__BEGIN_LIBRARIES_DISABLE_WARNINGS
#include "CppUnitTest.h"
__END_LIBRARIES_DISABLE_WARNINGS
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace CurrentDay = AdventOfCode::Year2019::Day10;
TEST_CLASS(Day10MonitoringStation)
{
public:
TEST_METHOD(maxNumAsteroidsDetected_SimpleTests)
{
const std::vector<std::string> map1 =
{
".#..#",
".....",
"#####",
"....#",
"...##"
};
Assert::AreEqual(8u, CurrentDay::maxNumAsteroidsDetected(map1));
const std::vector<std::string> map2 =
{
"......#.#.",
"#..#.#....",
"..#######.",
".#.#.###..",
".#..#.....",
"..#....#.#",
"#..#....#.",
".##.#..###",
"##...#..#.",
".#....####"
};
Assert::AreEqual(33u, CurrentDay::maxNumAsteroidsDetected(map2));
const std::vector<std::string> map3 =
{
"#.#...#.#.",
".###....#.",
".#....#...",
"##.#.#.#.#",
"....#.#.#.",
".##..###.#",
"..#...##..",
"..##....##",
"......#...",
".####.###."
};
Assert::AreEqual(35u, CurrentDay::maxNumAsteroidsDetected(map3));
const std::vector<std::string> map4 =
{
".#..#..###",
"####.###.#",
"....###.#.",
"..###.##.#",
"##.##.#.#.",
"....###..#",
"..#.#..#.#",
"#..#.#.###",
".##...##.#",
".....#.#.."
};
Assert::AreEqual(41u, CurrentDay::maxNumAsteroidsDetected(map4));
Assert::AreEqual(210u, CurrentDay::maxNumAsteroidsDetected(large_map));
}
TEST_METHOD(vaporizationOrder_SimpleTests)
{
auto vaporizationOrder = CurrentDay::vaporizationOrder(large_map);
auto dummy = CurrentDay::Coordinates{0, 0};
vaporizationOrder.insert(vaporizationOrder.begin(), dummy);
Assert::AreEqual(CurrentDay::Coordinates{11, 12}, vaporizationOrder.at(1));
Assert::AreEqual(CurrentDay::Coordinates{12, 1}, vaporizationOrder.at(2));
Assert::AreEqual(CurrentDay::Coordinates{12, 2}, vaporizationOrder.at(3));
Assert::AreEqual(CurrentDay::Coordinates{12, 8}, vaporizationOrder.at(10));
Assert::AreEqual(CurrentDay::Coordinates{16, 0}, vaporizationOrder.at(20));
Assert::AreEqual(CurrentDay::Coordinates{16, 9}, vaporizationOrder.at(50));
Assert::AreEqual(CurrentDay::Coordinates{10, 16}, vaporizationOrder.at(100));
Assert::AreEqual(CurrentDay::Coordinates{9, 6}, vaporizationOrder.at(199));
Assert::AreEqual(CurrentDay::Coordinates{8, 2}, vaporizationOrder.at(200));
Assert::AreEqual(CurrentDay::Coordinates{10, 9}, vaporizationOrder.at(201));
Assert::AreEqual(CurrentDay::Coordinates{11, 1}, vaporizationOrder.at(299));
}
private:
const std::vector<std::string> large_map =
{
".#..##.###...#######",
"##.############..##.",
".#.######.########.#",
".###.#######.####.#.",
"#####.##.#.##.###.##",
"..#####..#.#########",
"####################",
"#.####....###.#.#.##",
"##.#################",
"#####.##.###..####..",
"..######..##.#######",
"####.##.####...##..#",
".#####..#.######.###",
"##...#.##########...",
"#.##########.#######",
".####.#.###.###.#.##",
"....##.##.###..#####",
".#.#.###########.###",
"#.#.#.#####.####.###",
"###.##.####.##.#..##"
};
};
| 31.491935 | 85 | 0.42356 | [
"vector"
] |
69feb5ed8566169d5f237c183fecd0c490bee689 | 568 | cpp | C++ | DSA_UDEMY/Strings/findnoofsubstring.cpp | yusufkhan004/DSA-practice-problems | 04e0ea2b311a63a38fbf9d28e974b266da1a60a1 | [
"MIT"
] | null | null | null | DSA_UDEMY/Strings/findnoofsubstring.cpp | yusufkhan004/DSA-practice-problems | 04e0ea2b311a63a38fbf9d28e974b266da1a60a1 | [
"MIT"
] | null | null | null | DSA_UDEMY/Strings/findnoofsubstring.cpp | yusufkhan004/DSA-practice-problems | 04e0ea2b311a63a38fbf9d28e974b266da1a60a1 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
string bigstring = "I liked the movie, acting in movie was great.";
string smallstring = "zayn";
vector<int> arr;
auto index = bigstring.find(smallstring);
// while (index != -1)
// {
// arr.push_back(index);
// index = bigstring.find(smallstring, index + 1);
// }
if (index == -1)
{
cout << "Not found";
}
else
{
cout << "found";
}
// for (int i : arr)
// {
// cout << i << ",";
// }
return 0;
} | 17.75 | 71 | 0.482394 | [
"vector"
] |
0e0c2b0ebd4eddf9809b4f83d6dddc0e028a8243 | 1,293 | cxx | C++ | ARCHIVE/BRAINSSurfaceTools/vtkITK/Testing/VTKITKVectorReader.cxx | pnlbwh/BRAINSTools | a2fe63ab5b795f03da140a4081d1fef6314dab95 | [
"Apache-2.0"
] | null | null | null | ARCHIVE/BRAINSSurfaceTools/vtkITK/Testing/VTKITKVectorReader.cxx | pnlbwh/BRAINSTools | a2fe63ab5b795f03da140a4081d1fef6314dab95 | [
"Apache-2.0"
] | null | null | null | ARCHIVE/BRAINSSurfaceTools/vtkITK/Testing/VTKITKVectorReader.cxx | pnlbwh/BRAINSTools | a2fe63ab5b795f03da140a4081d1fef6314dab95 | [
"Apache-2.0"
] | 1 | 2022-02-08T05:39:46.000Z | 2022-02-08T05:39:46.000Z |
#include <vtkITKArchetypeImageSeriesVectorReaderFile.h>
// VTK includes
#include <vtkImageData.h>
int
main(int argc, char * argv[])
{
if (argc < 2)
{
std::cout << "ERROR: need to specify a file to try reading on the command line." << std::endl;
return 1;
}
std::cout << "Trying to read file '" << argv[1] << "'" << std::endl;
vtkITKArchetypeImageSeriesVectorReaderFile * vectorReader = vtkITKArchetypeImageSeriesVectorReaderFile::New();
vectorReader->SetArchetype(argv[1]);
vectorReader->SetOutputScalarTypeToNative();
vectorReader->SetDesiredCoordinateOrientationToNative();
try
{
vectorReader->Update();
}
catch (itk::ExceptionObject err)
{
std::cout << "Unable to read file '" << argv[1] << "', err = \n" << err << std::endl;
vectorReader->Delete();
return 1;
}
// now assign it to another image
vtkImageData * imageData;
imageData = vectorReader->GetOutput();
if (imageData)
{
std::cout << "Read file, image data has " << imageData->GetNumberOfPoints() << " points" << std::endl;
}
else
{
std::cout << "ERROR: image data is null from vector reader" << std::endl;
vectorReader->Delete();
return 1;
}
std::cout << "Deleting vector reader" << std::endl;
vectorReader->Delete();
return 0;
}
| 23.944444 | 112 | 0.649652 | [
"vector"
] |
0e0f73a999df923b7cf9f1ef0f0de701c4a9a163 | 6,825 | cpp | C++ | OnlineRindex_Demo.cpp | TNishimoto/OnlineRlbwt | f04a911cf95081d6f2f599d34914eabd927e0ae6 | [
"MIT"
] | 11 | 2018-05-10T16:37:28.000Z | 2021-04-29T12:08:42.000Z | OnlineRindex_Demo.cpp | itomomoti/OnlineRLBWT | 602bcd37b1effb660dcf6dba54d59be0879600a3 | [
"MIT"
] | null | null | null | OnlineRindex_Demo.cpp | itomomoti/OnlineRLBWT | 602bcd37b1effb660dcf6dba54d59be0879600a3 | [
"MIT"
] | 1 | 2019-05-27T04:20:05.000Z | 2019-05-27T04:20:05.000Z | /*!
* Copyright (c) 2018 Tomohiro I
*
* This program is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*/
/*!
* @file OnlineRindex_Demo.cpp
* @brief Demonstration for online r-index, index based on Run-length encoded Burrows–Wheeler transform (RLBWT).
* @author Tomohiro I
* @date 2018-05-10
*/
#include <stdint.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <chrono>
#include "cmdline.h"
#include "OnlineRindex.hpp"
#include "DynRleForRlbwt.hpp"
#include "DynSuccForRindex.hpp"
using namespace itmmti;
using SizeT = uint64_t; // Text length should fit in SizeT.
template<typename RindexT>
void searchOnRindex(const RindexT & rindex, std::string message)
{
//// Pattern search Demo
const uint64_t lenWithoutEm = rindex.getLenWithEndmarker() - 1;
while (true) {
constexpr static uint64_t bufsize = 512;
char buffer[bufsize] = "";
std::cout << message << std::endl;
if (std::fgets(buffer, bufsize, stdin) == NULL || buffer[0] == '\n') {
break;
}
uint64_t len = std::strlen(buffer);
if (len > 0) {
if (buffer[len - 1] == '\n') {
buffer[--len] = '\0';
} else {
while (getchar() != '\n') {};
}
}
std::cout << "\"" << buffer << "\"" << std::endl;
//// Counting...
auto t1 = std::chrono::high_resolution_clock::now();
auto tracker = rindex.getInitialPatTracker();
bool match = true;
uint64_t plen = 0;
for (unsigned char c = buffer[plen]; c != '\0'; c = buffer[++plen]) {
match = rindex.lfMap(tracker, c);
if (!match) break;
}
auto t2 = std::chrono::high_resolution_clock::now();
double microsec = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
std::cout << "Counting: done in " << microsec << " micro sec. Len = " << len << ". Prefix match length = " << plen << ". ";
if (match) {
const auto numOcc = rindex.getNumOcc(tracker);
std::cout << "NumOcc = " << numOcc << ". BwtInterval = [" << std::get<0>(tracker) << ".."
<< std::get<1>(tracker) << ")" << std::endl;
//// Note that the returned occ is end position (exclusive) of pattern.
//// To get beginning position, subtract pattern length.
unsigned char c;
do {
std::cout << "Print them all (y/n)? Or locate without printing (l): ";
c = getchar();
while (getchar() != '\n') {};
} while (!(c == 'y' || c == 'n' || c == 'l'));
//// Locating...
if (c == 'l') { // Locating without printing.
t1 = std::chrono::high_resolution_clock::now();
auto endPos = rindex.calcFstOcc(tracker);
for (auto num = numOcc; num; --num) {
endPos = rindex.calcNextPos(endPos);
}
t2 = std::chrono::high_resolution_clock::now();
microsec = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
std::cout << "Locating: done in " << microsec << " micro sec. "
<< microsec / numOcc << " micro sec. each." << std::endl;
if (!rindex.isReady()) { // dummy code to prevent optimization delete the locating codes
std::cout << endPos << std::endl;
}
} else if (c == 'y') { // Locating with printing.
t1 = std::chrono::high_resolution_clock::now();
auto endPos = rindex.calcFstOcc(tracker);
for (auto num = numOcc; num; --num) {
std::cout << endPos - len << ", ";
endPos = rindex.calcNextPos(endPos);
}
std::cout << std::endl;
t2 = std::chrono::high_resolution_clock::now();
microsec = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
std::cout << "Locating: done in " << microsec << " micro sec. " << microsec / numOcc << " micro sec. each." << std::endl;
}
} else {
std::cout << "Pttern does not match." << std::endl;
}
}
}
int main(int argc, char *argv[])
{
cmdline::parser parser;
parser.add<std::string>("input", 'i', "input file name", true);
parser.add<size_t>("step", 's', "number of characters to index in a single step", false, 1000000);
parser.add<bool>("verbose", 'v', "verbose", false, 0);
parser.add("help", 0, "print help");
parser.parse_check(argc, argv);
const std::string in = parser.get<std::string>("input");
const bool verbose = parser.get<bool>("verbose");
const size_t step = parser.get<size_t>("step");
std::cout << "R-index constructing..." << std::endl;
std::ifstream ifs(in);
size_t last_step = 0;
using BTreeNodeT = BTreeNode<16>; // BTree arity = {16, 32, 64, 128}
using BtmNodeMT = BtmNodeM_StepCode<BTreeNodeT, 32>; // BtmNode arity in {16, 32, 64, 128}.
using BtmMInfoT = BtmMInfo_BlockVec<BtmNodeMT, 512>; // Each block has 512 btmNodeM.
using BtmNodeST = BtmNodeS<BTreeNodeT, uint32_t, 8>; // CharT = uint32_t. BtmNode arity = {4, 8, 16, 32, 64, 128}.
using BtmSInfoT = BtmSInfo_BlockVec<BtmNodeST, 1024>; // Each block has 1024 btmNodeS.
using DynRleT = DynRleForRlbwt<WBitsBlockVec<1024>, Samples_WBitsBlockVec<1024>, BtmMInfoT, BtmSInfoT>;
using BtmNodeInSucc = BtmNodeForPSumWithVal<16>; // BtmNode arity = {16, 32, 64, 128}.
using DynSuccT = DynSuccForRindex<BTreeNodeT, BtmNodeInSucc>;
using RindexT = OnlineRlbwtIndex<DynRleT, DynSuccT>;
RindexT rindex(1);
SizeT pos = 0; // Current txt-pos (0base)
char c; // Assume that the input character fits in char.
unsigned char uc;
while (ifs.peek() != std::ios::traits_type::eof()) {
ifs.get(c);
uc = static_cast<unsigned char>(c);
if (pos > last_step + (step - 1)) {
if (verbose) {
rindex.printStatistics(std::cout, false);
}
last_step = pos;
const size_t totalBytes = rindex.calcMemBytes(true);
std::cout << " " << pos << " characters indexed in "
<< totalBytes << " bytes = "
<< (double)(totalBytes) / 1024 << " KiB = "
<< ((double)(totalBytes) / 1024) / 1024 << " MiB." << std::endl;
searchOnRindex(rindex, "Type a pattern to search. Or enter empty string to continue indexing.");
std::cout << "Quitted searching phase and continue indexing next " << step << " characters..." << std::endl;
}
rindex.extend(uc);
++pos;
}
ifs.close();
const size_t totalBytes = rindex.calcMemBytes(true);
std::cout << " " << pos << " characters indexed in "
<< totalBytes << " bytes = "
<< (double)(totalBytes) / 1024 << " KiB = "
<< ((double)(totalBytes) / 1024) / 1024 << " MiB." << std::endl;
searchOnRindex(rindex, "Type a pattern to search. Or enter empty string to quit.");
std::cout << "Quitted." << std::endl;
if (verbose) {
rindex.printStatistics(std::cout, false);
}
return 0;
}
| 37.916667 | 129 | 0.596337 | [
"transform"
] |
97c03aa6318418ad2cf3df5522f11e378657ca96 | 14,542 | cxx | C++ | smtk/bridge/remote/RemusRPCWorker.cxx | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | smtk/bridge/remote/RemusRPCWorker.cxx | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | 4 | 2016-11-10T15:49:51.000Z | 2017-02-06T23:24:16.000Z | smtk/bridge/remote/RemusRPCWorker.cxx | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt 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.
//=========================================================================
#ifndef SHIBOKEN_SKIP
#include "smtk/bridge/remote/RemusRPCWorker.h"
#include "smtk/bridge/remote/Session.h"
#include "smtk/io/ImportJSON.h"
#include "smtk/io/ExportJSON.h"
#include "smtk/model/SessionRegistrar.h"
#include "smtk/model/Operator.h"
#include "smtk/common/StringUtil.h"
#include "remus/proto/JobContent.h"
#include "remus/proto/JobProgress.h"
#include "remus/proto/JobResult.h"
#include "remus/proto/JobStatus.h"
#include "remus/worker/Job.h"
#include "remus/worker/Worker.h"
#include "cJSON.h"
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <sstream>
using namespace remus::proto;
using namespace smtk::model;
using namespace smtk::common;
namespace smtk {
namespace bridge {
namespace remote {
RemusRPCWorker::RemusRPCWorker()
{
this->m_modelMgr = smtk::model::Manager::create();
}
RemusRPCWorker::~RemusRPCWorker()
{
}
/**\brief Set an option to be used by the worker as it processes jobs.
*
* Options currently recognized include "default_kernel", "default_engine",
* "exclude_kernels", and "exclude_engines".
* These are used to constrain the worker to a specific modeler.
*
* The first two options are used to solve dilemmas where a file
* to be read or other operation to be performed might feasibly be
* executed using different kernels or engines.
* When a tie occurs, the defaults are used.
*
* The latter two options are used to prevent the application from
* accessing functionality built into SMTK but administratively
* prohibited (for example, due to stability problems or licensing
* issues).
* The exclusion rules are not applied to values in the default
* kernel and engine, so specifying the wildcard "*" for both
* the kernels and engines will prohibit any but the default
* from being used.
* Otherwise the "exclude_*" options should be comma-separated lists.
*/
void RemusRPCWorker::setOption(
const std::string& optName,
const std::string& optVal)
{
smtkDebugMacro(this->manager()->log(),
"set option \"" << optName << "\" to \"" << optVal << "\"");
StringList vals;
if (
optName.find("exclude_") == 0 && (
optName == "exclude_kernels" ||
optName == "exclude_engines"))
{
std::stringstream stream(optVal);
while (stream.good())
{
std::string token;
std::getline(stream, token, ',');
vals.push_back(StringUtil::trim(token));
}
}
else
{
vals.push_back(optVal);
}
this->m_options[optName] = vals;
}
/// Remove all options recorded by setOption.
void RemusRPCWorker::clearOptions()
{
this->m_options.clear();
}
/**\brief Evalate a JSON-RPC 2.0 request encapsulated in a Remus job.
*/
void RemusRPCWorker::processJob(
remus::worker::Worker*& w,
remus::worker::Job& jd,
remus::proto::JobRequirements& r)
{
(void)r;
JobProgress progress;
JobStatus status(jd.id(),remus::IN_PROGRESS);
// Mark start of job
progress.setValue(1);
status.updateProgress(progress);
w->updateStatus(status);
remus::worker::Worker* swapWorker = NULL;
cJSON* result = cJSON_CreateObject();
std::string content = jd.details("request");
if (content.empty())
{
this->generateError(result, "No request", "");
}
else
{
cJSON* req = cJSON_Parse(content.c_str());
smtkDebugMacro(this->manager()->log(),
"job \"" << content << "\"");
cJSON* spec;
cJSON* meth;
if (
!req ||
req->type != cJSON_Object ||
!(meth = cJSON_GetObjectItem(req, "method")) ||
meth->type != cJSON_String ||
!meth->valuestring ||
!(spec = cJSON_GetObjectItem(req, "jsonrpc")) ||
spec->type != cJSON_String ||
!spec->valuestring)
{
this->generateError(
result, "Malformed request; not an object or missing jsonrpc or method members.", "");
}
else
{
std::string methStr(meth->valuestring);
std::string specStr(spec->valuestring);
std::string reqIdStr;
cJSON* reqId = cJSON_GetObjectItem(req, "id");
cJSON* param = cJSON_GetObjectItem(req, "params");
smtkDebugMacro(this->manager()->log(),
"method \"" << methStr << "\"");
bool missingIdFatal = true;
if (reqId && reqId->type == cJSON_String)
{
reqIdStr = reqId->valuestring;
missingIdFatal = false;
}
// I. Requests:
// search-sessions (available)
// list-sessions (instantiated)
// create-session
// fetch-model
// operator-able
// operator-apply
//smtkDebugMacro(this->manager()->log(), " " << methStr);
if (methStr == "search-sessions")
{
smtk::model::StringList sessionTypeNames = this->m_modelMgr->sessionTypeNames();
cJSON_AddItemToObject(result, "result",
smtk::io::ExportJSON::createStringArray(sessionTypeNames));
}
else if (methStr == "session-filetypes")
{
cJSON* bname;
if (
!param ||
!(bname = cJSON_GetObjectItem(param, "session-name")) ||
bname->type != cJSON_String ||
!bname->valuestring ||
!bname->valuestring[0])
{
this->generateError(result, "Parameters not passed or session-name not specified.", reqIdStr);
}
else
{
cJSON* typeObj = cJSON_CreateObject();
smtk::model::StringData sessionFileTypes =
SessionRegistrar::sessionFileTypes(bname->valuestring);
for(PropertyNameWithStrings it = sessionFileTypes.begin();
it != sessionFileTypes.end(); ++it)
{
if(it->second.size())
cJSON_AddItemToObject(typeObj, it->first.c_str(),
smtk::io::ExportJSON::createStringArray(it->second));
}
cJSON_AddItemToObject(result, "result", typeObj);
}
}
else if (methStr == "create-session")
{
smtk::model::StringList sessionTypeNames = this->m_modelMgr->sessionTypeNames();
std::set<std::string> sessionSet(sessionTypeNames.begin(), sessionTypeNames.end());
cJSON* bname;
if (
!param ||
!(bname = cJSON_GetObjectItem(param, "session-name")) ||
bname->type != cJSON_String ||
!bname->valuestring ||
!bname->valuestring[0] ||
sessionSet.find(bname->valuestring) == sessionSet.end())
{
this->generateError(result,
"Parameters not passed or session-name not specified/invalid.",
reqIdStr);
}
else
{
// Pass options such as engine name (if any) to static setup
smtk::model::SessionStaticSetup bsetup =
smtk::model::SessionRegistrar::sessionStaticSetup(bname->valuestring);
cJSON* ename;
if (
bsetup &&
(ename = cJSON_GetObjectItem(param, "engine-name")) &&
ename->type == cJSON_String &&
!ename->valuestring && !ename->valuestring[0])
{
std::string defEngine = ename->valuestring;
if (!defEngine.empty())
{
StringList elist;
elist.push_back(ename->valuestring);
bsetup("engine", elist);
}
}
smtk::model::SessionConstructor bctor =
smtk::model::SessionRegistrar::sessionConstructor(bname->valuestring);
if (!bctor)
{
this->generateError(result,
"Unable to obtain session constructor", reqIdStr);
}
else
{
smtk::model::SessionPtr session = bctor();
if (!session || session->sessionId().isNull())
{
this->generateError(result,
"Unable to construct session or got NULL session ID.", reqIdStr);
}
else
{
this->m_modelMgr->registerSession(session);
cJSON* sess = cJSON_CreateObject();
smtk::io::ExportJSON::forManagerSession(
session->sessionId(), sess, this->m_modelMgr);
cJSON_AddItemToObject(result, "result", sess);
#if 0
// Now redefine our worker to be a new one whose
// requirements include a tag for this session.
// That way it can be singled out by the client that
// initiated the session.
r = make_JobRequirements(
r.meshTypes(), r.workerName(),
r.hasRequirements() ? r.requirements() : "");
r.tag(session->sessionId().toString());
remus::worker::ServerConnection conn2 =
remus::worker::make_ServerConnection(
w->connection().endpoint());
conn2.context(w->connection().context());
swapWorker = new remus::worker::Worker(r, conn2);
smtkDebugMacro(this->manager()->log(), "Redefining worker. "
<<"Requirements now tagged with "
<< session->sessionId().toString() << ".");
//cJSON_AddItemToObject(result, "result",
// cJSON_CreateString(session->sessionId().toString().c_str()));
#endif
}
}
}
}
else if (methStr == "fetch-model")
{
cJSON* model = cJSON_CreateObject();
// Never include session list or tessellation data
// Until someone makes us.
smtk::io::ExportJSON::fromModelManager(model, this->m_modelMgr,
static_cast<smtk::io::JSONFlags>(
smtk::io::JSON_ENTITIES | smtk::io::JSON_PROPERTIES));
cJSON_AddItemToObject(result, "result", model);
}
else if (methStr == "operator-able")
{
smtk::model::OperatorPtr localOp;
if (
!param ||
!smtk::io::ImportJSON::ofOperator(param, localOp, this->m_modelMgr) ||
!localOp)
{
this->generateError(result,
"Parameters not passed or invalid operator specified.",
reqIdStr);
}
else
{
bool able = localOp->ableToOperate();
cJSON_AddItemToObject(result, "result", cJSON_CreateBool(able ? 1 : 0));
}
}
else if (methStr == "operator-apply")
{
smtk::model::OperatorPtr localOp;
if (
!param ||
!smtk::io::ImportJSON::ofOperator(param, localOp, this->m_modelMgr) ||
!localOp)
{
this->generateError(result,
"Parameters not passed or invalid operator specified.",
reqIdStr);
}
else
{
smtk::model::OperatorResult ores = localOp->operate();
cJSON* oresult = cJSON_CreateObject();
smtk::io::ExportJSON::forOperatorResult(ores, oresult);
cJSON_AddItemToObject(result, "result", oresult);
}
}
// II. Notifications:
// delete session
else if (methStr == "delete-session")
{
missingIdFatal &= false; // Notifications do not require an "id" member in the request.
cJSON* bsess;
if (
!param ||
!(bsess = cJSON_GetObjectItem(param, "session-id")) ||
bsess->type != cJSON_String ||
!bsess->valuestring ||
!bsess->valuestring[0])
{
this->generateError(result, "Parameters not passed or session-id not specified/invalid.", reqIdStr);
}
else
{
smtk::model::SessionPtr session =
SessionRef(
this->m_modelMgr,
smtk::common::UUID(bsess->valuestring)
).session();
if (!session)
{
this->generateError(result, "No session with given session ID.", reqIdStr);
}
else
{
this->m_modelMgr->unregisterSession(session);
#if 0
// Remove tag from worker requirements.
r = make_JobRequirements(
r.meshTypes(), r.workerName(), r.hasRequirements() ? r.requirements() : "");
swapWorker = new remus::worker::Worker(r, w->connection());
smtkDebugMacro(this->manager()->log(), "Redefining worker. "
<< "Requirements now untagged, removed "
<< session->sessionId().toString() << ".");
#endif // 0
}
}
}
if (missingIdFatal)
{
this->generateError(result, "Method was a request but is missing \"id\".", reqIdStr);
}
}
}
progress.setValue(100);
//progress.setMessage("Mmph. Yeah!");
status.updateProgress(progress);
w->updateStatus(status);
char* response = cJSON_Print(result);
cJSON_Delete(result);
remus::proto::JobResult jobResult =
remus::proto::make_JobResult(
jd.id(), response, remus::common::ContentFormat::JSON);
smtkDebugMacro(this->manager()->log(), "Response is \"" << response << "\"");
w->returnResult(jobResult);
free(response);
if (swapWorker)
{
//delete w;
w = swapWorker;
}
}
/// Return the model manager used by the worker. This should never be NULL.
smtk::model::ManagerPtr RemusRPCWorker::manager()
{
return this->m_modelMgr;
}
/**\brief Set the model manager used by the worker. This is ignored if NULL.
*
* \warning
* This should only be called immediately after creating the worker,
* before any operations have been run.
*/
void RemusRPCWorker::setManager(smtk::model::ManagerPtr mgr)
{
if (mgr)
this->m_modelMgr = mgr;
}
void RemusRPCWorker::generateError(cJSON* err, const std::string& errMsg, const std::string& reqId)
{
cJSON* result = cJSON_CreateObject();
cJSON_AddItemToObject(err, "result", result);
cJSON_AddItemToObject(result, "error", cJSON_CreateString(errMsg.c_str()));
cJSON_AddItemToObject(result, "id", cJSON_CreateString(reqId.c_str()));
}
} // namespace remote
} // namespace bridge
} // namespace smtk
#endif // SHIBOKEN_SKIP
| 32.900452 | 110 | 0.583689 | [
"object",
"model"
] |
97c24f0a347cd0781e663ca99fd93185b655db2e | 5,671 | cpp | C++ | general_decimal_arithmetic/libgdatest/test_line.cpp | GaryHughes/stddecimal | ebec00e6cdad29a978ee5b0d4998e8b484d8dce1 | [
"MIT"
] | 5 | 2020-08-08T07:01:00.000Z | 2022-03-05T02:45:05.000Z | general_decimal_arithmetic/libgdatest/test_line.cpp | GaryHughes/stddecimal | ebec00e6cdad29a978ee5b0d4998e8b484d8dce1 | [
"MIT"
] | 6 | 2020-06-28T02:22:07.000Z | 2021-04-01T20:14:29.000Z | general_decimal_arithmetic/libgdatest/test_line.cpp | GaryHughes/stddecimal | ebec00e6cdad29a978ee5b0d4998e8b484d8dce1 | [
"MIT"
] | 1 | 2021-02-05T08:59:49.000Z | 2021-02-05T08:59:49.000Z | #include "test_line.hpp"
#include <boost/algorithm/string/trim_all.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
namespace gda
{
const boost::regex comment_regex("^\\s*--.*");
// keyword: value
const boost::regex directive_regex("^([^:]+):(.+)");
// add060 add '10000e+9' '70000' -> '1.00000E+13' Inexact Rounded
const boost::regex test_regex("^\\s*(\\S+)\\s+(\\S+)\\s+(\\.+\\s+){1,3}->\\s+(\\.+)\\s*(.*)");
test_line::test_line(std::string line)
{
boost::algorithm::trim_all(line);
if (line.empty())
{
m_type = line_type::blank;
return;
}
if (boost::regex_match(line, comment_regex)) {
m_type = line_type::comment;
return;
}
boost::smatch match;
if (boost::regex_match(line, match, directive_regex)) {
m_type = line_type::directive;
m_keyword = match[1].str();
boost::algorithm::trim_all(m_keyword);
m_value = match[2].str();
boost::algorithm::trim_all(m_value);
return;
}
std::string arrow = "->";
auto arrow_pos = line.find(arrow);
if (arrow_pos == std::string::npos) {
throw std::runtime_error("failed to find -> on line: " + line);
}
auto left = line.substr(0, arrow_pos);
auto right = line.substr(arrow_pos + arrow.length());
std::vector<std::string> tokens;
tokenise(left, tokens);
if (tokens.size() < 3 || tokens.size() > 5) {
throw std::runtime_error("there can only be between 3 and 5 tokens on the left of the arrow: " + line);
}
m_id = tokens[0];
m_operation = tokens[1];
m_operands.push_back(tokens[2]);
if (tokens.size() > 3) {
m_operands.push_back(tokens[3]);
if (tokens.size() > 4) {
m_operands.push_back(tokens[4]);
}
}
tokens.clear();
tokenise(right, tokens);
if (tokens.size() < 1) {
throw std::runtime_error("there must be atleast 1 token on the right of the arrow: " + line);
}
m_expected_result = tokens[0];
m_expected_conditions = parse_conditions(std::vector<std::string>(++tokens.begin(), tokens.end()));
m_type = line_type::test;
}
void test_line::tokenise(const std::string text, std::vector<std::string>& tokens)
{
std::string token;
const char not_space = 'a';
char previous = not_space;
bool quoted_token = false;
for (char c : text) {
if ((std::isspace(c) && !std::isspace(previous)) || (c == '\'' && previous != '\'')) {
if (!token.empty()) {
tokens.push_back(token);
token = "";
previous = not_space;
}
continue;
}
if (!std::isspace(c)) {
if (token.empty() && c == '\'') {
quoted_token = true;
}
else {
token += c;
}
}
previous = c;
}
if (!token.empty()) {
tokens.push_back(token);
}
}
std::decimal::fexcept_t test_line::parse_conditions(const std::vector<std::string>& conditions)
{
std::decimal::fexcept_t res = 0;
for (const auto& text : conditions) {
std::string condition = text;
boost::algorithm::to_lower(condition);
// clamped NA
if (condition == "conversion_syntax") { res |= std::decimal::FE_DEC_INVALID; }
else if (condition == "division_by_zero") { res |= std::decimal::FE_DEC_DIVBYZERO; }
else if (condition == "division_impossible") { res |= std::decimal::FE_DEC_INVALID; }
else if (condition == "division_undefined") { res |= std::decimal::FE_DEC_INVALID; }
else if (condition == "inexact") { res |= std::decimal::FE_DEC_INEXACT; }
else if (condition == "insufficient_storage") { res |= std::decimal::FE_DEC_INVALID; }
else if (condition == "invalid_context") { res |= std::decimal::FE_DEC_INVALID; }
else if (condition == "invalid_operation") { res |= std::decimal::FE_DEC_INVALID; }
// lost_digits (no equivalent)
else if (condition == "overflow") { res |= std::decimal::FE_DEC_OVERFLOW; }
// TODO dectest says IEEE has no equivalent, we get inexact so use that for now and investigate later
else if (condition == "rounded") { res |= std::decimal::FE_DEC_INEXACT; }
// subnormal (no equivalent)
else if (condition == "underflow") { res |= std::decimal::FE_DEC_UNDERFLOW; }
}
return res;
}
test_line::line_type test_line::type() const
{
return m_type;
}
bool test_line::is_blank() const
{
return type() == line_type::blank;
}
bool test_line::is_comment() const
{
return type() == line_type::comment;
}
bool test_line::is_directive() const
{
return type() == line_type::directive;
}
bool test_line::is_test() const
{
return type() == line_type::test;
}
const std::string& test_line::keyword() const
{
return m_keyword;
}
const std::string& test_line::value() const
{
return m_value;
}
const std::string& test_line::id() const
{
return m_id;
}
const std::string& test_line::operation() const
{
return m_operation;
}
const std::vector<std::string>& test_line::operands() const
{
return m_operands;
}
const std::string& test_line::expected_result() const
{
return m_expected_result;
}
std::decimal::fexcept_t test_line::expected_conditions() const
{
return m_expected_conditions;
}
} // namespace gda | 28.074257 | 111 | 0.576618 | [
"vector"
] |
97d5dcbe656216c48c3608050441a35a39789a8b | 14,835 | cpp | C++ | Source/Graphics/Vulkan/VkGpuSwapchain.cpp | InjectorGames/Inject | 09e74a83c287b81fd8272c10d6bae2b1aa785c0e | [
"BSD-3-Clause"
] | 2 | 2019-12-10T16:26:58.000Z | 2020-04-17T11:47:42.000Z | Source/Graphics/Vulkan/VkGpuSwapchain.cpp | InjectorGames/Inject | 09e74a83c287b81fd8272c10d6bae2b1aa785c0e | [
"BSD-3-Clause"
] | 28 | 2020-08-17T12:39:50.000Z | 2020-11-16T20:42:50.000Z | Source/Graphics/Vulkan/VkGpuSwapchain.cpp | InjectorGames/InjectorEngine | 09e74a83c287b81fd8272c10d6bae2b1aa785c0e | [
"BSD-3-Clause"
] | null | null | null | #include "Injector/Graphics/Vulkan/VkGpuSwapchain.hpp"
#include "Injector/Exception/NullException.hpp"
#include "Injector/Graphics/Vulkan/VkGpuImageFormat.hpp"
namespace Injector
{
vk::SurfaceFormatKHR VkGpuSwapchain::getBestSurfaceFormat(
vk::PhysicalDevice physicalDevice,
vk::SurfaceKHR surface)
{
auto surfaceFormats =
physicalDevice.getSurfaceFormatsKHR(surface);
auto surfaceFormat = surfaceFormats.at(0);
for (auto& format : surfaceFormats)
{
if (format.format == vk::Format::eB8G8R8A8Unorm &&
format.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear)
{
surfaceFormat = format;
break;
}
}
return surfaceFormat;
}
vk::PresentModeKHR VkGpuSwapchain::getBestPresentMode(
vk::PhysicalDevice physicalDevice,
vk::SurfaceKHR surface)
{
auto presentModes =
physicalDevice.getSurfacePresentModesKHR(surface);
auto presentMode = vk::PresentModeKHR::eFifo;
for (auto mode : presentModes)
{
if (mode == vk::PresentModeKHR::eMailbox)
{
presentMode = mode;
break;
}
}
for (auto mode : presentModes)
{
if (mode == vk::PresentModeKHR::eFifoRelaxed)
{
presentMode = mode;
break;
}
}
return presentMode;
}
vk::Extent2D VkGpuSwapchain::getBestExtent(
const vk::SurfaceCapabilitiesKHR& surfaceCapabilities,
const IntVector2& size)
{
if (surfaceCapabilities.currentExtent.width == UINT32_MAX)
{
return vk::Extent2D(
std::clamp(static_cast<uint32_t>(size.x),
surfaceCapabilities.minImageExtent.width,
surfaceCapabilities.maxImageExtent.width),
std::clamp(static_cast<uint32_t>(size.y),
surfaceCapabilities.minImageExtent.height,
surfaceCapabilities.maxImageExtent.height));
}
else
{
return surfaceCapabilities.currentExtent;
}
}
uint32_t VkGpuSwapchain::getBestImageCount(
const vk::SurfaceCapabilitiesKHR& capabilities)
{
auto imageCount =
capabilities.minImageCount + 1;
if (capabilities.maxImageCount > 0 &&
imageCount > capabilities.maxImageCount)
imageCount = capabilities.maxImageCount;
return imageCount;
}
vk::SurfaceTransformFlagBitsKHR VkGpuSwapchain::getBestTransform(
const vk::SurfaceCapabilitiesKHR& capabilities)
{
if(capabilities.supportedTransforms &
vk::SurfaceTransformFlagBitsKHR::eIdentity)
{
return vk::SurfaceTransformFlagBitsKHR::eIdentity;
}
else
{
return capabilities.currentTransform;
}
}
vk::CompositeAlphaFlagBitsKHR VkGpuSwapchain::getBestCompositeAlpha(
const vk::SurfaceCapabilitiesKHR& capabilities)
{
if (capabilities.supportedCompositeAlpha &
vk::CompositeAlphaFlagBitsKHR::eOpaque)
{
return vk::CompositeAlphaFlagBitsKHR::eOpaque;
}
else if (capabilities.supportedCompositeAlpha &
vk::CompositeAlphaFlagBitsKHR::ePreMultiplied)
{
return vk::CompositeAlphaFlagBitsKHR::ePreMultiplied;
}
else if (capabilities.supportedCompositeAlpha &
vk::CompositeAlphaFlagBitsKHR::ePostMultiplied)
{
return vk::CompositeAlphaFlagBitsKHR::ePostMultiplied;
}
else if (capabilities.supportedCompositeAlpha &
vk::CompositeAlphaFlagBitsKHR::eInherit)
{
return vk::CompositeAlphaFlagBitsKHR::eInherit;
}
else
{
throw Exception(
THIS_FUNCTION_NAME,
"No supported composite alpha");
}
}
vk::SwapchainKHR VkGpuSwapchain::createSwapchain(
vk::Device device,
vk::SurfaceKHR surface,
uint32_t imageCount,
vk::SurfaceFormatKHR surfaceFormat,
vk::Extent2D extent,
vk::SurfaceTransformFlagBitsKHR transform,
vk::CompositeAlphaFlagBitsKHR compositeAlpha,
vk::PresentModeKHR presentMode,
vk::SwapchainKHR oldSwapchain)
{
vk::SwapchainKHR swapchain;
auto swapchainCreateInfo = vk::SwapchainCreateInfoKHR(
vk::SwapchainCreateFlagsKHR(),
surface,
imageCount,
surfaceFormat.format,
surfaceFormat.colorSpace,
extent,
1,
vk::ImageUsageFlagBits::eColorAttachment,
vk::SharingMode::eExclusive,
0,
nullptr,
transform,
compositeAlpha,
presentMode,
true,
oldSwapchain);
auto result = device.createSwapchainKHR(
&swapchainCreateInfo,
nullptr,
&swapchain);
if (result != vk::Result::eSuccess)
{
throw Exception(
THIS_FUNCTION_NAME,
"Failed to create swapchain");
}
return swapchain;
}
vk::RenderPass VkGpuSwapchain::createRenderPass(
vk::Device device,
vk::Format colorFormat,
vk::Format depthFormat)
{
vk::RenderPass renderPass;
vk::AttachmentDescription attachmentDescriptions[2] =
{
vk::AttachmentDescription(
vk::AttachmentDescriptionFlags(),
colorFormat,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eClear,
vk::AttachmentStoreOp::eStore,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eUndefined,
vk::ImageLayout::ePresentSrcKHR),
vk::AttachmentDescription(
vk::AttachmentDescriptionFlags(),
depthFormat,
vk::SampleCountFlagBits::e1,
vk::AttachmentLoadOp::eClear,
vk::AttachmentStoreOp::eDontCare,
vk::AttachmentLoadOp::eDontCare,
vk::AttachmentStoreOp::eDontCare,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eDepthStencilAttachmentOptimal),
};
auto colorAttachmentReference = vk::AttachmentReference(
0,
vk::ImageLayout::eColorAttachmentOptimal);
auto depthAttachmentReference = vk::AttachmentReference(
1,
vk::ImageLayout::eDepthStencilAttachmentOptimal);
auto subpassDescription = vk::SubpassDescription(
vk::SubpassDescriptionFlags(),
vk::PipelineBindPoint::eGraphics,
0,
nullptr,
1,
&colorAttachmentReference,
nullptr,
&depthAttachmentReference,
0,
nullptr);
auto subpassDependency = vk::SubpassDependency(
VK_SUBPASS_EXTERNAL,
0,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::PipelineStageFlagBits::eColorAttachmentOutput,
vk::AccessFlags(),
vk::AccessFlagBits::eColorAttachmentWrite,
vk::DependencyFlags());
auto renderPassCreateInfo = vk::RenderPassCreateInfo(
vk::RenderPassCreateFlags(),
2,
attachmentDescriptions,
1,
&subpassDescription,
1,
&subpassDependency);
auto result = device.createRenderPass(
&renderPassCreateInfo,
nullptr,
&renderPass);
if (result != vk::Result::eSuccess)
{
throw Exception(
THIS_FUNCTION_NAME,
"Failed to create render pass");
}
return renderPass;
}
GpuImageFormat VkGpuSwapchain::getBestDepthFormat(
vk::PhysicalDevice physicalDevice)
{
auto properties = physicalDevice.getFormatProperties(
vk::Format::eD32SfloatS8Uint);
if((properties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment) ==
vk::FormatFeatureFlagBits::eDepthStencilAttachment)
{
return GpuImageFormat::D32S8;
}
properties = physicalDevice.getFormatProperties(
vk::Format::eD24UnormS8Uint);
if((properties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment) ==
vk::FormatFeatureFlagBits::eDepthStencilAttachment)
{
return GpuImageFormat::D24S8;
}
properties = physicalDevice.getFormatProperties(
vk::Format::eD16UnormS8Uint);
if((properties.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment) ==
vk::FormatFeatureFlagBits::eDepthStencilAttachment)
{
return GpuImageFormat::D16S8;
}
throw Exception(
THIS_FUNCTION_NAME,
"No supported depth format");
}
vk::ImageView VkGpuSwapchain::createDepthImageView(
vk::Device device,
vk::Image image,
vk::Format format)
{
vk::ImageView imageView;
auto imageViewCreateInfo = vk::ImageViewCreateInfo(
vk::ImageViewCreateFlags(),
image,
vk::ImageViewType::e2D,
format,
vk::ComponentMapping(),
vk::ImageSubresourceRange(
vk::ImageAspectFlagBits::eDepth,
0,
1,
0,
1));
auto result = device.createImageView(
&imageViewCreateInfo,
nullptr,
&imageView);
if(result != vk::Result::eSuccess)
{
throw Exception(
THIS_FUNCTION_NAME,
"Failed to create image view");
}
return imageView;
}
std::vector<std::shared_ptr<VkSwapchainData>> VkGpuSwapchain::createDatas(
vk::Device device,
vk::SwapchainKHR swapchain,
vk::RenderPass renderPass,
vk::CommandPool graphicsCommandPool,
vk::CommandPool presentCommandPool,
vk::Format format,
vk::ImageView depthImageView,
const vk::Extent2D& extent)
{
auto images = device.getSwapchainImagesKHR(swapchain);
auto datas = std::vector<std::shared_ptr<VkSwapchainData>>(images.size());
for (size_t i = 0; i < images.size(); i++)
{
datas[i] = std::make_shared<VkSwapchainData>(
device,
images[i],
renderPass,
graphicsCommandPool,
presentCommandPool,
format,
depthImageView,
extent);
}
return std::move(datas);
}
VkGpuSwapchain::VkGpuSwapchain() noexcept :
device(),
physicalDevice(),
extent(),
swapchain(),
renderPass(),
depthImage(),
depthImageView(),
datas()
{
}
VkGpuSwapchain::VkGpuSwapchain(
VmaAllocator allocator,
vk::Device _device,
vk::PhysicalDevice _physicalDevice,
vk::SurfaceKHR surface,
vk::CommandPool graphicsCommandPool,
vk::CommandPool presentCommandPool,
const IntVector2& size) :
device(_device),
physicalDevice(_physicalDevice)
{
if(!allocator)
{
throw NullException(
THIS_FUNCTION_NAME,
"allocator");
}
if(!_device)
{
throw NullException(
THIS_FUNCTION_NAME,
"device");
}
if(!_physicalDevice)
{
throw NullException(
THIS_FUNCTION_NAME,
"physicalDevice");
}
if(!surface)
{
throw NullException(
THIS_FUNCTION_NAME,
"surface");
}
if(!graphicsCommandPool)
{
throw NullException(
THIS_FUNCTION_NAME,
"graphicsCommandPool");
}
if(!presentCommandPool)
{
throw NullException(
THIS_FUNCTION_NAME,
"presentCommandPool");
}
auto surfaceFormat = getBestSurfaceFormat(
_physicalDevice,
surface);
auto presentMode = getBestPresentMode(
_physicalDevice,
surface);
auto capabilities =
_physicalDevice.getSurfaceCapabilitiesKHR(surface);
extent = getBestExtent(
capabilities,
size);
auto imageCount = getBestImageCount(capabilities);
auto transform = getBestTransform(capabilities);
auto compositeAlpha = getBestCompositeAlpha(capabilities);
swapchain = createSwapchain(
_device,
surface,
imageCount,
surfaceFormat,
extent,
transform,
compositeAlpha,
presentMode);
auto depthFormat = getBestDepthFormat(_physicalDevice);
auto vkDepthFormat = toVkGpuImageFormat(depthFormat);
depthImage = std::make_shared<VkGpuImage>(
allocator,
vk::ImageUsageFlagBits::eDepthStencilAttachment,
GpuImageType::Image2D,
depthFormat,
SizeVector3(
extent.width,
extent.height,
1));
depthImageView = createDepthImageView(
_device,
depthImage->getImage(),
vkDepthFormat);
renderPass = createRenderPass(
_device,
surfaceFormat.format,
vkDepthFormat);
datas = createDatas(
_device,
swapchain,
renderPass,
graphicsCommandPool,
presentCommandPool,
surfaceFormat.format,
depthImageView,
extent);
}
VkGpuSwapchain::VkGpuSwapchain(
VkGpuSwapchain&& _swapchain) noexcept
{
device = _swapchain.device;
physicalDevice = _swapchain.physicalDevice;
extent = _swapchain.extent;
swapchain = _swapchain.swapchain;
renderPass = _swapchain.renderPass;
depthImage = std::move(_swapchain.depthImage);
depthImageView = _swapchain.depthImageView;
datas = std::move(_swapchain.datas);
_swapchain.device = nullptr;
}
VkGpuSwapchain::~VkGpuSwapchain()
{
datas.clear();
if(device)
{
device.destroyRenderPass(renderPass);
device.destroyImageView(depthImageView);
device.destroySwapchainKHR(swapchain);
}
}
vk::Device VkGpuSwapchain::getDevice() const noexcept
{
return device;
}
vk::PhysicalDevice VkGpuSwapchain::getPhysicalDevice() const noexcept
{
return physicalDevice;
}
const vk::Extent2D& VkGpuSwapchain::getExtent() const noexcept
{
return extent;
}
vk::SwapchainKHR VkGpuSwapchain::getSwapchain() const noexcept
{
return swapchain;
}
vk::RenderPass VkGpuSwapchain::getRenderPass() const noexcept
{
return renderPass;
}
const std::vector<std::shared_ptr<VkSwapchainData>>&
VkGpuSwapchain::getDatas() const noexcept
{
return datas;
}
void VkGpuSwapchain::resize(
VmaAllocator allocator,
vk::SurfaceKHR surface,
vk::CommandPool graphicsCommandPool,
vk::CommandPool presentCommandPool,
const IntVector2& size)
{
if(!device)
{
throw NullException(
THIS_FUNCTION_NAME,
"device");
}
if(!allocator)
{
throw NullException(
THIS_FUNCTION_NAME,
"allocator");
}
if(!graphicsCommandPool)
{
throw NullException(
THIS_FUNCTION_NAME,
"graphicsCommandPool");
}
if(!presentCommandPool)
{
throw NullException(
THIS_FUNCTION_NAME,
"presentCommandPool");
}
datas.clear();
device.destroyRenderPass(renderPass);
device.destroyImageView(depthImageView);
auto surfaceFormat = getBestSurfaceFormat(
physicalDevice,
surface);
auto presentMode = getBestPresentMode(
physicalDevice,
surface);
auto capabilities =
physicalDevice.getSurfaceCapabilitiesKHR(surface);
extent = getBestExtent(
capabilities,
size);
auto imageCount = getBestImageCount(capabilities);
auto transform = getBestTransform(capabilities);
auto compositeAlpha = getBestCompositeAlpha(capabilities);
auto newSwapchain = createSwapchain(
device,
surface,
imageCount,
surfaceFormat,
extent,
transform,
compositeAlpha,
presentMode,
swapchain);
device.destroySwapchainKHR(swapchain);
swapchain = newSwapchain;
auto depthFormat = getBestDepthFormat(physicalDevice);
auto vkDepthFormat = toVkGpuImageFormat(depthFormat);
depthImage = std::make_shared<VkGpuImage>(
allocator,
vk::ImageUsageFlagBits::eDepthStencilAttachment,
GpuImageType::Image2D,
depthFormat,
SizeVector3(
size.x,
size.y,
1));
depthImageView = createDepthImageView(
device,
depthImage->getImage(),
vkDepthFormat);
renderPass = createRenderPass(
device,
surfaceFormat.format,
vkDepthFormat);
datas = createDatas(
device,
swapchain,
renderPass,
graphicsCommandPool,
presentCommandPool,
surfaceFormat.format,
depthImageView,
extent);
}
VkGpuSwapchain& VkGpuSwapchain::operator=(
VkGpuSwapchain&& _swapchain) noexcept
{
if(this != &_swapchain)
{
device = _swapchain.device;
physicalDevice = _swapchain.physicalDevice;
extent = _swapchain.extent;
swapchain = _swapchain.swapchain;
renderPass = _swapchain.renderPass;
depthImage = std::move(_swapchain.depthImage);
depthImageView = _swapchain.depthImageView;
datas = std::move(_swapchain.datas);
_swapchain.device = nullptr;
}
return *this;
}
}
| 23 | 95 | 0.727064 | [
"render",
"vector",
"transform"
] |
97d6e898ed676d44e3797e7a25f5753511839b3b | 6,350 | cpp | C++ | nvblox/src/core/camera.cpp | Isarm/nvblox | 9065b8ec973500d1bbd4abc219558e44b4b55ef6 | [
"Apache-2.0"
] | 83 | 2022-03-23T16:14:00.000Z | 2022-03-31T13:54:26.000Z | nvblox/src/core/camera.cpp | Isarm/nvblox | 9065b8ec973500d1bbd4abc219558e44b4b55ef6 | [
"Apache-2.0"
] | 4 | 2022-03-30T08:58:24.000Z | 2022-03-31T14:04:06.000Z | nvblox/src/core/camera.cpp | Isarm/nvblox | 9065b8ec973500d1bbd4abc219558e44b4b55ef6 | [
"Apache-2.0"
] | 5 | 2022-03-25T00:57:08.000Z | 2022-03-31T09:29:43.000Z | /*
Copyright 2022 NVIDIA CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "nvblox/core/camera.h"
namespace nvblox {
AxisAlignedBoundingBox Camera::getViewAABB(const Transform& T_L_C,
const float min_depth,
const float max_depth) const {
// Get the bounding corners of this view.
Eigen::Matrix<float, 8, 3> corners_C = getViewCorners(min_depth, max_depth);
Vector3f aabb_min, aabb_max;
aabb_min.setConstant(std::numeric_limits<float>::max());
aabb_max.setConstant(std::numeric_limits<float>::lowest());
// Transform it into the layer coordinate frame.
for (size_t i = 0; i < corners_C.rows(); i++) {
const Vector3f& corner_C = corners_C.row(i);
Vector3f corner_L = T_L_C * corner_C;
for (int i = 0; i < 3; i++) {
aabb_min(i) = std::min(aabb_min(i), corner_L(i));
aabb_max(i) = std::max(aabb_max(i), corner_L(i));
}
}
return AxisAlignedBoundingBox(aabb_min, aabb_max);
}
Frustum Camera::getViewFrustum(const Transform& T_L_C, const float min_depth,
const float max_depth) const {
return Frustum(*this, T_L_C, min_depth, max_depth);
}
Eigen::Matrix<float, 8, 3> Camera::getViewCorners(const float min_depth,
const float max_depth) const {
// Rays through the corners of the image plane
// Clockwise from the top left corner of the image.
const Vector3f ray_0_C =
rayFromImagePlaneCoordinates(Vector2f(0.0f, 0.0f)); // NOLINT
const Vector3f ray_1_C =
rayFromImagePlaneCoordinates(Vector2f(width_, 0.0f)); // NOLINT
const Vector3f ray_2_C =
rayFromImagePlaneCoordinates(Vector2f(width_, height_)); // NOLINT
const Vector3f ray_3_C =
rayFromImagePlaneCoordinates(Vector2f(0.0f, height_)); // NOLINT
// True bounding box from the 3D points
Eigen::Matrix<float, 8, 3> corners_C;
corners_C.row(0) = min_depth * ray_2_C;
corners_C.row(1) = min_depth * ray_1_C;
corners_C.row(2) = min_depth * ray_0_C,
corners_C.row(3) = min_depth * ray_3_C;
corners_C.row(4) = max_depth * ray_2_C;
corners_C.row(5) = max_depth * ray_1_C;
corners_C.row(6) = max_depth * ray_0_C;
corners_C.row(7) = max_depth * ray_3_C;
return corners_C;
}
// Frustum definitions.
Frustum::Frustum(const Camera& camera, const Transform& T_L_C, float min_depth,
float max_depth) {
Eigen::Matrix<float, 8, 3> corners_C =
camera.getViewCorners(min_depth, max_depth);
computeBoundingPlanes(corners_C, T_L_C);
}
void Frustum::computeBoundingPlanes(const Eigen::Matrix<float, 8, 3>& corners_C,
const Transform& T_L_C) {
// Transform the corners.
const Eigen::Matrix<float, 8, 3> corners_L =
(T_L_C * corners_C.transpose()).transpose();
// Near plane first.
bounding_planes_L_[0].setFromPoints(corners_L.row(0), corners_L.row(2),
corners_L.row(1));
// Far plane.
bounding_planes_L_[1].setFromPoints(corners_L.row(4), corners_L.row(5),
corners_L.row(6));
// Left.
bounding_planes_L_[2].setFromPoints(corners_L.row(3), corners_L.row(7),
corners_L.row(6));
// Right.
bounding_planes_L_[3].setFromPoints(corners_L.row(0), corners_L.row(5),
corners_L.row(4));
// Top.
bounding_planes_L_[4].setFromPoints(corners_L.row(3), corners_L.row(4),
corners_L.row(7));
// Bottom.
bounding_planes_L_[5].setFromPoints(corners_L.row(2), corners_L.row(6),
corners_L.row(5));
// Calculate AABB.
Vector3f aabb_min, aabb_max;
aabb_min.setConstant(std::numeric_limits<double>::max());
aabb_max.setConstant(std::numeric_limits<double>::lowest());
for (int i = 0; i < corners_L.cols(); i++) {
for (size_t j = 0; j < corners_L.rows(); j++) {
aabb_min(i) = std::min(aabb_min(i), corners_L(j, i));
aabb_max(i) = std::max(aabb_max(i), corners_L(j, i));
}
}
aabb_ = AxisAlignedBoundingBox(aabb_min, aabb_max);
}
bool Frustum::isPointInView(const Vector3f& point) const {
// Skip the AABB check, assume already been done.
for (size_t i = 0; i < bounding_planes_L_.size(); i++) {
if (!bounding_planes_L_[i].isPointInside(point)) {
return false;
}
}
return true;
}
bool Frustum::isAABBInView(const AxisAlignedBoundingBox& aabb) const {
// If we're not even close, don't bother checking the planes.
if (!aabb_.intersects(aabb)) {
return false;
}
constexpr int kNumCorners = 8;
// Check the center of the bounding box to see if it's within the AABB.
// This covers a corner case where the given AABB is larger than the
// frustum.
if (isPointInView(aabb.center())) {
return true;
}
// Iterate over all the corners of the bounding box and see if any are
// within the view frustum.
for (int i = 0; i < kNumCorners; i++) {
if (isPointInView(
aabb.corner(static_cast<Eigen::AlignedBox3f::CornerType>(i)))) {
return true;
}
}
return false;
}
// Bounding plane definitions.
void BoundingPlane::setFromPoints(const Vector3f& p1, const Vector3f& p2,
const Vector3f& p3) {
Vector3f p1p2 = p2 - p1;
Vector3f p1p3 = p3 - p1;
Vector3f cross = p1p2.cross(p1p3);
normal_ = cross.normalized();
distance_ = normal_.dot(p1);
}
void BoundingPlane::setFromDistanceNormal(const Vector3f& normal,
float distance) {
normal_ = normal;
distance_ = distance;
}
bool BoundingPlane::isPointInside(const Vector3f& point) const {
if (point.dot(normal_) >= distance_) {
return true;
}
return false;
}
} // namespace nvblox
| 34.89011 | 80 | 0.648189 | [
"transform",
"3d"
] |
97dd803a4493bdc1ded745b342a378377cd066ee | 6,799 | cpp | C++ | tests/msgpack-lite_test.cpp | Aliceljm1/msgpack-cpp-lite | ee9c5bf150607493c0d1ae1b74fd95f6bbe9fb4f | [
"Apache-2.0"
] | null | null | null | tests/msgpack-lite_test.cpp | Aliceljm1/msgpack-cpp-lite | ee9c5bf150607493c0d1ae1b74fd95f6bbe9fb4f | [
"Apache-2.0"
] | 1 | 2016-05-19T14:03:53.000Z | 2016-05-19T14:03:53.000Z | tests/msgpack-lite_test.cpp | Aliceljm1/msgpack-cpp-lite | ee9c5bf150607493c0d1ae1b74fd95f6bbe9fb4f | [
"Apache-2.0"
] | null | null | null | /**
* @file msgpack-lite_test.hpp
* @author Arturo Blas Jiménez <arturoblas@gmail.com>
* @version 0.1
*
* @section LICENSE
*
* \GPLv3
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* \Apache 2.0
*
* 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 "msgpack/msgpack-lite.hpp"
#include <gtest/gtest.h>
#include <sstream>
#include <limits>
using testing::Types;
/*
--------------------------------------------------------------------
UNIT TESTS
--------------------------------------------------------------------
*/
using namespace msgpack_lite;
struct get_printable {
template<typename T> inline const T& operator()(const T& t) {
return t;
}
inline std::string operator()(const std::wstring& t) {
std::string str;
str.assign(t.begin(), t.end());
return str;
}
};
template<typename T>
class TestHelper
{
public:
TestHelper() :
packer_(ss_), unpacker_(ss_) {
}
virtual void operator()() = 0;
protected:
virtual bool test(const T&input, T& output) = 0;
Packer packer_;
Unpacker unpacker_;
bool run(const T& input) {
T dest;
bool equal = test(input, dest);
if (!equal) {
std::cerr << "Error testing input " << get_printable()(input)
<< "-->" << get_printable()(dest) << std::endl;
}
ss_.str().clear();
return equal;
}
std::stringstream ss_;
};
//////////////////////////////////////////////////////////////////////
template<typename T, int samples = 2048>
class RangeTestHelper: public TestHelper<T>
{
public:
void operator()() {
typedef std::numeric_limits<T> limits;
long double min = limits::min(), max = limits::max();
long double step = ceil((max - min) / (samples));
EXPECT_TRUE(this->run((T) (min)));
EXPECT_TRUE(this->run((T)(max)));
EXPECT_TRUE(this->run((T)(0)));
for (long double i = min; i < max; i += step) {
bool ret = this->run((T) (i));
EXPECT_TRUE(ret);
if (!ret)
break;
}
}
};
//////////////////////////////////////////////////////////////////////
template<typename T>
class TestRange: public testing::Test {
};
// The list of types we want to test.
typedef Types<bool, char, short, int, long, unsigned char, unsigned short,
unsigned int, unsigned long, int8_t, int16_t, int32_t, int64_t, uint8_t,
uint16_t, uint32_t, uint64_t, float, double> TestTypes;
TYPED_TEST_CASE(TestRange, TestTypes);
//////////////////////////////////////////////////////////////////////
TYPED_TEST(TestRange, stream_operator)
{
class StreamOpRangeTestHelper :
public RangeTestHelper<TypeParam>
{
protected:
bool test(const TypeParam&input, TypeParam& output)
{
this->packer_ << input;
this->unpacker_ >> output;
return input == output;
}
};
StreamOpRangeTestHelper test;
test();
}
TYPED_TEST(TestRange, pack_unpack)
{
class PackUnpackRangeTestHelper :
public RangeTestHelper<TypeParam>
{
protected:
bool test(const TypeParam&input, TypeParam& output)
{
this->packer_.pack(input);
this->unpacker_.unpack(output);
return input == output;
}
};
PackUnpackRangeTestHelper test;
test();
}
//////////////////////////////////////////////////////////////////////
template<typename T>
class StringTestHelper: public TestHelper<T>
{
public:
void operator()() {
for (std::size_t i = 0; i < testStrings_.size(); i++) {
T str;
str.assign(testStrings_[i].begin(), testStrings_[i].end());
bool ret = this->run(str);
EXPECT_TRUE(ret);
if (!ret)
break;
}
}
protected:
virtual void SetUp()
{
testStrings_.push_back("");
testStrings_.push_back("a");
testStrings_.push_back("com.uoa.cs.test");
testStrings_.push_back("\n\t\testtest");
testStrings_.push_back("@#$@#&*^*('");
}
// virtual void TearDown() {}
std::vector<std::string> testStrings_;
};
//////////////////////////////////////////////////////////////////////
template<typename T>
class TestStrings: public testing::Test {
};
typedef Types<std::string, std::wstring> StringTypes;
TYPED_TEST_CASE(TestStrings, StringTypes);
//////////////////////////////////////////////////////////////////////
TYPED_TEST(TestStrings, stream_operator)
{
class StreamOpStringTestHelper :
public StringTestHelper<TypeParam>
{
protected:
bool test(const TypeParam&input, TypeParam& output)
{
this->packer_ << input;
this->unpacker_ >> output;
return input == output;
}
};
StreamOpStringTestHelper test;
test();
}
TYPED_TEST(TestStrings, pack_unpack)
{
class PackUnpackStringTestHelper :
public StringTestHelper<TypeParam>
{
protected:
bool test(const TypeParam&input, TypeParam& output)
{
this->packer_.pack(input);
this->unpacker_.unpack(output);
return input == output;
}
};
PackUnpackStringTestHelper test;
test();
}
// TODO: test pointers, parcelable, array and maps
TEST(Examples, example1)
{
Packer packer(std::cout);
int intValue = 0;
packer << intValue;
std::map<char, double> mapValue;
mapValue[0] = 0.0;
mapValue[1] = 1.1;
mapValue[2] = 2.2;
packer << mapValue;
}
TEST(Examples, example2)
{
Packer packer(std::cout);
std::list<int> listValue(10, 0);
packer.pack(listValue.begin(), listValue.end());
}
TEST(Examples, example3)
{
std::stringstream ss;
Unpacker unpacker(ss);
float floatVal;
unpacker >> floatVal;
}
TEST(Examples, example4)
{
std::stringstream ss;
Unpacker unpacker(ss);
while(true)
{
try
{
// Retrieve next object from the stream and display it
Object* obj = unpacker.unpack();
if(obj)
{
switch(obj->getType())
{
// Do stuff here
}
delete obj;
}
}
catch(const unpack_exception& e) // This is thrown when the stream end is reached
{
// We are done!
break;
}
}
}
| 21.180685 | 118 | 0.623474 | [
"object",
"vector"
] |
97e625f06530069f37e44b533d0eaa10a57426ae | 1,450 | cpp | C++ | leetcode/binary-tree/Traversals/987.(BFS)vertical-order-traversal-of-a-binary-tree.cpp | saurabhraj042/dsaPrep | 0973a03bc565a2850003c7e48d99b97ff83b1d01 | [
"MIT"
] | 23 | 2021-10-30T04:11:52.000Z | 2021-11-27T09:16:18.000Z | leetcode/binary-tree/Traversals/987.(BFS)vertical-order-traversal-of-a-binary-tree.cpp | Pawanupadhyay10/placement-prep | 0449fa7cbc56e7933e6b090936ab7c15ca5f290f | [
"MIT"
] | null | null | null | leetcode/binary-tree/Traversals/987.(BFS)vertical-order-traversal-of-a-binary-tree.cpp | Pawanupadhyay10/placement-prep | 0449fa7cbc56e7933e6b090936ab7c15ca5f290f | [
"MIT"
] | 4 | 2021-10-30T03:26:05.000Z | 2021-11-14T12:15:04.000Z | // saurabhraj042
// https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
vector<vector<int>> ans;
// map[col][row] = set of nodes in the resp column
map<int,map<int,multiset<int>>> mp;
queue<pair<TreeNode*,pair<int,int>>> q;
q.push({root,{0,0}});
while(!q.empty()){
auto p = q.front();
q.pop();
TreeNode* node = p.first;
int row = p.second.second;
int col = p.second.first;
mp[col][row].insert(node->val);
if(node->left) q.push({node->left, {col-1, row+1}});
if(node->right) q.push({node->right, {col+1, row+1}});
}
for(auto x:mp){
vector<int> columns;
for(auto z:x.second){
columns.insert(columns.end(),z.second.begin(),z.second.end());
}
ans.push_back(columns);
}
return ans;
}
}; | 30.851064 | 93 | 0.508276 | [
"vector"
] |
97e7a08a8f1bed43f36ee22e15948809990fa0d9 | 1,161 | cpp | C++ | fishmaster.cpp | urnenfeld/theFin | 9ac6c2089cdfb5cac412e51b4ef5674630de70c8 | [
"MIT"
] | null | null | null | fishmaster.cpp | urnenfeld/theFin | 9ac6c2089cdfb5cac412e51b4ef5674630de70c8 | [
"MIT"
] | null | null | null | fishmaster.cpp | urnenfeld/theFin | 9ac6c2089cdfb5cac412e51b4ef5674630de70c8 | [
"MIT"
] | null | null | null |
#include "fishmaster.h"
FishMaster::FishMaster(Context* context)
: Object(context)
, fisherTeam_()
, cachedFishes_()
, index_(0)
{
}
void
FishMaster::RegisterFisher(iFisher& fisher)
{
fisherTeam_.Push(&fisher);
}
Vector<Fish>
FishMaster::RetrieveFishes()
{
cachedFishes_.Clear();
index_ = 0;
for (iFisher* fisher: fisherTeam_) {
cachedFishes_.Push(fisher->RetrieveFishes());
}
return cachedFishes_;
}
void
FishMaster::Rescan()
{
for (iFisher* fisher: fisherTeam_) {
fisher->Rescan();
}
}
const Fish*
FishMaster::Next()
{
if (Valid()) {
index_ = (index_ + 1) % cachedFishes_.Size();
return &cachedFishes_.At(index_);
}
return nullptr;
}
const Fish*
FishMaster::Previous()
{
if (Valid()) {
if (index_ == 0) {
index_ = cachedFishes_.Size() - 1;
} else {
index_ = (index_ - 1) % cachedFishes_.Size();
}
return &cachedFishes_.At(index_);
}
return nullptr;
}
const Fish*
FishMaster::Current()
{
if (Valid()) {
return &cachedFishes_.At(index_);
}
return nullptr;
}
| 13.821429 | 57 | 0.579673 | [
"object",
"vector"
] |
97ea23e0929af507a71a179898ba45babb999fd7 | 10,290 | cpp | C++ | src/compiler/ParserOperator.cpp | LucvandenBrand/OperatorGraph | a15f2c9acfc9265e5ed5cbd89a8d3f7f638cb565 | [
"MIT"
] | null | null | null | src/compiler/ParserOperator.cpp | LucvandenBrand/OperatorGraph | a15f2c9acfc9265e5ed5cbd89a8d3f7f638cb565 | [
"MIT"
] | null | null | null | src/compiler/ParserOperator.cpp | LucvandenBrand/OperatorGraph | a15f2c9acfc9265e5ed5cbd89a8d3f7f638cb565 | [
"MIT"
] | null | null | null | #include <string>
#include <map>
#include <tuple>
#include <boost/variant/get.hpp>
#include <pga/core/Axis.h>
#include <pga/compiler/EnumUtils.h>
#include <pga/compiler/Symbol.h>
#include "ParserUtils.h"
#include "ParserSymbol.h"
#include "ParserOperator.h"
namespace PGA
{
namespace Compiler
{
namespace Parser
{
struct OperatorDescription
{
int numParameters;
int numSuccessors;
bool hasSuccessorParameters;
};
//////////////////////////////////////////////////////////////////////////
// NOTE: Has to follow the same order of the enumerator OperatorType
static OperatorDescription operatorDescriptions[] =
{
/* RESERVED */ { 0, 0, false },
/* TRANSLATE */ { 3, 1, false },
/* ROTATE */ { 3, 1, false },
/* SCALE */ { 3, 1, false },
/* EXTRUDE */ { 1, 1, false },
/* COMPSPLIT */ { 0, 3, false },
/* SUBDIV */ { 1, -1, true },
/* REPEAT */ { 3, 1, false },
/* DISCARD */ { 0, 0, false },
/* IF */ { 1, 2, false },
/* IFSIZELESS */ { 2, 2, false },
/* IFCOLLIDES */ { 1, 3, false },
/* GENERATE */ { 0, 0, false },
/* STOCHASTIC */ { 1, -1, true },
/* SET_AS_DYNAMIC_CONVEX_POLYGON */ { 3, 1, false },
/* SET_AS_DYNAMIC_CONVEX_RIGHT_PRISM */ { 3, 1, false },
/* SET_AS_DYNAMIC_CONCAVE_POLYGON */ { 3, 1, false },
/* SET_AS_DYNAMIC_CONCAVE_RIGHT_PRISM */ { 3, 1, false},
/* COLLIDER */ { 1, 1, false },
/* SWAPSIZE */ { 3, 1, false },
/* REPLICATE */ { 0, -1, false }
};
//////////////////////////////////////////////////////////////////////////
std::shared_ptr<PGA::Compiler::Parameter> createOperatorParameter(Operand operand, OperatorType operatorType, size_t idx)
{
switch (operatorType)
{
case PGA::Compiler::TRANSLATE:
if (idx >= 3)
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): Translate accepts only 3 parameters");
return toParameter(operand);
case PGA::Compiler::ROTATE:
if (idx >= 3)
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): Rotate accepts only 3 parameters");
return toParameter(operand);
case PGA::Compiler::SCALE:
if (idx >= 3)
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): Scale accepts only 3 parameters");
return toParameter(operand);
case PGA::Compiler::EXTRUDE:
// FIXME:
if (idx == 0)
return toParameter(operand);
else
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): Extrude accepts only 1 parameter");
break;
case PGA::Compiler::COMPSPLIT:
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): CompSplit accepts no parameters");
break;
case PGA::Compiler::SUBDIV:
if (idx >= 1)
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): SubDiv accepts only 1 parameter");
return toParameter(operand);
case PGA::Compiler::REPEAT:
if (idx < 3)
return toParameter(operand);
else
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): Repeat accepts only 3 parameter");
break;
case PGA::Compiler::DISCARD:
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): Discard accepts no parameters");
break;
case PGA::Compiler::IF:
if (idx == 0)
return toParameter(operand);
else
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): If accepts only 1 parameter");
break;
case PGA::Compiler::IFSIZELESS:
if (idx < 2)
return toParameter(operand);
else
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): IfSizeLess accepts only 2 parameter");
break;
case PGA::Compiler::IFCOLLIDES:
if (idx == 0)
return toParameter(operand);
else
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): IfCollides accepts only 1 parameter");
break;
case PGA::Compiler::GENERATE:
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): Generate accepts no parameters");
break;
case PGA::Compiler::STOCHASTIC:
if (idx == 0)
return toParameter(operand);
else
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): RandomRule accepts only 1 parameter");
break;
case PGA::Compiler::SET_AS_DYNAMIC_CONVEX_POLYGON:
case PGA::Compiler::SET_AS_DYNAMIC_CONVEX_RIGHT_PRISM:
case PGA::Compiler::SET_AS_DYNAMIC_CONCAVE_POLYGON:
case PGA::Compiler::SET_AS_DYNAMIC_CONCAVE_RIGHT_PRISM:
return toParameter(operand);
case PGA::Compiler::COLLIDER:
if (idx == 0)
return toParameter(operand);
else
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): Collider accepts only 1 parameter");
break;
case PGA::Compiler::SWAPSIZE:
if (idx >= 3)
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): SwapSize accepts only 3 parameters");
return toParameter(operand);
case PGA::Compiler::REPLICATE:
throw std::runtime_error("PGA::Compiler::Grammar::createOperatorParameter(): Replicate accepts no parameters");
break;
default:
break;
}
// FIXME:
return std::shared_ptr<PGA::Compiler::Parameter>();
}
//////////////////////////////////////////////////////////////////////////
void Operator::convertToAbstraction
(
std::vector<PGA::Compiler::Terminal>& terminals,
PGA::Compiler::Operator& operator_,
PGA::Compiler::Rule& rule
) const
{
OperatorType operatorType = static_cast<OperatorType>(this->operator_);
operator_.type = operatorType;
if (operatorType == OperatorType::IFCOLLIDES)
rule.containsIfCollide = true;
for (auto param_it = parameters.begin(); param_it != parameters.end(); ++param_it)
operator_.operatorParams.push_back(createOperatorParameter(*param_it, operatorType, std::distance(parameters.begin(), param_it)));
// FIXME: adding missing fields that should be declared in the grammar...
if (operatorType == OperatorType::EXTRUDE)
operator_.operatorParams.insert(operator_.operatorParams.begin(), std::shared_ptr<PGA::Compiler::Parameter>((new PGA::Compiler::Axis(Z))));
for (auto it1 = successors.begin(); it1 != successors.end(); ++it1)
{
for (auto it2 = it1->parameters.begin(); it2 != it1->parameters.end(); ++it2)
operator_.successorParams.push_back(createOperatorParameter(*it2, operatorType, std::distance(it1->parameters.begin(), it2)));
size_t successorIdx = operator_.successors.size();
std::string terminalName;
switch (it1->successor.which())
{
case 0:
{
terminalName = trim(boost::get<Symbol>(it1->successor).symbol);
std::shared_ptr<PGA::Compiler::Symbol> newSymbol(new PGA::Compiler::Symbol(terminalName));
newSymbol->id = nextSuccessorIdx();
newSymbol->myrule = operator_.myrule;
for (auto it3 = terminals.begin(); it3 != terminals.end(); ++it3)
{
if (std::find(it3->symbols.begin(), it3->symbols.end(), terminalName) != it3->symbols.end())
{
for (const auto& termAttr : it3->parameters)
newSymbol->terminalAttributes.push_back(termAttr);
break;
}
}
operator_.successors.push_back(newSymbol);
break;
}
case 1:
{
Operator op = boost::get<Operator>(it1->successor);
std::shared_ptr<PGA::Compiler::Operator> newOperator(new PGA::Compiler::Operator());
newOperator->id = nextSuccessorIdx();
newOperator->myrule = operator_.myrule;
terminalName = operator_.myrule;
for (auto it3 = terminals.begin(); it3 != terminals.end(); ++it3)
{
if (std::find(it3->symbols.begin(), it3->symbols.end(), terminalName) != it3->symbols.end())
{
newOperator->type = OperatorType::GENERATE;
for (const auto& termAttr : it3->parameters)
newOperator->terminalAttributes.push_back(termAttr);
break;
}
}
operator_.successors.push_back(newOperator);
op.convertToAbstraction(terminals, *newOperator, rule);
break;
}
}
}
}
bool Operator::check(Logger& logger)
{
bool successor = true;
auto operatorType = static_cast<OperatorType>(operator_);
auto operatorDescription = operatorDescriptions[operatorType];
if (parameters.size() < operatorDescription.numParameters)
{
logger.addMessage(Logger::LL_ERROR, "(line = %d, column = %d) %s requires at least %d parameters. %d parameters given", line + 1, column, PGA::Compiler::EnumUtils::toString(operatorType).c_str(), operatorDescription.numParameters, parameters.size());
successor = false;
}
if (operatorDescription.numSuccessors != -1 && operatorDescription.numSuccessors != successors.size())
{
logger.addMessage(Logger::LL_ERROR, "(line = %d, column = %d) %s requires %d successors but %d successors were given", line + 1, column, PGA::Compiler::EnumUtils::toString(operatorType).c_str(), operatorDescription.numSuccessors, parameters.size());
successor = false;
}
for (auto it = successors.begin(); it != successors.end(); ++it)
{
if (operatorDescription.hasSuccessorParameters)
{
if (it->parameters.size() == 0)
{
logger.addMessage(Logger::LL_ERROR, "(line = %d, column = %d) operator %s requires successor parameters", it->line + 1, it->column, PGA::Compiler::EnumUtils::toString(operatorType).c_str());
successor = false;
}
}
else
{
if (it->parameters.size() > 0)
{
logger.addMessage(Logger::LL_ERROR, "(line = %d, column = %d) operator %s cannot have successor parameters", it->line + 1, it->column, PGA::Compiler::EnumUtils::toString(operatorType).c_str());
successor = false;
}
}
}
for (auto it = successors.begin(); it != successors.end(); ++it)
{
if (it->successor.which() == 1)
{
Operator succOp = boost::get<Operator>(it->successor);
successor = succOp.check(logger);
return successor;
}
}
return successor;
}
}
}
} | 37.282609 | 255 | 0.637415 | [
"vector"
] |
97ece12dd2debd52c934ac0dca18200d886ea9c8 | 29,123 | cpp | C++ | src/sdk/flashdb/fdb_tsdb.cpp | southbear-club/aru | 24a3b28d9a168c28435e9cb5b5c10a2e404042a8 | [
"MIT"
] | 2 | 2021-10-21T12:25:23.000Z | 2021-10-22T00:38:35.000Z | src/sdk/flashdb/fdb_tsdb.cpp | southbear-club/aru | 24a3b28d9a168c28435e9cb5b5c10a2e404042a8 | [
"MIT"
] | null | null | null | src/sdk/flashdb/fdb_tsdb.cpp | southbear-club/aru | 24a3b28d9a168c28435e9cb5b5c10a2e404042a8 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020, Armink, <armink.ztl@gmail.com>
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file
* @brief TSDB feature.
*
* Time series log (like TSDB) feature implement source file.
*
* TSL is time series log, the TSDB saved many TSLs.
*/
#include <inttypes.h>
#include <string.h>
#include "ars/sdk/flashdb/flashdb.h"
#include "ars/sdk/flashdb/fdb_low_lvl.h"
#define FDB_LOG_TAG "[tsl]"
/* rewrite log prefix */
#undef FDB_LOG_PREFIX2
#define FDB_LOG_PREFIX2() FDB_PRINT("[%s] ", db_name(db))
#if defined(FDB_USING_TSDB)
/* magic word(`T`, `S`, `L`, `0`) */
#define SECTOR_MAGIC_WORD 0x304C5354
#define TSL_STATUS_TABLE_SIZE FDB_STATUS_TABLE_SIZE(FDB_TSL_STATUS_NUM)
#define SECTOR_HDR_DATA_SIZE (FDB_WG_ALIGN(sizeof(struct sector_hdr_data)))
#define LOG_IDX_DATA_SIZE (FDB_WG_ALIGN(sizeof(struct log_idx_data)))
#define LOG_IDX_TS_OFFSET ((unsigned long)(&((struct log_idx_data *)0)->time))
#define SECTOR_MAGIC_OFFSET ((unsigned long)(&((struct sector_hdr_data *)0)->magic))
#define SECTOR_START_TIME_OFFSET ((unsigned long)(&((struct sector_hdr_data *)0)->start_time))
#define SECTOR_END0_TIME_OFFSET ((unsigned long)(&((struct sector_hdr_data *)0)->end_info[0].time))
#define SECTOR_END0_IDX_OFFSET ((unsigned long)(&((struct sector_hdr_data *)0)->end_info[0].index))
#define SECTOR_END0_STATUS_OFFSET ((unsigned long)(&((struct sector_hdr_data *)0)->end_info[0].status))
#define SECTOR_END1_TIME_OFFSET ((unsigned long)(&((struct sector_hdr_data *)0)->end_info[1].time))
#define SECTOR_END1_IDX_OFFSET ((unsigned long)(&((struct sector_hdr_data *)0)->end_info[1].index))
#define SECTOR_END1_STATUS_OFFSET ((unsigned long)(&((struct sector_hdr_data *)0)->end_info[1].status))
/* the next address is get failed */
#define FAILED_ADDR 0xFFFFFFFF
#define db_name(db) (((fdb_db_t)db)->name)
#define db_init_ok(db) (((fdb_db_t)db)->init_ok)
#define db_sec_size(db) (((fdb_db_t)db)->sec_size)
#define db_max_size(db) (((fdb_db_t)db)->max_size)
#define db_lock(db) \
do { \
if (((fdb_db_t)db)->lock) ((fdb_db_t)db)->lock((fdb_db_t)db); \
} while(0);
#define db_unlock(db) \
do { \
if (((fdb_db_t)db)->unlock) ((fdb_db_t)db)->unlock((fdb_db_t)db); \
} while(0);
#define _FDB_WRITE_STATUS(db, addr, status_table, status_num, status_index) \
do { \
result = _fdb_write_status((fdb_db_t)db, addr, status_table, status_num, status_index);\
if (result != FDB_NO_ERR) return result; \
} while(0);
#define FLASH_WRITE(db, addr, buf, size) \
do { \
result = _fdb_flash_write((fdb_db_t)db, addr, buf, size); \
if (result != FDB_NO_ERR) return result; \
} while(0);
struct sector_hdr_data {
uint8_t status[FDB_STORE_STATUS_TABLE_SIZE]; /**< sector store status @see fdb_sector_store_status_t */
uint32_t magic; /**< magic word(`T`, `S`, `L`, `0`) */
fdb_time_t start_time; /**< the first start node's timestamp */
struct {
fdb_time_t time; /**< the last end node's timestamp */
uint32_t index; /**< the last end node's index */
uint8_t status[TSL_STATUS_TABLE_SIZE]; /**< end node status, @see fdb_tsl_status_t */
} end_info[2];
uint32_t reserved;
};
typedef struct sector_hdr_data *sector_hdr_data_t;
/* time series log node index data */
struct log_idx_data {
uint8_t status_table[TSL_STATUS_TABLE_SIZE]; /**< node status, @see fdb_tsl_status_t */
fdb_time_t time; /**< node timestamp */
uint32_t log_len; /**< node total length (header + name + value), must align by FDB_WRITE_GRAN */
uint32_t log_addr; /**< node address */
};
typedef struct log_idx_data *log_idx_data_t;
struct query_count_args {
fdb_tsl_status_t status;
size_t count;
};
struct check_sec_hdr_cb_args {
fdb_tsdb_t db;
bool check_failed;
size_t empty_num;
uint32_t empty_addr;
};
static fdb_err_t read_tsl(fdb_tsdb_t db, fdb_tsl_t tsl)
{
struct log_idx_data idx;
/* read TSL index raw data */
_fdb_flash_read((fdb_db_t)db, tsl->addr.index, (uint32_t *) &idx, sizeof(struct log_idx_data));
tsl->status = (fdb_tsl_status_t) _fdb_get_status(idx.status_table, FDB_TSL_STATUS_NUM);
if (tsl->status == FDB_TSL_PRE_WRITE) {
tsl->log_len = db->max_len;
tsl->addr.log = FDB_DATA_UNUSED;
tsl->time = 0;
} else {
tsl->log_len = idx.log_len;
tsl->addr.log = idx.log_addr;
tsl->time = idx.time;
}
return FDB_NO_ERR;
}
static uint32_t get_next_sector_addr(fdb_tsdb_t db, tsdb_sec_info_t pre_sec, uint32_t traversed_len)
{
if (traversed_len + db_sec_size(db) <= db_max_size(db)) {
if (pre_sec->addr + db_sec_size(db) < db_max_size(db)) {
return pre_sec->addr + db_sec_size(db);
} else {
/* the next sector is on the top of the partition */
return 0;
}
} else {
/* finished */
return FAILED_ADDR;
}
}
static uint32_t get_next_tsl_addr(tsdb_sec_info_t sector, fdb_tsl_t pre_tsl)
{
uint32_t addr = FAILED_ADDR;
if (sector->status == FDB_SECTOR_STORE_EMPTY) {
return FAILED_ADDR;
}
if (pre_tsl->addr.index + LOG_IDX_DATA_SIZE <= sector->end_idx) {
addr = pre_tsl->addr.index + LOG_IDX_DATA_SIZE;
} else {
/* no TSL */
return FAILED_ADDR;
}
return addr;
}
static fdb_err_t read_sector_info(fdb_tsdb_t db, uint32_t addr, tsdb_sec_info_t sector, bool traversal)
{
fdb_err_t result = FDB_NO_ERR;
struct sector_hdr_data sec_hdr;
FDB_ASSERT(sector);
/* read sector header raw data */
_fdb_flash_read((fdb_db_t)db, addr, (uint32_t *)&sec_hdr, sizeof(struct sector_hdr_data));
sector->addr = addr;
sector->magic = sec_hdr.magic;
/* check magic word */
if (sector->magic != SECTOR_MAGIC_WORD) {
sector->check_ok = false;
return FDB_INIT_FAILED;
}
sector->check_ok = true;
sector->status = (fdb_sector_store_status_t) _fdb_get_status(sec_hdr.status, FDB_SECTOR_STORE_STATUS_NUM);
sector->start_time = sec_hdr.start_time;
sector->end_info_stat[0] = (fdb_tsl_status_t) _fdb_get_status(sec_hdr.end_info[0].status, FDB_TSL_STATUS_NUM);
sector->end_info_stat[1] = (fdb_tsl_status_t) _fdb_get_status(sec_hdr.end_info[1].status, FDB_TSL_STATUS_NUM);
if (sector->end_info_stat[0] == FDB_TSL_WRITE) {
sector->end_time = sec_hdr.end_info[0].time;
sector->end_idx = sec_hdr.end_info[0].index;
} else if (sector->end_info_stat[1] == FDB_TSL_WRITE) {
sector->end_time = sec_hdr.end_info[1].time;
sector->end_idx = sec_hdr.end_info[1].index;
} else if (sector->end_info_stat[0] == FDB_TSL_PRE_WRITE && sector->end_info_stat[1] == FDB_TSL_PRE_WRITE) {
//TODO There is no valid end node info on this sector, need impl fast query this sector by fdb_tsl_iter_by_time
FDB_ASSERT(0);
}
/* traversal all TSL and calculate the remain space size */
sector->empty_idx = sector->addr + SECTOR_HDR_DATA_SIZE;
sector->empty_data = sector->addr + db_sec_size(db);
/* the TSL's data is saved from sector bottom, and the TSL's index saved from the sector top */
sector->remain = sector->empty_data - sector->empty_idx;
if (sector->status == FDB_SECTOR_STORE_USING && traversal) {
struct fdb_tsl tsl;
tsl.addr.index = sector->empty_idx;
while (read_tsl(db, &tsl) == FDB_NO_ERR) {
if (tsl.status == FDB_TSL_UNUSED) {
break;
}
sector->end_time = tsl.time;
sector->end_idx = tsl.addr.index;
sector->empty_idx += LOG_IDX_DATA_SIZE;
sector->empty_data -= FDB_WG_ALIGN(tsl.log_len);
tsl.addr.index += LOG_IDX_DATA_SIZE;
if (sector->remain > LOG_IDX_DATA_SIZE + FDB_WG_ALIGN(tsl.log_len)) {
sector->remain -= (LOG_IDX_DATA_SIZE + FDB_WG_ALIGN(tsl.log_len));
} else {
FDB_INFO("Error: this TSL (0x%08" PRIX32 ") size (%" PRIu32 ") is out of bound.\n", tsl.addr.index, tsl.log_len);
sector->remain = 0;
result = FDB_READ_ERR;
break;
}
}
}
return result;
}
static fdb_err_t format_sector(fdb_tsdb_t db, uint32_t addr)
{
fdb_err_t result = FDB_NO_ERR;
struct sector_hdr_data sec_hdr;
FDB_ASSERT(addr % db_sec_size(db) == 0);
result = _fdb_flash_erase((fdb_db_t)db, addr, db_sec_size(db));
if (result == FDB_NO_ERR) {
_FDB_WRITE_STATUS(db, addr, sec_hdr.status, FDB_SECTOR_STORE_STATUS_NUM, FDB_SECTOR_STORE_EMPTY);
/* set the magic */
sec_hdr.magic = SECTOR_MAGIC_WORD;
FLASH_WRITE(db, addr + SECTOR_MAGIC_OFFSET, &sec_hdr.magic, sizeof(sec_hdr.magic));
}
return result;
}
static void sector_iterator(fdb_tsdb_t db, tsdb_sec_info_t sector, fdb_sector_store_status_t status, void *arg1,
void *arg2, bool (*callback)(tsdb_sec_info_t sector, void *arg1, void *arg2), bool traversal)
{
uint32_t sec_addr = sector->addr, traversed_len = 0;
/* search all sectors */
do {
read_sector_info(db, sec_addr, sector, false);
if (status == FDB_SECTOR_STORE_UNUSED || status == sector->status) {
if (traversal) {
read_sector_info(db, sec_addr, sector, true);
}
/* iterator is interrupted when callback return true */
if (callback && callback(sector, arg1, arg2)) {
return;
}
}
traversed_len += db_sec_size(db);
} while ((sec_addr = get_next_sector_addr(db, sector, traversed_len)) != FAILED_ADDR);
}
static fdb_err_t write_tsl(fdb_tsdb_t db, fdb_blob_t blob, fdb_time_t time)
{
fdb_err_t result = FDB_NO_ERR;
struct log_idx_data idx;
uint32_t idx_addr = db->cur_sec.empty_idx;
idx.log_len = blob->size;
idx.time = time;
idx.log_addr = db->cur_sec.empty_data - FDB_WG_ALIGN(idx.log_len);
/* write the status will by write granularity */
_FDB_WRITE_STATUS(db, idx_addr, idx.status_table, FDB_TSL_STATUS_NUM, FDB_TSL_PRE_WRITE);
/* write other index info */
FLASH_WRITE(db, idx_addr + LOG_IDX_TS_OFFSET, &idx.time, sizeof(struct log_idx_data) - LOG_IDX_TS_OFFSET);
/* write blob data */
FLASH_WRITE(db, idx.log_addr, blob->buf, blob->size);
/* write the status will by write granularity */
_FDB_WRITE_STATUS(db, idx_addr, idx.status_table, FDB_TSL_STATUS_NUM, FDB_TSL_WRITE);
return result;
}
static fdb_err_t update_sec_status(fdb_tsdb_t db, tsdb_sec_info_t sector, fdb_blob_t blob, fdb_time_t cur_time)
{
fdb_err_t result = FDB_NO_ERR;
uint8_t status[FDB_STORE_STATUS_TABLE_SIZE];
if (sector->status == FDB_SECTOR_STORE_USING && sector->remain < LOG_IDX_DATA_SIZE + FDB_WG_ALIGN(blob->size)) {
if (db->rollover) {
uint8_t end_status[TSL_STATUS_TABLE_SIZE];
uint32_t end_index = sector->empty_idx - LOG_IDX_DATA_SIZE, new_sec_addr, cur_sec_addr = sector->addr;
/* save the end node index and timestamp */
if (sector->end_info_stat[0] == FDB_TSL_UNUSED) {
_FDB_WRITE_STATUS(db, cur_sec_addr + SECTOR_END0_STATUS_OFFSET, end_status, FDB_TSL_STATUS_NUM, FDB_TSL_PRE_WRITE);
FLASH_WRITE(db, cur_sec_addr + SECTOR_END0_TIME_OFFSET, (uint32_t * )&db->last_time, sizeof(fdb_time_t));
FLASH_WRITE(db, cur_sec_addr + SECTOR_END0_IDX_OFFSET, &end_index, sizeof(end_index));
_FDB_WRITE_STATUS(db, cur_sec_addr + SECTOR_END0_STATUS_OFFSET, end_status, FDB_TSL_STATUS_NUM, FDB_TSL_WRITE);
} else if (sector->end_info_stat[1] == FDB_TSL_UNUSED) {
_FDB_WRITE_STATUS(db, cur_sec_addr + SECTOR_END1_STATUS_OFFSET, end_status, FDB_TSL_STATUS_NUM, FDB_TSL_PRE_WRITE);
FLASH_WRITE(db, cur_sec_addr + SECTOR_END1_TIME_OFFSET, (uint32_t * )&db->last_time, sizeof(fdb_time_t));
FLASH_WRITE(db, cur_sec_addr + SECTOR_END1_IDX_OFFSET, &end_index, sizeof(end_index));
_FDB_WRITE_STATUS(db, cur_sec_addr + SECTOR_END1_STATUS_OFFSET, end_status, FDB_TSL_STATUS_NUM, FDB_TSL_WRITE);
}
/* change current sector to full */
_FDB_WRITE_STATUS(db, cur_sec_addr, status, FDB_SECTOR_STORE_STATUS_NUM, FDB_SECTOR_STORE_FULL);
/* calculate next sector address */
if (sector->addr + db_sec_size(db) < db_max_size(db)) {
new_sec_addr = sector->addr + db_sec_size(db);
} else {
new_sec_addr = 0;
}
read_sector_info(db, new_sec_addr, &db->cur_sec, false);
if (sector->status != FDB_SECTOR_STORE_EMPTY) {
/* calculate the oldest sector address */
if (new_sec_addr + db_sec_size(db) < db_max_size(db)) {
db->oldest_addr = new_sec_addr + db_sec_size(db);
} else {
db->oldest_addr = 0;
}
format_sector(db, new_sec_addr);
read_sector_info(db, new_sec_addr, &db->cur_sec, false);
}
} else {
/* not rollover */
return FDB_SAVED_FULL;
}
}
if (sector->status == FDB_SECTOR_STORE_EMPTY) {
/* change the sector to using */
sector->status = FDB_SECTOR_STORE_USING;
sector->start_time = cur_time;
_FDB_WRITE_STATUS(db, sector->addr, status, FDB_SECTOR_STORE_STATUS_NUM, FDB_SECTOR_STORE_USING);
/* save the start timestamp */
FLASH_WRITE(db, sector->addr + SECTOR_START_TIME_OFFSET, (uint32_t *)&cur_time, sizeof(fdb_time_t));
}
return result;
}
static fdb_err_t tsl_append(fdb_tsdb_t db, fdb_blob_t blob)
{
fdb_err_t result = FDB_NO_ERR;
fdb_time_t cur_time = db->get_time();
FDB_ASSERT(blob->size <= db->max_len);
result = update_sec_status(db, &db->cur_sec, blob, cur_time);
if (result != FDB_NO_ERR) {
return result;
}
/* write the TSL node */
result = write_tsl(db, blob, cur_time);
if (result != FDB_NO_ERR) {
return result;
}
/* recalculate the current using sector info */
db->cur_sec.end_idx = db->cur_sec.empty_idx;
db->cur_sec.end_time = cur_time;
db->cur_sec.empty_idx += LOG_IDX_DATA_SIZE;
db->cur_sec.empty_data -= FDB_WG_ALIGN(blob->size);
db->cur_sec.remain -= LOG_IDX_DATA_SIZE + FDB_WG_ALIGN(blob->size);
if (cur_time >= db->last_time) {
db->last_time = cur_time;
} else {
FDB_INFO("Warning: current timestamp (%" PRIdMAX ") is less than the last save timestamp (%" PRIdMAX ")\n", (intmax_t)cur_time, (intmax_t)(db->last_time));
}
return result;
}
/**
* Append a new log to TSDB.
*
* @param db database object
* @param blob log blob data
*
* @return result
*/
fdb_err_t fdb_tsl_append(fdb_tsdb_t db, fdb_blob_t blob)
{
fdb_err_t result = FDB_NO_ERR;
if (!db_init_ok(db)) {
FDB_INFO("Error: TSL (%s) isn't initialize OK.\n", db_name(db));
return FDB_INIT_FAILED;
}
db_lock(db);
result = tsl_append(db, blob);
db_unlock(db);
return result;
}
/**
* The TSDB iterator for each TSL.
*
* @param db database object
* @param cb callback
* @param arg callback argument
*/
void fdb_tsl_iter(fdb_tsdb_t db, fdb_tsl_cb cb, void *arg)
{
struct tsdb_sec_info sector;
uint32_t sec_addr, traversed_len = 0;
struct fdb_tsl tsl;
if (!db_init_ok(db)) {
FDB_INFO("Error: TSL (%s) isn't initialize OK.\n", db_name(db));
}
if (cb == NULL) {
return;
}
sec_addr = db->oldest_addr;
/* search all sectors */
do {
traversed_len += db_sec_size(db);
if (read_sector_info(db, sec_addr, §or, false) != FDB_NO_ERR) {
continue;
}
/* sector has TSL */
if (sector.status == FDB_SECTOR_STORE_USING || sector.status == FDB_SECTOR_STORE_FULL) {
if (sector.status == FDB_SECTOR_STORE_USING) {
/* copy the current using sector status */
sector = db->cur_sec;
}
tsl.addr.index = sector.addr + SECTOR_HDR_DATA_SIZE;
/* search all TSL */
do {
read_tsl(db, &tsl);
/* iterator is interrupted when callback return true */
if (cb(&tsl, arg)) {
return;
}
} while ((tsl.addr.index = get_next_tsl_addr(§or, &tsl)) != FAILED_ADDR);
}
} while ((sec_addr = get_next_sector_addr(db, §or, traversed_len)) != FAILED_ADDR);
}
/**
* The TSDB iterator for each TSL by timestamp.
*
* @param db database object
* @param from starting timestap
* @param to ending timestap
* @param cb callback
* @param arg callback argument
*/
void fdb_tsl_iter_by_time(fdb_tsdb_t db, fdb_time_t from, fdb_time_t to, fdb_tsl_cb cb, void *cb_arg)
{
struct tsdb_sec_info sector;
uint32_t sec_addr, oldest_addr = db->oldest_addr, traversed_len = 0;
struct fdb_tsl tsl;
bool found_start_tsl = false;
if (!db_init_ok(db)) {
FDB_INFO("Error: TSL (%s) isn't initialize OK.\n", db_name(db));
}
// FDB_INFO("from %s", ctime((const time_t * )&from));
// FDB_INFO("to %s", ctime((const time_t * )&to));
if (cb == NULL) {
return;
}
sec_addr = oldest_addr;
/* search all sectors */
do {
traversed_len += db_sec_size(db);
if (read_sector_info(db, sec_addr, §or, false) != FDB_NO_ERR) {
continue;
}
/* sector has TSL */
if ((sector.status == FDB_SECTOR_STORE_USING || sector.status == FDB_SECTOR_STORE_FULL)) {
if (sector.status == FDB_SECTOR_STORE_USING) {
/* copy the current using sector status */
sector = db->cur_sec;
}
if ((found_start_tsl) || (!found_start_tsl && ((from >= sector.start_time && from <= sector.end_time)
|| (sec_addr == oldest_addr && from <= sector.start_time)))) {
uint32_t start = sector.addr + SECTOR_HDR_DATA_SIZE, end = sector.end_idx;
found_start_tsl = true;
/* search start TSL address, using binary search algorithm */
while (start <= end) {
tsl.addr.index = start + ((end - start) / 2 + 1) / LOG_IDX_DATA_SIZE * LOG_IDX_DATA_SIZE;
read_tsl(db, &tsl);
if (tsl.time < from) {
start = tsl.addr.index + LOG_IDX_DATA_SIZE;
} else {
end = tsl.addr.index - LOG_IDX_DATA_SIZE;
}
}
tsl.addr.index = start;
/* search all TSL */
do {
read_tsl(db, &tsl);
if (tsl.time >= from && tsl.time <= to) {
/* iterator is interrupted when callback return true */
if (cb(&tsl, cb_arg)) {
return;
}
} else {
return;
}
} while ((tsl.addr.index = get_next_tsl_addr(§or, &tsl)) != FAILED_ADDR);
}
} else if (sector.status == FDB_SECTOR_STORE_EMPTY) {
return;
}
} while ((sec_addr = get_next_sector_addr(db, §or, traversed_len)) != FAILED_ADDR);
}
static bool query_count_cb(fdb_tsl_t tsl, void *arg)
{
struct query_count_args *args = (struct query_count_args *)arg;
if (tsl->status == args->status) {
args->count++;
}
return false;
}
/**
* Query some TSL's count by timestamp and status.
*
* @param db database object
* @param from starting timestap
* @param to ending timestap
* @param status status
*/
size_t fdb_tsl_query_count(fdb_tsdb_t db, fdb_time_t from, fdb_time_t to, fdb_tsl_status_t status)
{
struct query_count_args arg = { FDB_TSL_UNUSED, 0 };
arg.status = status;
if (!db_init_ok(db)) {
FDB_INFO("Error: TSL (%s) isn't initialize OK.\n", db_name(db));
return FDB_INIT_FAILED;
}
fdb_tsl_iter_by_time(db, from, to, query_count_cb, &arg);
return arg.count;
}
/**
* Set the TSL status.
*
* @param db database object
* @param tsl TSL object
* @param status status
*
* @return result
*/
fdb_err_t fdb_tsl_set_status(fdb_tsdb_t db, fdb_tsl_t tsl, fdb_tsl_status_t status)
{
fdb_err_t result = FDB_NO_ERR;
uint8_t status_table[TSL_STATUS_TABLE_SIZE];
/* write the status will by write granularity */
_FDB_WRITE_STATUS(db, tsl->addr.index, status_table, FDB_TSL_STATUS_NUM, status);
return result;
}
/**
* Convert the TSL object to blob object
*
* @param tsl TSL object
* @param blob blob object
*
* @return new blob object
*/
fdb_blob_t fdb_tsl_to_blob(fdb_tsl_t tsl, fdb_blob_t blob)
{
blob->saved.addr = tsl->addr.log;
blob->saved.meta_addr = tsl->addr.index;
blob->saved.len = tsl->log_len;
return blob;
}
static bool check_sec_hdr_cb(tsdb_sec_info_t sector, void *arg1, void *arg2)
{
struct check_sec_hdr_cb_args *arg = (struct check_sec_hdr_cb_args *)arg1;
fdb_tsdb_t db = arg->db;
if (!sector->check_ok) {
FDB_INFO("Sector (0x%08" PRIu32 ") header info is incorrect.\n", sector->addr);
(arg->check_failed) = true;
return true;
} else if (sector->status == FDB_SECTOR_STORE_USING) {
if (db->cur_sec.addr == FDB_DATA_UNUSED) {
memcpy(&db->cur_sec, sector, sizeof(struct tsdb_sec_info));
} else {
FDB_INFO("Warning: Sector status is wrong, there are multiple sectors in use.\n");
(arg->check_failed) = true;
return true;
}
} else if (sector->status == FDB_SECTOR_STORE_EMPTY) {
(arg->empty_num) += 1;
arg->empty_addr = sector->addr;
if ((arg->empty_num) == 1 && db->cur_sec.addr == FDB_DATA_UNUSED) {
memcpy(&db->cur_sec, sector, sizeof(struct tsdb_sec_info));
}
}
return false;
}
static bool format_all_cb(tsdb_sec_info_t sector, void *arg1, void *arg2)
{
fdb_tsdb_t db = (fdb_tsdb_t)arg1;
format_sector(db, sector->addr);
return false;
}
static void tsl_format_all(fdb_tsdb_t db)
{
struct tsdb_sec_info sector;
sector.addr = 0;
sector_iterator(db, §or, FDB_SECTOR_STORE_UNUSED, db, NULL, format_all_cb, false);
db->oldest_addr = 0;
db->cur_sec.addr = 0;
db->last_time = 0;
/* read the current using sector info */
read_sector_info(db, db->cur_sec.addr, &db->cur_sec, false);
FDB_INFO("All sector format finished.\n");
}
/**
* Clean all the data in the TSDB.
*
* @note It's DANGEROUS. This operation is not reversible.
*
* @param db database object
*/
void fdb_tsl_clean(fdb_tsdb_t db)
{
db_lock(db);
tsl_format_all(db);
db_unlock(db);
}
/**
* This function will get or set some options of the database
*
* @param db database object
* @param cmd the control command
* @param arg the argument
*/
void fdb_tsdb_control(fdb_tsdb_t db, int cmd, void *arg)
{
FDB_ASSERT(db);
switch (cmd) {
case FDB_TSDB_CTRL_SET_SEC_SIZE:
/* this change MUST before database initialization */
FDB_ASSERT(db->parent.init_ok == false);
db->parent.sec_size = *(uint32_t *)arg;
break;
case FDB_TSDB_CTRL_GET_SEC_SIZE:
*(uint32_t *)arg = db->parent.sec_size;
break;
case FDB_TSDB_CTRL_SET_LOCK:
db->parent.lock = (void (*)(fdb_db_t db))arg;
break;
case FDB_TSDB_CTRL_SET_UNLOCK:
db->parent.unlock = (void (*)(fdb_db_t db))arg;
break;
case FDB_TSDB_CTRL_SET_ROLLOVER:
db->rollover = *(bool *)arg;
break;
case FDB_TSDB_CTRL_GET_ROLLOVER:
*(bool *)arg = db->rollover;
break;
case FDB_TSDB_CTRL_GET_LAST_TIME:
*(fdb_time_t *)arg = db->last_time;
break;
case FDB_TSDB_CTRL_SET_FILE_MODE:
#ifdef FDB_USING_FILE_MODE
/* this change MUST before database initialization */
FDB_ASSERT(db->parent.init_ok == false);
db->parent.file_mode = *(bool *)arg;
#else
FDB_INFO("Error: set file mode Failed. Please defined the FDB_USING_FILE_MODE macro.");
#endif
break;
case FDB_TSDB_CTRL_SET_MAX_SIZE:
#ifdef FDB_USING_FILE_MODE
/* this change MUST before database initialization */
FDB_ASSERT(db->parent.init_ok == false);
db->parent.max_size = *(uint32_t *)arg;
#endif
break;
case FDB_TSDB_CTRL_SET_NOT_FORMAT:
/* this change MUST before database initialization */
FDB_ASSERT(db->parent.init_ok == false);
db->parent.not_formatable = *(bool *)arg;
break;
}
}
/**
* The time series database initialization.
*
* @param db database object
* @param name database name
* @param part_name partition name
* @param get_time get current time function
* @param max_len maximum length of each log
* @param user_data user data
*
* @return result
*/
fdb_err_t fdb_tsdb_init(fdb_tsdb_t db, const char *name, const char *part_name, fdb_get_time get_time, size_t max_len, void *user_data)
{
fdb_err_t result = FDB_NO_ERR;
struct tsdb_sec_info sector;
struct check_sec_hdr_cb_args check_sec_arg = { db, false, 0, 0};
FDB_ASSERT(get_time);
result = _fdb_init_ex((fdb_db_t)db, name, part_name, FDB_DB_TYPE_TS, user_data);
if (result != FDB_NO_ERR) {
goto __exit;
}
db->get_time = get_time;
db->max_len = max_len;
/* default rollover flag is true */
db->rollover = true;
db->oldest_addr = FDB_DATA_UNUSED;
db->cur_sec.addr = FDB_DATA_UNUSED;
/* must less than sector size */
FDB_ASSERT(max_len < db_sec_size(db));
/* check all sector header */
sector.addr = 0;
sector_iterator(db, §or, FDB_SECTOR_STORE_UNUSED, &check_sec_arg, NULL, check_sec_hdr_cb, true);
/* format all sector when check failed */
if (check_sec_arg.check_failed) {
if (db->parent.not_formatable) {
result = FDB_READ_ERR;
goto __exit;
} else {
tsl_format_all(db);
}
} else {
uint32_t latest_addr;
if (check_sec_arg.empty_num > 0) {
latest_addr = check_sec_arg.empty_addr;
} else {
latest_addr = db->cur_sec.addr;
}
/* db->cur_sec is the latest sector, and the next is the oldest sector */
if (latest_addr + db_sec_size(db) >= db_max_size(db)) {
/* db->cur_sec is the the bottom of the partition */
db->oldest_addr = 0;
} else {
db->oldest_addr = latest_addr + db_sec_size(db);
}
}
FDB_DEBUG("TSDB (%s) oldest sectors is 0x%08" PRIX32 ", current using sector is 0x%08" PRIX32 ".\n", db_name(db), db->oldest_addr,
db->cur_sec.addr);
/* read the current using sector info */
read_sector_info(db, db->cur_sec.addr, &db->cur_sec, true);
/* get last save time */
if (db->cur_sec.status == FDB_SECTOR_STORE_USING) {
db->last_time = db->cur_sec.end_time;
} else if (db->cur_sec.status == FDB_SECTOR_STORE_EMPTY && db->oldest_addr != db->cur_sec.addr) {
struct tsdb_sec_info sec;
uint32_t addr = db->cur_sec.addr;
if (addr == 0) {
addr = db_max_size(db) - db_sec_size(db);
} else {
addr -= db_sec_size(db);
}
read_sector_info(db, addr, &sec, false);
db->last_time = sec.end_time;
}
__exit:
_fdb_init_finish((fdb_db_t)db, result);
return result;
}
/**
* The time series database deinitialization.
*
* @param db database object
*
* @return result
*/
fdb_err_t fdb_tsdb_deinit(fdb_tsdb_t db)
{
_fdb_deinit((fdb_db_t) db);
return FDB_NO_ERR;
}
#endif /* defined(FDB_USING_TSDB) */
| 35.386391 | 163 | 0.608419 | [
"object"
] |
97fef56c60dc363d05607d2996495d63d39e8d5a | 8,542 | cpp | C++ | src/callbacks/callback_gradient_check.cpp | andy-yoo/lbann-andy | 237c45c392e7a5548796ac29537ab0a374e7e825 | [
"Apache-2.0"
] | null | null | null | src/callbacks/callback_gradient_check.cpp | andy-yoo/lbann-andy | 237c45c392e7a5548796ac29537ab0a374e7e825 | [
"Apache-2.0"
] | null | null | null | src/callbacks/callback_gradient_check.cpp | andy-yoo/lbann-andy | 237c45c392e7a5548796ac29537ab0a374e7e825 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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.
//
// lbann_callback_gradient_check .hpp .cpp - Callback hooks for gradient check
////////////////////////////////////////////////////////////////////////////////
#include "lbann/callbacks/callback_gradient_check.hpp"
namespace lbann {
lbann_callback_gradient_check::lbann_callback_gradient_check(DataType step_size,
bool verbose,
bool fail_on_error)
: m_step_size(step_size),
m_verbose(verbose),
m_fail_on_error(fail_on_error) {}
void lbann_callback_gradient_check::on_test_begin(model *m) {
// Get model members
lbann_comm *comm = m->get_comm();
const std::vector<Layer*>& layers = m->get_layers();
// Initialize network for testing
for (auto&& w : m->get_weights()) {
auto&& opt = w->get_optimizer();
if (opt != nullptr) { opt->clear_gradient(); }
}
layers[0]->forward_prop();
// Compute objective function
const DataType objective = compute_objective_function(m);
// Choose finite difference step
// Note: Consider a central difference scheme:
// f'(x) ~ ( - f(x+2h) + 8 f(x+h) - 8 f(x-h) + f(x-2h) ) / 12h
// By Taylor's theorem, the truncation error is bounded by
// E_trunc <= | f'''''(xi) | / 18 * h^4
// Assuming f can be computed to a relative accuracy of epsilon,
// E_fl <= epsilon * | f(chi) | / h
// For simplicity, we assume f(chi) ~ f(x), and | f'''''(xi) | ~ 1.
// If step size is not specified, then we choose h so that
// E_fl <= sqrt(epsilon)
const DataType epsilon = std::pow(std::numeric_limits<DataType>::epsilon(), 0.9);
DataType step_size = m_step_size;
if (m_step_size <= DataType(0)) {
step_size = std::fabs(objective) * std::sqrt(epsilon);
}
DataType expected_error = (epsilon * objective / step_size
+ std::pow(step_size, 4) / 18);
expected_error = std::pow(expected_error, 0.9);
// Compute gradients
m->get_objective_function()->differentiate();
m->get_objective_function()->compute_weight_regularization();
for (int l = layers.size() - 1; l > 0; --l) {
layers[l]->back_prop();
}
// Print objective function value
if (comm->am_world_master()) {
std::cout << "--------------------------------------------------------------------------------" << std::endl
<< "Gradient checking..." << std::endl
<< " Objective function value = " << objective << std::endl
<< " Step size = " << step_size << std::endl
<< " Expected gradient error = " << expected_error << std::endl;
}
for (weights *w : m->get_weights()) {
if (w->get_optimizer() == nullptr) {
continue;
}
if (comm->am_world_master()) {
std::cout << "Checking " << w->get_name() << std::endl;
}
// Get weights matrix and gradient
const AbsDistMat& weights_matrix = w->get_values();
const AbsDistMat& gradient = w->get_optimizer()->get_gradient();
// Iterate through weights matrix entries
for (El::Int col = 0; col < weights_matrix.Width(); ++col) {
for (El::Int row = 0; row < weights_matrix.Height(); ++row) {
const bool weight_is_local = weights_matrix.IsLocal(row, col);
const El::Int local_row = (weight_is_local ?
weights_matrix.LocalRow(row) :
0);
const El::Int local_col = (weight_is_local ?
weights_matrix.LocalCol(col) :
0);
const DataType initial_weight = (weight_is_local ?
weights_matrix.GetLocal(local_row,
local_col) :
DataType(0));
// Compute objective function values
// Note: matrix entry is reset after computing objective
// function values
w->set_value(initial_weight + 2 * step_size, row, col);
const DataType f_2h = compute_objective_function(m);
w->set_value(initial_weight + step_size, row, col);
const DataType f_h = compute_objective_function(m);
w->set_value(initial_weight - step_size, row, col);
const DataType f_nh = compute_objective_function(m);
w->set_value(initial_weight - 2 * step_size, row, col);
const DataType f_n2h = compute_objective_function(m);
w->set_value(initial_weight, row, col);
// Compute relative error in gradient.
// Note: only weight owner participates
if (weight_is_local && weights_matrix.RedundantRank() == 0) {
const DataType analytical_gradient
= gradient.GetLocal(local_row, local_col);
const DataType numerical_gradient
= (- f_2h + 8 * f_h - 8 * f_nh + f_n2h) / (12 * step_size);
const DataType error = std::fabs(analytical_gradient - numerical_gradient);
auto relative_error = DataType(0);
if (error != DataType(0)) {
relative_error = error / std::max(std::fabs(analytical_gradient),
std::fabs(numerical_gradient));
}
// Print warning if relative error is large
if (error > expected_error || std::isnan(error) || std::isinf(error)) {
std::cout << " GRADIENT ERROR: " << w->get_name() << ", "
<< "entry (" << row << "," << col << ")" << std::endl;
std::cout << " Weight = " << initial_weight << std::endl
<< " Analytical gradient = " << analytical_gradient << std::endl
<< " Numerical gradient = " << numerical_gradient << std::endl
<< " Error = " << error << std::endl
<< " Relative error = " << relative_error << std::endl;
if (m_fail_on_error) {
throw lbann_exception("callback_gradient_check: found large error in gradient");
}
} else if (m_verbose) {
std::cout << " " << w->get_name() << ", "
<< "entry (" << row << "," << col << ")" << std::endl;
std::cout << " Weight = " << initial_weight << std::endl
<< " Analytical gradient = " << analytical_gradient << std::endl
<< " Numerical gradient = " << numerical_gradient << std::endl
<< " Error = " << error << std::endl
<< " Relative error = " << relative_error << std::endl;
}
}
}
}
}
if (comm->am_world_master()) {
std::cout << "--------------------------------------------------------------------------------" << std::endl;
}
}
DataType lbann_callback_gradient_check::compute_objective_function(model *m) {
const std::vector<Layer*>& layers = m->get_layers();
objective_function* obj_fn = m->get_objective_function();
for (size_t l = 1; l < layers.size(); l++) {
layers[l]->forward_prop();
}
obj_fn->start_evaluation(m->get_execution_mode(),
m->get_current_mini_batch_size());
return obj_fn->finish_evaluation(m->get_execution_mode(),
m->get_current_mini_batch_size());
}
} // namespace lbann
| 44.489583 | 113 | 0.549871 | [
"vector",
"model"
] |
97ff04f059b686a80355f9c923c9e11248200e55 | 2,060 | cpp | C++ | card.cpp | guiqiqi/DurakRobot | 4eaad895cf78bbcc6897944877e9a88a8f617ce0 | [
"MIT"
] | 3 | 2020-02-29T04:28:38.000Z | 2021-05-29T07:35:11.000Z | card.cpp | guiqiqi/DurakRobot | 4eaad895cf78bbcc6897944877e9a88a8f617ce0 | [
"MIT"
] | null | null | null | card.cpp | guiqiqi/DurakRobot | 4eaad895cf78bbcc6897944877e9a88a8f617ce0 | [
"MIT"
] | 1 | 2021-05-30T04:33:23.000Z | 2021-05-30T04:33:23.000Z |
#include "card.h"
int iCard::compare(const iCard* first, const iCard* second) {
return (global::iranks[first->_rank] - global::iranks[second->_rank]);
}
iCard::iCard(std::string suit, std::string rank) {
this->_rank = rank; this->_suit = suit;
}
std::string iCard::rank(void) const {
return this->_rank;
}
std::string iCard::suit(void) const {
return this->_suit;
}
bool iCard::operator>(const iCard*& card) {
int diff = this->compare(this, card);
if (diff > 0) return true;
return false;
}
bool iCard::operator<(const iCard*& card) {
int diff = this->compare(this, card);
if (diff < 0) return true;
return false;
}
bool iCard::operator>=(const iCard*& card) {
int diff = this->compare(this, card);
if (diff >= 0) return true;
return false;
}
bool iCard::operator<=(const iCard*& card) {
int diff = this->compare(this, card);
if (diff <= 0) return true;
return false;
}
bool iCard::operator==(const iCard*& card) {
int diff = this->compare(this, card);
if (diff == 0) return true;
return false;
}
std::ostream& operator<<(std::ostream& out, const iCard& card) {
out << card._suit << ' ' << card._rank;
return out;
}
CardManager::CardManager(void) {
for (auto& suit : global::suits) {
for (auto& rank : global::ranks) {
iCard* card = new iCard(suit, rank);
auto key = std::make_pair(suit, rank);
this->library[key] = card;
this->all.push_back(card);
}
}
}
// Free all memory
CardManager::~CardManager(void) {
for (auto& card : this->all)
delete card;
}
// Get copy for all cards
std::vector<iCard*> CardManager::getall(void) {
return this->all;
}
// Get the memory reference of the specified card
iCard* CardManager::get(std::string& suit, std::string& rank) {
auto key = std::make_pair(suit, rank);
// If found card
if (this->library.find(key) != this->library.end())
return this->library[key];
return nullptr;
}
iCard* CardManager::get(std::pair<std::string, std::string>& key) {
return this->library[key];
}
| 23.678161 | 72 | 0.63301 | [
"vector"
] |
3f03755e69a3068c38a29fe7d43553dbfa0a8ff1 | 387,908 | cpp | C++ | external/swak/libraries/swakParsers/bison/SubsetValueExpressionParser.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/swakParsers/bison/SubsetValueExpressionParser.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/swak/libraries/swakParsers/bison/SubsetValueExpressionParser.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /* A Bison parser, made by GNU Bison 2.5. */
/* Skeleton implementation for Bison LALR(1) parsers in C++
Copyright (C) 2002-2011 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
// Take the name prefix into account.
#define yylex parserSubsetlex
/* First part of user declarations. */
/* Line 293 of lalr1.cc */
#line 40 "../SubsetValueExpressionParser.yy"
#include <volFields.hpp>
#include <functional>
#include <cmath>
namespace CML {
class SubsetValueExpressionDriver;
}
const CML::scalar HugeVal=1e40;
using CML::SubsetValueExpressionDriver;
void yyerror(char *);
#include "swakVersion.hpp"
#include "DebugOStream.hpp"
/* Line 293 of lalr1.cc */
#line 62 "SubsetValueExpressionParser.tab.cc"
#include "SubsetValueExpressionParser.tab.hh"
/* User implementation prologue. */
/* Line 299 of lalr1.cc */
#line 96 "../SubsetValueExpressionParser.yy"
#include "SubsetValueExpressionDriverYY.hpp"
#include "swakChecks.hpp"
#include "CommonPluginFunction.hpp"
namespace CML {
template<class T>
autoPtr<Field<T> > SubsetValueExpressionDriver::evaluatePluginFunction(
const word &name,
const parserSubset::location &loc,
int &scanned,
bool isPoint
) {
if(debug || traceParsing()) {
Info << "Excuting plugin-function " << name << " ( returning type "
<< pTraits<T>::typeName << ") on " << this->content()
<< " position "
<< loc.end.column-1 << endl;
}
autoPtr<CommonPluginFunction> theFunction(
this->newPluginFunction(
name
)
);
// scanned+=1;
autoPtr<Field<T> > result(
theFunction->evaluate<T>(
this->content().substr(
loc.end.column-1
),
scanned,
isPoint
).ptr()
);
if(debug || traceParsing()) {
Info << "Scanned: " << scanned << endl;
}
return result;
}
}
/* Line 299 of lalr1.cc */
#line 120 "SubsetValueExpressionParser.tab.cc"
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* FIXME: INFRINGES ON USER NAME SPACE */
# define YY_(msgid) dgettext ("bison-runtime", msgid)
# endif
# endif
# ifndef YY_
# define YY_(msgid) msgid
# endif
#endif
/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
If N is 0, then set CURRENT to the empty location which ends
the previous symbol: RHS[0] (always defined). */
#define YYRHSLOC(Rhs, K) ((Rhs)[K])
#ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (N) \
{ \
(Current).begin = YYRHSLOC (Rhs, 1).begin; \
(Current).end = YYRHSLOC (Rhs, N).end; \
} \
else \
{ \
(Current).begin = (Current).end = YYRHSLOC (Rhs, 0).end; \
} \
while (false)
#endif
/* Suppress unused-variable warnings by "using" E. */
#define YYUSE(e) ((void) (e))
/* Enable debugging if requested. */
#if YYDEBUG
/* A pseudo ostream that takes yydebug_ into account. */
# define YYCDEBUG if (yydebug_) (*yycdebug_)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug_) \
{ \
*yycdebug_ << Title << ' '; \
yy_symbol_print_ ((Type), (Value), (Location)); \
*yycdebug_ << std::endl; \
} \
} while (false)
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug_) \
yy_reduce_print_ (Rule); \
} while (false)
# define YY_STACK_PRINT() \
do { \
if (yydebug_) \
yystack_print_ (); \
} while (false)
#else /* !YYDEBUG */
# define YYCDEBUG if (false) std::cerr
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_REDUCE_PRINT(Rule)
# define YY_STACK_PRINT()
#endif /* !YYDEBUG */
#define yyerrok (yyerrstatus_ = 0)
#define yyclearin (yychar = yyempty_)
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus_)
namespace parserSubset {
/* Line 382 of lalr1.cc */
#line 206 "SubsetValueExpressionParser.tab.cc"
/* Return YYSTR after stripping away unnecessary quotes and
backslashes, so that it's suitable for yyerror. The heuristic is
that double-quoting is unnecessary unless the string contains an
apostrophe, a comma, or backslash (other than backslash-backslash).
YYSTR is taken from yytname. */
std::string
SubsetValueExpressionParser::yytnamerr_ (const char *yystr)
{
if (*yystr == '"')
{
std::string yyr = "";
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
yyr += *yyp;
break;
case '"':
return yyr;
}
do_not_strip_quotes: ;
}
return yystr;
}
/// Build a parser object.
SubsetValueExpressionParser::SubsetValueExpressionParser (void * scanner_yyarg, SubsetValueExpressionDriver& driver_yyarg, int start_token_yyarg, int numberOfFunctionChars_yyarg)
:
#if YYDEBUG
yydebug_ (false),
yycdebug_ (&std::cerr),
#endif
scanner (scanner_yyarg),
driver (driver_yyarg),
start_token (start_token_yyarg),
numberOfFunctionChars (numberOfFunctionChars_yyarg)
{
}
SubsetValueExpressionParser::~SubsetValueExpressionParser ()
{
}
#if YYDEBUG
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
inline void
SubsetValueExpressionParser::yy_symbol_value_print_ (int yytype,
const semantic_type* yyvaluep, const location_type* yylocationp)
{
YYUSE (yylocationp);
YYUSE (yyvaluep);
switch (yytype)
{
case 3: /* "\"timeline\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 284 "SubsetValueExpressionParser.tab.cc"
break;
case 4: /* "\"lookup\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 293 "SubsetValueExpressionParser.tab.cc"
break;
case 5: /* "\"scalarID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 302 "SubsetValueExpressionParser.tab.cc"
break;
case 6: /* "\"vectorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 311 "SubsetValueExpressionParser.tab.cc"
break;
case 7: /* "\"logicalID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 320 "SubsetValueExpressionParser.tab.cc"
break;
case 8: /* "\"tensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 329 "SubsetValueExpressionParser.tab.cc"
break;
case 9: /* "\"symmTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 338 "SubsetValueExpressionParser.tab.cc"
break;
case 10: /* "\"sphericalTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 347 "SubsetValueExpressionParser.tab.cc"
break;
case 11: /* "\"pointScalarID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 356 "SubsetValueExpressionParser.tab.cc"
break;
case 12: /* "\"pointVectorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 365 "SubsetValueExpressionParser.tab.cc"
break;
case 13: /* "\"pointLogicalID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 374 "SubsetValueExpressionParser.tab.cc"
break;
case 14: /* "\"pointTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 383 "SubsetValueExpressionParser.tab.cc"
break;
case 15: /* "\"pointSymmTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 392 "SubsetValueExpressionParser.tab.cc"
break;
case 16: /* "\"pointSphericalTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 401 "SubsetValueExpressionParser.tab.cc"
break;
case 17: /* "\"F_scalarID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 410 "SubsetValueExpressionParser.tab.cc"
break;
case 18: /* "\"F_pointScalarID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 419 "SubsetValueExpressionParser.tab.cc"
break;
case 19: /* "\"F_vectorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 428 "SubsetValueExpressionParser.tab.cc"
break;
case 20: /* "\"F_pointVectorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 437 "SubsetValueExpressionParser.tab.cc"
break;
case 21: /* "\"F_tensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 446 "SubsetValueExpressionParser.tab.cc"
break;
case 22: /* "\"F_pointTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 455 "SubsetValueExpressionParser.tab.cc"
break;
case 23: /* "\"F_symmTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 464 "SubsetValueExpressionParser.tab.cc"
break;
case 24: /* "\"F_pointSymmTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 473 "SubsetValueExpressionParser.tab.cc"
break;
case 25: /* "\"F_sphericalTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 482 "SubsetValueExpressionParser.tab.cc"
break;
case 26: /* "\"F_pointSphericalTensorID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 491 "SubsetValueExpressionParser.tab.cc"
break;
case 27: /* "\"F_logicalID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 500 "SubsetValueExpressionParser.tab.cc"
break;
case 28: /* "\"F_pointLogicalID\"" */
/* Line 449 of lalr1.cc */
#line 358 "../SubsetValueExpressionParser.yy"
{ debug_stream () << *(yyvaluep->name); };
/* Line 449 of lalr1.cc */
#line 509 "SubsetValueExpressionParser.tab.cc"
break;
case 29: /* "\"value\"" */
/* Line 449 of lalr1.cc */
#line 364 "../SubsetValueExpressionParser.yy"
{ debug_stream () << (yyvaluep->val); };
/* Line 449 of lalr1.cc */
#line 518 "SubsetValueExpressionParser.tab.cc"
break;
case 30: /* "\"integer\"" */
/* Line 449 of lalr1.cc */
#line 364 "../SubsetValueExpressionParser.yy"
{ debug_stream () << (yyvaluep->integer); };
/* Line 449 of lalr1.cc */
#line 527 "SubsetValueExpressionParser.tab.cc"
break;
case 31: /* "\"vector\"" */
/* Line 449 of lalr1.cc */
#line 359 "../SubsetValueExpressionParser.yy"
{
CML::OStringStream buff;
buff << *(yyvaluep->vec);
debug_stream () << buff.str().c_str();
};
/* Line 449 of lalr1.cc */
#line 540 "SubsetValueExpressionParser.tab.cc"
break;
case 32: /* "\"sexpression\"" */
/* Line 449 of lalr1.cc */
#line 364 "../SubsetValueExpressionParser.yy"
{ debug_stream () << (yyvaluep->val); };
/* Line 449 of lalr1.cc */
#line 549 "SubsetValueExpressionParser.tab.cc"
break;
case 33: /* "\"expression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->sfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 561 "SubsetValueExpressionParser.tab.cc"
break;
case 34: /* "\"pexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->sfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 573 "SubsetValueExpressionParser.tab.cc"
break;
case 35: /* "\"lexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->lfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 585 "SubsetValueExpressionParser.tab.cc"
break;
case 36: /* "\"plexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->lfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 597 "SubsetValueExpressionParser.tab.cc"
break;
case 37: /* "\"vexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->vfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 609 "SubsetValueExpressionParser.tab.cc"
break;
case 38: /* "\"pvexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->vfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 621 "SubsetValueExpressionParser.tab.cc"
break;
case 39: /* "\"texpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->tfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 633 "SubsetValueExpressionParser.tab.cc"
break;
case 40: /* "\"ptexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->tfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 645 "SubsetValueExpressionParser.tab.cc"
break;
case 41: /* "\"yexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->yfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 657 "SubsetValueExpressionParser.tab.cc"
break;
case 42: /* "\"pyexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->yfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 669 "SubsetValueExpressionParser.tab.cc"
break;
case 43: /* "\"hexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->hfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 681 "SubsetValueExpressionParser.tab.cc"
break;
case 44: /* "\"phexpression\"" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->hfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 693 "SubsetValueExpressionParser.tab.cc"
break;
case 197: /* "vexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->vfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 705 "SubsetValueExpressionParser.tab.cc"
break;
case 198: /* "evaluateVectorFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->vfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 717 "SubsetValueExpressionParser.tab.cc"
break;
case 199: /* "scalar" */
/* Line 449 of lalr1.cc */
#line 364 "../SubsetValueExpressionParser.yy"
{ debug_stream () << (yyvaluep->val); };
/* Line 449 of lalr1.cc */
#line 726 "SubsetValueExpressionParser.tab.cc"
break;
case 200: /* "sreduced" */
/* Line 449 of lalr1.cc */
#line 364 "../SubsetValueExpressionParser.yy"
{ debug_stream () << (yyvaluep->val); };
/* Line 449 of lalr1.cc */
#line 735 "SubsetValueExpressionParser.tab.cc"
break;
case 201: /* "vreduced" */
/* Line 449 of lalr1.cc */
#line 359 "../SubsetValueExpressionParser.yy"
{
CML::OStringStream buff;
buff << *(yyvaluep->vec);
debug_stream () << buff.str().c_str();
};
/* Line 449 of lalr1.cc */
#line 748 "SubsetValueExpressionParser.tab.cc"
break;
case 202: /* "exp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->sfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 760 "SubsetValueExpressionParser.tab.cc"
break;
case 203: /* "evaluateScalarFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->sfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 772 "SubsetValueExpressionParser.tab.cc"
break;
case 204: /* "texp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->tfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 784 "SubsetValueExpressionParser.tab.cc"
break;
case 205: /* "evaluateTensorFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->tfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 796 "SubsetValueExpressionParser.tab.cc"
break;
case 206: /* "yexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->yfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 808 "SubsetValueExpressionParser.tab.cc"
break;
case 207: /* "evaluateSymmTensorFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->yfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 820 "SubsetValueExpressionParser.tab.cc"
break;
case 208: /* "hexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->hfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 832 "SubsetValueExpressionParser.tab.cc"
break;
case 209: /* "evaluateSphericalTensorFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->hfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 844 "SubsetValueExpressionParser.tab.cc"
break;
case 210: /* "lexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->lfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 856 "SubsetValueExpressionParser.tab.cc"
break;
case 211: /* "evaluateLogicalFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->lfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 868 "SubsetValueExpressionParser.tab.cc"
break;
case 212: /* "vector" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->vfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 880 "SubsetValueExpressionParser.tab.cc"
break;
case 213: /* "tensor" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->tfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 892 "SubsetValueExpressionParser.tab.cc"
break;
case 214: /* "symmTensor" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->yfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 904 "SubsetValueExpressionParser.tab.cc"
break;
case 215: /* "sphericalTensor" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->hfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 916 "SubsetValueExpressionParser.tab.cc"
break;
case 216: /* "pvexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->vfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 928 "SubsetValueExpressionParser.tab.cc"
break;
case 217: /* "evaluatePointVectorFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->vfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 940 "SubsetValueExpressionParser.tab.cc"
break;
case 218: /* "pexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->sfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 952 "SubsetValueExpressionParser.tab.cc"
break;
case 219: /* "evaluatePointScalarFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->sfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 964 "SubsetValueExpressionParser.tab.cc"
break;
case 220: /* "ptexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->tfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 976 "SubsetValueExpressionParser.tab.cc"
break;
case 221: /* "evaluatePointTensorFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->tfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 988 "SubsetValueExpressionParser.tab.cc"
break;
case 222: /* "pyexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->yfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 1000 "SubsetValueExpressionParser.tab.cc"
break;
case 223: /* "evaluatePointSymmTensorFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->yfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 1012 "SubsetValueExpressionParser.tab.cc"
break;
case 224: /* "phexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->hfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 1024 "SubsetValueExpressionParser.tab.cc"
break;
case 225: /* "evaluatePointSphericalTensorFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->hfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 1036 "SubsetValueExpressionParser.tab.cc"
break;
case 226: /* "plexp" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->lfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 1048 "SubsetValueExpressionParser.tab.cc"
break;
case 227: /* "evaluatePointLogicalFunction" */
/* Line 449 of lalr1.cc */
#line 365 "../SubsetValueExpressionParser.yy"
{
debug_stream () << "<No name field>" << (yyvaluep->lfield);
// << CML::pTraits<(*$$)::cmptType>::typeName << ">";
};
/* Line 449 of lalr1.cc */
#line 1060 "SubsetValueExpressionParser.tab.cc"
break;
default:
break;
}
}
void
SubsetValueExpressionParser::yy_symbol_print_ (int yytype,
const semantic_type* yyvaluep, const location_type* yylocationp)
{
*yycdebug_ << (yytype < yyntokens_ ? "token" : "nterm")
<< ' ' << yytname_[yytype] << " ("
<< *yylocationp << ": ";
yy_symbol_value_print_ (yytype, yyvaluep, yylocationp);
*yycdebug_ << ')';
}
#endif
void
SubsetValueExpressionParser::yydestruct_ (const char* yymsg,
int yytype, semantic_type* yyvaluep, location_type* yylocationp)
{
YYUSE (yylocationp);
YYUSE (yymsg);
YYUSE (yyvaluep);
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
switch (yytype)
{
case 3: /* "\"timeline\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1099 "SubsetValueExpressionParser.tab.cc"
break;
case 4: /* "\"lookup\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1108 "SubsetValueExpressionParser.tab.cc"
break;
case 5: /* "\"scalarID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1117 "SubsetValueExpressionParser.tab.cc"
break;
case 6: /* "\"vectorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1126 "SubsetValueExpressionParser.tab.cc"
break;
case 7: /* "\"logicalID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1135 "SubsetValueExpressionParser.tab.cc"
break;
case 8: /* "\"tensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1144 "SubsetValueExpressionParser.tab.cc"
break;
case 9: /* "\"symmTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1153 "SubsetValueExpressionParser.tab.cc"
break;
case 10: /* "\"sphericalTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1162 "SubsetValueExpressionParser.tab.cc"
break;
case 11: /* "\"pointScalarID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1171 "SubsetValueExpressionParser.tab.cc"
break;
case 12: /* "\"pointVectorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1180 "SubsetValueExpressionParser.tab.cc"
break;
case 13: /* "\"pointLogicalID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1189 "SubsetValueExpressionParser.tab.cc"
break;
case 14: /* "\"pointTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1198 "SubsetValueExpressionParser.tab.cc"
break;
case 15: /* "\"pointSymmTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1207 "SubsetValueExpressionParser.tab.cc"
break;
case 16: /* "\"pointSphericalTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1216 "SubsetValueExpressionParser.tab.cc"
break;
case 17: /* "\"F_scalarID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1225 "SubsetValueExpressionParser.tab.cc"
break;
case 18: /* "\"F_pointScalarID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1234 "SubsetValueExpressionParser.tab.cc"
break;
case 19: /* "\"F_vectorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1243 "SubsetValueExpressionParser.tab.cc"
break;
case 20: /* "\"F_pointVectorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1252 "SubsetValueExpressionParser.tab.cc"
break;
case 21: /* "\"F_tensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1261 "SubsetValueExpressionParser.tab.cc"
break;
case 22: /* "\"F_pointTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1270 "SubsetValueExpressionParser.tab.cc"
break;
case 23: /* "\"F_symmTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1279 "SubsetValueExpressionParser.tab.cc"
break;
case 24: /* "\"F_pointSymmTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1288 "SubsetValueExpressionParser.tab.cc"
break;
case 25: /* "\"F_sphericalTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1297 "SubsetValueExpressionParser.tab.cc"
break;
case 26: /* "\"F_pointSphericalTensorID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1306 "SubsetValueExpressionParser.tab.cc"
break;
case 27: /* "\"F_logicalID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1315 "SubsetValueExpressionParser.tab.cc"
break;
case 28: /* "\"F_pointLogicalID\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->name); };
/* Line 480 of lalr1.cc */
#line 1324 "SubsetValueExpressionParser.tab.cc"
break;
case 29: /* "\"value\"" */
/* Line 480 of lalr1.cc */
#line 356 "../SubsetValueExpressionParser.yy"
{};
/* Line 480 of lalr1.cc */
#line 1333 "SubsetValueExpressionParser.tab.cc"
break;
case 30: /* "\"integer\"" */
/* Line 480 of lalr1.cc */
#line 356 "../SubsetValueExpressionParser.yy"
{};
/* Line 480 of lalr1.cc */
#line 1342 "SubsetValueExpressionParser.tab.cc"
break;
case 31: /* "\"vector\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->vec); };
/* Line 480 of lalr1.cc */
#line 1351 "SubsetValueExpressionParser.tab.cc"
break;
case 32: /* "\"sexpression\"" */
/* Line 480 of lalr1.cc */
#line 356 "../SubsetValueExpressionParser.yy"
{};
/* Line 480 of lalr1.cc */
#line 1360 "SubsetValueExpressionParser.tab.cc"
break;
case 33: /* "\"expression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->sfield); };
/* Line 480 of lalr1.cc */
#line 1369 "SubsetValueExpressionParser.tab.cc"
break;
case 34: /* "\"pexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->sfield); };
/* Line 480 of lalr1.cc */
#line 1378 "SubsetValueExpressionParser.tab.cc"
break;
case 35: /* "\"lexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->lfield); };
/* Line 480 of lalr1.cc */
#line 1387 "SubsetValueExpressionParser.tab.cc"
break;
case 36: /* "\"plexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->lfield); };
/* Line 480 of lalr1.cc */
#line 1396 "SubsetValueExpressionParser.tab.cc"
break;
case 37: /* "\"vexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->vfield); };
/* Line 480 of lalr1.cc */
#line 1405 "SubsetValueExpressionParser.tab.cc"
break;
case 38: /* "\"pvexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->vfield); };
/* Line 480 of lalr1.cc */
#line 1414 "SubsetValueExpressionParser.tab.cc"
break;
case 39: /* "\"texpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->tfield); };
/* Line 480 of lalr1.cc */
#line 1423 "SubsetValueExpressionParser.tab.cc"
break;
case 40: /* "\"ptexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->tfield); };
/* Line 480 of lalr1.cc */
#line 1432 "SubsetValueExpressionParser.tab.cc"
break;
case 41: /* "\"yexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->yfield); };
/* Line 480 of lalr1.cc */
#line 1441 "SubsetValueExpressionParser.tab.cc"
break;
case 42: /* "\"pyexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->yfield); };
/* Line 480 of lalr1.cc */
#line 1450 "SubsetValueExpressionParser.tab.cc"
break;
case 43: /* "\"hexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->hfield); };
/* Line 480 of lalr1.cc */
#line 1459 "SubsetValueExpressionParser.tab.cc"
break;
case 44: /* "\"phexpression\"" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->hfield); };
/* Line 480 of lalr1.cc */
#line 1468 "SubsetValueExpressionParser.tab.cc"
break;
case 197: /* "vexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->vfield); };
/* Line 480 of lalr1.cc */
#line 1477 "SubsetValueExpressionParser.tab.cc"
break;
case 198: /* "evaluateVectorFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->vfield); };
/* Line 480 of lalr1.cc */
#line 1486 "SubsetValueExpressionParser.tab.cc"
break;
case 199: /* "scalar" */
/* Line 480 of lalr1.cc */
#line 356 "../SubsetValueExpressionParser.yy"
{};
/* Line 480 of lalr1.cc */
#line 1495 "SubsetValueExpressionParser.tab.cc"
break;
case 200: /* "sreduced" */
/* Line 480 of lalr1.cc */
#line 356 "../SubsetValueExpressionParser.yy"
{};
/* Line 480 of lalr1.cc */
#line 1504 "SubsetValueExpressionParser.tab.cc"
break;
case 201: /* "vreduced" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->vec); };
/* Line 480 of lalr1.cc */
#line 1513 "SubsetValueExpressionParser.tab.cc"
break;
case 202: /* "exp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->sfield); };
/* Line 480 of lalr1.cc */
#line 1522 "SubsetValueExpressionParser.tab.cc"
break;
case 203: /* "evaluateScalarFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->sfield); };
/* Line 480 of lalr1.cc */
#line 1531 "SubsetValueExpressionParser.tab.cc"
break;
case 204: /* "texp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->tfield); };
/* Line 480 of lalr1.cc */
#line 1540 "SubsetValueExpressionParser.tab.cc"
break;
case 205: /* "evaluateTensorFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->tfield); };
/* Line 480 of lalr1.cc */
#line 1549 "SubsetValueExpressionParser.tab.cc"
break;
case 206: /* "yexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->yfield); };
/* Line 480 of lalr1.cc */
#line 1558 "SubsetValueExpressionParser.tab.cc"
break;
case 207: /* "evaluateSymmTensorFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->yfield); };
/* Line 480 of lalr1.cc */
#line 1567 "SubsetValueExpressionParser.tab.cc"
break;
case 208: /* "hexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->hfield); };
/* Line 480 of lalr1.cc */
#line 1576 "SubsetValueExpressionParser.tab.cc"
break;
case 209: /* "evaluateSphericalTensorFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->hfield); };
/* Line 480 of lalr1.cc */
#line 1585 "SubsetValueExpressionParser.tab.cc"
break;
case 210: /* "lexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->lfield); };
/* Line 480 of lalr1.cc */
#line 1594 "SubsetValueExpressionParser.tab.cc"
break;
case 211: /* "evaluateLogicalFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->lfield); };
/* Line 480 of lalr1.cc */
#line 1603 "SubsetValueExpressionParser.tab.cc"
break;
case 212: /* "vector" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->vfield); };
/* Line 480 of lalr1.cc */
#line 1612 "SubsetValueExpressionParser.tab.cc"
break;
case 213: /* "tensor" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->tfield); };
/* Line 480 of lalr1.cc */
#line 1621 "SubsetValueExpressionParser.tab.cc"
break;
case 214: /* "symmTensor" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->yfield); };
/* Line 480 of lalr1.cc */
#line 1630 "SubsetValueExpressionParser.tab.cc"
break;
case 215: /* "sphericalTensor" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->hfield); };
/* Line 480 of lalr1.cc */
#line 1639 "SubsetValueExpressionParser.tab.cc"
break;
case 216: /* "pvexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->vfield); };
/* Line 480 of lalr1.cc */
#line 1648 "SubsetValueExpressionParser.tab.cc"
break;
case 217: /* "evaluatePointVectorFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->vfield); };
/* Line 480 of lalr1.cc */
#line 1657 "SubsetValueExpressionParser.tab.cc"
break;
case 218: /* "pexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->sfield); };
/* Line 480 of lalr1.cc */
#line 1666 "SubsetValueExpressionParser.tab.cc"
break;
case 219: /* "evaluatePointScalarFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->sfield); };
/* Line 480 of lalr1.cc */
#line 1675 "SubsetValueExpressionParser.tab.cc"
break;
case 220: /* "ptexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->tfield); };
/* Line 480 of lalr1.cc */
#line 1684 "SubsetValueExpressionParser.tab.cc"
break;
case 221: /* "evaluatePointTensorFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->tfield); };
/* Line 480 of lalr1.cc */
#line 1693 "SubsetValueExpressionParser.tab.cc"
break;
case 222: /* "pyexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->yfield); };
/* Line 480 of lalr1.cc */
#line 1702 "SubsetValueExpressionParser.tab.cc"
break;
case 223: /* "evaluatePointSymmTensorFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->yfield); };
/* Line 480 of lalr1.cc */
#line 1711 "SubsetValueExpressionParser.tab.cc"
break;
case 224: /* "phexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->hfield); };
/* Line 480 of lalr1.cc */
#line 1720 "SubsetValueExpressionParser.tab.cc"
break;
case 225: /* "evaluatePointSphericalTensorFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->hfield); };
/* Line 480 of lalr1.cc */
#line 1729 "SubsetValueExpressionParser.tab.cc"
break;
case 226: /* "plexp" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->lfield); };
/* Line 480 of lalr1.cc */
#line 1738 "SubsetValueExpressionParser.tab.cc"
break;
case 227: /* "evaluatePointLogicalFunction" */
/* Line 480 of lalr1.cc */
#line 354 "../SubsetValueExpressionParser.yy"
{ delete (yyvaluep->lfield); };
/* Line 480 of lalr1.cc */
#line 1747 "SubsetValueExpressionParser.tab.cc"
break;
default:
break;
}
}
void
SubsetValueExpressionParser::yypop_ (unsigned int n)
{
yystate_stack_.pop (n);
yysemantic_stack_.pop (n);
yylocation_stack_.pop (n);
}
#if YYDEBUG
std::ostream&
SubsetValueExpressionParser::debug_stream () const
{
return *yycdebug_;
}
void
SubsetValueExpressionParser::set_debug_stream (std::ostream& o)
{
yycdebug_ = &o;
}
SubsetValueExpressionParser::debug_level_type
SubsetValueExpressionParser::debug_level () const
{
return yydebug_;
}
void
SubsetValueExpressionParser::set_debug_level (debug_level_type l)
{
yydebug_ = l;
}
#endif
inline bool
SubsetValueExpressionParser::yy_pact_value_is_default_ (int yyvalue)
{
return yyvalue == yypact_ninf_;
}
inline bool
SubsetValueExpressionParser::yy_table_value_is_error_ (int yyvalue)
{
return yyvalue == yytable_ninf_;
}
int
SubsetValueExpressionParser::parse ()
{
/// Lookahead and lookahead in internal form.
int yychar = yyempty_;
int yytoken = 0;
/* State. */
int yyn;
int yylen = 0;
int yystate = 0;
/* Error handling. */
int yynerrs_ = 0;
int yyerrstatus_ = 0;
/// Semantic value of the lookahead.
semantic_type yylval;
/// Location of the lookahead.
location_type yylloc;
/// The locations where the error started and ended.
location_type yyerror_range[3];
/// $$.
semantic_type yyval;
/// @$.
location_type yyloc;
int yyresult;
YYCDEBUG << "Starting parse" << std::endl;
/* User initialization code. */
/* Line 565 of lalr1.cc */
#line 73 "../SubsetValueExpressionParser.yy"
{
// Initialize the initial location.
// @$.begin.filename = @$.end.filename = &driver.file;
numberOfFunctionChars=0;
}
/* Line 565 of lalr1.cc */
#line 1846 "SubsetValueExpressionParser.tab.cc"
/* Initialize the stacks. The initial state will be pushed in
yynewstate, since the latter expects the semantical and the
location values to have been already stored, initialize these
stacks with a primary value. */
yystate_stack_ = state_stack_type (0);
yysemantic_stack_ = semantic_stack_type (0);
yylocation_stack_ = location_stack_type (0);
yysemantic_stack_.push (yylval);
yylocation_stack_.push (yylloc);
/* New state. */
yynewstate:
yystate_stack_.push (yystate);
YYCDEBUG << "Entering state " << yystate << std::endl;
/* Accept? */
if (yystate == yyfinal_)
goto yyacceptlab;
goto yybackup;
/* Backup. */
yybackup:
/* Try to take a decision without lookahead. */
yyn = yypact_[yystate];
if (yy_pact_value_is_default_ (yyn))
goto yydefault;
/* Read a lookahead token. */
if (yychar == yyempty_)
{
YYCDEBUG << "Reading a token: ";
yychar = yylex (&yylval, &yylloc, scanner, driver, start_token, numberOfFunctionChars);
}
/* Convert token to internal form. */
if (yychar <= yyeof_)
{
yychar = yytoken = yyeof_;
YYCDEBUG << "Now at end of input." << std::endl;
}
else
{
yytoken = yytranslate_ (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || yylast_ < yyn || yycheck_[yyn] != yytoken)
goto yydefault;
/* Reduce or error. */
yyn = yytable_[yyn];
if (yyn <= 0)
{
if (yy_table_value_is_error_ (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the token being shifted. */
yychar = yyempty_;
yysemantic_stack_.push (yylval);
yylocation_stack_.push (yylloc);
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus_)
--yyerrstatus_;
yystate = yyn;
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact_[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
yylen = yyr2_[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
`$$ = $1'. Otherwise, use the top of the stack.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. */
if (yylen)
yyval = yysemantic_stack_[yylen - 1];
else
yyval = yysemantic_stack_[0];
{
slice<location_type, location_stack_type> slice (yylocation_stack_, yylen);
YYLLOC_DEFAULT (yyloc, slice, yylen);
}
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 2:
/* Line 690 of lalr1.cc */
#line 375 "../SubsetValueExpressionParser.yy"
{ driver.parserLastPos()=(yylocation_stack_[(1) - (1)]).end.column; }
break;
case 4:
/* Line 690 of lalr1.cc */
#line 380 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::scalar>((yysemantic_stack_[(3) - (2)].sfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 5:
/* Line 690 of lalr1.cc */
#line 386 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::scalar>((yysemantic_stack_[(3) - (2)].sfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 6:
/* Line 690 of lalr1.cc */
#line 392 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::scalar>((yysemantic_stack_[(3) - (2)].sfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 7:
/* Line 690 of lalr1.cc */
#line 398 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::scalar>((yysemantic_stack_[(3) - (2)].sfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 8:
/* Line 690 of lalr1.cc */
#line 404 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::vector>((yysemantic_stack_[(3) - (2)].vfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 9:
/* Line 690 of lalr1.cc */
#line 410 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::vector>((yysemantic_stack_[(3) - (2)].vfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 10:
/* Line 690 of lalr1.cc */
#line 416 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::vector>((yysemantic_stack_[(3) - (2)].vfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 11:
/* Line 690 of lalr1.cc */
#line 422 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::vector>((yysemantic_stack_[(3) - (2)].vfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 12:
/* Line 690 of lalr1.cc */
#line 428 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::tensor>((yysemantic_stack_[(3) - (2)].tfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 13:
/* Line 690 of lalr1.cc */
#line 434 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::tensor>((yysemantic_stack_[(3) - (2)].tfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 14:
/* Line 690 of lalr1.cc */
#line 440 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::tensor>((yysemantic_stack_[(3) - (2)].tfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 15:
/* Line 690 of lalr1.cc */
#line 446 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::tensor>((yysemantic_stack_[(3) - (2)].tfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 16:
/* Line 690 of lalr1.cc */
#line 452 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::symmTensor>((yysemantic_stack_[(3) - (2)].yfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 17:
/* Line 690 of lalr1.cc */
#line 458 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::symmTensor>((yysemantic_stack_[(3) - (2)].yfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 18:
/* Line 690 of lalr1.cc */
#line 464 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::symmTensor>((yysemantic_stack_[(3) - (2)].yfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 19:
/* Line 690 of lalr1.cc */
#line 470 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::symmTensor>((yysemantic_stack_[(3) - (2)].yfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 20:
/* Line 690 of lalr1.cc */
#line 476 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::sphericalTensor>((yysemantic_stack_[(3) - (2)].hfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 21:
/* Line 690 of lalr1.cc */
#line 482 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::sphericalTensor>((yysemantic_stack_[(3) - (2)].hfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 22:
/* Line 690 of lalr1.cc */
#line 488 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::sphericalTensor>((yysemantic_stack_[(3) - (2)].hfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 23:
/* Line 690 of lalr1.cc */
#line 494 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::sphericalTensor>((yysemantic_stack_[(3) - (2)].hfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 24:
/* Line 690 of lalr1.cc */
#line 500 "../SubsetValueExpressionParser.yy"
{
driver.setResult<bool>((yysemantic_stack_[(3) - (2)].lfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 25:
/* Line 690 of lalr1.cc */
#line 506 "../SubsetValueExpressionParser.yy"
{
driver.setResult<bool>((yysemantic_stack_[(3) - (2)].lfield));
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 26:
/* Line 690 of lalr1.cc */
#line 512 "../SubsetValueExpressionParser.yy"
{
driver.setResult<bool>((yysemantic_stack_[(3) - (2)].lfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 27:
/* Line 690 of lalr1.cc */
#line 518 "../SubsetValueExpressionParser.yy"
{
driver.setResult<bool>((yysemantic_stack_[(3) - (2)].lfield),true);
driver.parserLastPos()=(yylocation_stack_[(3) - (3)]).end.column-1;
YYACCEPT;
}
break;
case 28:
/* Line 690 of lalr1.cc */
#line 524 "../SubsetValueExpressionParser.yy"
{
driver.parserLastPos()=(yylocation_stack_[(2) - (2)]).end.column-1;
YYACCEPT;
}
break;
case 29:
/* Line 690 of lalr1.cc */
#line 529 "../SubsetValueExpressionParser.yy"
{
driver.parserLastPos()=(yylocation_stack_[(2) - (2)]).end.column-1;
YYACCEPT;
}
break;
case 32:
/* Line 690 of lalr1.cc */
#line 538 "../SubsetValueExpressionParser.yy"
{ driver.setResult<CML::scalar>((yysemantic_stack_[(1) - (1)].sfield)); }
break;
case 33:
/* Line 690 of lalr1.cc */
#line 539 "../SubsetValueExpressionParser.yy"
{ driver.setResult<CML::vector>((yysemantic_stack_[(1) - (1)].vfield)); }
break;
case 34:
/* Line 690 of lalr1.cc */
#line 540 "../SubsetValueExpressionParser.yy"
{ driver.setResult<bool>((yysemantic_stack_[(1) - (1)].lfield)); }
break;
case 35:
/* Line 690 of lalr1.cc */
#line 541 "../SubsetValueExpressionParser.yy"
{ driver.setResult<CML::scalar>((yysemantic_stack_[(1) - (1)].sfield),true); }
break;
case 36:
/* Line 690 of lalr1.cc */
#line 542 "../SubsetValueExpressionParser.yy"
{ driver.setResult<CML::vector>((yysemantic_stack_[(1) - (1)].vfield),true); }
break;
case 37:
/* Line 690 of lalr1.cc */
#line 543 "../SubsetValueExpressionParser.yy"
{ driver.setResult<bool>((yysemantic_stack_[(1) - (1)].lfield),true); }
break;
case 38:
/* Line 690 of lalr1.cc */
#line 544 "../SubsetValueExpressionParser.yy"
{ driver.setResult<CML::tensor>((yysemantic_stack_[(1) - (1)].tfield)); }
break;
case 39:
/* Line 690 of lalr1.cc */
#line 545 "../SubsetValueExpressionParser.yy"
{ driver.setResult<CML::tensor>((yysemantic_stack_[(1) - (1)].tfield),true); }
break;
case 40:
/* Line 690 of lalr1.cc */
#line 546 "../SubsetValueExpressionParser.yy"
{ driver.setResult<CML::symmTensor>((yysemantic_stack_[(1) - (1)].yfield)); }
break;
case 41:
/* Line 690 of lalr1.cc */
#line 547 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::symmTensor>((yysemantic_stack_[(1) - (1)].yfield),true);
}
break;
case 42:
/* Line 690 of lalr1.cc */
#line 550 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::sphericalTensor>((yysemantic_stack_[(1) - (1)].hfield));
}
break;
case 43:
/* Line 690 of lalr1.cc */
#line 553 "../SubsetValueExpressionParser.yy"
{
driver.setResult<CML::sphericalTensor>((yysemantic_stack_[(1) - (1)].hfield),true);
}
break;
case 44:
/* Line 690 of lalr1.cc */
#line 558 "../SubsetValueExpressionParser.yy"
{ driver.startVectorComponent(); }
break;
case 45:
/* Line 690 of lalr1.cc */
#line 561 "../SubsetValueExpressionParser.yy"
{ driver.startTensorComponent(); }
break;
case 46:
/* Line 690 of lalr1.cc */
#line 564 "../SubsetValueExpressionParser.yy"
{ driver.startEatCharacters(); }
break;
case 47:
/* Line 690 of lalr1.cc */
#line 567 "../SubsetValueExpressionParser.yy"
{ (yyval.vfield) = (yysemantic_stack_[(1) - (1)].vfield); }
break;
case 48:
/* Line 690 of lalr1.cc */
#line 568 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.makeField<CML::vector>(*(yysemantic_stack_[(1) - (1)].vec)).ptr();
delete (yysemantic_stack_[(1) - (1)].vec);
}
break;
case 49:
/* Line 690 of lalr1.cc */
#line 572 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) + *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 50:
/* Line 690 of lalr1.cc */
#line 577 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 51:
/* Line 690 of lalr1.cc */
#line 582 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 52:
/* Line 690 of lalr1.cc */
#line 587 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].tfield) & *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 53:
/* Line 690 of lalr1.cc */
#line 592 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) & *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 54:
/* Line 690 of lalr1.cc */
#line 597 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].yfield) & *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 55:
/* Line 690 of lalr1.cc */
#line 602 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) & *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 56:
/* Line 690 of lalr1.cc */
#line 607 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].hfield) & *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 57:
/* Line 690 of lalr1.cc */
#line 612 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) & *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 58:
/* Line 690 of lalr1.cc */
#line 617 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 59:
/* Line 690 of lalr1.cc */
#line 622 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) ^ *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 60:
/* Line 690 of lalr1.cc */
#line 627 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) - *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 61:
/* Line 690 of lalr1.cc */
#line 632 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(-*(yysemantic_stack_[(2) - (2)].vfield));
delete (yysemantic_stack_[(2) - (2)].vfield);
}
break;
case 62:
/* Line 690 of lalr1.cc */
#line 636 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(*(*(yysemantic_stack_[(2) - (2)].tfield)));
delete (yysemantic_stack_[(2) - (2)].tfield);
}
break;
case 63:
/* Line 690 of lalr1.cc */
#line 640 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(*(*(yysemantic_stack_[(2) - (2)].yfield)));
delete (yysemantic_stack_[(2) - (2)].yfield);
}
break;
case 64:
/* Line 690 of lalr1.cc */
#line 644 "../SubsetValueExpressionParser.yy"
{ (yyval.vfield) = (yysemantic_stack_[(3) - (2)].vfield); }
break;
case 65:
/* Line 690 of lalr1.cc */
#line 645 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(CML::eigenValues(*(yysemantic_stack_[(4) - (3)].tfield)));
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 66:
/* Line 690 of lalr1.cc */
#line 649 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(CML::eigenValues(*(yysemantic_stack_[(4) - (3)].yfield)));
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 67:
/* Line 690 of lalr1.cc */
#line 653 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::XX)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::XY)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::XZ)()
).ptr();
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 68:
/* Line 690 of lalr1.cc */
#line 661 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::YX)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::YY)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::YZ)()
).ptr();
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 69:
/* Line 690 of lalr1.cc */
#line 669 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::ZX)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::ZY)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::ZZ)()
).ptr();
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 70:
/* Line 690 of lalr1.cc */
#line 677 "../SubsetValueExpressionParser.yy"
{
// $$ = new CML::vectorField( CML::diag(*$3) ); // not implemented?
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (3)].tfield)->component(CML::tensor::XX)(),
(yysemantic_stack_[(4) - (3)].tfield)->component(CML::tensor::YY)(),
(yysemantic_stack_[(4) - (3)].tfield)->component(CML::tensor::ZZ)()
).ptr();
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 71:
/* Line 690 of lalr1.cc */
#line 686 "../SubsetValueExpressionParser.yy"
{
// $$ = new CML::vectorField( CML::diag(*$3) ); // not implemented?
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (3)].yfield)->component(CML::symmTensor::XX)(),
(yysemantic_stack_[(4) - (3)].yfield)->component(CML::symmTensor::YY)(),
(yysemantic_stack_[(4) - (3)].yfield)->component(CML::symmTensor::ZZ)()
).ptr();
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 72:
/* Line 690 of lalr1.cc */
#line 695 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].vfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].vfield));
(yyval.vfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].vfield),*(yysemantic_stack_[(5) - (5)].vfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].vfield); delete (yysemantic_stack_[(5) - (5)].vfield);
}
break;
case 73:
/* Line 690 of lalr1.cc */
#line 700 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.makePositionField().ptr();
}
break;
case 74:
/* Line 690 of lalr1.cc */
#line 703 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.makeFaceNormalField().ptr();
}
break;
case 75:
/* Line 690 of lalr1.cc */
#line 706 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.makeFaceAreaField().ptr();
}
break;
case 77:
/* Line 690 of lalr1.cc */
#line 714 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield)=driver.getVectorField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 78:
/* Line 690 of lalr1.cc */
#line 718 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield)=driver.getVectorField(*(yysemantic_stack_[(4) - (3)].name),true).ptr();
delete (yysemantic_stack_[(4) - (3)].name);
}
break;
case 79:
/* Line 690 of lalr1.cc */
#line 722 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = CML::min(*(yysemantic_stack_[(6) - (3)].vfield),*(yysemantic_stack_[(6) - (5)].vfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].vfield); delete (yysemantic_stack_[(6) - (5)].vfield);
}
break;
case 80:
/* Line 690 of lalr1.cc */
#line 726 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = CML::max(*(yysemantic_stack_[(6) - (3)].vfield),*(yysemantic_stack_[(6) - (5)].vfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].vfield); delete (yysemantic_stack_[(6) - (5)].vfield);
}
break;
case 81:
/* Line 690 of lalr1.cc */
#line 733 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield)=driver.evaluatePluginFunction<CML::vector>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 82:
/* Line 690 of lalr1.cc */
#line 744 "../SubsetValueExpressionParser.yy"
{ (yyval.val) = (yysemantic_stack_[(1) - (1)].val); }
break;
case 83:
/* Line 690 of lalr1.cc */
#line 745 "../SubsetValueExpressionParser.yy"
{ (yyval.val) = -(yysemantic_stack_[(2) - (2)].val); }
break;
case 84:
/* Line 690 of lalr1.cc */
#line 748 "../SubsetValueExpressionParser.yy"
{
(yyval.val) = CML::gMin(*(yysemantic_stack_[(4) - (3)].sfield));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 85:
/* Line 690 of lalr1.cc */
#line 752 "../SubsetValueExpressionParser.yy"
{
(yyval.val) = CML::gMax(*(yysemantic_stack_[(4) - (3)].sfield));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 86:
/* Line 690 of lalr1.cc */
#line 756 "../SubsetValueExpressionParser.yy"
{
(yyval.val) = CML::gMin(*(yysemantic_stack_[(4) - (3)].sfield));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 87:
/* Line 690 of lalr1.cc */
#line 760 "../SubsetValueExpressionParser.yy"
{
(yyval.val) = CML::gMax(*(yysemantic_stack_[(4) - (3)].sfield));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 88:
/* Line 690 of lalr1.cc */
#line 764 "../SubsetValueExpressionParser.yy"
{
(yyval.val) = CML::gSum(*(yysemantic_stack_[(4) - (3)].sfield));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 89:
/* Line 690 of lalr1.cc */
#line 768 "../SubsetValueExpressionParser.yy"
{
(yyval.val) = CML::gSum(*(yysemantic_stack_[(4) - (3)].sfield));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 90:
/* Line 690 of lalr1.cc */
#line 772 "../SubsetValueExpressionParser.yy"
{
(yyval.val) = CML::gAverage(*(yysemantic_stack_[(4) - (3)].sfield));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 91:
/* Line 690 of lalr1.cc */
#line 776 "../SubsetValueExpressionParser.yy"
{
(yyval.val) = CML::gAverage(*(yysemantic_stack_[(4) - (3)].sfield));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 92:
/* Line 690 of lalr1.cc */
#line 782 "../SubsetValueExpressionParser.yy"
{
CML::vector tmp(HugeVal,HugeVal,HugeVal);
if(((yysemantic_stack_[(4) - (3)].vfield)->size())>0) {
tmp=CML::min(*(yysemantic_stack_[(4) - (3)].vfield));
}
CML::reduce(tmp,CML::minOp<CML::vector>());
(yyval.vec) = new CML::vector(tmp);
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 93:
/* Line 690 of lalr1.cc */
#line 791 "../SubsetValueExpressionParser.yy"
{
CML::vector tmp(-HugeVal,-HugeVal,-HugeVal);
if(((yysemantic_stack_[(4) - (3)].vfield)->size())>0) {
tmp=CML::max(*(yysemantic_stack_[(4) - (3)].vfield));
}
CML::reduce(tmp,CML::maxOp<CML::vector>());
(yyval.vec) = new CML::vector(tmp);
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 94:
/* Line 690 of lalr1.cc */
#line 800 "../SubsetValueExpressionParser.yy"
{
CML::vector tmp(HugeVal,HugeVal,HugeVal);
if(((yysemantic_stack_[(4) - (3)].vfield)->size())>0) {
tmp=CML::min(*(yysemantic_stack_[(4) - (3)].vfield));
}
CML::reduce(tmp,CML::minOp<CML::vector>());
(yyval.vec) = new CML::vector(tmp);
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 95:
/* Line 690 of lalr1.cc */
#line 809 "../SubsetValueExpressionParser.yy"
{
CML::vector tmp(-HugeVal,-HugeVal,-HugeVal);
if(((yysemantic_stack_[(4) - (3)].vfield)->size())>0) {
tmp=CML::max(*(yysemantic_stack_[(4) - (3)].vfield));
}
CML::reduce(tmp,CML::maxOp<CML::vector>());
(yyval.vec) = new CML::vector(tmp);
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 96:
/* Line 690 of lalr1.cc */
#line 818 "../SubsetValueExpressionParser.yy"
{
CML::vectorField *pos=driver.makePositionField().ptr();
(yyval.vec) = new CML::vector(
driver.getPositionOfMinimum(
*(yysemantic_stack_[(4) - (3)].sfield),
*pos
)
);
delete pos;
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 97:
/* Line 690 of lalr1.cc */
#line 829 "../SubsetValueExpressionParser.yy"
{
CML::vectorField *pos=driver.makePositionField().ptr();
(yyval.vec) = new CML::vector(
driver.getPositionOfMaximum(
*(yysemantic_stack_[(4) - (3)].sfield),
*pos
)
);
delete pos;
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 98:
/* Line 690 of lalr1.cc */
#line 840 "../SubsetValueExpressionParser.yy"
{
(yyval.vec) = new CML::vector(CML::gSum(*(yysemantic_stack_[(4) - (3)].vfield)));
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 99:
/* Line 690 of lalr1.cc */
#line 844 "../SubsetValueExpressionParser.yy"
{
(yyval.vec) = new CML::vector(CML::gSum(*(yysemantic_stack_[(4) - (3)].vfield)));
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 100:
/* Line 690 of lalr1.cc */
#line 848 "../SubsetValueExpressionParser.yy"
{
(yyval.vec) = new CML::vector(CML::gAverage(*(yysemantic_stack_[(4) - (3)].vfield)));
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 101:
/* Line 690 of lalr1.cc */
#line 852 "../SubsetValueExpressionParser.yy"
{
(yyval.vec) = new CML::vector(CML::gAverage(*(yysemantic_stack_[(4) - (3)].vfield)));
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 102:
/* Line 690 of lalr1.cc */
#line 858 "../SubsetValueExpressionParser.yy"
{ (yyval.sfield) = driver.makeField((yysemantic_stack_[(1) - (1)].val)).ptr(); }
break;
case 103:
/* Line 690 of lalr1.cc */
#line 859 "../SubsetValueExpressionParser.yy"
{ (yyval.sfield) = driver.makeField((yysemantic_stack_[(1) - (1)].val)).ptr(); }
break;
case 104:
/* Line 690 of lalr1.cc */
#line 860 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].sfield) + *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 105:
/* Line 690 of lalr1.cc */
#line 865 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].sfield) - *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 106:
/* Line 690 of lalr1.cc */
#line 870 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 107:
/* Line 690 of lalr1.cc */
#line 875 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = driver.makeModuloField(*(yysemantic_stack_[(3) - (1)].sfield),*(yysemantic_stack_[(3) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 108:
/* Line 690 of lalr1.cc */
#line 880 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].sfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 109:
/* Line 690 of lalr1.cc */
#line 890 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(6) - (3)].sfield),(yysemantic_stack_[(6) - (5)].sfield));
(yyval.sfield) = new CML::scalarField(CML::pow(*(yysemantic_stack_[(6) - (3)].sfield), *(yysemantic_stack_[(6) - (5)].sfield)));
delete (yysemantic_stack_[(6) - (3)].sfield); delete (yysemantic_stack_[(6) - (5)].sfield);
}
break;
case 110:
/* Line 690 of lalr1.cc */
#line 895 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::log(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 111:
/* Line 690 of lalr1.cc */
#line 899 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::exp(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 112:
/* Line 690 of lalr1.cc */
#line 903 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].vfield) & *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 113:
/* Line 690 of lalr1.cc */
#line 908 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].tfield) && *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 114:
/* Line 690 of lalr1.cc */
#line 913 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].tfield) && *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 115:
/* Line 690 of lalr1.cc */
#line 918 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].tfield) && *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 116:
/* Line 690 of lalr1.cc */
#line 923 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].yfield) && *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 117:
/* Line 690 of lalr1.cc */
#line 928 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].yfield) && *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 118:
/* Line 690 of lalr1.cc */
#line 933 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].yfield) && *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 119:
/* Line 690 of lalr1.cc */
#line 938 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].hfield) && *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 120:
/* Line 690 of lalr1.cc */
#line 943 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].hfield) && *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 121:
/* Line 690 of lalr1.cc */
#line 948 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].hfield) && *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 122:
/* Line 690 of lalr1.cc */
#line 953 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(-*(yysemantic_stack_[(2) - (2)].sfield));
delete (yysemantic_stack_[(2) - (2)].sfield);
}
break;
case 123:
/* Line 690 of lalr1.cc */
#line 957 "../SubsetValueExpressionParser.yy"
{ (yyval.sfield) = (yysemantic_stack_[(3) - (2)].sfield); }
break;
case 124:
/* Line 690 of lalr1.cc */
#line 958 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sqr(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 125:
/* Line 690 of lalr1.cc */
#line 962 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sqrt(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 126:
/* Line 690 of lalr1.cc */
#line 966 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sin(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 127:
/* Line 690 of lalr1.cc */
#line 970 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::cos(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 128:
/* Line 690 of lalr1.cc */
#line 974 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::tan(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 129:
/* Line 690 of lalr1.cc */
#line 978 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::log10(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 130:
/* Line 690 of lalr1.cc */
#line 982 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::asin(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 131:
/* Line 690 of lalr1.cc */
#line 986 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::acos(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 132:
/* Line 690 of lalr1.cc */
#line 990 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::atan(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 133:
/* Line 690 of lalr1.cc */
#line 994 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sinh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 134:
/* Line 690 of lalr1.cc */
#line 998 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::cosh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 135:
/* Line 690 of lalr1.cc */
#line 1002 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::tanh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 136:
/* Line 690 of lalr1.cc */
#line 1006 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::asinh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 137:
/* Line 690 of lalr1.cc */
#line 1010 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::acosh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 138:
/* Line 690 of lalr1.cc */
#line 1014 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::atanh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 139:
/* Line 690 of lalr1.cc */
#line 1018 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::erf(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 140:
/* Line 690 of lalr1.cc */
#line 1022 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::erfc(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 141:
/* Line 690 of lalr1.cc */
#line 1026 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::lgamma(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 142:
/* Line 690 of lalr1.cc */
#line 1030 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::j0(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 143:
/* Line 690 of lalr1.cc */
#line 1034 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::j1(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 144:
/* Line 690 of lalr1.cc */
#line 1038 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::y0(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 145:
/* Line 690 of lalr1.cc */
#line 1042 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::y1(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 146:
/* Line 690 of lalr1.cc */
#line 1046 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sign(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 147:
/* Line 690 of lalr1.cc */
#line 1050 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::pos(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 148:
/* Line 690 of lalr1.cc */
#line 1054 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::neg(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 149:
/* Line 690 of lalr1.cc */
#line 1058 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 150:
/* Line 690 of lalr1.cc */
#line 1062 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].vfield)));
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 151:
/* Line 690 of lalr1.cc */
#line 1066 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].tfield)));
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 152:
/* Line 690 of lalr1.cc */
#line 1070 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].yfield)));
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 153:
/* Line 690 of lalr1.cc */
#line 1074 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].hfield)));
delete (yysemantic_stack_[(4) - (3)].hfield);
}
break;
case 154:
/* Line 690 of lalr1.cc */
#line 1078 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 155:
/* Line 690 of lalr1.cc */
#line 1082 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].vfield)));
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 156:
/* Line 690 of lalr1.cc */
#line 1086 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].tfield)));
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 157:
/* Line 690 of lalr1.cc */
#line 1090 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].yfield)));
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 158:
/* Line 690 of lalr1.cc */
#line 1094 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].hfield)));
delete (yysemantic_stack_[(4) - (3)].hfield);
}
break;
case 159:
/* Line 690 of lalr1.cc */
#line 1098 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField( CML::tr(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 160:
/* Line 690 of lalr1.cc */
#line 1102 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField( CML::tr(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 161:
/* Line 690 of lalr1.cc */
#line 1106 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField( CML::tr(*(yysemantic_stack_[(4) - (3)].hfield)) );
delete (yysemantic_stack_[(4) - (3)].hfield);
}
break;
case 162:
/* Line 690 of lalr1.cc */
#line 1110 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField( CML::det(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 163:
/* Line 690 of lalr1.cc */
#line 1114 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField( CML::det(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 164:
/* Line 690 of lalr1.cc */
#line 1118 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField( CML::det(*(yysemantic_stack_[(4) - (3)].hfield)) );
delete (yysemantic_stack_[(4) - (3)].hfield);
}
break;
case 165:
/* Line 690 of lalr1.cc */
#line 1122 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].vfield)->component(0));
delete (yysemantic_stack_[(4) - (1)].vfield);
}
break;
case 166:
/* Line 690 of lalr1.cc */
#line 1126 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].vfield)->component(1));
delete (yysemantic_stack_[(4) - (1)].vfield);
}
break;
case 167:
/* Line 690 of lalr1.cc */
#line 1130 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].vfield)->component(2));
delete (yysemantic_stack_[(4) - (1)].vfield);
}
break;
case 168:
/* Line 690 of lalr1.cc */
#line 1134 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(0));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 169:
/* Line 690 of lalr1.cc */
#line 1138 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(1));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 170:
/* Line 690 of lalr1.cc */
#line 1142 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(2));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 171:
/* Line 690 of lalr1.cc */
#line 1146 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(3));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 172:
/* Line 690 of lalr1.cc */
#line 1150 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(4));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 173:
/* Line 690 of lalr1.cc */
#line 1154 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(5));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 174:
/* Line 690 of lalr1.cc */
#line 1158 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(6));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 175:
/* Line 690 of lalr1.cc */
#line 1162 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(7));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 176:
/* Line 690 of lalr1.cc */
#line 1166 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(8));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 177:
/* Line 690 of lalr1.cc */
#line 1170 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(0));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 178:
/* Line 690 of lalr1.cc */
#line 1174 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(1));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 179:
/* Line 690 of lalr1.cc */
#line 1178 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(2));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 180:
/* Line 690 of lalr1.cc */
#line 1182 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(3));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 181:
/* Line 690 of lalr1.cc */
#line 1186 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(4));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 182:
/* Line 690 of lalr1.cc */
#line 1190 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(5));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 183:
/* Line 690 of lalr1.cc */
#line 1194 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].hfield)->component(0));
delete (yysemantic_stack_[(4) - (1)].hfield);
}
break;
case 184:
/* Line 690 of lalr1.cc */
#line 1198 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].sfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].sfield));
(yyval.sfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].sfield),*(yysemantic_stack_[(5) - (5)].sfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].sfield); delete (yysemantic_stack_[(5) - (5)].sfield);
}
break;
case 185:
/* Line 690 of lalr1.cc */
#line 1203 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeField(
CML::constant::mathematical::pi
).ptr();
}
break;
case 186:
/* Line 690 of lalr1.cc */
#line 1212 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeIdField().ptr();
}
break;
case 187:
/* Line 690 of lalr1.cc */
#line 1215 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeField(
CML::scalar(CML::Pstream::myProcNo())
).ptr();
}
break;
case 188:
/* Line 690 of lalr1.cc */
#line 1220 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.weights(driver.size()).ptr();
}
break;
case 189:
/* Line 690 of lalr1.cc */
#line 1223 "../SubsetValueExpressionParser.yy"
{ (yyval.sfield) = driver.makeFaceFlipField().ptr(); }
break;
case 190:
/* Line 690 of lalr1.cc */
#line 1224 "../SubsetValueExpressionParser.yy"
{ (yyval.sfield) = driver.makeRandomField().ptr(); }
break;
case 191:
/* Line 690 of lalr1.cc */
#line 1225 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeRandomField(-(yysemantic_stack_[(4) - (3)].integer)).ptr();
}
break;
case 192:
/* Line 690 of lalr1.cc */
#line 1228 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeGaussRandomField().ptr();
}
break;
case 193:
/* Line 690 of lalr1.cc */
#line 1231 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeGaussRandomField(-(yysemantic_stack_[(4) - (3)].integer)).ptr();
}
break;
case 194:
/* Line 690 of lalr1.cc */
#line 1234 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeRandomField(1).ptr();
}
break;
case 195:
/* Line 690 of lalr1.cc */
#line 1237 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeRandomField((yysemantic_stack_[(4) - (3)].integer)+1).ptr();
}
break;
case 196:
/* Line 690 of lalr1.cc */
#line 1240 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeGaussRandomField(1).ptr();
}
break;
case 197:
/* Line 690 of lalr1.cc */
#line 1243 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeGaussRandomField((yysemantic_stack_[(4) - (3)].integer)+1).ptr();
}
break;
case 198:
/* Line 690 of lalr1.cc */
#line 1246 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeField(driver.runTime().deltaT().value()).ptr();
}
break;
case 199:
/* Line 690 of lalr1.cc */
#line 1249 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeField(driver.runTime().time().value()).ptr();
}
break;
case 200:
/* Line 690 of lalr1.cc */
#line 1256 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeFaceAreaMagField().ptr();
}
break;
case 201:
/* Line 690 of lalr1.cc */
#line 1259 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = driver.makeCellVolumeField().ptr();
}
break;
case 203:
/* Line 690 of lalr1.cc */
#line 1263 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield)=driver.getScalarField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 204:
/* Line 690 of lalr1.cc */
#line 1267 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield)=driver.getScalarField(*(yysemantic_stack_[(4) - (3)].name),true).ptr();
delete (yysemantic_stack_[(4) - (3)].name);
}
break;
case 205:
/* Line 690 of lalr1.cc */
#line 1271 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield)=driver.getLine(*(yysemantic_stack_[(1) - (1)].name),driver.runTime().time().value()).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 206:
/* Line 690 of lalr1.cc */
#line 1275 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield)=driver.getLookup(*(yysemantic_stack_[(4) - (1)].name),*(yysemantic_stack_[(4) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(4) - (1)].name); delete(yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 207:
/* Line 690 of lalr1.cc */
#line 1279 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = CML::min(*(yysemantic_stack_[(6) - (3)].sfield),*(yysemantic_stack_[(6) - (5)].sfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].sfield); delete (yysemantic_stack_[(6) - (5)].sfield);
}
break;
case 208:
/* Line 690 of lalr1.cc */
#line 1283 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = CML::max(*(yysemantic_stack_[(6) - (3)].sfield),*(yysemantic_stack_[(6) - (5)].sfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].sfield); delete (yysemantic_stack_[(6) - (5)].sfield);
}
break;
case 209:
/* Line 690 of lalr1.cc */
#line 1290 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield)=driver.evaluatePluginFunction<CML::scalar>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 210:
/* Line 690 of lalr1.cc */
#line 1301 "../SubsetValueExpressionParser.yy"
{ (yyval.tfield) = (yysemantic_stack_[(1) - (1)].tfield); }
break;
case 211:
/* Line 690 of lalr1.cc */
#line 1302 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) + *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 212:
/* Line 690 of lalr1.cc */
#line 1307 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) + *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 213:
/* Line 690 of lalr1.cc */
#line 1312 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) + *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 214:
/* Line 690 of lalr1.cc */
#line 1317 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].yfield) + *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 215:
/* Line 690 of lalr1.cc */
#line 1322 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].hfield) + *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 216:
/* Line 690 of lalr1.cc */
#line 1327 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 217:
/* Line 690 of lalr1.cc */
#line 1332 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 218:
/* Line 690 of lalr1.cc */
#line 1337 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].vfield) * *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 219:
/* Line 690 of lalr1.cc */
#line 1342 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) & *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 220:
/* Line 690 of lalr1.cc */
#line 1347 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].yfield) & *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 221:
/* Line 690 of lalr1.cc */
#line 1352 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) & *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 222:
/* Line 690 of lalr1.cc */
#line 1357 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].hfield) & *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 223:
/* Line 690 of lalr1.cc */
#line 1362 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) & *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 224:
/* Line 690 of lalr1.cc */
#line 1367 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 225:
/* Line 690 of lalr1.cc */
#line 1372 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) - *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 226:
/* Line 690 of lalr1.cc */
#line 1377 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) - *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 227:
/* Line 690 of lalr1.cc */
#line 1382 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) - *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 228:
/* Line 690 of lalr1.cc */
#line 1387 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].yfield) - *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 229:
/* Line 690 of lalr1.cc */
#line 1392 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].hfield) - *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 230:
/* Line 690 of lalr1.cc */
#line 1397 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField(-*(yysemantic_stack_[(2) - (2)].tfield));
delete (yysemantic_stack_[(2) - (2)].tfield);
}
break;
case 231:
/* Line 690 of lalr1.cc */
#line 1401 "../SubsetValueExpressionParser.yy"
{ (yyval.tfield) = (yysemantic_stack_[(3) - (2)].tfield); }
break;
case 232:
/* Line 690 of lalr1.cc */
#line 1402 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::skew(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 233:
/* Line 690 of lalr1.cc */
#line 1406 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField(CML::eigenVectors(*(yysemantic_stack_[(4) - (3)].tfield)));
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 234:
/* Line 690 of lalr1.cc */
#line 1410 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField(CML::eigenVectors(*(yysemantic_stack_[(4) - (3)].yfield)));
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 235:
/* Line 690 of lalr1.cc */
#line 1414 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::inv(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 236:
/* Line 690 of lalr1.cc */
#line 1418 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::cof(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 237:
/* Line 690 of lalr1.cc */
#line 1422 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::dev(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 238:
/* Line 690 of lalr1.cc */
#line 1426 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::dev2(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 239:
/* Line 690 of lalr1.cc */
#line 1430 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( (yysemantic_stack_[(6) - (1)].tfield)->T() );
delete (yysemantic_stack_[(6) - (1)].tfield);
}
break;
case 240:
/* Line 690 of lalr1.cc */
#line 1434 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].tfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].tfield));
(yyval.tfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].tfield),*(yysemantic_stack_[(5) - (5)].tfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].tfield); delete (yysemantic_stack_[(5) - (5)].tfield);
}
break;
case 242:
/* Line 690 of lalr1.cc */
#line 1444 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield)=driver.getTensorField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 243:
/* Line 690 of lalr1.cc */
#line 1448 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield)=driver.getTensorField(*(yysemantic_stack_[(4) - (3)].name),true).ptr();
delete (yysemantic_stack_[(4) - (3)].name);
}
break;
case 244:
/* Line 690 of lalr1.cc */
#line 1452 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = CML::min(*(yysemantic_stack_[(6) - (3)].tfield),*(yysemantic_stack_[(6) - (5)].tfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].tfield); delete (yysemantic_stack_[(6) - (5)].tfield);
}
break;
case 245:
/* Line 690 of lalr1.cc */
#line 1456 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = CML::max(*(yysemantic_stack_[(6) - (3)].tfield),*(yysemantic_stack_[(6) - (5)].tfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].tfield); delete (yysemantic_stack_[(6) - (5)].tfield);
}
break;
case 246:
/* Line 690 of lalr1.cc */
#line 1463 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield)=driver.evaluatePluginFunction<CML::tensor>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 247:
/* Line 690 of lalr1.cc */
#line 1475 "../SubsetValueExpressionParser.yy"
{ (yyval.yfield) = (yysemantic_stack_[(1) - (1)].yfield); }
break;
case 248:
/* Line 690 of lalr1.cc */
#line 1476 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) + *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 249:
/* Line 690 of lalr1.cc */
#line 1481 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) + *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 250:
/* Line 690 of lalr1.cc */
#line 1486 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].hfield) + *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 251:
/* Line 690 of lalr1.cc */
#line 1491 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 252:
/* Line 690 of lalr1.cc */
#line 1496 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 253:
/* Line 690 of lalr1.cc */
#line 1501 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(
symm(*(yysemantic_stack_[(3) - (1)].yfield) & *(yysemantic_stack_[(3) - (3)].yfield))
);
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 254:
/* Line 690 of lalr1.cc */
#line 1512 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].hfield) & *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 255:
/* Line 690 of lalr1.cc */
#line 1517 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) & *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 256:
/* Line 690 of lalr1.cc */
#line 1522 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 257:
/* Line 690 of lalr1.cc */
#line 1527 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) - *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 258:
/* Line 690 of lalr1.cc */
#line 1532 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) - *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 259:
/* Line 690 of lalr1.cc */
#line 1537 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].hfield) - *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 260:
/* Line 690 of lalr1.cc */
#line 1542 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField(-*(yysemantic_stack_[(2) - (2)].yfield));
delete (yysemantic_stack_[(2) - (2)].yfield);
}
break;
case 261:
/* Line 690 of lalr1.cc */
#line 1546 "../SubsetValueExpressionParser.yy"
{ (yyval.yfield) = (yysemantic_stack_[(3) - (2)].yfield); }
break;
case 262:
/* Line 690 of lalr1.cc */
#line 1547 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::symm(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 263:
/* Line 690 of lalr1.cc */
#line 1551 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::symm(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 264:
/* Line 690 of lalr1.cc */
#line 1555 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::twoSymm(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 265:
/* Line 690 of lalr1.cc */
#line 1559 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::twoSymm(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 266:
/* Line 690 of lalr1.cc */
#line 1563 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::inv(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 267:
/* Line 690 of lalr1.cc */
#line 1567 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::cof(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 268:
/* Line 690 of lalr1.cc */
#line 1571 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::dev(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 269:
/* Line 690 of lalr1.cc */
#line 1575 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::dev2(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 270:
/* Line 690 of lalr1.cc */
#line 1579 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::sqr(*(yysemantic_stack_[(4) - (3)].vfield)) );
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 271:
/* Line 690 of lalr1.cc */
#line 1583 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = (yysemantic_stack_[(6) - (1)].yfield);
}
break;
case 272:
/* Line 690 of lalr1.cc */
#line 1586 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].yfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].yfield));
(yyval.yfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].yfield),*(yysemantic_stack_[(5) - (5)].yfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].yfield); delete (yysemantic_stack_[(5) - (5)].yfield);
}
break;
case 274:
/* Line 690 of lalr1.cc */
#line 1596 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield)=driver.getSymmTensorField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 275:
/* Line 690 of lalr1.cc */
#line 1600 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield)=driver.getSymmTensorField(*(yysemantic_stack_[(4) - (3)].name),true).ptr();
delete (yysemantic_stack_[(4) - (3)].name);
}
break;
case 276:
/* Line 690 of lalr1.cc */
#line 1604 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = CML::min(*(yysemantic_stack_[(6) - (3)].yfield),*(yysemantic_stack_[(6) - (5)].yfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].yfield); delete (yysemantic_stack_[(6) - (5)].yfield);
}
break;
case 277:
/* Line 690 of lalr1.cc */
#line 1608 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = CML::max(*(yysemantic_stack_[(6) - (3)].yfield),*(yysemantic_stack_[(6) - (5)].yfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].yfield); delete (yysemantic_stack_[(6) - (5)].yfield);
}
break;
case 278:
/* Line 690 of lalr1.cc */
#line 1615 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield)=driver.evaluatePluginFunction<CML::symmTensor>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 279:
/* Line 690 of lalr1.cc */
#line 1627 "../SubsetValueExpressionParser.yy"
{ (yyval.hfield) = (yysemantic_stack_[(1) - (1)].hfield); }
break;
case 280:
/* Line 690 of lalr1.cc */
#line 1628 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = driver.makeField(CML::sphericalTensor(1)).ptr();
}
break;
case 281:
/* Line 690 of lalr1.cc */
#line 1631 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) + *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 282:
/* Line 690 of lalr1.cc */
#line 1636 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 283:
/* Line 690 of lalr1.cc */
#line 1641 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 284:
/* Line 690 of lalr1.cc */
#line 1646 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) & *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 285:
/* Line 690 of lalr1.cc */
#line 1651 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 286:
/* Line 690 of lalr1.cc */
#line 1656 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) - *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 287:
/* Line 690 of lalr1.cc */
#line 1661 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = new CML::sphericalTensorField(-*(yysemantic_stack_[(2) - (2)].hfield));
delete (yysemantic_stack_[(2) - (2)].hfield);
}
break;
case 288:
/* Line 690 of lalr1.cc */
#line 1665 "../SubsetValueExpressionParser.yy"
{ (yyval.hfield) = (yysemantic_stack_[(3) - (2)].hfield); }
break;
case 289:
/* Line 690 of lalr1.cc */
#line 1666 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = new CML::sphericalTensorField( CML::sph(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 290:
/* Line 690 of lalr1.cc */
#line 1670 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = new CML::sphericalTensorField( CML::sph(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 291:
/* Line 690 of lalr1.cc */
#line 1674 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = new CML::sphericalTensorField( CML::sph(*(yysemantic_stack_[(4) - (3)].hfield)) );
delete (yysemantic_stack_[(4) - (3)].hfield);
}
break;
case 292:
/* Line 690 of lalr1.cc */
#line 1678 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = new CML::sphericalTensorField( CML::inv(*(yysemantic_stack_[(4) - (3)].hfield)) );
delete (yysemantic_stack_[(4) - (3)].hfield);
}
break;
case 293:
/* Line 690 of lalr1.cc */
#line 1682 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = (yysemantic_stack_[(6) - (1)].hfield);
}
break;
case 294:
/* Line 690 of lalr1.cc */
#line 1685 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].hfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].hfield));
(yyval.hfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].hfield),*(yysemantic_stack_[(5) - (5)].hfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].hfield); delete (yysemantic_stack_[(5) - (5)].hfield);
}
break;
case 296:
/* Line 690 of lalr1.cc */
#line 1695 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield)=driver.getSphericalTensorField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 297:
/* Line 690 of lalr1.cc */
#line 1699 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield)=driver.getSphericalTensorField(*(yysemantic_stack_[(4) - (3)].name),true).ptr();
delete (yysemantic_stack_[(4) - (3)].name);
}
break;
case 298:
/* Line 690 of lalr1.cc */
#line 1703 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = CML::min(*(yysemantic_stack_[(6) - (3)].hfield),*(yysemantic_stack_[(6) - (5)].hfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].hfield); delete (yysemantic_stack_[(6) - (5)].hfield);
}
break;
case 299:
/* Line 690 of lalr1.cc */
#line 1707 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = CML::max(*(yysemantic_stack_[(6) - (3)].hfield),*(yysemantic_stack_[(6) - (5)].hfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].hfield); delete (yysemantic_stack_[(6) - (5)].hfield);
}
break;
case 300:
/* Line 690 of lalr1.cc */
#line 1714 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield)=driver.evaluatePluginFunction<CML::sphericalTensor>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 301:
/* Line 690 of lalr1.cc */
#line 1726 "../SubsetValueExpressionParser.yy"
{ (yyval.lfield) = driver.makeField(true).ptr(); }
break;
case 302:
/* Line 690 of lalr1.cc */
#line 1727 "../SubsetValueExpressionParser.yy"
{ (yyval.lfield) = driver.makeField(false).ptr(); }
break;
case 303:
/* Line 690 of lalr1.cc */
#line 1728 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(*(yysemantic_stack_[(3) - (1)].sfield),std::less<CML::scalar>(),*(yysemantic_stack_[(3) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 304:
/* Line 690 of lalr1.cc */
#line 1733 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(*(yysemantic_stack_[(3) - (1)].sfield),std::greater<CML::scalar>(),*(yysemantic_stack_[(3) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 305:
/* Line 690 of lalr1.cc */
#line 1738 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(*(yysemantic_stack_[(3) - (1)].sfield),std::less_equal<CML::scalar>(),*(yysemantic_stack_[(3) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 306:
/* Line 690 of lalr1.cc */
#line 1743 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(
*(yysemantic_stack_[(3) - (1)].sfield),
std::greater_equal<CML::scalar>(),
*(yysemantic_stack_[(3) - (3)].sfield)
).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 307:
/* Line 690 of lalr1.cc */
#line 1752 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(*(yysemantic_stack_[(3) - (1)].sfield),std::equal_to<CML::scalar>(),*(yysemantic_stack_[(3) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 308:
/* Line 690 of lalr1.cc */
#line 1757 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(
*(yysemantic_stack_[(3) - (1)].sfield),
std::not_equal_to<CML::scalar>(),
*(yysemantic_stack_[(3) - (3)].sfield)
).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 309:
/* Line 690 of lalr1.cc */
#line 1766 "../SubsetValueExpressionParser.yy"
{ (yyval.lfield) = (yysemantic_stack_[(3) - (2)].lfield); }
break;
case 310:
/* Line 690 of lalr1.cc */
#line 1767 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].lfield),(yysemantic_stack_[(3) - (3)].lfield));
(yyval.lfield) = driver.doLogicalOp(
*(yysemantic_stack_[(3) - (1)].lfield),
std::logical_and<CML::scalar>(),
*(yysemantic_stack_[(3) - (3)].lfield)
).ptr();
delete (yysemantic_stack_[(3) - (1)].lfield); delete (yysemantic_stack_[(3) - (3)].lfield);
}
break;
case 311:
/* Line 690 of lalr1.cc */
#line 1776 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].lfield),(yysemantic_stack_[(3) - (3)].lfield));
(yyval.lfield) = driver.doLogicalOp(
*(yysemantic_stack_[(3) - (1)].lfield),
std::logical_or<CML::scalar>(),
*(yysemantic_stack_[(3) - (3)].lfield)
).ptr();
delete (yysemantic_stack_[(3) - (1)].lfield); delete (yysemantic_stack_[(3) - (3)].lfield);
}
break;
case 312:
/* Line 690 of lalr1.cc */
#line 1785 "../SubsetValueExpressionParser.yy"
{
(yyval.lfield) = driver.doLogicalNot(*(yysemantic_stack_[(2) - (2)].lfield)).ptr();
delete (yysemantic_stack_[(2) - (2)].lfield);
}
break;
case 314:
/* Line 690 of lalr1.cc */
#line 1790 "../SubsetValueExpressionParser.yy"
{
(yyval.lfield)=driver.getVariable<bool>(*(yysemantic_stack_[(1) - (1)].name),driver.size()).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 315:
/* Line 690 of lalr1.cc */
#line 1797 "../SubsetValueExpressionParser.yy"
{
(yyval.lfield)=driver.evaluatePluginFunction<bool>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 316:
/* Line 690 of lalr1.cc */
#line 1809 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.composeVectorField(*(yysemantic_stack_[(8) - (3)].sfield),*(yysemantic_stack_[(8) - (5)].sfield),*(yysemantic_stack_[(8) - (7)].sfield)).ptr();
delete (yysemantic_stack_[(8) - (3)].sfield); delete (yysemantic_stack_[(8) - (5)].sfield); delete (yysemantic_stack_[(8) - (7)].sfield);
}
break;
case 317:
/* Line 690 of lalr1.cc */
#line 1815 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = driver.composeTensorField(
*(yysemantic_stack_[(20) - (3)].sfield),*(yysemantic_stack_[(20) - (5)].sfield),*(yysemantic_stack_[(20) - (7)].sfield),
*(yysemantic_stack_[(20) - (9)].sfield),*(yysemantic_stack_[(20) - (11)].sfield),*(yysemantic_stack_[(20) - (13)].sfield),
*(yysemantic_stack_[(20) - (15)].sfield),*(yysemantic_stack_[(20) - (17)].sfield),*(yysemantic_stack_[(20) - (19)].sfield)
).ptr();
delete (yysemantic_stack_[(20) - (3)].sfield); delete (yysemantic_stack_[(20) - (5)].sfield); delete (yysemantic_stack_[(20) - (7)].sfield); delete (yysemantic_stack_[(20) - (9)].sfield); delete (yysemantic_stack_[(20) - (11)].sfield);
delete (yysemantic_stack_[(20) - (13)].sfield); delete (yysemantic_stack_[(20) - (15)].sfield); delete (yysemantic_stack_[(20) - (17)].sfield); delete (yysemantic_stack_[(20) - (19)].sfield);
}
break;
case 318:
/* Line 690 of lalr1.cc */
#line 1825 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = driver.composeSymmTensorField(
*(yysemantic_stack_[(14) - (3)].sfield),*(yysemantic_stack_[(14) - (5)].sfield),*(yysemantic_stack_[(14) - (7)].sfield),
*(yysemantic_stack_[(14) - (9)].sfield),*(yysemantic_stack_[(14) - (11)].sfield),
*(yysemantic_stack_[(14) - (13)].sfield)
).ptr();
delete (yysemantic_stack_[(14) - (3)].sfield); delete (yysemantic_stack_[(14) - (5)].sfield); delete (yysemantic_stack_[(14) - (7)].sfield); delete (yysemantic_stack_[(14) - (9)].sfield); delete (yysemantic_stack_[(14) - (11)].sfield); delete (yysemantic_stack_[(14) - (13)].sfield);
}
break;
case 319:
/* Line 690 of lalr1.cc */
#line 1834 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = driver.composeSphericalTensorField(*(yysemantic_stack_[(4) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 320:
/* Line 690 of lalr1.cc */
#line 1839 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) + *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 321:
/* Line 690 of lalr1.cc */
#line 1844 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 322:
/* Line 690 of lalr1.cc */
#line 1849 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 323:
/* Line 690 of lalr1.cc */
#line 1854 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].tfield) & *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 324:
/* Line 690 of lalr1.cc */
#line 1859 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) & *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 325:
/* Line 690 of lalr1.cc */
#line 1864 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].yfield) & *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 326:
/* Line 690 of lalr1.cc */
#line 1869 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) & *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 327:
/* Line 690 of lalr1.cc */
#line 1874 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].hfield) & *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 328:
/* Line 690 of lalr1.cc */
#line 1879 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) & *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 329:
/* Line 690 of lalr1.cc */
#line 1884 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 330:
/* Line 690 of lalr1.cc */
#line 1889 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) ^ *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 331:
/* Line 690 of lalr1.cc */
#line 1894 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.vfield) = new CML::vectorField(*(yysemantic_stack_[(3) - (1)].vfield) - *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 332:
/* Line 690 of lalr1.cc */
#line 1899 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(-*(yysemantic_stack_[(2) - (2)].vfield));
delete (yysemantic_stack_[(2) - (2)].vfield);
}
break;
case 333:
/* Line 690 of lalr1.cc */
#line 1903 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(*(*(yysemantic_stack_[(2) - (2)].tfield)));
delete (yysemantic_stack_[(2) - (2)].tfield);
}
break;
case 334:
/* Line 690 of lalr1.cc */
#line 1907 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(*(*(yysemantic_stack_[(2) - (2)].yfield)));
delete (yysemantic_stack_[(2) - (2)].yfield);
}
break;
case 335:
/* Line 690 of lalr1.cc */
#line 1911 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(CML::eigenValues(*(yysemantic_stack_[(4) - (3)].tfield)));
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 336:
/* Line 690 of lalr1.cc */
#line 1915 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = new CML::vectorField(CML::eigenValues(*(yysemantic_stack_[(4) - (3)].yfield)));
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 337:
/* Line 690 of lalr1.cc */
#line 1919 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::XX)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::XY)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::XZ)()
).ptr();
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 338:
/* Line 690 of lalr1.cc */
#line 1927 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::YX)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::YY)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::YZ)()
).ptr();
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 339:
/* Line 690 of lalr1.cc */
#line 1935 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::ZX)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::ZY)(),
(yysemantic_stack_[(4) - (1)].tfield)->component(CML::tensor::ZZ)()
).ptr();
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 340:
/* Line 690 of lalr1.cc */
#line 1943 "../SubsetValueExpressionParser.yy"
{
// $$ = new CML::vectorField( CML::diag(*$3) ); // not implemented?
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (3)].tfield)->component(CML::tensor::XX)(),
(yysemantic_stack_[(4) - (3)].tfield)->component(CML::tensor::YY)(),
(yysemantic_stack_[(4) - (3)].tfield)->component(CML::tensor::ZZ)()
).ptr();
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 341:
/* Line 690 of lalr1.cc */
#line 1952 "../SubsetValueExpressionParser.yy"
{
// $$ = new CML::vectorField( CML::diag(*$3) ); // not implemented?
(yyval.vfield) = driver.composeVectorField(
(yysemantic_stack_[(4) - (3)].yfield)->component(CML::symmTensor::XX)(),
(yysemantic_stack_[(4) - (3)].yfield)->component(CML::symmTensor::YY)(),
(yysemantic_stack_[(4) - (3)].yfield)->component(CML::symmTensor::ZZ)()
).ptr();
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 342:
/* Line 690 of lalr1.cc */
#line 1961 "../SubsetValueExpressionParser.yy"
{ (yyval.vfield) = (yysemantic_stack_[(3) - (2)].vfield); }
break;
case 343:
/* Line 690 of lalr1.cc */
#line 1962 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].vfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].vfield));
(yyval.vfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].vfield),*(yysemantic_stack_[(5) - (5)].vfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].vfield); delete (yysemantic_stack_[(5) - (5)].vfield);
}
break;
case 345:
/* Line 690 of lalr1.cc */
#line 1973 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield)=driver.getVectorField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 346:
/* Line 690 of lalr1.cc */
#line 1977 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = CML::min(*(yysemantic_stack_[(6) - (3)].vfield),*(yysemantic_stack_[(6) - (5)].vfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].vfield); delete (yysemantic_stack_[(6) - (5)].vfield);
}
break;
case 347:
/* Line 690 of lalr1.cc */
#line 1981 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield) = CML::max(*(yysemantic_stack_[(6) - (3)].vfield),*(yysemantic_stack_[(6) - (5)].vfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].vfield); delete (yysemantic_stack_[(6) - (5)].vfield);
}
break;
case 348:
/* Line 690 of lalr1.cc */
#line 1988 "../SubsetValueExpressionParser.yy"
{
(yyval.vfield)=driver.evaluatePluginFunction<CML::vector>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 349:
/* Line 690 of lalr1.cc */
#line 2000 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].sfield) + *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 350:
/* Line 690 of lalr1.cc */
#line 2005 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].sfield) - *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 351:
/* Line 690 of lalr1.cc */
#line 2010 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 352:
/* Line 690 of lalr1.cc */
#line 2015 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = driver.makeModuloField(*(yysemantic_stack_[(3) - (1)].sfield),*(yysemantic_stack_[(3) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 353:
/* Line 690 of lalr1.cc */
#line 2020 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].sfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 354:
/* Line 690 of lalr1.cc */
#line 2025 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::pow(*(yysemantic_stack_[(6) - (3)].sfield), (yysemantic_stack_[(6) - (5)].val)));
delete (yysemantic_stack_[(6) - (3)].sfield);
}
break;
case 355:
/* Line 690 of lalr1.cc */
#line 2029 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(6) - (3)].sfield),(yysemantic_stack_[(6) - (5)].sfield));
(yyval.sfield) = new CML::scalarField(CML::pow(*(yysemantic_stack_[(6) - (3)].sfield), *(yysemantic_stack_[(6) - (5)].sfield)));
delete (yysemantic_stack_[(6) - (3)].sfield); delete (yysemantic_stack_[(6) - (5)].sfield);
}
break;
case 356:
/* Line 690 of lalr1.cc */
#line 2034 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::log(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 357:
/* Line 690 of lalr1.cc */
#line 2038 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::exp(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 358:
/* Line 690 of lalr1.cc */
#line 2042 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].vfield) & *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 359:
/* Line 690 of lalr1.cc */
#line 2047 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].tfield) && *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 360:
/* Line 690 of lalr1.cc */
#line 2052 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].tfield) && *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 361:
/* Line 690 of lalr1.cc */
#line 2057 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].tfield) && *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 362:
/* Line 690 of lalr1.cc */
#line 2062 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].yfield) && *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 363:
/* Line 690 of lalr1.cc */
#line 2067 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].yfield) && *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 364:
/* Line 690 of lalr1.cc */
#line 2072 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].yfield) && *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 365:
/* Line 690 of lalr1.cc */
#line 2077 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].hfield) && *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 366:
/* Line 690 of lalr1.cc */
#line 2082 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].hfield) && *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 367:
/* Line 690 of lalr1.cc */
#line 2087 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.sfield) = new CML::scalarField(*(yysemantic_stack_[(3) - (1)].hfield) && *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 368:
/* Line 690 of lalr1.cc */
#line 2092 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(-*(yysemantic_stack_[(2) - (2)].sfield));
delete (yysemantic_stack_[(2) - (2)].sfield);
}
break;
case 369:
/* Line 690 of lalr1.cc */
#line 2096 "../SubsetValueExpressionParser.yy"
{ (yyval.sfield) = (yysemantic_stack_[(3) - (2)].sfield); }
break;
case 370:
/* Line 690 of lalr1.cc */
#line 2097 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sqr(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 371:
/* Line 690 of lalr1.cc */
#line 2101 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sqrt(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 372:
/* Line 690 of lalr1.cc */
#line 2105 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sin(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 373:
/* Line 690 of lalr1.cc */
#line 2109 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::cos(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 374:
/* Line 690 of lalr1.cc */
#line 2113 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::tan(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 375:
/* Line 690 of lalr1.cc */
#line 2117 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::log10(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 376:
/* Line 690 of lalr1.cc */
#line 2121 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::asin(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 377:
/* Line 690 of lalr1.cc */
#line 2125 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::acos(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 378:
/* Line 690 of lalr1.cc */
#line 2129 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::atan(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 379:
/* Line 690 of lalr1.cc */
#line 2133 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sinh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 380:
/* Line 690 of lalr1.cc */
#line 2137 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::cosh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 381:
/* Line 690 of lalr1.cc */
#line 2141 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::tanh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 382:
/* Line 690 of lalr1.cc */
#line 2145 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::asinh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 383:
/* Line 690 of lalr1.cc */
#line 2149 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::acosh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 384:
/* Line 690 of lalr1.cc */
#line 2153 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::atanh(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 385:
/* Line 690 of lalr1.cc */
#line 2157 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::erf(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 386:
/* Line 690 of lalr1.cc */
#line 2161 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::erfc(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 387:
/* Line 690 of lalr1.cc */
#line 2165 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::lgamma(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 388:
/* Line 690 of lalr1.cc */
#line 2169 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::j0(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 389:
/* Line 690 of lalr1.cc */
#line 2173 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::j1(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 390:
/* Line 690 of lalr1.cc */
#line 2177 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::y0(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 391:
/* Line 690 of lalr1.cc */
#line 2181 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::y1(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 392:
/* Line 690 of lalr1.cc */
#line 2185 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::sign(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 393:
/* Line 690 of lalr1.cc */
#line 2189 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::pos(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 394:
/* Line 690 of lalr1.cc */
#line 2193 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::neg(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 395:
/* Line 690 of lalr1.cc */
#line 2197 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 396:
/* Line 690 of lalr1.cc */
#line 2201 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].vfield)));
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 397:
/* Line 690 of lalr1.cc */
#line 2205 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].tfield)));
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 398:
/* Line 690 of lalr1.cc */
#line 2209 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].yfield)));
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 399:
/* Line 690 of lalr1.cc */
#line 2213 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::mag(*(yysemantic_stack_[(4) - (3)].hfield)));
delete (yysemantic_stack_[(4) - (3)].hfield);
}
break;
case 400:
/* Line 690 of lalr1.cc */
#line 2217 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].sfield)));
delete (yysemantic_stack_[(4) - (3)].sfield);
}
break;
case 401:
/* Line 690 of lalr1.cc */
#line 2221 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].vfield)));
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 402:
/* Line 690 of lalr1.cc */
#line 2225 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].tfield)));
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 403:
/* Line 690 of lalr1.cc */
#line 2229 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].yfield)));
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 404:
/* Line 690 of lalr1.cc */
#line 2233 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField(CML::magSqr(*(yysemantic_stack_[(4) - (3)].hfield)));
delete (yysemantic_stack_[(4) - (3)].hfield);
}
break;
case 405:
/* Line 690 of lalr1.cc */
#line 2237 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].vfield)->component(0));
delete (yysemantic_stack_[(4) - (1)].vfield);
}
break;
case 406:
/* Line 690 of lalr1.cc */
#line 2241 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].vfield)->component(1));
delete (yysemantic_stack_[(4) - (1)].vfield);
}
break;
case 407:
/* Line 690 of lalr1.cc */
#line 2245 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].vfield)->component(2));
delete (yysemantic_stack_[(4) - (1)].vfield);
}
break;
case 408:
/* Line 690 of lalr1.cc */
#line 2249 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(0));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 409:
/* Line 690 of lalr1.cc */
#line 2253 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(1));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 410:
/* Line 690 of lalr1.cc */
#line 2257 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(2));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 411:
/* Line 690 of lalr1.cc */
#line 2261 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(3));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 412:
/* Line 690 of lalr1.cc */
#line 2265 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(4));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 413:
/* Line 690 of lalr1.cc */
#line 2269 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(5));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 414:
/* Line 690 of lalr1.cc */
#line 2273 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(6));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 415:
/* Line 690 of lalr1.cc */
#line 2277 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(7));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 416:
/* Line 690 of lalr1.cc */
#line 2281 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].tfield)->component(8));
delete (yysemantic_stack_[(4) - (1)].tfield);
}
break;
case 417:
/* Line 690 of lalr1.cc */
#line 2285 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(0));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 418:
/* Line 690 of lalr1.cc */
#line 2289 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(1));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 419:
/* Line 690 of lalr1.cc */
#line 2293 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(2));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 420:
/* Line 690 of lalr1.cc */
#line 2297 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(3));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 421:
/* Line 690 of lalr1.cc */
#line 2301 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(4));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 422:
/* Line 690 of lalr1.cc */
#line 2305 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].yfield)->component(5));
delete (yysemantic_stack_[(4) - (1)].yfield);
}
break;
case 423:
/* Line 690 of lalr1.cc */
#line 2309 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = new CML::scalarField((yysemantic_stack_[(4) - (1)].hfield)->component(0));
delete (yysemantic_stack_[(4) - (1)].hfield);
}
break;
case 424:
/* Line 690 of lalr1.cc */
#line 2313 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].sfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].sfield));
(yyval.sfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].sfield),*(yysemantic_stack_[(5) - (5)].sfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].sfield); delete (yysemantic_stack_[(5) - (5)].sfield);
}
break;
case 426:
/* Line 690 of lalr1.cc */
#line 2323 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield)=driver.getScalarField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 427:
/* Line 690 of lalr1.cc */
#line 2327 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = CML::min(*(yysemantic_stack_[(6) - (3)].sfield),*(yysemantic_stack_[(6) - (5)].sfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].sfield); delete (yysemantic_stack_[(6) - (5)].sfield);
}
break;
case 428:
/* Line 690 of lalr1.cc */
#line 2331 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield) = CML::max(*(yysemantic_stack_[(6) - (3)].sfield),*(yysemantic_stack_[(6) - (5)].sfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].sfield); delete (yysemantic_stack_[(6) - (5)].sfield);
}
break;
case 429:
/* Line 690 of lalr1.cc */
#line 2338 "../SubsetValueExpressionParser.yy"
{
(yyval.sfield)=driver.evaluatePluginFunction<CML::scalar>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 430:
/* Line 690 of lalr1.cc */
#line 2350 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) + *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 431:
/* Line 690 of lalr1.cc */
#line 2355 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 432:
/* Line 690 of lalr1.cc */
#line 2360 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 433:
/* Line 690 of lalr1.cc */
#line 2365 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].vfield),(yysemantic_stack_[(3) - (3)].vfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].vfield) * *(yysemantic_stack_[(3) - (3)].vfield));
delete (yysemantic_stack_[(3) - (1)].vfield); delete (yysemantic_stack_[(3) - (3)].vfield);
}
break;
case 434:
/* Line 690 of lalr1.cc */
#line 2370 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) & *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 435:
/* Line 690 of lalr1.cc */
#line 2375 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].yfield) & *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 436:
/* Line 690 of lalr1.cc */
#line 2380 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) & *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 437:
/* Line 690 of lalr1.cc */
#line 2385 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].hfield) & *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 438:
/* Line 690 of lalr1.cc */
#line 2390 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) & *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 439:
/* Line 690 of lalr1.cc */
#line 2395 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 440:
/* Line 690 of lalr1.cc */
#line 2400 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].tfield),(yysemantic_stack_[(3) - (3)].tfield));
(yyval.tfield) = new CML::tensorField(*(yysemantic_stack_[(3) - (1)].tfield) - *(yysemantic_stack_[(3) - (3)].tfield));
delete (yysemantic_stack_[(3) - (1)].tfield); delete (yysemantic_stack_[(3) - (3)].tfield);
}
break;
case 441:
/* Line 690 of lalr1.cc */
#line 2405 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField(-*(yysemantic_stack_[(2) - (2)].tfield));
delete (yysemantic_stack_[(2) - (2)].tfield);
}
break;
case 442:
/* Line 690 of lalr1.cc */
#line 2409 "../SubsetValueExpressionParser.yy"
{ (yyval.tfield) = (yysemantic_stack_[(3) - (2)].tfield); }
break;
case 443:
/* Line 690 of lalr1.cc */
#line 2410 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::skew(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 444:
/* Line 690 of lalr1.cc */
#line 2414 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField(CML::eigenVectors(*(yysemantic_stack_[(4) - (3)].tfield)));
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 445:
/* Line 690 of lalr1.cc */
#line 2418 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField(CML::eigenVectors(*(yysemantic_stack_[(4) - (3)].yfield)));
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 446:
/* Line 690 of lalr1.cc */
#line 2422 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::inv(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 447:
/* Line 690 of lalr1.cc */
#line 2426 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::cof(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 448:
/* Line 690 of lalr1.cc */
#line 2430 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::dev(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 449:
/* Line 690 of lalr1.cc */
#line 2434 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( CML::dev2(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 450:
/* Line 690 of lalr1.cc */
#line 2438 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = new CML::tensorField( (yysemantic_stack_[(6) - (1)].tfield)->T() );
delete (yysemantic_stack_[(6) - (1)].tfield);
}
break;
case 451:
/* Line 690 of lalr1.cc */
#line 2442 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].tfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].tfield));
(yyval.tfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].tfield),*(yysemantic_stack_[(5) - (5)].tfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].tfield); delete (yysemantic_stack_[(5) - (5)].tfield);
}
break;
case 453:
/* Line 690 of lalr1.cc */
#line 2452 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield)=driver.getTensorField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 454:
/* Line 690 of lalr1.cc */
#line 2456 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = CML::min(*(yysemantic_stack_[(6) - (3)].tfield),*(yysemantic_stack_[(6) - (5)].tfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].tfield); delete (yysemantic_stack_[(6) - (5)].tfield);
}
break;
case 455:
/* Line 690 of lalr1.cc */
#line 2460 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield) = CML::max(*(yysemantic_stack_[(6) - (3)].tfield),*(yysemantic_stack_[(6) - (5)].tfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].tfield); delete (yysemantic_stack_[(6) - (5)].tfield);
}
break;
case 456:
/* Line 690 of lalr1.cc */
#line 2467 "../SubsetValueExpressionParser.yy"
{
(yyval.tfield)=driver.evaluatePluginFunction<CML::tensor>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 457:
/* Line 690 of lalr1.cc */
#line 2479 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) + *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 458:
/* Line 690 of lalr1.cc */
#line 2484 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 459:
/* Line 690 of lalr1.cc */
#line 2489 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 460:
/* Line 690 of lalr1.cc */
#line 2494 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(
symm(*(yysemantic_stack_[(3) - (1)].yfield) & *(yysemantic_stack_[(3) - (3)].yfield))
);
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 461:
/* Line 690 of lalr1.cc */
#line 2505 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].hfield) & *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 462:
/* Line 690 of lalr1.cc */
#line 2510 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) & *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 463:
/* Line 690 of lalr1.cc */
#line 2515 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 464:
/* Line 690 of lalr1.cc */
#line 2520 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].yfield),(yysemantic_stack_[(3) - (3)].yfield));
(yyval.yfield) = new CML::symmTensorField(*(yysemantic_stack_[(3) - (1)].yfield) - *(yysemantic_stack_[(3) - (3)].yfield));
delete (yysemantic_stack_[(3) - (1)].yfield); delete (yysemantic_stack_[(3) - (3)].yfield);
}
break;
case 465:
/* Line 690 of lalr1.cc */
#line 2525 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField(-*(yysemantic_stack_[(2) - (2)].yfield));
delete (yysemantic_stack_[(2) - (2)].yfield);
}
break;
case 466:
/* Line 690 of lalr1.cc */
#line 2529 "../SubsetValueExpressionParser.yy"
{ (yyval.yfield) = (yysemantic_stack_[(3) - (2)].yfield); }
break;
case 467:
/* Line 690 of lalr1.cc */
#line 2530 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::symm(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 468:
/* Line 690 of lalr1.cc */
#line 2534 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::symm(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 469:
/* Line 690 of lalr1.cc */
#line 2538 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::twoSymm(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 470:
/* Line 690 of lalr1.cc */
#line 2542 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::twoSymm(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 471:
/* Line 690 of lalr1.cc */
#line 2546 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::inv(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 472:
/* Line 690 of lalr1.cc */
#line 2550 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::cof(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 473:
/* Line 690 of lalr1.cc */
#line 2554 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::dev(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 474:
/* Line 690 of lalr1.cc */
#line 2558 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::dev2(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 475:
/* Line 690 of lalr1.cc */
#line 2562 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = new CML::symmTensorField( CML::sqr(*(yysemantic_stack_[(4) - (3)].vfield)) );
delete (yysemantic_stack_[(4) - (3)].vfield);
}
break;
case 476:
/* Line 690 of lalr1.cc */
#line 2566 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = (yysemantic_stack_[(6) - (1)].yfield);
}
break;
case 477:
/* Line 690 of lalr1.cc */
#line 2569 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].yfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].yfield));
(yyval.yfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].yfield),*(yysemantic_stack_[(5) - (5)].yfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].yfield); delete (yysemantic_stack_[(5) - (5)].yfield);
}
break;
case 479:
/* Line 690 of lalr1.cc */
#line 2579 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield)=driver.getSymmTensorField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 480:
/* Line 690 of lalr1.cc */
#line 2583 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = CML::min(*(yysemantic_stack_[(6) - (3)].yfield),*(yysemantic_stack_[(6) - (5)].yfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].yfield); delete (yysemantic_stack_[(6) - (5)].yfield);
}
break;
case 481:
/* Line 690 of lalr1.cc */
#line 2587 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield) = CML::max(*(yysemantic_stack_[(6) - (3)].yfield),*(yysemantic_stack_[(6) - (5)].yfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].yfield); delete (yysemantic_stack_[(6) - (5)].yfield);
}
break;
case 482:
/* Line 690 of lalr1.cc */
#line 2594 "../SubsetValueExpressionParser.yy"
{
(yyval.yfield)=driver.evaluatePluginFunction<CML::symmTensor>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 483:
/* Line 690 of lalr1.cc */
#line 2605 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) + *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 484:
/* Line 690 of lalr1.cc */
#line 2610 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].sfield) * *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 485:
/* Line 690 of lalr1.cc */
#line 2615 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) * *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 486:
/* Line 690 of lalr1.cc */
#line 2620 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) & *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 487:
/* Line 690 of lalr1.cc */
#line 2625 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) / *(yysemantic_stack_[(3) - (3)].sfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 488:
/* Line 690 of lalr1.cc */
#line 2630 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].hfield),(yysemantic_stack_[(3) - (3)].hfield));
(yyval.hfield) = new CML::sphericalTensorField(*(yysemantic_stack_[(3) - (1)].hfield) - *(yysemantic_stack_[(3) - (3)].hfield));
delete (yysemantic_stack_[(3) - (1)].hfield); delete (yysemantic_stack_[(3) - (3)].hfield);
}
break;
case 489:
/* Line 690 of lalr1.cc */
#line 2635 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = new CML::sphericalTensorField(-*(yysemantic_stack_[(2) - (2)].hfield));
delete (yysemantic_stack_[(2) - (2)].hfield);
}
break;
case 490:
/* Line 690 of lalr1.cc */
#line 2639 "../SubsetValueExpressionParser.yy"
{ (yyval.hfield) = (yysemantic_stack_[(3) - (2)].hfield); }
break;
case 491:
/* Line 690 of lalr1.cc */
#line 2640 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = new CML::sphericalTensorField( CML::sph(*(yysemantic_stack_[(4) - (3)].tfield)) );
delete (yysemantic_stack_[(4) - (3)].tfield);
}
break;
case 492:
/* Line 690 of lalr1.cc */
#line 2644 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = new CML::sphericalTensorField( CML::sph(*(yysemantic_stack_[(4) - (3)].yfield)) );
delete (yysemantic_stack_[(4) - (3)].yfield);
}
break;
case 493:
/* Line 690 of lalr1.cc */
#line 2648 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = new CML::sphericalTensorField( CML::sph(*(yysemantic_stack_[(4) - (3)].hfield)) );
delete (yysemantic_stack_[(4) - (3)].hfield);
}
break;
case 494:
/* Line 690 of lalr1.cc */
#line 2652 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = (yysemantic_stack_[(6) - (1)].hfield);
}
break;
case 495:
/* Line 690 of lalr1.cc */
#line 2655 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (3)].hfield)); sameSize((yysemantic_stack_[(5) - (1)].lfield),(yysemantic_stack_[(5) - (5)].hfield));
(yyval.hfield) = driver.doConditional(*(yysemantic_stack_[(5) - (1)].lfield),*(yysemantic_stack_[(5) - (3)].hfield),*(yysemantic_stack_[(5) - (5)].hfield)).ptr();
delete (yysemantic_stack_[(5) - (1)].lfield); delete (yysemantic_stack_[(5) - (3)].hfield); delete (yysemantic_stack_[(5) - (5)].hfield);
}
break;
case 497:
/* Line 690 of lalr1.cc */
#line 2665 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield)=driver.getSphericalTensorField(*(yysemantic_stack_[(1) - (1)].name)).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 498:
/* Line 690 of lalr1.cc */
#line 2669 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = CML::min(*(yysemantic_stack_[(6) - (3)].hfield),*(yysemantic_stack_[(6) - (5)].hfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].hfield); delete (yysemantic_stack_[(6) - (5)].hfield);
}
break;
case 499:
/* Line 690 of lalr1.cc */
#line 2673 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield) = CML::max(*(yysemantic_stack_[(6) - (3)].hfield),*(yysemantic_stack_[(6) - (5)].hfield)).ptr();
delete (yysemantic_stack_[(6) - (3)].hfield); delete (yysemantic_stack_[(6) - (5)].hfield);
}
break;
case 500:
/* Line 690 of lalr1.cc */
#line 2680 "../SubsetValueExpressionParser.yy"
{
(yyval.hfield)=driver.evaluatePluginFunction<CML::sphericalTensor>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
case 501:
/* Line 690 of lalr1.cc */
#line 2691 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(*(yysemantic_stack_[(3) - (1)].sfield),std::less<CML::scalar>(),*(yysemantic_stack_[(3) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 502:
/* Line 690 of lalr1.cc */
#line 2696 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(*(yysemantic_stack_[(3) - (1)].sfield),std::greater<CML::scalar>(),*(yysemantic_stack_[(3) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 503:
/* Line 690 of lalr1.cc */
#line 2701 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(
*(yysemantic_stack_[(3) - (1)].sfield),
std::less_equal<CML::scalar>(),
*(yysemantic_stack_[(3) - (3)].sfield)
).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 504:
/* Line 690 of lalr1.cc */
#line 2710 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(
*(yysemantic_stack_[(3) - (1)].sfield),
std::greater_equal<CML::scalar>(),
*(yysemantic_stack_[(3) - (3)].sfield)
).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 505:
/* Line 690 of lalr1.cc */
#line 2719 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(*(yysemantic_stack_[(3) - (1)].sfield),std::equal_to<CML::scalar>(),*(yysemantic_stack_[(3) - (3)].sfield)).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 506:
/* Line 690 of lalr1.cc */
#line 2724 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].sfield),(yysemantic_stack_[(3) - (3)].sfield));
(yyval.lfield) = driver.doCompare(
*(yysemantic_stack_[(3) - (1)].sfield),
std::not_equal_to<CML::scalar>(),
*(yysemantic_stack_[(3) - (3)].sfield)
).ptr();
delete (yysemantic_stack_[(3) - (1)].sfield); delete (yysemantic_stack_[(3) - (3)].sfield);
}
break;
case 507:
/* Line 690 of lalr1.cc */
#line 2733 "../SubsetValueExpressionParser.yy"
{ (yyval.lfield) = (yysemantic_stack_[(3) - (2)].lfield); }
break;
case 508:
/* Line 690 of lalr1.cc */
#line 2734 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].lfield),(yysemantic_stack_[(3) - (3)].lfield));
(yyval.lfield) = driver.doLogicalOp(
*(yysemantic_stack_[(3) - (1)].lfield),
std::logical_and<CML::scalar>(),
*(yysemantic_stack_[(3) - (3)].lfield)
).ptr();
delete (yysemantic_stack_[(3) - (1)].lfield); delete (yysemantic_stack_[(3) - (3)].lfield);
}
break;
case 509:
/* Line 690 of lalr1.cc */
#line 2743 "../SubsetValueExpressionParser.yy"
{
sameSize((yysemantic_stack_[(3) - (1)].lfield),(yysemantic_stack_[(3) - (3)].lfield));
(yyval.lfield) = driver.doLogicalOp(
*(yysemantic_stack_[(3) - (1)].lfield),
std::logical_or<CML::scalar>(),
*(yysemantic_stack_[(3) - (3)].lfield)
).ptr();
delete (yysemantic_stack_[(3) - (1)].lfield); delete (yysemantic_stack_[(3) - (3)].lfield);
}
break;
case 510:
/* Line 690 of lalr1.cc */
#line 2752 "../SubsetValueExpressionParser.yy"
{
(yyval.lfield) = driver.doLogicalNot(*(yysemantic_stack_[(2) - (2)].lfield)).ptr();
delete (yysemantic_stack_[(2) - (2)].lfield);
}
break;
case 512:
/* Line 690 of lalr1.cc */
#line 2757 "../SubsetValueExpressionParser.yy"
{
(yyval.lfield)=driver.getVariable<bool>(*(yysemantic_stack_[(1) - (1)].name),driver.pointSize()).ptr();
delete (yysemantic_stack_[(1) - (1)].name);
}
break;
case 513:
/* Line 690 of lalr1.cc */
#line 2764 "../SubsetValueExpressionParser.yy"
{
(yyval.lfield)=driver.evaluatePluginFunction<bool>(
*(yysemantic_stack_[(3) - (1)].name),
(yylocation_stack_[(3) - (2)]),
numberOfFunctionChars,
false
).ptr();
delete (yysemantic_stack_[(3) - (1)].name);
}
break;
/* Line 690 of lalr1.cc */
#line 7169 "SubsetValueExpressionParser.tab.cc"
default:
break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action
invokes YYABORT, YYACCEPT, or YYERROR immediately after altering
yychar. In the case of YYABORT or YYACCEPT, an incorrect
destructor might then be invoked immediately. In the case of
YYERROR, subsequent parser actions might lead to an incorrect
destructor call or verbose syntax error message before the
lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1_[yyn], &yyval, &yyloc);
yypop_ (yylen);
yylen = 0;
YY_STACK_PRINT ();
yysemantic_stack_.push (yyval);
yylocation_stack_.push (yyloc);
/* Shift the result of the reduction. */
yyn = yyr1_[yyn];
yystate = yypgoto_[yyn - yyntokens_] + yystate_stack_[0];
if (0 <= yystate && yystate <= yylast_
&& yycheck_[yystate] == yystate_stack_[0])
yystate = yytable_[yystate];
else
yystate = yydefgoto_[yyn - yyntokens_];
goto yynewstate;
/*------------------------------------.
| yyerrlab -- here on detecting error |
`------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yytranslate_ (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus_)
{
++yynerrs_;
if (yychar == yyempty_)
yytoken = yyempty_;
error (yylloc, yysyntax_error_ (yystate, yytoken));
}
yyerror_range[1] = yylloc;
if (yyerrstatus_ == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= yyeof_)
{
/* Return failure if at end of input. */
if (yychar == yyeof_)
YYABORT;
}
else
{
yydestruct_ ("Error: discarding", yytoken, &yylval, &yylloc);
yychar = yyempty_;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (false)
goto yyerrorlab;
yyerror_range[1] = yylocation_stack_[yylen - 1];
/* Do not reclaim the symbols of the rule which action triggered
this YYERROR. */
yypop_ (yylen);
yylen = 0;
yystate = yystate_stack_[0];
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus_ = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact_[yystate];
if (!yy_pact_value_is_default_ (yyn))
{
yyn += yyterror_;
if (0 <= yyn && yyn <= yylast_ && yycheck_[yyn] == yyterror_)
{
yyn = yytable_[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yystate_stack_.height () == 1)
YYABORT;
yyerror_range[1] = yylocation_stack_[0];
yydestruct_ ("Error: popping",
yystos_[yystate],
&yysemantic_stack_[0], &yylocation_stack_[0]);
yypop_ ();
yystate = yystate_stack_[0];
YY_STACK_PRINT ();
}
yyerror_range[2] = yylloc;
// Using YYLLOC is tempting, but would change the location of
// the lookahead. YYLOC is available though.
YYLLOC_DEFAULT (yyloc, yyerror_range, 2);
yysemantic_stack_.push (yylval);
yylocation_stack_.push (yyloc);
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos_[yyn],
&yysemantic_stack_[0], &yylocation_stack_[0]);
yystate = yyn;
goto yynewstate;
/* Accept. */
yyacceptlab:
yyresult = 0;
goto yyreturn;
/* Abort. */
yyabortlab:
yyresult = 1;
goto yyreturn;
yyreturn:
if (yychar != yyempty_)
{
/* Make sure we have latest lookahead translation. See comments
at user semantic actions for why this is necessary. */
yytoken = yytranslate_ (yychar);
yydestruct_ ("Cleanup: discarding lookahead", yytoken, &yylval,
&yylloc);
}
/* Do not reclaim the symbols of the rule which action triggered
this YYABORT or YYACCEPT. */
yypop_ (yylen);
while (yystate_stack_.height () != 1)
{
yydestruct_ ("Cleanup: popping",
yystos_[yystate_stack_[0]],
&yysemantic_stack_[0],
&yylocation_stack_[0]);
yypop_ ();
}
return yyresult;
}
// Generate an error message.
std::string
SubsetValueExpressionParser::yysyntax_error_ (int yystate, int yytoken)
{
std::string yyres;
// Number of reported tokens (one for the "unexpected", one per
// "expected").
size_t yycount = 0;
// Its maximum.
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
// Arguments of yyformat.
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yytoken) is
if this state is a consistent state with a default action.
Thus, detecting the absence of a lookahead is sufficient to
determine that there is no unexpected or expected token to
report. In that case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is
a consistent state with a default action. There might have
been a previous inconsistent state, consistent state with a
non-default action, or user semantic action that manipulated
yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state
merging (from LALR or IELR) and default reductions corrupt the
expected token list. However, the list is correct for
canonical LR with one exception: it will still contain any
token that will not be accepted due to an error action in a
later state.
*/
if (yytoken != yyempty_)
{
yyarg[yycount++] = yytname_[yytoken];
int yyn = yypact_[yystate];
if (!yy_pact_value_is_default_ (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = yylast_ - yyn + 1;
int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_;
for (int yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck_[yyx + yyn] == yyx && yyx != yyterror_
&& !yy_table_value_is_error_ (yytable_[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
break;
}
else
yyarg[yycount++] = yytname_[yyx];
}
}
}
char const* yyformat = 0;
switch (yycount)
{
#define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
#undef YYCASE_
}
// Argument number.
size_t yyi = 0;
for (char const* yyp = yyformat; *yyp; ++yyp)
if (yyp[0] == '%' && yyp[1] == 's' && yyi < yycount)
{
yyres += yytnamerr_ (yyarg[yyi++]);
++yyp;
}
else
yyres += *yyp;
return yyres;
}
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
const short int SubsetValueExpressionParser::yypact_ninf_ = -368;
const short int
SubsetValueExpressionParser::yypact_[] =
{
128, 2067, 2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327,
2327, 2327, 2327, 2327, 2861, 2861, 2861, 2861, 2861, 2861,
2861, 2861, 2861, 2861, 2861, 2861, -174, -171, 18, -368,
-368, -167, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -165, -163, -159, -149, -143, -103,
-98, -91, -89, -85, -82, -75, -368, -59, -57, -53,
-52, -368, -368, -368, -368, -44, -41, -32, -29, -18,
-17, 21, 25, 34, 38, 42, 44, 45, 47, 52,
57, 61, 65, 72, 74, 79, 88, 101, 108, 109,
111, 118, 119, 121, 131, 136, 138, 177, 181, 182,
190, 191, 192, 194, 198, 205, 207, 210, 211, 213,
217, 221, 224, 228, 229, 241, 242, 243, 244, 247,
249, 250, 251, 252, 257, 263, 264, 277, 278, 307,
2067, 2067, 2067, 2067, -368, 5406, 51, -368, -368, 2612,
51, 268, 51, 846, 51, 942, 51, -121, 51, -368,
-368, -368, -368, 5414, 51, 5390, 51, 999, 51, 1077,
51, 1390, 51, -28, 51, 312, 313, 314, 350, 351,
352, 353, 357, 358, 359, 360, 363, 372, 376, 380,
381, 382, 383, 388, 389, 390, 391, 394, 398, 401,
403, 416, 417, 418, 419, 422, 423, 424, 425, 433,
434, 435, 439, 442, 443, 444, 449, 455, 2327, 2327,
2327, 2327, 5406, 4653, 268, 846, 942, -121, 2920, 5336,
2612, 2059, 1030, -30, 1177, 36, 1607, 49, -67, -151,
456, 458, 464, 472, 474, 475, 476, 477, 478, 482,
486, 487, 488, 489, 491, 494, 495, 496, 497, 533,
534, 535, 536, 537, 538, 541, 545, 546, 547, 548,
550, 554, 556, 558, 560, 564, 568, 569, 571, 576,
577, 579, 580, 2861, 2861, 2861, 2861, 5414, 4671, 999,
1077, 1390, -28, 2939, 5348, 5390, 5089, 4453, 63, 4466,
76, 4479, 90, -63, -125, -368, -368, -368, 2327, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, 2327, 2327, 2327, 2327, -26, -24, -124, -22, -20,
-25, -23, -21, 50, 77, 104, 461, 397, 2067, 2067,
2067, 2067, 2067, 2067, 2067, 2067, 2067, 2067, 2327, 2327,
2067, 2067, 2067, 2067, 2067, 2067, 2067, 2067, 2067, 2067,
2067, 2067, 2067, 2067, 2067, 2067, 2067, 2067, 2067, 2067,
2067, 2067, 2067, 2067, 2067, 2327, 2067, 2067, 2067, 2327,
2067, 2067, 2067, 2067, 2067, 2067, 2067, 553, 583, 584,
-73, -368, -69, 140, 587, 588, -368, 590, 593, 594,
-69, 140, 590, 593, 5102, 2958, 103, 196, 209, -76,
5115, 2977, 374, 387, 405, -72, -368, -368, 2327, 2327,
2327, 2327, 2327, 2327, -368, -368, 51, -368, 2327, 2327,
2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327, -368,
2327, 2327, 2327, 2327, 2327, 2327, -368, -368, 2327, 2327,
2327, 2327, 2327, 2327, -368, -368, 2327, 2327, 2327, 2327,
2327, 2327, -368, -368, 2327, 2327, 2327, -368, 2861, 2861,
2861, 2861, 2861, 2861, -368, -368, 2861, 2861, 2861, 2861,
2861, 2861, 2861, 2861, 2861, 2861, 2861, -368, 2861, 2861,
2861, 2861, 2861, 2861, -368, -368, 2861, 2861, 2861, 2861,
2861, 2861, -368, -368, 2861, 2861, 2861, 2861, 2861, 2861,
-368, -368, 2861, 2861, 2861, -368, 2327, 2327, 2327, 2327,
2327, 2327, 2327, 2327, 2067, 2067, 2327, 2327, 2327, 2327,
2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327,
2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327,
2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327, 2327, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, 2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861,
2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861,
2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861,
2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861, 2861,
2861, 2861, 2861, 2861, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, 2996, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, 4689,
4707, 4725, 3015, 602, -368, 603, -368, -368, 604, -368,
607, -368, -368, -368, -368, -368, -368, -368, -368, 614,
619, 620, 621, 623, 4743, 4761, 3034, 3053, 3072, 3091,
5128, 3110, 493, 552, 608, 5141, 3129, 624, 637, 650,
5154, 3148, 664, 682, 720, 5167, 3167, 735, 748, 792,
3186, 3205, 3224, 3243, 3262, 3281, 318, 912, 4492, 4505,
4518, 5050, 2854, 4531, 4544, 4557, 5063, 2882, 4570, 4583,
4596, 5076, 2901, 4609, 4622, 4635, 3300, 3319, 5180, 3338,
5193, 3357, 5206, 3376, 5219, 3395, 5232, 3414, 5245, 3433,
3452, 3471, 3490, 3509, 3528, 3547, 3566, 3585, 3604, 3623,
3642, 3661, 3680, 3699, 3718, 3737, 3756, 3775, 3794, 3813,
3832, 3851, 3870, 3889, 3908, 3927, 3946, 3965, 3984, 4003,
4022, 4041, 4060, 4079, 4098, 4117, 4136, 4155, 4174, 4193,
4212, 4231, 807, 832, 875, 926, 958, 1017, 1064, 1102,
1248, 1261, 1284, 1312, 1325, 1343, 1377, 1421, 1434, 1447,
1494, 1507, 1529, 1593, 1641, 1654, 1667, 1683, 1746, 1774,
1788, 1812, 1825, 1839, 1852, 1878, 1930, 1946, 2073, 2091,
2104, 2117, 2130, 2143, 2184, 2197, 2210, 2361, 2375, 2396,
2409, 2422, 2499, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -71, -71,
-73, -368, -368, -73, -69, 140, 587, -73, 120, -368,
2612, 2612, 2612, 2612, 2612, 2612, 28, 28, -368, -73,
-368, -69, 140, 587, -368, 767, 1049, 2234, -58, 107,
115, -58, 107, 115, -368, -368, -73, -69, 140, 587,
-31, 767, 1049, 2234, -58, 107, 115, -58, 107, 115,
-368, -368, -73, -69, 140, 587, -54, 767, 1049, 2234,
-58, 107, 115, -58, 107, 115, -368, -368, -73, -69,
140, 587, -66, 142, 5031, 460, 575, 893, -8, -368,
-27, -27, 588, -368, -368, 588, 590, 593, 594, 588,
137, 5390, 5390, 5390, 5390, 5390, 5390, 95, 95, -368,
588, -368, 590, 593, 594, -368, 5422, 5430, 5438, 125,
125, -368, -368, 588, 590, 593, 594, -15, 5422, 5430,
5438, 188, 188, -368, -368, 588, 590, 593, 594, -5,
5422, 5430, 5438, 212, 212, -368, -368, 588, 590, 593,
594, -60, 1126, 5045, 1715, 1973, 2328, 407, -368, 5258,
4250, 5271, 4269, 5360, 4779, 5372, 4797, -368, 2327, 2327,
2327, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, 2327, 2505, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, 2327, -368, 2327, -368, 2327, 2327, 2327,
2861, -368, 2861, -368, 2861, 2861, 2861, 2327, -368, 2327,
-368, 2327, 2327, 2327, 2861, -368, 2861, -368, 2861, 2861,
2861, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, 592, -368, -368, -368, -368, -368, -368,
626, -368, 631, 2327, 2327, 2327, 2327, 2327, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, 632, -368, -368, -368, -368, -368, -368,
633, -368, 635, 2861, 2861, 2861, 2861, 2861, 4815, 4833,
4851, 4288, -368, 2683, 640, 4307, 5284, 4326, 2539, 2554,
2567, 5297, 4345, 2580, 2593, 2677, 5310, 4364, 2717, 2730,
2743, 5323, 4383, 2756, 2769, 2782, 644, 646, 647, 5406,
2612, 268, 846, 942, 649, 651, 654, 5414, 5390, 999,
1077, 1390, 2327, 2327, 2327, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, -368, -368, -368, -368, -368,
-368, -368, -368, -368, -368, 4402, 4869, 4887, -368, 2327,
2327, 4905, 4923, 2327, 2327, 4941, 4959, 2327, 2327, 4977,
4421, 2327, -368, 4995, 2327, 5013, 2327, 4440, -368
};
/* YYDEFACT[S] -- default reduction number in state S. Performed when
YYTABLE doesn't specify something else to do. Zero means the
default is an error. */
const unsigned short int
SubsetValueExpressionParser::yydefact_[] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
205, 0, 203, 77, 314, 242, 274, 296, 426, 345,
512, 453, 479, 497, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 102, 0, 0, 0,
0, 301, 302, 280, 185, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 3, 33, 0, 103, 48, 32,
0, 38, 0, 40, 0, 42, 0, 34, 0, 47,
210, 247, 279, 36, 0, 35, 0, 39, 0, 41,
0, 43, 0, 37, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 28, 29, 1, 0, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61, 122, 230, 260, 287, 332, 368, 441, 465, 489,
62, 63, 333, 334, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 312, 510, 0, 0,
0, 0, 0, 0, 44, 30, 0, 76, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 202,
0, 0, 0, 0, 0, 0, 45, 241, 0, 0,
0, 0, 0, 0, 45, 273, 0, 0, 0, 0,
0, 0, 45, 295, 0, 0, 0, 313, 0, 0,
0, 0, 0, 0, 44, 344, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 425, 0, 0,
0, 0, 0, 0, 45, 452, 0, 0, 0, 0,
0, 0, 45, 478, 0, 0, 0, 0, 0, 0,
45, 496, 0, 0, 0, 511, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 4,
5, 8, 9, 12, 13, 16, 17, 20, 21, 24,
25, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6, 7, 10, 11, 14, 15,
18, 19, 22, 23, 26, 27, 0, 209, 429, 81,
348, 246, 456, 278, 482, 300, 500, 315, 513, 0,
0, 0, 0, 0, 190, 0, 194, 186, 0, 192,
0, 196, 73, 200, 201, 75, 74, 198, 199, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 187, 188, 189, 64, 123, 231, 261,
288, 309, 342, 369, 442, 466, 490, 507, 60, 49,
218, 51, 58, 112, 53, 55, 57, 59, 0, 31,
308, 307, 303, 304, 306, 305, 105, 104, 107, 50,
106, 216, 251, 282, 108, 113, 114, 115, 225, 226,
227, 211, 212, 213, 217, 224, 52, 219, 221, 223,
0, 116, 117, 118, 228, 257, 258, 214, 248, 249,
252, 256, 54, 220, 253, 255, 0, 119, 120, 121,
229, 259, 286, 215, 250, 281, 283, 285, 56, 222,
254, 284, 0, 0, 0, 0, 0, 0, 311, 310,
331, 320, 433, 322, 329, 358, 324, 326, 328, 330,
0, 506, 505, 501, 502, 504, 503, 350, 349, 352,
321, 351, 431, 458, 484, 353, 359, 360, 361, 440,
430, 432, 439, 323, 434, 436, 438, 0, 362, 363,
364, 464, 457, 459, 463, 325, 435, 460, 462, 0,
365, 366, 367, 488, 483, 485, 487, 327, 437, 461,
486, 0, 0, 0, 0, 0, 0, 509, 508, 0,
0, 0, 0, 0, 0, 0, 0, 206, 0, 0,
0, 319, 191, 195, 193, 197, 204, 78, 243, 275,
297, 0, 0, 110, 356, 111, 357, 150, 149, 151,
152, 153, 396, 395, 397, 398, 399, 155, 154, 156,
157, 158, 401, 400, 402, 403, 404, 126, 372, 127,
373, 128, 374, 0, 92, 0, 84, 0, 0, 0,
0, 94, 0, 86, 0, 0, 0, 0, 93, 0,
85, 0, 0, 0, 0, 95, 0, 87, 0, 0,
0, 96, 97, 100, 90, 101, 91, 98, 88, 99,
89, 270, 124, 475, 370, 125, 371, 129, 375, 130,
376, 131, 377, 132, 378, 133, 379, 134, 380, 135,
381, 136, 382, 137, 383, 138, 384, 139, 385, 140,
386, 141, 387, 142, 388, 143, 389, 144, 390, 145,
391, 146, 392, 147, 393, 148, 394, 70, 71, 340,
341, 159, 160, 161, 237, 268, 448, 473, 263, 262,
468, 467, 232, 443, 162, 163, 164, 236, 267, 447,
472, 235, 266, 292, 446, 471, 289, 290, 291, 491,
492, 493, 265, 264, 470, 469, 238, 269, 449, 474,
65, 66, 335, 336, 233, 234, 444, 445, 165, 166,
167, 67, 68, 69, 168, 169, 170, 171, 172, 173,
174, 175, 176, 0, 177, 178, 179, 180, 181, 182,
0, 183, 0, 0, 0, 0, 0, 0, 405, 406,
407, 337, 338, 339, 408, 409, 410, 411, 412, 413,
414, 415, 416, 0, 417, 418, 419, 420, 421, 422,
0, 423, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 82, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 72,
184, 240, 272, 294, 0, 0, 0, 343, 424, 451,
477, 495, 0, 0, 0, 109, 83, 354, 355, 79,
207, 244, 276, 298, 346, 427, 454, 480, 498, 80,
208, 245, 277, 299, 347, 428, 455, 481, 499, 239,
271, 293, 450, 476, 494, 0, 0, 0, 316, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 318, 0, 0, 0, 0, 0, 317
};
/* YYPGOTO[NTERM-NUM]. */
const short int
SubsetValueExpressionParser::yypgoto_[] =
{
-368, -368, -368, -137, -368, 216, -367, 5269, 1534, -368,
-368, -368, -368, -1, -368, 1363, -368, 1211, -368, 962,
-368, 35, -368, -368, -368, -368, -368, 616, -368, 126,
-368, 282, -368, 665, -368, 885, -368, 39, -368
};
/* YYDEFGOTO[NTERM-NUM]. */
const short int
SubsetValueExpressionParser::yydefgoto_[] =
{
-1, 28, 29, 417, 134, 838, 870, 617, 212, 136,
1234, 137, 138, 220, 140, 214, 142, 215, 144, 216,
146, 217, 148, 149, 150, 151, 152, 277, 154, 285,
156, 279, 158, 280, 160, 281, 162, 282, 164
};
/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule which
number is the opposite. If YYTABLE_NINF_, syntax error. */
const signed char SubsetValueExpressionParser::yytable_ninf_ = -1;
const unsigned short int
SubsetValueExpressionParser::yytable_[] =
{
139, 213, 218, 429, 633, 437, 635, 445, 638, 453,
640, 457, 295, 454, 296, 455, 456, 465, 297, 477,
298, 485, 299, 493, 300, 501, 1191, 505, 301, 1184,
1185, 1186, 1221, 1187, 1188, 560, 147, 1189, 302, 502,
163, 503, 504, 454, 303, 455, 456, 228, 229, 1171,
1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181,
1182, 615, 637, 293, 294, 1201, 1202, 1203, 1204, 1205,
1206, 1207, 1208, 1209, 1210, 1211, 1212, 886, 1214, 1215,
1216, 1192, 1217, 1218, 304, 902, 1219, 1222, 454, 305,
455, 456, 502, 1190, 503, 504, 306, 454, 307, 455,
456, 502, 308, 503, 504, 309, 410, 411, 412, 413,
821, 414, 310, 414, 827, 436, 1183, 947, 559, 433,
434, 435, 614, 415, 416, 959, 436, 155, 311, 381,
312, 395, 1213, 971, 313, 314, 502, 430, 503, 504,
278, 283, 1220, 315, 431, 432, 316, 433, 434, 435,
460, 461, 462, 463, 436, 317, 554, 464, 318, 456,
634, 642, 636, 643, 639, 644, 641, 399, 406, 319,
320, 405, 407, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
1168, 1169, 1170, 438, 426, 427, 428, 381, 321, 395,
439, 440, 322, 441, 442, 443, 446, 1198, 1199, 1200,
444, 323, 556, 447, 448, 324, 449, 450, 451, 325,
478, 326, 327, 452, 328, 558, 645, 479, 480, 329,
481, 482, 483, 486, 330, 399, 406, 484, 331, 609,
487, 488, 332, 489, 490, 491, 386, 494, 401, 333,
492, 334, 611, 646, 495, 496, 335, 497, 498, 499,
430, 474, 475, 476, 500, 336, 613, 431, 432, 839,
433, 434, 435, 157, 441, 442, 443, 436, 337, 818,
647, 444, 449, 450, 451, 338, 339, 616, 340, 452,
287, 288, 481, 482, 483, 341, 342, 1193, 343, 484,
629, 630, 631, 632, 405, 407, 408, 409, 344, 410,
411, 412, 413, 345, 444, 346, 414, 654, 656, 658,
661, 671, 680, 682, 684, 687, 697, 706, 707, 709,
713, 717, 720, 722, 724, 726, 728, 730, 732, 734,
736, 738, 740, 742, 744, 746, 748, 750, 752, 754,
756, 758, 760, 438, 347, 489, 490, 491, 348, 349,
439, 440, 492, 441, 442, 443, 446, 350, 351, 352,
444, 353, 819, 447, 448, 354, 449, 450, 451, 497,
498, 499, 355, 452, 356, 820, 500, 357, 358, 386,
359, 401, 649, 650, 360, 651, 652, 653, 361, 831,
832, 362, 387, 392, 402, 363, 364, 840, 841, 842,
843, 844, 845, 846, 847, 848, 850, 854, 365, 366,
367, 368, 864, 865, 369, 430, 370, 371, 372, 373,
880, 881, 431, 432, 374, 433, 434, 435, 896, 897,
375, 376, 436, 904, 655, 657, 659, 666, 676, 681,
683, 685, 692, 702, 377, 378, 711, 715, 719, 721,
723, 725, 727, 729, 731, 733, 735, 737, 739, 741,
743, 745, 747, 749, 751, 753, 755, 757, 759, 761,
908, 909, 408, 409, 379, 410, 411, 412, 413, 506,
507, 508, 414, 1033, 1034, 654, 656, 658, 661, 671,
680, 682, 684, 687, 697, 717, 720, 722, 724, 726,
728, 730, 732, 734, 736, 738, 740, 742, 744, 746,
748, 750, 752, 754, 756, 758, 760, 509, 510, 511,
512, 478, 977, 978, 513, 514, 515, 516, 479, 480,
517, 481, 482, 483, 486, 387, 392, 402, 484, 518,
824, 487, 488, 519, 489, 490, 491, 520, 521, 522,
523, 492, 494, 825, 504, 524, 525, 526, 527, 495,
496, 528, 497, 498, 499, 529, 913, 914, 530, 500,
531, 826, 921, 922, 923, 924, 925, 926, 927, 928,
929, 931, 935, 532, 533, 534, 535, 941, 942, 536,
537, 538, 539, 667, 677, 953, 954, 153, 693, 703,
540, 541, 542, 965, 966, 1195, 543, 430, 973, 544,
545, 546, 284, 286, 431, 432, 547, 433, 434, 435,
980, 982, 548, 561, 436, 562, 764, 648, 771, 775,
778, 563, 784, 789, 794, 799, 803, 807, 811, 564,
430, 565, 566, 567, 568, 569, 159, 431, 432, 570,
433, 434, 435, 571, 572, 573, 574, 436, 575, 1009,
920, 576, 577, 578, 579, 289, 290, 655, 657, 659,
666, 676, 681, 683, 685, 984, 986, 719, 721, 723,
725, 727, 729, 731, 733, 735, 737, 739, 741, 743,
745, 747, 749, 751, 753, 755, 757, 759, 761, 438,
580, 581, 582, 583, 584, 585, 439, 440, 586, 441,
442, 443, 587, 588, 589, 590, 444, 591, 1010, 813,
1196, 592, 438, 593, 916, 594, 385, 595, 400, 439,
440, 596, 441, 442, 443, 597, 598, 932, 599, 444,
936, 939, 940, 600, 601, 944, 602, 603, 948, 814,
815, 452, 464, 956, 484, 446, 960, 492, 500, 1256,
0, 968, 447, 448, 974, 449, 450, 451, 992, 993,
994, 478, 452, 995, 1011, 388, 393, 403, 479, 480,
996, 481, 482, 483, 486, 997, 998, 999, 484, 1000,
1014, 487, 488, 1257, 489, 490, 491, 494, 1258, 1264,
1265, 492, 1266, 1015, 495, 496, 1277, 497, 498, 499,
1299, 430, 1300, 1301, 500, 1302, 1016, 1303, 431, 432,
1304, 433, 434, 435, 0, 0, 667, 677, 436, 438,
1019, 693, 703, 0, 0, 0, 439, 440, 0, 441,
442, 443, 0, 0, 0, 0, 444, 0, 1020, 0,
0, 0, 0, 0, 0, 764, 771, 775, 778, 784,
789, 794, 799, 803, 807, 811, 161, 446, 0, 385,
0, 400, 0, 0, 447, 448, 0, 449, 450, 451,
0, 0, 478, 0, 452, 0, 1021, 291, 292, 479,
480, 0, 481, 482, 483, 486, 0, 0, 0, 484,
0, 1024, 487, 488, 0, 489, 490, 491, 0, 0,
0, 0, 492, 0, 1025, 0, 0, 0, 388, 393,
403, 431, 432, 0, 433, 434, 435, 665, 675, 0,
0, 436, 691, 701, 0, 0, 710, 714, 718, 494,
0, 0, 0, 145, 0, 0, 495, 496, 0, 497,
498, 499, 226, 227, 430, 0, 500, 0, 1026, 0,
0, 431, 432, 0, 433, 434, 435, 1228, 1229, 1230,
0, 436, 0, 1117, 0, 0, 668, 678, 0, 438,
1231, 694, 704, 0, 0, 0, 439, 440, 0, 441,
442, 443, 0, 438, 0, 389, 444, 404, 1118, 0,
439, 440, 0, 441, 442, 443, 0, 0, 0, 765,
444, 772, 776, 0, 1237, 785, 790, 795, 800, 804,
808, 812, 478, 0, 0, 0, 0, 0, 1247, 479,
480, 0, 481, 482, 483, 0, 0, 0, 1197, 484,
446, 1119, 0, 0, 0, 0, 0, 447, 448, 0,
449, 450, 451, 0, 910, 911, 912, 452, 915, 919,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 930, 384, 486, 398, 0, 0, 1035, 1036, 943,
487, 488, 0, 489, 490, 491, 0, 955, 0, 446,
492, 0, 1120, 0, 0, 967, 447, 448, 972, 449,
450, 451, 0, 0, 0, 430, 452, 917, 1235, 0,
979, 981, 431, 432, 0, 433, 434, 435, 0, 0,
933, 0, 436, 937, 1121, 0, 0, 0, 945, 0,
0, 949, 951, 952, 0, 0, 957, 0, 389, 961,
404, 0, 0, 0, 969, 0, 478, 975, 1242, 0,
384, 0, 398, 479, 480, 0, 481, 482, 483, 0,
665, 675, 1252, 484, 438, 983, 985, 718, 0, 0,
0, 439, 440, 1260, 441, 442, 443, 430, 0, 0,
0, 444, 0, 1122, 431, 432, 0, 433, 434, 435,
0, 0, 143, 0, 436, 553, 669, 679, 0, 224,
225, 695, 705, 439, 440, 0, 441, 442, 443, 668,
678, 446, 0, 444, 694, 704, 0, 0, 447, 448,
0, 449, 450, 451, 486, 0, 0, 0, 452, 0,
1123, 487, 488, 0, 489, 490, 491, 796, 765, 772,
776, 492, 785, 790, 795, 800, 804, 808, 812, 430,
0, 1305, 1306, 1307, 0, 0, 431, 432, 0, 433,
434, 435, 0, 0, 0, 0, 436, 0, 1124, 0,
0, 1223, 0, 664, 674, 0, 0, 0, 690, 700,
458, 459, 0, 460, 461, 462, 463, 0, 1311, 1312,
464, 0, 1315, 1316, 0, 0, 1319, 1320, 0, 0,
1323, 0, 0, 1325, 0, 1327, 1243, 768, 0, 0,
0, 781, 0, 788, 793, 0, 0, 0, 0, 0,
1253, 383, 391, 397, 438, 0, 0, 918, 0, 0,
1268, 439, 440, 0, 441, 442, 443, 0, 0, 386,
934, 444, 555, 938, 141, 0, 0, 0, 946, 222,
223, 950, 0, 0, 836, 0, 958, 0, 0, 962,
963, 964, 0, 0, 970, 0, 0, 976, 0, 853,
0, 0, 857, 860, 863, 0, 0, 869, 0, 0,
873, 876, 879, 0, 0, 885, 0, 0, 889, 892,
895, 0, 0, 901, 0, 438, 907, 0, 0, 383,
391, 397, 439, 440, 0, 441, 442, 443, 478, 0,
0, 0, 444, 0, 1125, 479, 480, 0, 481, 482,
483, 0, 0, 0, 0, 484, 0, 1126, 0, 669,
679, 486, 0, 0, 695, 705, 0, 0, 487, 488,
0, 489, 490, 491, 0, 0, 0, 0, 492, 0,
1127, 664, 674, 0, 0, 0, 690, 700, 0, 430,
0, 0, 0, 0, 796, 0, 431, 432, 0, 433,
434, 435, 438, 382, 390, 396, 436, 0, 1128, 439,
440, 0, 441, 442, 443, 788, 793, 1269, 0, 444,
478, 1129, 0, 0, 0, 387, 0, 479, 480, 0,
481, 482, 483, 0, 0, 0, 0, 484, 0, 1130,
0, 0, 0, 0, 0, 135, 0, 0, 219, 221,
0, 0, 663, 673, 486, 0, 0, 689, 699, 0,
0, 487, 488, 0, 489, 490, 491, 494, 0, 0,
0, 492, 0, 1131, 495, 496, 0, 497, 498, 499,
0, 382, 390, 396, 500, 763, 767, 770, 774, 0,
780, 783, 787, 792, 798, 802, 806, 810, 430, 0,
0, 0, 0, 0, 0, 431, 432, 0, 433, 434,
435, 478, 0, 0, 0, 436, 0, 1132, 479, 480,
0, 481, 482, 483, 430, 0, 0, 0, 484, 0,
1133, 431, 432, 835, 433, 434, 435, 0, 0, 0,
0, 436, 0, 1134, 0, 0, 0, 0, 852, 0,
0, 856, 859, 862, 0, 0, 868, 0, 0, 872,
875, 878, 0, 0, 884, 0, 1241, 888, 891, 894,
0, 438, 900, 0, 380, 906, 394, 0, 439, 440,
1251, 441, 442, 443, 446, 0, 0, 0, 444, 0,
1135, 447, 448, 0, 449, 450, 451, 0, 0, 0,
0, 452, 0, 1136, 662, 672, 430, 0, 0, 688,
698, 0, 0, 431, 432, 0, 433, 434, 435, 0,
1244, 0, 0, 436, 0, 1137, 0, 0, 0, 0,
663, 673, 0, 0, 1254, 689, 699, 762, 766, 769,
773, 777, 779, 782, 786, 791, 797, 801, 805, 809,
0, 0, 380, 0, 394, 0, 0, 0, 0, 763,
770, 774, 0, 783, 787, 792, 798, 802, 806, 810,
438, 0, 0, 0, 0, 0, 0, 439, 440, 0,
441, 442, 443, 0, 446, 834, 0, 444, 0, 1138,
0, 447, 448, 0, 449, 450, 451, 0, 0, 0,
851, 452, 557, 855, 858, 861, 0, 0, 867, 0,
0, 871, 874, 877, 0, 0, 883, 0, 478, 887,
890, 893, 0, 0, 899, 479, 480, 905, 481, 482,
483, 486, 0, 0, 0, 484, 0, 1139, 487, 488,
0, 489, 490, 491, 430, 0, 0, 0, 492, 1267,
1140, 431, 432, 0, 433, 434, 435, 0, 0, 385,
438, 436, 0, 1141, 0, 0, 0, 439, 440, 0,
441, 442, 443, 0, 0, 660, 670, 444, 0, 1142,
686, 696, 662, 672, 708, 712, 716, 688, 698, 0,
1225, 0, 478, 0, 0, 0, 0, 0, 0, 479,
480, 1270, 481, 482, 483, 0, 0, 0, 388, 484,
0, 762, 769, 773, 777, 782, 786, 791, 797, 801,
805, 809, 0, 446, 0, 0, 0, 0, 0, 0,
447, 448, 0, 449, 450, 451, 0, 0, 0, 0,
452, 1245, 1143, 0, 0, 0, 0, 0, 0, 0,
0, 478, 828, 829, 830, 1255, 833, 837, 479, 480,
0, 481, 482, 483, 0, 486, 0, 0, 484, 0,
1144, 849, 487, 488, 0, 489, 490, 491, 0, 866,
0, 0, 492, 0, 1145, 0, 0, 882, 0, 430,
0, 0, 0, 0, 0, 898, 431, 432, 903, 433,
434, 435, 438, 0, 0, 0, 436, 0, 1146, 439,
440, 1240, 441, 442, 443, 0, 446, 0, 0, 444,
0, 1147, 0, 447, 448, 1250, 449, 450, 451, 478,
0, 0, 0, 452, 0, 1148, 479, 480, 0, 481,
482, 483, 0, 0, 0, 0, 484, 0, 1149, 0,
0, 0, 0, 660, 670, 486, 0, 0, 686, 696,
716, 0, 487, 488, 0, 489, 490, 491, 0, 0,
0, 0, 492, 0, 1150, 0, 0, 0, 0, 0,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 494, 0, 0,
0, 0, 0, 0, 495, 496, 0, 497, 498, 499,
0, 0, 1271, 430, 500, 0, 1151, 0, 389, 0,
431, 432, 0, 433, 434, 435, 0, 0, 0, 0,
436, 0, 1152, 0, 0, 0, 0, 0, 1226, 0,
486, 57, 58, 59, 60, 61, 62, 487, 488, 0,
489, 490, 491, 0, 0, 0, 0, 492, 0, 1263,
63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 0, 0, 0, 0, 114, 115, 116, 117, 118,
119, 120, 121, 122, 123, 124, 125, 126, 127, 128,
129, 0, 0, 408, 409, 0, 410, 411, 412, 413,
438, 130, 0, 414, 131, 552, 0, 439, 440, 1239,
441, 442, 443, 0, 132, 133, 0, 444, 478, 1153,
0, 0, 0, 1249, 0, 479, 480, 0, 481, 482,
483, 486, 0, 0, 0, 484, 0, 1154, 487, 488,
0, 489, 490, 491, 430, 0, 0, 0, 492, 0,
1155, 431, 432, 0, 433, 434, 435, 438, 0, 0,
0, 436, 0, 1156, 439, 440, 0, 441, 442, 443,
478, 0, 0, 0, 444, 0, 1157, 479, 480, 0,
481, 482, 483, 0, 0, 0, 0, 484, 0, 1158,
30, 31, 32, 33, 34, 35, 36, 37, 0, 0,
0, 0, 0, 0, 44, 0, 46, 0, 48, 0,
50, 486, 52, 0, 54, 0, 56, 0, 487, 488,
0, 489, 490, 491, 430, 0, 0, 0, 492, 0,
1159, 431, 432, 0, 433, 434, 435, 438, 0, 0,
0, 436, 0, 1160, 439, 440, 0, 441, 442, 443,
0, 0, 0, 0, 444, 0, 1161, 0, 0, 0,
1238, 57, 58, 59, 60, 61, 62, 1262, 447, 448,
0, 449, 450, 451, 1248, 0, 0, 0, 452, 0,
63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
73, 74, 75, 76, 77, 165, 166, 167, 168, 169,
170, 171, 172, 173, 174, 88, 89, 90, 91, 175,
176, 177, 178, 179, 180, 181, 182, 183, 184, 185,
186, 187, 188, 189, 190, 191, 192, 193, 194, 195,
196, 0, 0, 0, 0, 197, 115, 198, 199, 200,
119, 201, 202, 203, 204, 205, 206, 207, 127, 128,
129, 0, 0, 1227, 0, 494, 0, 0, 0, 0,
0, 208, 495, 496, 209, 497, 498, 499, 0, 0,
0, 0, 500, 0, 210, 211, 38, 39, 40, 41,
42, 43, 0, 45, 0, 47, 0, 49, 478, 51,
0, 53, 0, 55, 1232, 479, 480, 0, 481, 482,
483, 0, 486, 0, 0, 484, 0, 1162, 0, 487,
488, 0, 489, 490, 491, 0, 0, 0, 1261, 492,
0, 1163, 0, 430, 0, 0, 0, 1236, 0, 0,
431, 432, 0, 433, 434, 435, 438, 0, 0, 0,
436, 1246, 1164, 439, 440, 0, 441, 442, 443, 478,
0, 0, 0, 444, 0, 1165, 479, 480, 0, 481,
482, 483, 0, 0, 0, 0, 484, 0, 1166, 0,
0, 0, 0, 230, 231, 232, 233, 234, 235, 236,
237, 238, 239, 0, 0, 0, 0, 240, 241, 242,
243, 244, 245, 246, 247, 248, 249, 250, 251, 252,
253, 254, 255, 256, 257, 258, 259, 260, 261, 0,
0, 0, 0, 262, 0, 263, 264, 265, 0, 266,
267, 268, 269, 270, 271, 272, 486, 0, 0, 0,
0, 0, 0, 487, 488, 0, 489, 490, 491, 1233,
0, 0, 274, 492, 0, 1167, 0, 0, 0, 0,
0, 0, 275, 276, 38, 39, 40, 41, 42, 43,
0, 45, 0, 47, 0, 49, 430, 51, 0, 53,
0, 55, 1276, 431, 432, 0, 433, 434, 435, 0,
0, 438, 0, 436, 0, 1281, 0, 1259, 439, 440,
0, 441, 442, 443, 446, 0, 0, 0, 444, 0,
1282, 447, 448, 0, 449, 450, 451, 478, 0, 0,
0, 452, 0, 1283, 479, 480, 0, 481, 482, 483,
486, 0, 0, 0, 484, 0, 1286, 487, 488, 0,
489, 490, 491, 0, 0, 0, 0, 492, 0, 1287,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 230, 231, 232, 233, 234, 235, 236, 237, 238,
239, 0, 0, 0, 0, 240, 241, 242, 243, 244,
245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
255, 256, 257, 258, 259, 260, 261, 0, 0, 0,
0, 262, 0, 263, 264, 265, 0, 266, 267, 268,
269, 270, 271, 272, 494, 0, 0, 0, 0, 0,
0, 495, 496, 0, 497, 498, 499, 273, 0, 0,
274, 500, 0, 1288, 0, 0, 0, 0, 0, 0,
275, 276, 38, 39, 40, 41, 42, 43, 0, 45,
0, 47, 0, 49, 430, 51, 0, 53, 0, 55,
0, 431, 432, 0, 433, 434, 435, 438, 0, 0,
0, 436, 0, 1291, 439, 440, 0, 441, 442, 443,
446, 0, 0, 0, 444, 0, 1292, 447, 448, 0,
449, 450, 451, 478, 0, 0, 0, 452, 0, 1293,
479, 480, 0, 481, 482, 483, 486, 0, 0, 0,
484, 0, 1296, 487, 488, 0, 489, 490, 491, 494,
0, 0, 0, 492, 0, 1297, 495, 496, 0, 497,
498, 499, 0, 0, 0, 0, 500, 0, 1298, 230,
231, 232, 233, 234, 235, 236, 237, 238, 239, 0,
0, 0, 0, 240, 241, 242, 243, 244, 245, 246,
247, 248, 249, 250, 251, 252, 253, 254, 255, 256,
257, 258, 259, 260, 261, 0, 0, 0, 0, 262,
0, 263, 264, 265, 0, 266, 267, 268, 269, 270,
271, 272, 466, 467, 468, 469, 470, 471, 472, 473,
474, 475, 476, 0, 0, 273, 0, 0, 274, 1042,
1043, 0, 0, 0, 0, 0, 0, 0, 275, 276,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 0, 0, 0, 0, 0, 0, 1049, 1050, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 1056, 1057, 418, 419,
420, 421, 422, 423, 424, 425, 426, 427, 428, 0,
0, 0, 0, 0, 0, 0, 550, 466, 467, 468,
469, 470, 471, 472, 473, 474, 475, 476, 0, 0,
0, 0, 0, 0, 0, 605, 418, 419, 420, 421,
422, 423, 424, 425, 426, 427, 428, 0, 0, 0,
0, 0, 0, 0, 817, 466, 467, 468, 469, 470,
471, 472, 473, 474, 475, 476, 0, 0, 0, 0,
0, 0, 0, 823, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427, 428, 0, 0, 0, 0, 0,
0, 0, 987, 418, 419, 420, 421, 422, 423, 424,
425, 426, 427, 428, 0, 0, 0, 0, 0, 0,
0, 991, 418, 419, 420, 421, 422, 423, 424, 425,
426, 427, 428, 0, 0, 0, 0, 0, 0, 0,
1003, 466, 467, 468, 469, 470, 471, 472, 473, 474,
475, 476, 0, 0, 0, 0, 0, 0, 0, 1004,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 0, 0, 0, 0, 0, 0, 0, 1005, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 0, 1006, 418, 419,
420, 421, 422, 423, 424, 425, 426, 427, 428, 0,
0, 0, 0, 0, 0, 0, 1008, 466, 467, 468,
469, 470, 471, 472, 473, 474, 475, 476, 0, 0,
0, 0, 0, 0, 0, 1013, 418, 419, 420, 421,
422, 423, 424, 425, 426, 427, 428, 0, 0, 0,
0, 0, 0, 0, 1018, 466, 467, 468, 469, 470,
471, 472, 473, 474, 475, 476, 0, 0, 0, 0,
0, 0, 0, 1023, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427, 428, 0, 0, 0, 0, 0,
0, 0, 1027, 466, 467, 468, 469, 470, 471, 472,
473, 474, 475, 476, 0, 0, 0, 0, 0, 0,
0, 1028, 418, 419, 420, 421, 422, 423, 424, 425,
426, 427, 428, 0, 0, 0, 0, 0, 0, 0,
1029, 466, 467, 468, 469, 470, 471, 472, 473, 474,
475, 476, 0, 0, 0, 0, 0, 0, 0, 1030,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 0, 0, 0, 0, 0, 0, 0, 1031, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 0, 1032, 418, 419,
420, 421, 422, 423, 424, 425, 426, 427, 428, 0,
0, 0, 0, 0, 0, 0, 1061, 418, 419, 420,
421, 422, 423, 424, 425, 426, 427, 428, 0, 0,
0, 0, 0, 0, 0, 1062, 418, 419, 420, 421,
422, 423, 424, 425, 426, 427, 428, 0, 0, 0,
0, 0, 0, 0, 1064, 466, 467, 468, 469, 470,
471, 472, 473, 474, 475, 476, 0, 0, 0, 0,
0, 0, 0, 1066, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427, 428, 0, 0, 0, 0, 0,
0, 0, 1068, 466, 467, 468, 469, 470, 471, 472,
473, 474, 475, 476, 0, 0, 0, 0, 0, 0,
0, 1070, 418, 419, 420, 421, 422, 423, 424, 425,
426, 427, 428, 0, 0, 0, 0, 0, 0, 0,
1072, 466, 467, 468, 469, 470, 471, 472, 473, 474,
475, 476, 0, 0, 0, 0, 0, 0, 0, 1074,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 0, 0, 0, 0, 0, 0, 0, 1075, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 0, 1076, 418, 419,
420, 421, 422, 423, 424, 425, 426, 427, 428, 0,
0, 0, 0, 0, 0, 0, 1077, 466, 467, 468,
469, 470, 471, 472, 473, 474, 475, 476, 0, 0,
0, 0, 0, 0, 0, 1078, 418, 419, 420, 421,
422, 423, 424, 425, 426, 427, 428, 0, 0, 0,
0, 0, 0, 0, 1079, 466, 467, 468, 469, 470,
471, 472, 473, 474, 475, 476, 0, 0, 0, 0,
0, 0, 0, 1080, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427, 428, 0, 0, 0, 0, 0,
0, 0, 1081, 466, 467, 468, 469, 470, 471, 472,
473, 474, 475, 476, 0, 0, 0, 0, 0, 0,
0, 1082, 418, 419, 420, 421, 422, 423, 424, 425,
426, 427, 428, 0, 0, 0, 0, 0, 0, 0,
1083, 466, 467, 468, 469, 470, 471, 472, 473, 474,
475, 476, 0, 0, 0, 0, 0, 0, 0, 1084,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 0, 0, 0, 0, 0, 0, 0, 1085, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 0, 1086, 418, 419,
420, 421, 422, 423, 424, 425, 426, 427, 428, 0,
0, 0, 0, 0, 0, 0, 1087, 466, 467, 468,
469, 470, 471, 472, 473, 474, 475, 476, 0, 0,
0, 0, 0, 0, 0, 1088, 418, 419, 420, 421,
422, 423, 424, 425, 426, 427, 428, 0, 0, 0,
0, 0, 0, 0, 1089, 466, 467, 468, 469, 470,
471, 472, 473, 474, 475, 476, 0, 0, 0, 0,
0, 0, 0, 1090, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427, 428, 0, 0, 0, 0, 0,
0, 0, 1091, 466, 467, 468, 469, 470, 471, 472,
473, 474, 475, 476, 0, 0, 0, 0, 0, 0,
0, 1092, 418, 419, 420, 421, 422, 423, 424, 425,
426, 427, 428, 0, 0, 0, 0, 0, 0, 0,
1093, 466, 467, 468, 469, 470, 471, 472, 473, 474,
475, 476, 0, 0, 0, 0, 0, 0, 0, 1094,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 0, 0, 0, 0, 0, 0, 0, 1095, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 0, 1096, 418, 419,
420, 421, 422, 423, 424, 425, 426, 427, 428, 0,
0, 0, 0, 0, 0, 0, 1097, 466, 467, 468,
469, 470, 471, 472, 473, 474, 475, 476, 0, 0,
0, 0, 0, 0, 0, 1098, 418, 419, 420, 421,
422, 423, 424, 425, 426, 427, 428, 0, 0, 0,
0, 0, 0, 0, 1099, 466, 467, 468, 469, 470,
471, 472, 473, 474, 475, 476, 0, 0, 0, 0,
0, 0, 0, 1100, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427, 428, 0, 0, 0, 0, 0,
0, 0, 1101, 466, 467, 468, 469, 470, 471, 472,
473, 474, 475, 476, 0, 0, 0, 0, 0, 0,
0, 1102, 418, 419, 420, 421, 422, 423, 424, 425,
426, 427, 428, 0, 0, 0, 0, 0, 0, 0,
1103, 466, 467, 468, 469, 470, 471, 472, 473, 474,
475, 476, 0, 0, 0, 0, 0, 0, 0, 1104,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 0, 0, 0, 0, 0, 0, 0, 1105, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 0, 1106, 418, 419,
420, 421, 422, 423, 424, 425, 426, 427, 428, 0,
0, 0, 0, 0, 0, 0, 1107, 466, 467, 468,
469, 470, 471, 472, 473, 474, 475, 476, 0, 0,
0, 0, 0, 0, 0, 1108, 418, 419, 420, 421,
422, 423, 424, 425, 426, 427, 428, 0, 0, 0,
0, 0, 0, 0, 1109, 466, 467, 468, 469, 470,
471, 472, 473, 474, 475, 476, 0, 0, 0, 0,
0, 0, 0, 1110, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427, 428, 0, 0, 0, 0, 0,
0, 0, 1111, 466, 467, 468, 469, 470, 471, 472,
473, 474, 475, 476, 0, 0, 0, 0, 0, 0,
0, 1112, 418, 419, 420, 421, 422, 423, 424, 425,
426, 427, 428, 0, 0, 0, 0, 0, 0, 0,
1113, 466, 467, 468, 469, 470, 471, 472, 473, 474,
475, 476, 0, 0, 0, 0, 0, 0, 0, 1114,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 0, 0, 0, 0, 0, 0, 0, 1115, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 0, 1116, 466, 467,
468, 469, 470, 471, 472, 473, 474, 475, 476, 0,
0, 0, 0, 0, 0, 0, 1043, 466, 467, 468,
469, 470, 471, 472, 473, 474, 475, 476, 0, 0,
0, 0, 0, 0, 0, 1057, 418, 419, 420, 421,
422, 423, 424, 425, 426, 427, 428, 0, 0, 0,
0, 0, 0, 0, 1275, 466, 467, 468, 469, 470,
471, 472, 473, 474, 475, 476, 0, 0, 0, 0,
0, 0, 0, 1278, 418, 419, 420, 421, 422, 423,
424, 425, 426, 427, 428, 0, 0, 0, 0, 0,
0, 0, 1280, 466, 467, 468, 469, 470, 471, 472,
473, 474, 475, 476, 0, 0, 0, 0, 0, 0,
0, 1285, 418, 419, 420, 421, 422, 423, 424, 425,
426, 427, 428, 0, 0, 0, 0, 0, 0, 0,
1290, 466, 467, 468, 469, 470, 471, 472, 473, 474,
475, 476, 0, 0, 0, 0, 0, 0, 0, 1295,
418, 419, 420, 421, 422, 423, 424, 425, 426, 427,
428, 0, 0, 0, 0, 0, 0, 0, 1308, 418,
419, 420, 421, 422, 423, 424, 425, 426, 427, 428,
0, 0, 0, 0, 0, 0, 0, 1322, 418, 419,
420, 421, 422, 423, 424, 425, 426, 427, 428, 0,
478, 0, 0, 0, 0, 0, 1328, 479, 480, 0,
481, 482, 483, 486, 0, 0, 0, 484, 608, 0,
487, 488, 0, 489, 490, 491, 494, 0, 0, 0,
492, 610, 0, 495, 496, 0, 497, 498, 499, 430,
0, 0, 0, 500, 612, 0, 431, 432, 0, 433,
434, 435, 438, 0, 0, 0, 436, 1037, 0, 439,
440, 0, 441, 442, 443, 446, 0, 0, 0, 444,
1038, 0, 447, 448, 0, 449, 450, 451, 478, 0,
0, 0, 452, 1039, 0, 479, 480, 0, 481, 482,
483, 486, 0, 0, 0, 484, 1044, 0, 487, 488,
0, 489, 490, 491, 494, 0, 0, 0, 492, 1045,
0, 495, 496, 0, 497, 498, 499, 430, 0, 0,
0, 500, 1046, 0, 431, 432, 0, 433, 434, 435,
438, 0, 0, 0, 436, 1051, 0, 439, 440, 0,
441, 442, 443, 446, 0, 0, 0, 444, 1052, 0,
447, 448, 0, 449, 450, 451, 478, 0, 0, 0,
452, 1053, 0, 479, 480, 0, 481, 482, 483, 486,
0, 0, 0, 484, 1058, 0, 487, 488, 0, 489,
490, 491, 494, 0, 0, 0, 492, 1059, 0, 495,
496, 0, 497, 498, 499, 0, 0, 0, 0, 500,
1060, 418, 419, 420, 421, 422, 423, 424, 425, 426,
427, 428, 0, 0, 0, 0, 0, 0, 549, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 604, 418, 419, 420,
421, 422, 423, 424, 425, 426, 427, 428, 0, 0,
0, 0, 0, 0, 988, 418, 419, 420, 421, 422,
423, 424, 425, 426, 427, 428, 0, 0, 0, 0,
0, 0, 989, 418, 419, 420, 421, 422, 423, 424,
425, 426, 427, 428, 0, 0, 0, 0, 0, 0,
990, 418, 419, 420, 421, 422, 423, 424, 425, 426,
427, 428, 0, 0, 0, 0, 0, 0, 1001, 466,
467, 468, 469, 470, 471, 472, 473, 474, 475, 476,
0, 0, 0, 0, 0, 0, 1002, 466, 467, 468,
469, 470, 471, 472, 473, 474, 475, 476, 0, 0,
0, 0, 0, 0, 1042, 466, 467, 468, 469, 470,
471, 472, 473, 474, 475, 476, 0, 0, 0, 0,
0, 0, 1056, 418, 419, 420, 421, 422, 423, 424,
425, 426, 427, 428, 0, 0, 0, 0, 0, 0,
1272, 418, 419, 420, 421, 422, 423, 424, 425, 426,
427, 428, 0, 0, 0, 0, 0, 0, 1273, 418,
419, 420, 421, 422, 423, 424, 425, 426, 427, 428,
0, 0, 0, 0, 0, 0, 1274, 418, 419, 420,
421, 422, 423, 424, 425, 426, 427, 428, 0, 0,
0, 0, 0, 0, 1309, 418, 419, 420, 421, 422,
423, 424, 425, 426, 427, 428, 0, 0, 0, 0,
0, 0, 1310, 418, 419, 420, 421, 422, 423, 424,
425, 426, 427, 428, 0, 0, 0, 0, 0, 0,
1313, 418, 419, 420, 421, 422, 423, 424, 425, 426,
427, 428, 0, 0, 0, 0, 0, 0, 1314, 418,
419, 420, 421, 422, 423, 424, 425, 426, 427, 428,
0, 0, 0, 0, 0, 0, 1317, 418, 419, 420,
421, 422, 423, 424, 425, 426, 427, 428, 0, 0,
0, 0, 0, 0, 1318, 418, 419, 420, 421, 422,
423, 424, 425, 426, 427, 428, 0, 0, 0, 0,
0, 0, 1321, 418, 419, 420, 421, 422, 423, 424,
425, 426, 427, 428, 0, 0, 0, 0, 0, 0,
1324, 418, 419, 420, 421, 422, 423, 424, 425, 426,
427, 428, 0, 0, 0, 0, 1194, 0, 1326, 418,
419, 420, 421, 422, 423, 424, 425, 426, 427, 428,
1224, 0, 0, 466, 467, 468, 469, 470, 471, 472,
473, 474, 475, 476, 458, 459, 0, 460, 461, 462,
463, 0, 0, 0, 464, 1040, 1041, 408, 409, 0,
410, 411, 412, 413, 0, 0, 0, 414, 1047, 1048,
458, 459, 0, 460, 461, 462, 463, 0, 0, 0,
464, 1054, 1055, 458, 459, 0, 460, 461, 462, 463,
0, 0, 0, 464, 0, 607, 408, 409, 0, 410,
411, 412, 413, 0, 0, 0, 414, 0, 816, 458,
459, 0, 460, 461, 462, 463, 0, 0, 0, 464,
0, 822, 408, 409, 0, 410, 411, 412, 413, 0,
0, 0, 414, 0, 1007, 458, 459, 0, 460, 461,
462, 463, 0, 0, 0, 464, 0, 1012, 408, 409,
0, 410, 411, 412, 413, 0, 0, 0, 414, 0,
1017, 458, 459, 0, 460, 461, 462, 463, 0, 0,
0, 464, 0, 1022, 408, 409, 0, 410, 411, 412,
413, 0, 0, 0, 414, 0, 1063, 458, 459, 0,
460, 461, 462, 463, 0, 0, 0, 464, 0, 1065,
408, 409, 0, 410, 411, 412, 413, 0, 0, 0,
414, 0, 1067, 458, 459, 0, 460, 461, 462, 463,
0, 0, 0, 464, 0, 1069, 408, 409, 0, 410,
411, 412, 413, 0, 0, 0, 414, 0, 1071, 458,
459, 0, 460, 461, 462, 463, 0, 0, 0, 464,
0, 1073, 458, 459, 0, 460, 461, 462, 463, 0,
0, 0, 464, 0, 1041, 458, 459, 0, 460, 461,
462, 463, 0, 0, 0, 464, 0, 1055, 408, 409,
0, 410, 411, 412, 413, 0, 0, 0, 414, 0,
1279, 458, 459, 0, 460, 461, 462, 463, 0, 0,
0, 464, 0, 1284, 408, 409, 0, 410, 411, 412,
413, 0, 0, 0, 414, 0, 1289, 458, 459, 0,
460, 461, 462, 463, 0, 0, 0, 464, 0, 1294,
408, 409, 0, 410, 411, 412, 413, 0, 0, 0,
414, 551, 458, 459, 0, 460, 461, 462, 463, 0,
0, 0, 464, 606, 458, 459, 0, 460, 461, 462,
463, 0, 0, 0, 464, 1040, 458, 459, 0, 460,
461, 462, 463, 0, 0, 0, 464, 1054, 466, 467,
468, 469, 470, 471, 472, 473, 474, 475, 476, 618,
619, 620, 621, 622, 623, 624, 625, 626, 627, 628,
408, 409, 0, 410, 411, 412, 413, 0, 458, 459,
414, 460, 461, 462, 463, 0, 479, 480, 464, 481,
482, 483, 0, 0, 487, 488, 484, 489, 490, 491,
0, 0, 495, 496, 492, 497, 498, 499, 0, 0,
0, 0, 500
};
/* YYCHECK. */
const short int
SubsetValueExpressionParser::yycheck_[] =
{
1, 2, 3, 140, 30, 142, 30, 144, 30, 146,
30, 148, 186, 164, 185, 166, 167, 154, 0, 156,
187, 158, 187, 160, 187, 162, 92, 164, 187, 83,
84, 85, 92, 87, 88, 186, 1, 91, 187, 164,
1, 166, 167, 164, 187, 166, 167, 12, 13, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
91, 186, 186, 24, 25, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 444, 83, 84,
85, 147, 87, 88, 187, 452, 91, 147, 164, 187,
166, 167, 164, 147, 166, 167, 187, 164, 187, 166,
167, 164, 187, 166, 167, 187, 177, 178, 179, 180,
186, 184, 187, 184, 186, 184, 147, 484, 185, 177,
178, 179, 185, 72, 73, 492, 184, 1, 187, 130,
187, 132, 147, 500, 187, 187, 164, 167, 166, 167,
14, 15, 147, 187, 174, 175, 187, 177, 178, 179,
177, 178, 179, 180, 184, 187, 186, 184, 187, 167,
186, 186, 186, 186, 186, 186, 186, 132, 133, 187,
187, 132, 133, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
80, 81, 82, 167, 176, 177, 178, 208, 187, 210,
174, 175, 187, 177, 178, 179, 167, 80, 81, 82,
184, 187, 186, 174, 175, 187, 177, 178, 179, 187,
167, 187, 187, 184, 187, 186, 186, 174, 175, 187,
177, 178, 179, 167, 187, 210, 211, 184, 187, 186,
174, 175, 187, 177, 178, 179, 130, 167, 132, 187,
184, 187, 186, 186, 174, 175, 187, 177, 178, 179,
167, 176, 177, 178, 184, 187, 186, 174, 175, 416,
177, 178, 179, 1, 177, 178, 179, 184, 187, 186,
186, 184, 177, 178, 179, 187, 187, 298, 187, 184,
18, 19, 177, 178, 179, 187, 187, 165, 187, 184,
311, 312, 313, 314, 275, 276, 174, 175, 187, 177,
178, 179, 180, 187, 184, 187, 184, 328, 329, 330,
331, 332, 333, 334, 335, 336, 337, 338, 339, 340,
341, 342, 343, 344, 345, 346, 347, 348, 349, 350,
351, 352, 353, 354, 355, 356, 357, 358, 359, 360,
361, 362, 363, 167, 187, 177, 178, 179, 187, 187,
174, 175, 184, 177, 178, 179, 167, 187, 187, 187,
184, 187, 186, 174, 175, 187, 177, 178, 179, 177,
178, 179, 187, 184, 187, 186, 184, 187, 187, 273,
187, 275, 5, 6, 187, 8, 9, 10, 187, 410,
411, 187, 130, 131, 132, 187, 187, 418, 419, 420,
421, 422, 423, 424, 425, 426, 427, 428, 187, 187,
187, 187, 433, 434, 187, 167, 187, 187, 187, 187,
441, 442, 174, 175, 187, 177, 178, 179, 449, 450,
187, 187, 184, 454, 328, 329, 330, 331, 332, 333,
334, 335, 336, 337, 187, 187, 340, 341, 342, 343,
344, 345, 346, 347, 348, 349, 350, 351, 352, 353,
354, 355, 356, 357, 358, 359, 360, 361, 362, 363,
455, 456, 174, 175, 187, 177, 178, 179, 180, 187,
187, 187, 184, 185, 186, 506, 507, 508, 509, 510,
511, 512, 513, 514, 515, 516, 517, 518, 519, 520,
521, 522, 523, 524, 525, 526, 527, 528, 529, 530,
531, 532, 533, 534, 535, 536, 537, 187, 187, 187,
187, 167, 503, 504, 187, 187, 187, 187, 174, 175,
187, 177, 178, 179, 167, 273, 274, 275, 184, 187,
186, 174, 175, 187, 177, 178, 179, 187, 187, 187,
187, 184, 167, 186, 167, 187, 187, 187, 187, 174,
175, 187, 177, 178, 179, 187, 460, 461, 187, 184,
187, 186, 466, 467, 468, 469, 470, 471, 472, 473,
474, 475, 476, 187, 187, 187, 187, 481, 482, 187,
187, 187, 187, 331, 332, 489, 490, 1, 336, 337,
187, 187, 187, 497, 498, 165, 187, 167, 502, 187,
187, 187, 16, 17, 174, 175, 187, 177, 178, 179,
514, 515, 187, 187, 184, 187, 364, 186, 366, 367,
368, 187, 370, 371, 372, 373, 374, 375, 376, 187,
167, 187, 187, 187, 187, 187, 1, 174, 175, 187,
177, 178, 179, 187, 187, 187, 187, 184, 187, 186,
464, 187, 187, 187, 187, 20, 21, 561, 562, 563,
564, 565, 566, 567, 568, 569, 570, 571, 572, 573,
574, 575, 576, 577, 578, 579, 580, 581, 582, 583,
584, 585, 586, 587, 588, 589, 590, 591, 592, 167,
187, 187, 187, 187, 187, 187, 174, 175, 187, 177,
178, 179, 187, 187, 187, 187, 184, 187, 186, 186,
165, 187, 167, 187, 462, 187, 130, 187, 132, 174,
175, 187, 177, 178, 179, 187, 187, 475, 187, 184,
478, 479, 480, 187, 187, 483, 187, 187, 486, 186,
186, 184, 184, 491, 184, 167, 494, 184, 184, 187,
-1, 499, 174, 175, 502, 177, 178, 179, 186, 186,
186, 167, 184, 186, 186, 130, 131, 132, 174, 175,
186, 177, 178, 179, 167, 186, 186, 186, 184, 186,
186, 174, 175, 187, 177, 178, 179, 167, 187, 187,
187, 184, 187, 186, 174, 175, 186, 177, 178, 179,
186, 167, 186, 186, 184, 186, 186, 186, 174, 175,
186, 177, 178, 179, -1, -1, 564, 565, 184, 167,
186, 569, 570, -1, -1, -1, 174, 175, -1, 177,
178, 179, -1, -1, -1, -1, 184, -1, 186, -1,
-1, -1, -1, -1, -1, 593, 594, 595, 596, 597,
598, 599, 600, 601, 602, 603, 1, 167, -1, 273,
-1, 275, -1, -1, 174, 175, -1, 177, 178, 179,
-1, -1, 167, -1, 184, -1, 186, 22, 23, 174,
175, -1, 177, 178, 179, 167, -1, -1, -1, 184,
-1, 186, 174, 175, -1, 177, 178, 179, -1, -1,
-1, -1, 184, -1, 186, -1, -1, -1, 273, 274,
275, 174, 175, -1, 177, 178, 179, 331, 332, -1,
-1, 184, 336, 337, -1, -1, 340, 341, 342, 167,
-1, -1, -1, 1, -1, -1, 174, 175, -1, 177,
178, 179, 10, 11, 167, -1, 184, -1, 186, -1,
-1, 174, 175, -1, 177, 178, 179, 988, 989, 990,
-1, 184, -1, 186, -1, -1, 331, 332, -1, 167,
1001, 336, 337, -1, -1, -1, 174, 175, -1, 177,
178, 179, -1, 167, -1, 130, 184, 132, 186, -1,
174, 175, -1, 177, 178, 179, -1, -1, -1, 364,
184, 366, 367, -1, 1035, 370, 371, 372, 373, 374,
375, 376, 167, -1, -1, -1, -1, -1, 1049, 174,
175, -1, 177, 178, 179, -1, -1, -1, 165, 184,
167, 186, -1, -1, -1, -1, -1, 174, 175, -1,
177, 178, 179, -1, 458, 459, 460, 184, 462, 463,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, 475, 130, 167, 132, -1, -1, 185, 186, 483,
174, 175, -1, 177, 178, 179, -1, 491, -1, 167,
184, -1, 186, -1, -1, 499, 174, 175, 502, 177,
178, 179, -1, -1, -1, 167, 184, 462, 1002, -1,
514, 515, 174, 175, -1, 177, 178, 179, -1, -1,
475, -1, 184, 478, 186, -1, -1, -1, 483, -1,
-1, 486, 487, 488, -1, -1, 491, -1, 273, 494,
275, -1, -1, -1, 499, -1, 167, 502, 1042, -1,
208, -1, 210, 174, 175, -1, 177, 178, 179, -1,
564, 565, 1056, 184, 167, 569, 570, 571, -1, -1,
-1, 174, 175, 1194, 177, 178, 179, 167, -1, -1,
-1, 184, -1, 186, 174, 175, -1, 177, 178, 179,
-1, -1, 1, -1, 184, 185, 331, 332, -1, 8,
9, 336, 337, 174, 175, -1, 177, 178, 179, 564,
565, 167, -1, 184, 569, 570, -1, -1, 174, 175,
-1, 177, 178, 179, 167, -1, -1, -1, 184, -1,
186, 174, 175, -1, 177, 178, 179, 372, 593, 594,
595, 184, 597, 598, 599, 600, 601, 602, 603, 167,
-1, 1272, 1273, 1274, -1, -1, 174, 175, -1, 177,
178, 179, -1, -1, -1, -1, 184, -1, 186, -1,
-1, 165, -1, 331, 332, -1, -1, -1, 336, 337,
174, 175, -1, 177, 178, 179, 180, -1, 1309, 1310,
184, -1, 1313, 1314, -1, -1, 1317, 1318, -1, -1,
1321, -1, -1, 1324, -1, 1326, 1044, 365, -1, -1,
-1, 369, -1, 371, 372, -1, -1, -1, -1, -1,
1058, 130, 131, 132, 167, -1, -1, 462, -1, -1,
1224, 174, 175, -1, 177, 178, 179, -1, -1, 1233,
475, 184, 185, 478, 1, -1, -1, -1, 483, 6,
7, 486, -1, -1, 412, -1, 491, -1, -1, 494,
495, 496, -1, -1, 499, -1, -1, 502, -1, 427,
-1, -1, 430, 431, 432, -1, -1, 435, -1, -1,
438, 439, 440, -1, -1, 443, -1, -1, 446, 447,
448, -1, -1, 451, -1, 167, 454, -1, -1, 208,
209, 210, 174, 175, -1, 177, 178, 179, 167, -1,
-1, -1, 184, -1, 186, 174, 175, -1, 177, 178,
179, -1, -1, -1, -1, 184, -1, 186, -1, 564,
565, 167, -1, -1, 569, 570, -1, -1, 174, 175,
-1, 177, 178, 179, -1, -1, -1, -1, 184, -1,
186, 509, 510, -1, -1, -1, 514, 515, -1, 167,
-1, -1, -1, -1, 599, -1, 174, 175, -1, 177,
178, 179, 167, 130, 131, 132, 184, -1, 186, 174,
175, -1, 177, 178, 179, 543, 544, 1225, -1, 184,
167, 186, -1, -1, -1, 1233, -1, 174, 175, -1,
177, 178, 179, -1, -1, -1, -1, 184, -1, 186,
-1, -1, -1, -1, -1, 1, -1, -1, 4, 5,
-1, -1, 331, 332, 167, -1, -1, 336, 337, -1,
-1, 174, 175, -1, 177, 178, 179, 167, -1, -1,
-1, 184, -1, 186, 174, 175, -1, 177, 178, 179,
-1, 208, 209, 210, 184, 364, 365, 366, 367, -1,
369, 370, 371, 372, 373, 374, 375, 376, 167, -1,
-1, -1, -1, -1, -1, 174, 175, -1, 177, 178,
179, 167, -1, -1, -1, 184, -1, 186, 174, 175,
-1, 177, 178, 179, 167, -1, -1, -1, 184, -1,
186, 174, 175, 412, 177, 178, 179, -1, -1, -1,
-1, 184, -1, 186, -1, -1, -1, -1, 427, -1,
-1, 430, 431, 432, -1, -1, 435, -1, -1, 438,
439, 440, -1, -1, 443, -1, 1040, 446, 447, 448,
-1, 167, 451, -1, 130, 454, 132, -1, 174, 175,
1054, 177, 178, 179, 167, -1, -1, -1, 184, -1,
186, 174, 175, -1, 177, 178, 179, -1, -1, -1,
-1, 184, -1, 186, 331, 332, 167, -1, -1, 336,
337, -1, -1, 174, 175, -1, 177, 178, 179, -1,
1045, -1, -1, 184, -1, 186, -1, -1, -1, -1,
509, 510, -1, -1, 1059, 514, 515, 364, 365, 366,
367, 368, 369, 370, 371, 372, 373, 374, 375, 376,
-1, -1, 208, -1, 210, -1, -1, -1, -1, 538,
539, 540, -1, 542, 543, 544, 545, 546, 547, 548,
167, -1, -1, -1, -1, -1, -1, 174, 175, -1,
177, 178, 179, -1, 167, 412, -1, 184, -1, 186,
-1, 174, 175, -1, 177, 178, 179, -1, -1, -1,
427, 184, 185, 430, 431, 432, -1, -1, 435, -1,
-1, 438, 439, 440, -1, -1, 443, -1, 167, 446,
447, 448, -1, -1, 451, 174, 175, 454, 177, 178,
179, 167, -1, -1, -1, 184, -1, 186, 174, 175,
-1, 177, 178, 179, 167, -1, -1, -1, 184, 1223,
186, 174, 175, -1, 177, 178, 179, -1, -1, 1233,
167, 184, -1, 186, -1, -1, -1, 174, 175, -1,
177, 178, 179, -1, -1, 331, 332, 184, -1, 186,
336, 337, 509, 510, 340, 341, 342, 514, 515, -1,
165, -1, 167, -1, -1, -1, -1, -1, -1, 174,
175, 1226, 177, 178, 179, -1, -1, -1, 1233, 184,
-1, 538, 539, 540, 541, 542, 543, 544, 545, 546,
547, 548, -1, 167, -1, -1, -1, -1, -1, -1,
174, 175, -1, 177, 178, 179, -1, -1, -1, -1,
184, 1046, 186, -1, -1, -1, -1, -1, -1, -1,
-1, 167, 408, 409, 410, 1060, 412, 413, 174, 175,
-1, 177, 178, 179, -1, 167, -1, -1, 184, -1,
186, 427, 174, 175, -1, 177, 178, 179, -1, 435,
-1, -1, 184, -1, 186, -1, -1, 443, -1, 167,
-1, -1, -1, -1, -1, 451, 174, 175, 454, 177,
178, 179, 167, -1, -1, -1, 184, -1, 186, 174,
175, 1039, 177, 178, 179, -1, 167, -1, -1, 184,
-1, 186, -1, 174, 175, 1053, 177, 178, 179, 167,
-1, -1, -1, 184, -1, 186, 174, 175, -1, 177,
178, 179, -1, -1, -1, -1, 184, -1, 186, -1,
-1, -1, -1, 509, 510, 167, -1, -1, 514, 515,
516, -1, 174, 175, -1, 177, 178, 179, -1, -1,
-1, -1, 184, -1, 186, -1, -1, -1, -1, -1,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 167, -1, -1,
-1, -1, -1, -1, 174, 175, -1, 177, 178, 179,
-1, -1, 1227, 167, 184, -1, 186, -1, 1233, -1,
174, 175, -1, 177, 178, 179, -1, -1, -1, -1,
184, -1, 186, -1, -1, -1, -1, -1, 165, -1,
167, 74, 75, 76, 77, 78, 79, 174, 175, -1,
177, 178, 179, -1, -1, -1, -1, 184, -1, 1197,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
123, 124, 125, 126, 127, 128, 129, 130, 131, 132,
133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, -1, -1, -1, -1, 148, 149, 150, 151, 152,
153, 154, 155, 156, 157, 158, 159, 160, 161, 162,
163, -1, -1, 174, 175, -1, 177, 178, 179, 180,
167, 174, -1, 184, 177, 186, -1, 174, 175, 1038,
177, 178, 179, -1, 187, 188, -1, 184, 167, 186,
-1, -1, -1, 1052, -1, 174, 175, -1, 177, 178,
179, 167, -1, -1, -1, 184, -1, 186, 174, 175,
-1, 177, 178, 179, 167, -1, -1, -1, 184, -1,
186, 174, 175, -1, 177, 178, 179, 167, -1, -1,
-1, 184, -1, 186, 174, 175, -1, 177, 178, 179,
167, -1, -1, -1, 184, -1, 186, 174, 175, -1,
177, 178, 179, -1, -1, -1, -1, 184, -1, 186,
3, 4, 5, 6, 7, 8, 9, 10, -1, -1,
-1, -1, -1, -1, 17, -1, 19, -1, 21, -1,
23, 167, 25, -1, 27, -1, 29, -1, 174, 175,
-1, 177, 178, 179, 167, -1, -1, -1, 184, -1,
186, 174, 175, -1, 177, 178, 179, 167, -1, -1,
-1, 184, -1, 186, 174, 175, -1, 177, 178, 179,
-1, -1, -1, -1, 184, -1, 186, -1, -1, -1,
1037, 74, 75, 76, 77, 78, 79, 1196, 174, 175,
-1, 177, 178, 179, 1051, -1, -1, -1, 184, -1,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
123, 124, 125, 126, 127, 128, 129, 130, 131, 132,
133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, -1, -1, -1, -1, 148, 149, 150, 151, 152,
153, 154, 155, 156, 157, 158, 159, 160, 161, 162,
163, -1, -1, 165, -1, 167, -1, -1, -1, -1,
-1, 174, 174, 175, 177, 177, 178, 179, -1, -1,
-1, -1, 184, -1, 187, 188, 11, 12, 13, 14,
15, 16, -1, 18, -1, 20, -1, 22, 167, 24,
-1, 26, -1, 28, 29, 174, 175, -1, 177, 178,
179, -1, 167, -1, -1, 184, -1, 186, -1, 174,
175, -1, 177, 178, 179, -1, -1, -1, 1195, 184,
-1, 186, -1, 167, -1, -1, -1, 1033, -1, -1,
174, 175, -1, 177, 178, 179, 167, -1, -1, -1,
184, 1047, 186, 174, 175, -1, 177, 178, 179, 167,
-1, -1, -1, 184, -1, 186, 174, 175, -1, 177,
178, 179, -1, -1, -1, -1, 184, -1, 186, -1,
-1, -1, -1, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, -1, -1, -1, -1, 122, 123, 124,
125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
135, 136, 137, 138, 139, 140, 141, 142, 143, -1,
-1, -1, -1, 148, -1, 150, 151, 152, -1, 154,
155, 156, 157, 158, 159, 160, 167, -1, -1, -1,
-1, -1, -1, 174, 175, -1, 177, 178, 179, 174,
-1, -1, 177, 184, -1, 186, -1, -1, -1, -1,
-1, -1, 187, 188, 11, 12, 13, 14, 15, 16,
-1, 18, -1, 20, -1, 22, 167, 24, -1, 26,
-1, 28, 29, 174, 175, -1, 177, 178, 179, -1,
-1, 167, -1, 184, -1, 186, -1, 1193, 174, 175,
-1, 177, 178, 179, 167, -1, -1, -1, 184, -1,
186, 174, 175, -1, 177, 178, 179, 167, -1, -1,
-1, 184, -1, 186, 174, 175, -1, 177, 178, 179,
167, -1, -1, -1, 184, -1, 186, 174, 175, -1,
177, 178, 179, -1, -1, -1, -1, 184, -1, 186,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, 108, 109, 110, 111, 112, 113, 114, 115, 116,
117, -1, -1, -1, -1, 122, 123, 124, 125, 126,
127, 128, 129, 130, 131, 132, 133, 134, 135, 136,
137, 138, 139, 140, 141, 142, 143, -1, -1, -1,
-1, 148, -1, 150, 151, 152, -1, 154, 155, 156,
157, 158, 159, 160, 167, -1, -1, -1, -1, -1,
-1, 174, 175, -1, 177, 178, 179, 174, -1, -1,
177, 184, -1, 186, -1, -1, -1, -1, -1, -1,
187, 188, 11, 12, 13, 14, 15, 16, -1, 18,
-1, 20, -1, 22, 167, 24, -1, 26, -1, 28,
-1, 174, 175, -1, 177, 178, 179, 167, -1, -1,
-1, 184, -1, 186, 174, 175, -1, 177, 178, 179,
167, -1, -1, -1, 184, -1, 186, 174, 175, -1,
177, 178, 179, 167, -1, -1, -1, 184, -1, 186,
174, 175, -1, 177, 178, 179, 167, -1, -1, -1,
184, -1, 186, 174, 175, -1, 177, 178, 179, 167,
-1, -1, -1, 184, -1, 186, 174, 175, -1, 177,
178, 179, -1, -1, -1, -1, 184, -1, 186, 108,
109, 110, 111, 112, 113, 114, 115, 116, 117, -1,
-1, -1, -1, 122, 123, 124, 125, 126, 127, 128,
129, 130, 131, 132, 133, 134, 135, 136, 137, 138,
139, 140, 141, 142, 143, -1, -1, -1, -1, 148,
-1, 150, 151, 152, -1, 154, 155, 156, 157, 158,
159, 160, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, -1, -1, 174, -1, -1, 177, 185,
186, -1, -1, -1, -1, -1, -1, -1, 187, 188,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, -1, -1, -1, -1, -1, -1, 185, 186, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, 185, 186, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, -1,
-1, -1, -1, -1, -1, -1, 186, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, -1, 186, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, -1, -1, -1,
-1, -1, -1, -1, 186, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, -1, 186, 168, 169, 170, 171, 172, 173,
174, 175, 176, 177, 178, -1, -1, -1, -1, -1,
-1, -1, 186, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
-1, 186, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, -1, -1, -1, -1, -1, -1, -1,
186, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, -1, 186,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, -1, -1, -1, -1, -1, -1, -1, 186, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, -1, 186, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, -1,
-1, -1, -1, -1, -1, -1, 186, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, -1, 186, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, -1, -1, -1,
-1, -1, -1, -1, 186, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, -1, 186, 168, 169, 170, 171, 172, 173,
174, 175, 176, 177, 178, -1, -1, -1, -1, -1,
-1, -1, 186, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
-1, 186, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, -1, -1, -1, -1, -1, -1, -1,
186, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, -1, 186,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, -1, -1, -1, -1, -1, -1, -1, 186, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, -1, 186, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, -1,
-1, -1, -1, -1, -1, -1, 186, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, -1, 186, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, -1, -1, -1,
-1, -1, -1, -1, 186, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, -1, 186, 168, 169, 170, 171, 172, 173,
174, 175, 176, 177, 178, -1, -1, -1, -1, -1,
-1, -1, 186, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
-1, 186, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, -1, -1, -1, -1, -1, -1, -1,
186, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, -1, 186,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, -1, -1, -1, -1, -1, -1, -1, 186, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, -1, 186, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, -1,
-1, -1, -1, -1, -1, -1, 186, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, -1, 186, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, -1, -1, -1,
-1, -1, -1, -1, 186, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, -1, 186, 168, 169, 170, 171, 172, 173,
174, 175, 176, 177, 178, -1, -1, -1, -1, -1,
-1, -1, 186, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
-1, 186, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, -1, -1, -1, -1, -1, -1, -1,
186, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, -1, 186,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, -1, -1, -1, -1, -1, -1, -1, 186, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, -1, 186, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, -1,
-1, -1, -1, -1, -1, -1, 186, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, -1, 186, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, -1, -1, -1,
-1, -1, -1, -1, 186, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, -1, 186, 168, 169, 170, 171, 172, 173,
174, 175, 176, 177, 178, -1, -1, -1, -1, -1,
-1, -1, 186, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
-1, 186, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, -1, -1, -1, -1, -1, -1, -1,
186, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, -1, 186,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, -1, -1, -1, -1, -1, -1, -1, 186, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, -1, 186, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, -1,
-1, -1, -1, -1, -1, -1, 186, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, -1, 186, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, -1, -1, -1,
-1, -1, -1, -1, 186, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, -1, 186, 168, 169, 170, 171, 172, 173,
174, 175, 176, 177, 178, -1, -1, -1, -1, -1,
-1, -1, 186, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
-1, 186, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, -1, -1, -1, -1, -1, -1, -1,
186, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, -1, 186,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, -1, -1, -1, -1, -1, -1, -1, 186, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, -1, 186, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, -1,
-1, -1, -1, -1, -1, -1, 186, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, -1, 186, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, -1, -1, -1,
-1, -1, -1, -1, 186, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, -1, 186, 168, 169, 170, 171, 172, 173,
174, 175, 176, 177, 178, -1, -1, -1, -1, -1,
-1, -1, 186, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
-1, 186, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, -1, -1, -1, -1, -1, -1, -1,
186, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, -1, 186,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, -1, -1, -1, -1, -1, -1, -1, 186, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, -1, 186, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, -1,
-1, -1, -1, -1, -1, -1, 186, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, -1, 186, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, -1, -1, -1,
-1, -1, -1, -1, 186, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, -1, 186, 168, 169, 170, 171, 172, 173,
174, 175, 176, 177, 178, -1, -1, -1, -1, -1,
-1, -1, 186, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
-1, 186, 168, 169, 170, 171, 172, 173, 174, 175,
176, 177, 178, -1, -1, -1, -1, -1, -1, -1,
186, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, -1, 186,
168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
178, -1, -1, -1, -1, -1, -1, -1, 186, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, -1, 186, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, -1,
167, -1, -1, -1, -1, -1, 186, 174, 175, -1,
177, 178, 179, 167, -1, -1, -1, 184, 185, -1,
174, 175, -1, 177, 178, 179, 167, -1, -1, -1,
184, 185, -1, 174, 175, -1, 177, 178, 179, 167,
-1, -1, -1, 184, 185, -1, 174, 175, -1, 177,
178, 179, 167, -1, -1, -1, 184, 185, -1, 174,
175, -1, 177, 178, 179, 167, -1, -1, -1, 184,
185, -1, 174, 175, -1, 177, 178, 179, 167, -1,
-1, -1, 184, 185, -1, 174, 175, -1, 177, 178,
179, 167, -1, -1, -1, 184, 185, -1, 174, 175,
-1, 177, 178, 179, 167, -1, -1, -1, 184, 185,
-1, 174, 175, -1, 177, 178, 179, 167, -1, -1,
-1, 184, 185, -1, 174, 175, -1, 177, 178, 179,
167, -1, -1, -1, 184, 185, -1, 174, 175, -1,
177, 178, 179, 167, -1, -1, -1, 184, 185, -1,
174, 175, -1, 177, 178, 179, 167, -1, -1, -1,
184, 185, -1, 174, 175, -1, 177, 178, 179, 167,
-1, -1, -1, 184, 185, -1, 174, 175, -1, 177,
178, 179, 167, -1, -1, -1, 184, 185, -1, 174,
175, -1, 177, 178, 179, -1, -1, -1, -1, 184,
185, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, 185, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, 185, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, 185, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, 185, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
185, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, 185, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, 185, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, 185, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, 185, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
185, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, 185, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, 185, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, 185, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, 185, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
185, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, -1, -1, 185, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
-1, -1, -1, -1, -1, -1, 185, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, -1, -1,
-1, -1, -1, -1, 185, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, -1, -1, -1, -1,
-1, -1, 185, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, -1, -1, -1, -1, -1, -1,
185, 168, 169, 170, 171, 172, 173, 174, 175, 176,
177, 178, -1, -1, -1, -1, 165, -1, 185, 168,
169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
165, -1, -1, 168, 169, 170, 171, 172, 173, 174,
175, 176, 177, 178, 174, 175, -1, 177, 178, 179,
180, -1, -1, -1, 184, 185, 186, 174, 175, -1,
177, 178, 179, 180, -1, -1, -1, 184, 185, 186,
174, 175, -1, 177, 178, 179, 180, -1, -1, -1,
184, 185, 186, 174, 175, -1, 177, 178, 179, 180,
-1, -1, -1, 184, -1, 186, 174, 175, -1, 177,
178, 179, 180, -1, -1, -1, 184, -1, 186, 174,
175, -1, 177, 178, 179, 180, -1, -1, -1, 184,
-1, 186, 174, 175, -1, 177, 178, 179, 180, -1,
-1, -1, 184, -1, 186, 174, 175, -1, 177, 178,
179, 180, -1, -1, -1, 184, -1, 186, 174, 175,
-1, 177, 178, 179, 180, -1, -1, -1, 184, -1,
186, 174, 175, -1, 177, 178, 179, 180, -1, -1,
-1, 184, -1, 186, 174, 175, -1, 177, 178, 179,
180, -1, -1, -1, 184, -1, 186, 174, 175, -1,
177, 178, 179, 180, -1, -1, -1, 184, -1, 186,
174, 175, -1, 177, 178, 179, 180, -1, -1, -1,
184, -1, 186, 174, 175, -1, 177, 178, 179, 180,
-1, -1, -1, 184, -1, 186, 174, 175, -1, 177,
178, 179, 180, -1, -1, -1, 184, -1, 186, 174,
175, -1, 177, 178, 179, 180, -1, -1, -1, 184,
-1, 186, 174, 175, -1, 177, 178, 179, 180, -1,
-1, -1, 184, -1, 186, 174, 175, -1, 177, 178,
179, 180, -1, -1, -1, 184, -1, 186, 174, 175,
-1, 177, 178, 179, 180, -1, -1, -1, 184, -1,
186, 174, 175, -1, 177, 178, 179, 180, -1, -1,
-1, 184, -1, 186, 174, 175, -1, 177, 178, 179,
180, -1, -1, -1, 184, -1, 186, 174, 175, -1,
177, 178, 179, 180, -1, -1, -1, 184, -1, 186,
174, 175, -1, 177, 178, 179, 180, -1, -1, -1,
184, 185, 174, 175, -1, 177, 178, 179, 180, -1,
-1, -1, 184, 185, 174, 175, -1, 177, 178, 179,
180, -1, -1, -1, 184, 185, 174, 175, -1, 177,
178, 179, 180, -1, -1, -1, 184, 185, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, 300,
301, 302, 303, 304, 305, 306, 307, 308, 309, 310,
174, 175, -1, 177, 178, 179, 180, -1, 174, 175,
184, 177, 178, 179, 180, -1, 174, 175, 184, 177,
178, 179, -1, -1, 174, 175, 184, 177, 178, 179,
-1, -1, 174, 175, 184, 177, 178, 179, -1, -1,
-1, -1, 184
};
/* STOS_[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
const unsigned char
SubsetValueExpressionParser::yystos_[] =
{
0, 45, 46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 190, 191,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 74, 75, 76,
77, 78, 79, 93, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
140, 141, 142, 143, 148, 149, 150, 151, 152, 153,
154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
174, 177, 187, 188, 193, 197, 198, 200, 201, 202,
203, 204, 205, 206, 207, 208, 209, 210, 211, 212,
213, 214, 215, 216, 217, 218, 219, 220, 221, 222,
223, 224, 225, 226, 227, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 122, 123, 124, 125, 126,
127, 128, 129, 130, 131, 132, 133, 134, 135, 136,
137, 138, 139, 140, 141, 142, 143, 148, 150, 151,
152, 154, 155, 156, 157, 158, 159, 160, 174, 177,
187, 188, 197, 202, 204, 206, 208, 210, 202, 197,
202, 197, 204, 204, 206, 206, 208, 208, 210, 210,
108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
122, 123, 124, 125, 126, 127, 128, 129, 130, 131,
132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
142, 143, 148, 150, 151, 152, 154, 155, 156, 157,
158, 159, 160, 174, 177, 187, 188, 216, 218, 220,
222, 224, 226, 218, 216, 218, 216, 220, 220, 222,
222, 224, 224, 226, 226, 186, 185, 0, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
197, 202, 204, 206, 208, 216, 218, 220, 222, 224,
204, 206, 220, 222, 197, 202, 204, 206, 208, 210,
216, 218, 220, 222, 224, 226, 210, 226, 174, 175,
177, 178, 179, 180, 184, 72, 73, 192, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, 192,
167, 174, 175, 177, 178, 179, 184, 192, 167, 174,
175, 177, 178, 179, 184, 192, 167, 174, 175, 177,
178, 179, 184, 192, 164, 166, 167, 192, 174, 175,
177, 178, 179, 180, 184, 192, 168, 169, 170, 171,
172, 173, 174, 175, 176, 177, 178, 192, 167, 174,
175, 177, 178, 179, 184, 192, 167, 174, 175, 177,
178, 179, 184, 192, 167, 174, 175, 177, 178, 179,
184, 192, 164, 166, 167, 192, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 185,
186, 185, 186, 185, 186, 185, 186, 185, 186, 185,
186, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 187, 187, 187, 187, 187, 187,
187, 187, 187, 187, 185, 186, 185, 186, 185, 186,
185, 186, 185, 186, 185, 186, 202, 196, 196, 196,
196, 196, 196, 196, 196, 196, 196, 196, 196, 202,
202, 202, 202, 30, 186, 30, 186, 186, 30, 186,
30, 186, 186, 186, 186, 186, 186, 186, 186, 5,
6, 8, 9, 10, 202, 218, 202, 218, 202, 218,
197, 202, 204, 206, 208, 216, 218, 220, 222, 224,
197, 202, 204, 206, 208, 216, 218, 220, 222, 224,
202, 218, 202, 218, 202, 218, 197, 202, 204, 206,
208, 216, 218, 220, 222, 224, 197, 202, 204, 206,
208, 216, 218, 220, 222, 224, 202, 202, 197, 202,
216, 218, 197, 202, 216, 218, 197, 202, 216, 218,
202, 218, 202, 218, 202, 218, 202, 218, 202, 218,
202, 218, 202, 218, 202, 218, 202, 218, 202, 218,
202, 218, 202, 218, 202, 218, 202, 218, 202, 218,
202, 218, 202, 218, 202, 218, 202, 218, 202, 218,
202, 218, 204, 206, 220, 222, 204, 206, 208, 204,
206, 220, 222, 204, 206, 220, 222, 204, 220, 204,
206, 208, 204, 206, 220, 222, 204, 206, 208, 220,
222, 204, 206, 208, 220, 222, 224, 204, 206, 220,
222, 204, 206, 220, 222, 204, 206, 220, 222, 204,
206, 220, 222, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 197, 197,
197, 202, 202, 197, 204, 206, 208, 197, 194, 192,
202, 202, 202, 202, 202, 202, 202, 202, 202, 197,
202, 204, 206, 208, 202, 204, 206, 208, 204, 206,
208, 204, 206, 208, 202, 202, 197, 204, 206, 208,
195, 204, 206, 208, 204, 206, 208, 204, 206, 208,
202, 202, 197, 204, 206, 208, 195, 204, 206, 208,
204, 206, 208, 204, 206, 208, 202, 202, 197, 204,
206, 208, 195, 197, 202, 204, 206, 208, 210, 210,
216, 216, 216, 218, 218, 216, 220, 222, 224, 216,
194, 218, 218, 218, 218, 218, 218, 218, 218, 218,
216, 218, 220, 222, 224, 218, 220, 222, 224, 220,
220, 218, 218, 216, 220, 222, 224, 195, 220, 222,
224, 222, 222, 218, 218, 216, 220, 222, 224, 195,
220, 222, 224, 224, 224, 218, 218, 216, 220, 222,
224, 195, 216, 218, 220, 222, 224, 226, 226, 216,
218, 216, 218, 216, 218, 216, 218, 186, 185, 185,
185, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 185, 185, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 185, 186, 185, 186, 185, 185, 185,
185, 186, 185, 186, 185, 185, 185, 185, 186, 185,
186, 185, 185, 185, 185, 186, 185, 186, 185, 185,
185, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 80, 81,
82, 80, 81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 147, 83, 84, 85, 87, 88, 91,
147, 92, 147, 165, 165, 165, 165, 165, 80, 81,
82, 80, 81, 82, 83, 84, 85, 86, 87, 88,
89, 90, 91, 147, 83, 84, 85, 87, 88, 91,
147, 92, 147, 165, 165, 165, 165, 165, 202, 202,
202, 202, 29, 174, 199, 218, 197, 202, 204, 206,
208, 216, 218, 220, 222, 224, 197, 202, 204, 206,
208, 216, 218, 220, 222, 224, 187, 187, 187, 197,
202, 204, 206, 208, 187, 187, 187, 216, 218, 220,
222, 224, 185, 185, 185, 186, 29, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 186, 186, 186, 186, 186,
186, 186, 186, 186, 186, 202, 202, 202, 186, 185,
185, 202, 202, 185, 185, 202, 202, 185, 185, 202,
202, 185, 186, 202, 185, 202, 185, 202, 186
};
#if YYDEBUG
/* TOKEN_NUMBER_[YYLEX-NUM] -- Internal symbol number corresponding
to YYLEX-NUM. */
const unsigned short int
SubsetValueExpressionParser::yytoken_number_[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
285, 286, 287, 288, 289, 290, 291, 292, 293, 294,
295, 296, 297, 298, 299, 300, 301, 302, 303, 304,
305, 306, 307, 308, 309, 310, 311, 312, 313, 314,
315, 316, 317, 318, 319, 320, 321, 322, 323, 324,
325, 326, 327, 328, 329, 330, 331, 332, 333, 334,
335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 352, 353, 354,
355, 356, 357, 358, 359, 360, 361, 362, 363, 364,
365, 366, 367, 368, 369, 370, 371, 372, 373, 374,
375, 376, 377, 378, 379, 380, 381, 382, 383, 384,
385, 386, 387, 388, 389, 390, 391, 392, 393, 394,
395, 396, 397, 398, 399, 400, 401, 402, 403, 404,
405, 406, 407, 408, 409, 410, 411, 412, 413, 414,
415, 416, 417, 418, 63, 58, 419, 420, 421, 422,
60, 62, 423, 424, 45, 43, 37, 42, 47, 38,
94, 425, 426, 427, 46, 44, 41, 40, 33
};
#endif
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
const unsigned char
SubsetValueExpressionParser::yyr1_[] =
{
0, 189, 190, 191, 191, 191, 191, 191, 191, 191,
191, 191, 191, 191, 191, 191, 191, 191, 191, 191,
191, 191, 191, 191, 191, 191, 191, 191, 191, 191,
192, 192, 193, 193, 193, 193, 193, 193, 193, 193,
193, 193, 193, 193, 194, 195, 196, 197, 197, 197,
197, 197, 197, 197, 197, 197, 197, 197, 197, 197,
197, 197, 197, 197, 197, 197, 197, 197, 197, 197,
197, 197, 197, 197, 197, 197, 197, 197, 197, 197,
197, 198, 199, 199, 200, 200, 200, 200, 200, 200,
200, 200, 201, 201, 201, 201, 201, 201, 201, 201,
201, 201, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
202, 202, 202, 202, 202, 202, 202, 202, 202, 203,
204, 204, 204, 204, 204, 204, 204, 204, 204, 204,
204, 204, 204, 204, 204, 204, 204, 204, 204, 204,
204, 204, 204, 204, 204, 204, 204, 204, 204, 204,
204, 204, 204, 204, 204, 204, 205, 206, 206, 206,
206, 206, 206, 206, 206, 206, 206, 206, 206, 206,
206, 206, 206, 206, 206, 206, 206, 206, 206, 206,
206, 206, 206, 206, 206, 206, 206, 206, 207, 208,
208, 208, 208, 208, 208, 208, 208, 208, 208, 208,
208, 208, 208, 208, 208, 208, 208, 208, 208, 208,
209, 210, 210, 210, 210, 210, 210, 210, 210, 210,
210, 210, 210, 210, 210, 211, 212, 213, 214, 215,
216, 216, 216, 216, 216, 216, 216, 216, 216, 216,
216, 216, 216, 216, 216, 216, 216, 216, 216, 216,
216, 216, 216, 216, 216, 216, 216, 216, 217, 218,
218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
218, 218, 218, 218, 218, 218, 218, 218, 218, 218,
218, 218, 218, 218, 218, 218, 218, 218, 218, 219,
220, 220, 220, 220, 220, 220, 220, 220, 220, 220,
220, 220, 220, 220, 220, 220, 220, 220, 220, 220,
220, 220, 220, 220, 220, 220, 221, 222, 222, 222,
222, 222, 222, 222, 222, 222, 222, 222, 222, 222,
222, 222, 222, 222, 222, 222, 222, 222, 222, 222,
222, 222, 223, 224, 224, 224, 224, 224, 224, 224,
224, 224, 224, 224, 224, 224, 224, 224, 224, 224,
225, 226, 226, 226, 226, 226, 226, 226, 226, 226,
226, 226, 226, 227
};
/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
const unsigned char
SubsetValueExpressionParser::yyr2_[] =
{
0, 2, 1, 2, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 2, 2,
1, 2, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 0, 0, 0, 1, 1, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 2, 2, 2, 3, 4, 4, 4, 4, 4,
4, 4, 5, 3, 3, 3, 2, 1, 4, 6,
6, 3, 1, 2, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 1, 1, 3, 3, 3, 3, 3, 6,
4, 4, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 2, 3, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 5, 1, 3, 3, 3, 3,
3, 4, 3, 4, 3, 4, 3, 4, 3, 3,
3, 3, 2, 1, 4, 1, 4, 6, 6, 3,
1, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 3, 4, 4, 4, 4, 4, 4, 4, 6,
5, 2, 1, 4, 6, 6, 3, 1, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 3, 4, 4, 4, 4, 4, 4, 4, 4,
4, 6, 5, 2, 1, 4, 6, 6, 3, 1,
1, 3, 3, 3, 3, 3, 3, 2, 3, 4,
4, 4, 4, 6, 5, 2, 1, 4, 6, 6,
3, 1, 1, 3, 3, 3, 3, 3, 3, 3,
3, 3, 2, 2, 1, 3, 8, 20, 14, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 2, 2, 2, 4, 4, 4, 4, 4,
4, 4, 3, 5, 2, 1, 6, 6, 3, 3,
3, 3, 3, 3, 6, 6, 4, 4, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 2, 3,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 5, 2, 1, 6, 6, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 2, 3, 4, 4, 4, 4, 4, 4, 4,
6, 5, 2, 1, 6, 6, 3, 3, 3, 3,
3, 3, 3, 3, 3, 2, 3, 4, 4, 4,
4, 4, 4, 4, 4, 4, 6, 5, 2, 1,
6, 6, 3, 3, 3, 3, 3, 3, 3, 2,
3, 4, 4, 4, 6, 5, 2, 1, 6, 6,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 1, 3
};
#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at \a yyntokens_, nonterminals. */
const char*
const SubsetValueExpressionParser::yytname_[] =
{
"$end", "error", "$undefined", "\"timeline\"", "\"lookup\"",
"\"scalarID\"", "\"vectorID\"", "\"logicalID\"", "\"tensorID\"",
"\"symmTensorID\"", "\"sphericalTensorID\"", "\"pointScalarID\"",
"\"pointVectorID\"", "\"pointLogicalID\"", "\"pointTensorID\"",
"\"pointSymmTensorID\"", "\"pointSphericalTensorID\"", "\"F_scalarID\"",
"\"F_pointScalarID\"", "\"F_vectorID\"", "\"F_pointVectorID\"",
"\"F_tensorID\"", "\"F_pointTensorID\"", "\"F_symmTensorID\"",
"\"F_pointSymmTensorID\"", "\"F_sphericalTensorID\"",
"\"F_pointSphericalTensorID\"", "\"F_logicalID\"",
"\"F_pointLogicalID\"", "\"value\"", "\"integer\"", "\"vector\"",
"\"sexpression\"", "\"expression\"", "\"pexpression\"",
"\"lexpression\"", "\"plexpression\"", "\"vexpression\"",
"\"pvexpression\"", "\"texpression\"", "\"ptexpression\"",
"\"yexpression\"", "\"pyexpression\"", "\"hexpression\"",
"\"phexpression\"", "START_DEFAULT", "START_FACE_SCALAR_COMMA",
"START_FACE_SCALAR_CLOSE", "START_FACE_VECTOR_COMMA",
"START_FACE_VECTOR_CLOSE", "START_FACE_TENSOR_COMMA",
"START_FACE_TENSOR_CLOSE", "START_FACE_YTENSOR_COMMA",
"START_FACE_YTENSOR_CLOSE", "START_FACE_HTENSOR_COMMA",
"START_FACE_HTENSOR_CLOSE", "START_FACE_LOGICAL_COMMA",
"START_FACE_LOGICAL_CLOSE", "START_POINT_SCALAR_COMMA",
"START_POINT_SCALAR_CLOSE", "START_POINT_VECTOR_COMMA",
"START_POINT_VECTOR_CLOSE", "START_POINT_TENSOR_COMMA",
"START_POINT_TENSOR_CLOSE", "START_POINT_YTENSOR_COMMA",
"START_POINT_YTENSOR_CLOSE", "START_POINT_HTENSOR_COMMA",
"START_POINT_HTENSOR_CLOSE", "START_POINT_LOGICAL_COMMA",
"START_POINT_LOGICAL_CLOSE", "START_CLOSE_ONLY", "START_COMMA_ONLY",
"TOKEN_LAST_FUNCTION_CHAR", "TOKEN_IN_FUNCTION_CHAR", "TOKEN_VECTOR",
"TOKEN_TENSOR", "TOKEN_SYMM_TENSOR", "TOKEN_SPHERICAL_TENSOR",
"TOKEN_TRUE", "TOKEN_FALSE", "TOKEN_x", "TOKEN_y", "TOKEN_z", "TOKEN_xx",
"TOKEN_xy", "TOKEN_xz", "TOKEN_yx", "TOKEN_yy", "TOKEN_yz", "TOKEN_zx",
"TOKEN_zy", "TOKEN_zz", "TOKEN_ii", "TOKEN_unitTensor", "TOKEN_pi",
"TOKEN_rand", "TOKEN_randFixed", "TOKEN_id", "TOKEN_randNormal",
"TOKEN_randNormalFixed", "TOKEN_position", "TOKEN_area", "TOKEN_volume",
"TOKEN_Sf", "TOKEN_normal", "TOKEN_deltaT", "TOKEN_time",
"TOKEN_oldTime", "TOKEN_pow", "TOKEN_log", "TOKEN_exp", "TOKEN_mag",
"TOKEN_magSqr", "TOKEN_sin", "TOKEN_cos", "TOKEN_tan", "TOKEN_min",
"TOKEN_max", "TOKEN_minPosition", "TOKEN_maxPosition", "TOKEN_average",
"TOKEN_sum", "TOKEN_sqr", "TOKEN_sqrt", "TOKEN_log10", "TOKEN_asin",
"TOKEN_acos", "TOKEN_atan", "TOKEN_sinh", "TOKEN_cosh", "TOKEN_tanh",
"TOKEN_asinh", "TOKEN_acosh", "TOKEN_atanh", "TOKEN_erf", "TOKEN_erfc",
"TOKEN_lgamma", "TOKEN_besselJ0", "TOKEN_besselJ1", "TOKEN_besselY0",
"TOKEN_besselY1", "TOKEN_sign", "TOKEN_pos", "TOKEN_neg",
"TOKEN_toPoint", "TOKEN_toFace", "TOKEN_points", "TOKEN_transpose",
"TOKEN_diag", "TOKEN_tr", "TOKEN_dev", "TOKEN_symm", "TOKEN_skew",
"TOKEN_det", "TOKEN_cof", "TOKEN_inv", "TOKEN_sph", "TOKEN_twoSymm",
"TOKEN_dev2", "TOKEN_eigenValues", "TOKEN_eigenVectors", "TOKEN_cpu",
"TOKEN_weight", "TOKEN_flip", "'?'", "':'", "TOKEN_OR", "TOKEN_AND",
"TOKEN_NEQ", "TOKEN_EQ", "'<'", "'>'", "TOKEN_GEQ", "TOKEN_LEQ", "'-'",
"'+'", "'%'", "'*'", "'/'", "'&'", "'^'", "TOKEN_HODGE", "TOKEN_NOT",
"TOKEN_NEG", "'.'", "','", "')'", "'('", "'!'", "$accept",
"switch_start", "switch_expr", "restOfFunction", "unit",
"vectorComponentSwitch", "tensorComponentSwitch", "eatCharactersSwitch",
"vexp", "evaluateVectorFunction", "scalar", "sreduced", "vreduced",
"exp", "evaluateScalarFunction", "texp", "evaluateTensorFunction",
"yexp", "evaluateSymmTensorFunction", "hexp",
"evaluateSphericalTensorFunction", "lexp", "evaluateLogicalFunction",
"vector", "tensor", "symmTensor", "sphericalTensor", "pvexp",
"evaluatePointVectorFunction", "pexp", "evaluatePointScalarFunction",
"ptexp", "evaluatePointTensorFunction", "pyexp",
"evaluatePointSymmTensorFunction", "phexp",
"evaluatePointSphericalTensorFunction", "plexp",
"evaluatePointLogicalFunction", 0
};
#endif
#if YYDEBUG
/* YYRHS -- A `-1'-separated list of the rules' RHS. */
const SubsetValueExpressionParser::rhs_number_type
SubsetValueExpressionParser::yyrhs_[] =
{
190, 0, -1, 191, -1, 45, 193, -1, 46, 202,
185, -1, 47, 202, 186, -1, 58, 218, 185, -1,
59, 218, 186, -1, 48, 197, 185, -1, 49, 197,
186, -1, 60, 216, 185, -1, 61, 216, 186, -1,
50, 204, 185, -1, 51, 204, 186, -1, 62, 220,
185, -1, 63, 220, 186, -1, 52, 206, 185, -1,
53, 206, 186, -1, 64, 222, 185, -1, 65, 222,
186, -1, 54, 208, 185, -1, 55, 208, 186, -1,
66, 224, 185, -1, 67, 224, 186, -1, 56, 210,
185, -1, 57, 210, 186, -1, 68, 226, 185, -1,
69, 226, 186, -1, 70, 186, -1, 71, 185, -1,
72, -1, 73, 192, -1, 202, -1, 197, -1, 210,
-1, 218, -1, 216, -1, 226, -1, 204, -1, 220,
-1, 206, -1, 222, -1, 208, -1, 224, -1, -1,
-1, -1, 212, -1, 201, -1, 197, 175, 197, -1,
202, 177, 197, -1, 197, 177, 202, -1, 204, 179,
197, -1, 197, 179, 204, -1, 206, 179, 197, -1,
197, 179, 206, -1, 208, 179, 197, -1, 197, 179,
208, -1, 197, 178, 202, -1, 197, 180, 197, -1,
197, 174, 197, -1, 174, 197, -1, 177, 204, -1,
177, 206, -1, 187, 197, 186, -1, 159, 187, 204,
186, -1, 159, 187, 206, 186, -1, 204, 184, 195,
80, -1, 204, 184, 195, 81, -1, 204, 184, 195,
82, -1, 148, 187, 204, 186, -1, 148, 187, 206,
186, -1, 210, 164, 197, 165, 197, -1, 100, 187,
186, -1, 104, 187, 186, -1, 103, 187, 186, -1,
198, 192, -1, 6, -1, 107, 187, 6, 186, -1,
116, 187, 197, 185, 197, 186, -1, 117, 187, 197,
185, 197, 186, -1, 19, 187, 196, -1, 29, -1,
174, 29, -1, 116, 187, 202, 186, -1, 117, 187,
202, 186, -1, 116, 187, 218, 186, -1, 117, 187,
218, 186, -1, 121, 187, 202, 186, -1, 121, 187,
218, 186, -1, 120, 187, 202, 186, -1, 120, 187,
218, 186, -1, 116, 187, 197, 186, -1, 117, 187,
197, 186, -1, 116, 187, 216, 186, -1, 117, 187,
216, 186, -1, 118, 187, 202, 186, -1, 119, 187,
202, 186, -1, 121, 187, 197, 186, -1, 121, 187,
216, 186, -1, 120, 187, 197, 186, -1, 120, 187,
216, 186, -1, 29, -1, 200, -1, 202, 175, 202,
-1, 202, 174, 202, -1, 202, 177, 202, -1, 202,
176, 202, -1, 202, 178, 202, -1, 108, 187, 202,
185, 202, 186, -1, 109, 187, 202, 186, -1, 110,
187, 202, 186, -1, 197, 179, 197, -1, 204, 167,
204, -1, 204, 167, 206, -1, 204, 167, 208, -1,
206, 167, 204, -1, 206, 167, 206, -1, 206, 167,
208, -1, 208, 167, 204, -1, 208, 167, 206, -1,
208, 167, 208, -1, 174, 202, -1, 187, 202, 186,
-1, 122, 187, 202, 186, -1, 123, 187, 202, 186,
-1, 113, 187, 202, 186, -1, 114, 187, 202, 186,
-1, 115, 187, 202, 186, -1, 124, 187, 202, 186,
-1, 125, 187, 202, 186, -1, 126, 187, 202, 186,
-1, 127, 187, 202, 186, -1, 128, 187, 202, 186,
-1, 129, 187, 202, 186, -1, 130, 187, 202, 186,
-1, 131, 187, 202, 186, -1, 132, 187, 202, 186,
-1, 133, 187, 202, 186, -1, 134, 187, 202, 186,
-1, 135, 187, 202, 186, -1, 136, 187, 202, 186,
-1, 137, 187, 202, 186, -1, 138, 187, 202, 186,
-1, 139, 187, 202, 186, -1, 140, 187, 202, 186,
-1, 141, 187, 202, 186, -1, 142, 187, 202, 186,
-1, 143, 187, 202, 186, -1, 111, 187, 202, 186,
-1, 111, 187, 197, 186, -1, 111, 187, 204, 186,
-1, 111, 187, 206, 186, -1, 111, 187, 208, 186,
-1, 112, 187, 202, 186, -1, 112, 187, 197, 186,
-1, 112, 187, 204, 186, -1, 112, 187, 206, 186,
-1, 112, 187, 208, 186, -1, 149, 187, 204, 186,
-1, 149, 187, 206, 186, -1, 149, 187, 208, 186,
-1, 153, 187, 204, 186, -1, 153, 187, 206, 186,
-1, 153, 187, 208, 186, -1, 197, 184, 194, 80,
-1, 197, 184, 194, 81, -1, 197, 184, 194, 82,
-1, 204, 184, 195, 83, -1, 204, 184, 195, 84,
-1, 204, 184, 195, 85, -1, 204, 184, 195, 86,
-1, 204, 184, 195, 87, -1, 204, 184, 195, 88,
-1, 204, 184, 195, 89, -1, 204, 184, 195, 90,
-1, 204, 184, 195, 91, -1, 206, 184, 195, 83,
-1, 206, 184, 195, 84, -1, 206, 184, 195, 85,
-1, 206, 184, 195, 87, -1, 206, 184, 195, 88,
-1, 206, 184, 195, 91, -1, 208, 184, 195, 92,
-1, 210, 164, 202, 165, 202, -1, 94, -1, 97,
187, 186, -1, 161, 187, 186, -1, 162, 187, 186,
-1, 163, 187, 186, -1, 95, 187, 186, -1, 95,
187, 30, 186, -1, 98, 187, 186, -1, 98, 187,
30, 186, -1, 96, 187, 186, -1, 96, 187, 30,
186, -1, 99, 187, 186, -1, 99, 187, 30, 186,
-1, 105, 187, 186, -1, 106, 187, 186, -1, 101,
187, 186, -1, 102, 187, 186, -1, 203, 192, -1,
5, -1, 107, 187, 5, 186, -1, 3, -1, 4,
187, 202, 186, -1, 116, 187, 202, 185, 202, 186,
-1, 117, 187, 202, 185, 202, 186, -1, 17, 187,
196, -1, 213, -1, 204, 175, 204, -1, 204, 175,
206, -1, 204, 175, 208, -1, 206, 175, 204, -1,
208, 175, 204, -1, 202, 177, 204, -1, 204, 177,
202, -1, 197, 177, 197, -1, 204, 179, 204, -1,
206, 179, 204, -1, 204, 179, 206, -1, 208, 179,
204, -1, 204, 179, 208, -1, 204, 178, 202, -1,
204, 174, 204, -1, 204, 174, 206, -1, 204, 174,
208, -1, 206, 174, 204, -1, 208, 174, 204, -1,
174, 204, -1, 187, 204, 186, -1, 152, 187, 204,
186, -1, 160, 187, 204, 186, -1, 160, 187, 206,
186, -1, 155, 187, 204, 186, -1, 154, 187, 204,
186, -1, 150, 187, 204, 186, -1, 158, 187, 204,
186, -1, 204, 184, 195, 147, 187, 186, -1, 210,
164, 204, 165, 204, -1, 205, 192, -1, 8, -1,
107, 187, 8, 186, -1, 116, 187, 204, 185, 204,
186, -1, 117, 187, 204, 185, 204, 186, -1, 21,
187, 196, -1, 214, -1, 206, 175, 206, -1, 206,
175, 208, -1, 208, 175, 206, -1, 202, 177, 206,
-1, 206, 177, 202, -1, 206, 179, 206, -1, 208,
179, 206, -1, 206, 179, 208, -1, 206, 178, 202,
-1, 206, 174, 206, -1, 206, 174, 208, -1, 208,
174, 206, -1, 174, 206, -1, 187, 206, 186, -1,
151, 187, 206, 186, -1, 151, 187, 204, 186, -1,
157, 187, 206, 186, -1, 157, 187, 204, 186, -1,
155, 187, 206, 186, -1, 154, 187, 206, 186, -1,
150, 187, 206, 186, -1, 158, 187, 206, 186, -1,
122, 187, 197, 186, -1, 206, 184, 195, 147, 187,
186, -1, 210, 164, 206, 165, 206, -1, 207, 192,
-1, 9, -1, 107, 187, 9, 186, -1, 116, 187,
206, 185, 206, 186, -1, 117, 187, 206, 185, 206,
186, -1, 23, 187, 196, -1, 215, -1, 93, -1,
208, 175, 208, -1, 202, 177, 208, -1, 208, 177,
202, -1, 208, 179, 208, -1, 208, 178, 202, -1,
208, 174, 208, -1, 174, 208, -1, 187, 208, 186,
-1, 156, 187, 204, 186, -1, 156, 187, 206, 186,
-1, 156, 187, 208, 186, -1, 155, 187, 208, 186,
-1, 208, 184, 195, 147, 187, 186, -1, 210, 164,
208, 165, 208, -1, 209, 192, -1, 10, -1, 107,
187, 10, 186, -1, 116, 187, 208, 185, 208, 186,
-1, 117, 187, 208, 185, 208, 186, -1, 25, 187,
196, -1, 78, -1, 79, -1, 202, 170, 202, -1,
202, 171, 202, -1, 202, 173, 202, -1, 202, 172,
202, -1, 202, 169, 202, -1, 202, 168, 202, -1,
187, 210, 186, -1, 210, 167, 210, -1, 210, 166,
210, -1, 188, 210, -1, 211, 192, -1, 7, -1,
27, 187, 196, -1, 74, 187, 202, 185, 202, 185,
202, 186, -1, 75, 187, 202, 185, 202, 185, 202,
185, 202, 185, 202, 185, 202, 185, 202, 185, 202,
185, 202, 186, -1, 76, 187, 202, 185, 202, 185,
202, 185, 202, 185, 202, 185, 202, 186, -1, 77,
187, 202, 186, -1, 216, 175, 216, -1, 218, 177,
216, -1, 216, 177, 218, -1, 220, 179, 216, -1,
216, 179, 220, -1, 222, 179, 216, -1, 216, 179,
222, -1, 224, 179, 216, -1, 216, 179, 224, -1,
216, 178, 218, -1, 216, 180, 216, -1, 216, 174,
216, -1, 174, 216, -1, 177, 220, -1, 177, 222,
-1, 159, 187, 220, 186, -1, 159, 187, 222, 186,
-1, 220, 184, 195, 80, -1, 220, 184, 195, 81,
-1, 220, 184, 195, 82, -1, 148, 187, 220, 186,
-1, 148, 187, 222, 186, -1, 187, 216, 186, -1,
226, 164, 216, 165, 216, -1, 217, 192, -1, 12,
-1, 116, 187, 216, 185, 216, 186, -1, 117, 187,
216, 185, 216, 186, -1, 20, 187, 196, -1, 218,
175, 218, -1, 218, 174, 218, -1, 218, 177, 218,
-1, 218, 176, 218, -1, 218, 178, 218, -1, 108,
187, 218, 185, 199, 186, -1, 108, 187, 218, 185,
218, 186, -1, 109, 187, 218, 186, -1, 110, 187,
218, 186, -1, 216, 179, 216, -1, 220, 167, 220,
-1, 220, 167, 222, -1, 220, 167, 224, -1, 222,
167, 220, -1, 222, 167, 222, -1, 222, 167, 224,
-1, 224, 167, 220, -1, 224, 167, 222, -1, 224,
167, 224, -1, 174, 218, -1, 187, 218, 186, -1,
122, 187, 218, 186, -1, 123, 187, 218, 186, -1,
113, 187, 218, 186, -1, 114, 187, 218, 186, -1,
115, 187, 218, 186, -1, 124, 187, 218, 186, -1,
125, 187, 218, 186, -1, 126, 187, 218, 186, -1,
127, 187, 218, 186, -1, 128, 187, 218, 186, -1,
129, 187, 218, 186, -1, 130, 187, 218, 186, -1,
131, 187, 218, 186, -1, 132, 187, 218, 186, -1,
133, 187, 218, 186, -1, 134, 187, 218, 186, -1,
135, 187, 218, 186, -1, 136, 187, 218, 186, -1,
137, 187, 218, 186, -1, 138, 187, 218, 186, -1,
139, 187, 218, 186, -1, 140, 187, 218, 186, -1,
141, 187, 218, 186, -1, 142, 187, 218, 186, -1,
143, 187, 218, 186, -1, 111, 187, 218, 186, -1,
111, 187, 216, 186, -1, 111, 187, 220, 186, -1,
111, 187, 222, 186, -1, 111, 187, 224, 186, -1,
112, 187, 218, 186, -1, 112, 187, 216, 186, -1,
112, 187, 220, 186, -1, 112, 187, 222, 186, -1,
112, 187, 224, 186, -1, 216, 184, 194, 80, -1,
216, 184, 194, 81, -1, 216, 184, 194, 82, -1,
220, 184, 195, 83, -1, 220, 184, 195, 84, -1,
220, 184, 195, 85, -1, 220, 184, 195, 86, -1,
220, 184, 195, 87, -1, 220, 184, 195, 88, -1,
220, 184, 195, 89, -1, 220, 184, 195, 90, -1,
220, 184, 195, 91, -1, 222, 184, 195, 83, -1,
222, 184, 195, 84, -1, 222, 184, 195, 85, -1,
222, 184, 195, 87, -1, 222, 184, 195, 88, -1,
222, 184, 195, 91, -1, 224, 184, 195, 92, -1,
226, 164, 218, 165, 218, -1, 219, 192, -1, 11,
-1, 116, 187, 218, 185, 218, 186, -1, 117, 187,
218, 185, 218, 186, -1, 18, 187, 196, -1, 220,
175, 220, -1, 218, 177, 220, -1, 220, 177, 218,
-1, 216, 177, 216, -1, 220, 179, 220, -1, 222,
179, 220, -1, 220, 179, 222, -1, 224, 179, 220,
-1, 220, 179, 224, -1, 220, 178, 218, -1, 220,
174, 220, -1, 174, 220, -1, 187, 220, 186, -1,
152, 187, 220, 186, -1, 160, 187, 220, 186, -1,
160, 187, 222, 186, -1, 155, 187, 220, 186, -1,
154, 187, 220, 186, -1, 150, 187, 220, 186, -1,
158, 187, 220, 186, -1, 220, 184, 195, 147, 187,
186, -1, 226, 164, 220, 165, 220, -1, 221, 192,
-1, 14, -1, 116, 187, 220, 185, 220, 186, -1,
117, 187, 220, 185, 220, 186, -1, 22, 187, 196,
-1, 222, 175, 222, -1, 218, 177, 222, -1, 222,
177, 218, -1, 222, 179, 222, -1, 224, 179, 222,
-1, 222, 179, 224, -1, 222, 178, 218, -1, 222,
174, 222, -1, 174, 222, -1, 187, 222, 186, -1,
151, 187, 222, 186, -1, 151, 187, 220, 186, -1,
157, 187, 222, 186, -1, 157, 187, 220, 186, -1,
155, 187, 222, 186, -1, 154, 187, 222, 186, -1,
150, 187, 222, 186, -1, 158, 187, 222, 186, -1,
122, 187, 216, 186, -1, 222, 184, 195, 147, 187,
186, -1, 226, 164, 222, 165, 222, -1, 223, 192,
-1, 15, -1, 116, 187, 222, 185, 222, 186, -1,
117, 187, 222, 185, 222, 186, -1, 24, 187, 196,
-1, 224, 175, 224, -1, 218, 177, 224, -1, 224,
177, 218, -1, 224, 179, 224, -1, 224, 178, 218,
-1, 224, 174, 224, -1, 174, 224, -1, 187, 224,
186, -1, 156, 187, 220, 186, -1, 156, 187, 222,
186, -1, 156, 187, 224, 186, -1, 224, 184, 195,
147, 187, 186, -1, 226, 164, 224, 165, 224, -1,
225, 192, -1, 16, -1, 116, 187, 224, 185, 224,
186, -1, 117, 187, 224, 185, 224, 186, -1, 26,
187, 196, -1, 218, 170, 218, -1, 218, 171, 218,
-1, 218, 173, 218, -1, 218, 172, 218, -1, 218,
169, 218, -1, 218, 168, 218, -1, 187, 226, 186,
-1, 226, 167, 226, -1, 226, 166, 226, -1, 188,
226, -1, 227, 192, -1, 13, -1, 28, 187, 196,
-1
};
/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
YYRHS. */
const unsigned short int
SubsetValueExpressionParser::yyprhs_[] =
{
0, 0, 3, 5, 8, 12, 16, 20, 24, 28,
32, 36, 40, 44, 48, 52, 56, 60, 64, 68,
72, 76, 80, 84, 88, 92, 96, 100, 104, 107,
110, 112, 115, 117, 119, 121, 123, 125, 127, 129,
131, 133, 135, 137, 139, 140, 141, 142, 144, 146,
150, 154, 158, 162, 166, 170, 174, 178, 182, 186,
190, 194, 197, 200, 203, 207, 212, 217, 222, 227,
232, 237, 242, 248, 252, 256, 260, 263, 265, 270,
277, 284, 288, 290, 293, 298, 303, 308, 313, 318,
323, 328, 333, 338, 343, 348, 353, 358, 363, 368,
373, 378, 383, 385, 387, 391, 395, 399, 403, 407,
414, 419, 424, 428, 432, 436, 440, 444, 448, 452,
456, 460, 464, 467, 471, 476, 481, 486, 491, 496,
501, 506, 511, 516, 521, 526, 531, 536, 541, 546,
551, 556, 561, 566, 571, 576, 581, 586, 591, 596,
601, 606, 611, 616, 621, 626, 631, 636, 641, 646,
651, 656, 661, 666, 671, 676, 681, 686, 691, 696,
701, 706, 711, 716, 721, 726, 731, 736, 741, 746,
751, 756, 761, 766, 771, 777, 779, 783, 787, 791,
795, 799, 804, 808, 813, 817, 822, 826, 831, 835,
839, 843, 847, 850, 852, 857, 859, 864, 871, 878,
882, 884, 888, 892, 896, 900, 904, 908, 912, 916,
920, 924, 928, 932, 936, 940, 944, 948, 952, 956,
960, 963, 967, 972, 977, 982, 987, 992, 997, 1002,
1009, 1015, 1018, 1020, 1025, 1032, 1039, 1043, 1045, 1049,
1053, 1057, 1061, 1065, 1069, 1073, 1077, 1081, 1085, 1089,
1093, 1096, 1100, 1105, 1110, 1115, 1120, 1125, 1130, 1135,
1140, 1145, 1152, 1158, 1161, 1163, 1168, 1175, 1182, 1186,
1188, 1190, 1194, 1198, 1202, 1206, 1210, 1214, 1217, 1221,
1226, 1231, 1236, 1241, 1248, 1254, 1257, 1259, 1264, 1271,
1278, 1282, 1284, 1286, 1290, 1294, 1298, 1302, 1306, 1310,
1314, 1318, 1322, 1325, 1328, 1330, 1334, 1343, 1364, 1379,
1384, 1388, 1392, 1396, 1400, 1404, 1408, 1412, 1416, 1420,
1424, 1428, 1432, 1435, 1438, 1441, 1446, 1451, 1456, 1461,
1466, 1471, 1476, 1480, 1486, 1489, 1491, 1498, 1505, 1509,
1513, 1517, 1521, 1525, 1529, 1536, 1543, 1548, 1553, 1557,
1561, 1565, 1569, 1573, 1577, 1581, 1585, 1589, 1593, 1596,
1600, 1605, 1610, 1615, 1620, 1625, 1630, 1635, 1640, 1645,
1650, 1655, 1660, 1665, 1670, 1675, 1680, 1685, 1690, 1695,
1700, 1705, 1710, 1715, 1720, 1725, 1730, 1735, 1740, 1745,
1750, 1755, 1760, 1765, 1770, 1775, 1780, 1785, 1790, 1795,
1800, 1805, 1810, 1815, 1820, 1825, 1830, 1835, 1840, 1845,
1850, 1855, 1860, 1865, 1870, 1876, 1879, 1881, 1888, 1895,
1899, 1903, 1907, 1911, 1915, 1919, 1923, 1927, 1931, 1935,
1939, 1943, 1946, 1950, 1955, 1960, 1965, 1970, 1975, 1980,
1985, 1992, 1998, 2001, 2003, 2010, 2017, 2021, 2025, 2029,
2033, 2037, 2041, 2045, 2049, 2053, 2056, 2060, 2065, 2070,
2075, 2080, 2085, 2090, 2095, 2100, 2105, 2112, 2118, 2121,
2123, 2130, 2137, 2141, 2145, 2149, 2153, 2157, 2161, 2165,
2168, 2172, 2177, 2182, 2187, 2194, 2200, 2203, 2205, 2212,
2219, 2223, 2227, 2231, 2235, 2239, 2243, 2247, 2251, 2255,
2259, 2262, 2265, 2267
};
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
const unsigned short int
SubsetValueExpressionParser::yyrline_[] =
{
0, 374, 374, 378, 379, 385, 391, 397, 403, 409,
415, 421, 427, 433, 439, 445, 451, 457, 463, 469,
475, 481, 487, 493, 499, 505, 511, 517, 523, 528,
535, 536, 538, 539, 540, 541, 542, 543, 544, 545,
546, 547, 550, 553, 558, 561, 564, 567, 568, 572,
577, 582, 587, 592, 597, 602, 607, 612, 617, 622,
627, 632, 636, 640, 644, 645, 649, 653, 661, 669,
677, 686, 695, 700, 703, 706, 713, 714, 718, 722,
726, 732, 744, 745, 748, 752, 756, 760, 764, 768,
772, 776, 782, 791, 800, 809, 818, 829, 840, 844,
848, 852, 858, 859, 860, 865, 870, 875, 880, 890,
895, 899, 903, 908, 913, 918, 923, 928, 933, 938,
943, 948, 953, 957, 958, 962, 966, 970, 974, 978,
982, 986, 990, 994, 998, 1002, 1006, 1010, 1014, 1018,
1022, 1026, 1030, 1034, 1038, 1042, 1046, 1050, 1054, 1058,
1062, 1066, 1070, 1074, 1078, 1082, 1086, 1090, 1094, 1098,
1102, 1106, 1110, 1114, 1118, 1122, 1126, 1130, 1134, 1138,
1142, 1146, 1150, 1154, 1158, 1162, 1166, 1170, 1174, 1178,
1182, 1186, 1190, 1194, 1198, 1203, 1212, 1215, 1220, 1223,
1224, 1225, 1228, 1231, 1234, 1237, 1240, 1243, 1246, 1249,
1256, 1259, 1262, 1263, 1267, 1271, 1275, 1279, 1283, 1289,
1301, 1302, 1307, 1312, 1317, 1322, 1327, 1332, 1337, 1342,
1347, 1352, 1357, 1362, 1367, 1372, 1377, 1382, 1387, 1392,
1397, 1401, 1402, 1406, 1410, 1414, 1418, 1422, 1426, 1430,
1434, 1443, 1444, 1448, 1452, 1456, 1462, 1475, 1476, 1481,
1486, 1491, 1496, 1501, 1512, 1517, 1522, 1527, 1532, 1537,
1542, 1546, 1547, 1551, 1555, 1559, 1563, 1567, 1571, 1575,
1579, 1583, 1586, 1595, 1596, 1600, 1604, 1608, 1614, 1627,
1628, 1631, 1636, 1641, 1646, 1651, 1656, 1661, 1665, 1666,
1670, 1674, 1678, 1682, 1685, 1694, 1695, 1699, 1703, 1707,
1713, 1726, 1727, 1728, 1733, 1738, 1743, 1752, 1757, 1766,
1767, 1776, 1785, 1789, 1790, 1796, 1809, 1815, 1825, 1834,
1839, 1844, 1849, 1854, 1859, 1864, 1869, 1874, 1879, 1884,
1889, 1894, 1899, 1903, 1907, 1911, 1915, 1919, 1927, 1935,
1943, 1952, 1961, 1962, 1972, 1973, 1977, 1981, 1987, 2000,
2005, 2010, 2015, 2020, 2025, 2029, 2034, 2038, 2042, 2047,
2052, 2057, 2062, 2067, 2072, 2077, 2082, 2087, 2092, 2096,
2097, 2101, 2105, 2109, 2113, 2117, 2121, 2125, 2129, 2133,
2137, 2141, 2145, 2149, 2153, 2157, 2161, 2165, 2169, 2173,
2177, 2181, 2185, 2189, 2193, 2197, 2201, 2205, 2209, 2213,
2217, 2221, 2225, 2229, 2233, 2237, 2241, 2245, 2249, 2253,
2257, 2261, 2265, 2269, 2273, 2277, 2281, 2285, 2289, 2293,
2297, 2301, 2305, 2309, 2313, 2322, 2323, 2327, 2331, 2337,
2350, 2355, 2360, 2365, 2370, 2375, 2380, 2385, 2390, 2395,
2400, 2405, 2409, 2410, 2414, 2418, 2422, 2426, 2430, 2434,
2438, 2442, 2451, 2452, 2456, 2460, 2466, 2479, 2484, 2489,
2494, 2505, 2510, 2515, 2520, 2525, 2529, 2530, 2534, 2538,
2542, 2546, 2550, 2554, 2558, 2562, 2566, 2569, 2578, 2579,
2583, 2587, 2593, 2605, 2610, 2615, 2620, 2625, 2630, 2635,
2639, 2640, 2644, 2648, 2652, 2655, 2664, 2665, 2669, 2673,
2679, 2691, 2696, 2701, 2710, 2719, 2724, 2733, 2734, 2743,
2752, 2756, 2757, 2763
};
// Print the state stack on the debug stream.
void
SubsetValueExpressionParser::yystack_print_ ()
{
*yycdebug_ << "Stack now";
for (state_stack_type::const_iterator i = yystate_stack_.begin ();
i != yystate_stack_.end (); ++i)
*yycdebug_ << ' ' << *i;
*yycdebug_ << std::endl;
}
// Report on the debug stream that the rule \a yyrule is going to be reduced.
void
SubsetValueExpressionParser::yy_reduce_print_ (int yyrule)
{
unsigned int yylno = yyrline_[yyrule];
int yynrhs = yyr2_[yyrule];
/* Print the symbols being reduced, and their result. */
*yycdebug_ << "Reducing stack by rule " << yyrule - 1
<< " (line " << yylno << "):" << std::endl;
/* The symbols being reduced. */
for (int yyi = 0; yyi < yynrhs; yyi++)
YY_SYMBOL_PRINT (" $" << yyi + 1 << " =",
yyrhs_[yyprhs_[yyrule] + yyi],
&(yysemantic_stack_[(yynrhs) - (yyi + 1)]),
&(yylocation_stack_[(yynrhs) - (yyi + 1)]));
}
#endif // YYDEBUG
/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
SubsetValueExpressionParser::token_number_type
SubsetValueExpressionParser::yytranslate_ (int t)
{
static
const token_number_type
translate_table[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 188, 2, 2, 2, 176, 179, 2,
187, 186, 177, 175, 185, 174, 184, 178, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 165, 2,
170, 2, 171, 164, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 180, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 121, 122, 123, 124,
125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
135, 136, 137, 138, 139, 140, 141, 142, 143, 144,
145, 146, 147, 148, 149, 150, 151, 152, 153, 154,
155, 156, 157, 158, 159, 160, 161, 162, 163, 166,
167, 168, 169, 172, 173, 181, 182, 183
};
if ((unsigned int) t <= yyuser_token_number_max_)
return translate_table[t];
else
return yyundef_token_;
}
const int SubsetValueExpressionParser::yyeof_ = 0;
const int SubsetValueExpressionParser::yylast_ = 5622;
const int SubsetValueExpressionParser::yynnts_ = 39;
const int SubsetValueExpressionParser::yyempty_ = -2;
const int SubsetValueExpressionParser::yyfinal_ = 297;
const int SubsetValueExpressionParser::yyterror_ = 1;
const int SubsetValueExpressionParser::yyerrcode_ = 256;
const int SubsetValueExpressionParser::yyntokens_ = 189;
const unsigned int SubsetValueExpressionParser::yyuser_token_number_max_ = 427;
const SubsetValueExpressionParser::token_number_type SubsetValueExpressionParser::yyundef_token_ = 2;
} // parserSubset
/* Line 1136 of lalr1.cc */
#line 9695 "SubsetValueExpressionParser.tab.cc"
/* Line 1138 of lalr1.cc */
#line 2776 "../SubsetValueExpressionParser.yy"
void parserSubset::SubsetValueExpressionParser::error (
const parserSubset::SubsetValueExpressionParser::location_type& l,
const std::string& m
)
{
driver.error (l, m);
}
| 39.998763 | 295 | 0.490078 | [
"object",
"vector"
] |
3f04c75a9221f95b6fd7331fd814c49988bcd8bf | 2,262 | cpp | C++ | demo/Main.cpp | Godlike/Pegasus | 4cf48b39c6899974c4ff164305be7830726ca8d6 | [
"MIT"
] | 11 | 2017-06-18T20:57:06.000Z | 2019-10-21T22:46:04.000Z | demo/Main.cpp | Godlike/Pegasus | 4cf48b39c6899974c4ff164305be7830726ca8d6 | [
"MIT"
] | 107 | 2017-04-24T18:25:17.000Z | 2018-12-21T21:46:34.000Z | demo/Main.cpp | Godlike/Pegasus | 4cf48b39c6899974c4ff164305be7830726ca8d6 | [
"MIT"
] | 3 | 2017-05-15T08:20:33.000Z | 2020-05-19T17:42:04.000Z | /*
* Copyright (C) 2017-2018 by Godlike
* This code is licensed under the MIT license (MIT)
* (http://opensource.org/licenses/MIT)
*/
#include "demo/Demo.hpp"
std::list<pegasus::Demo::Primitive*> g_objects;
void KeyButtonCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action == GLFW_PRESS)
return;
pegasus::Demo& demo = pegasus::Demo::GetInstance();
switch (key)
{
case GLFW_KEY_M:
for (uint8_t index = 0; index < 100; ++index)
{
pegasus::mechanics::Body body;
body.linearMotion.position = glm::dvec3(std::rand() % 300 / 10.f, std::rand() % 300 / 10.f, std::rand() % 300 / 10.f);
body.linearMotion.velocity = glm::dvec3(std::rand() % 10 / 10.f, std::rand() % 10 / 10.f, std::rand() % 10 / 10.f);
static uint8_t isBox = false;
isBox = !isBox;
if (isBox)
{
glm::vec3 const k = { 0,0,rand() % 10 / 10.f + 0.1f };
glm::vec3 const j = { 0,rand() % 10 / 10.f + 0.1f,0 };
glm::vec3 const i = { rand() % 10 / 10.f + 0.1f,0,0 };
g_objects.push_back(&demo.MakeBox(
body, i, j, k, pegasus::scene::Primitive::Type::DYNAMIC
));
}
else
{
float const radius = rand() % 10 / 10.f + 0.1f;
g_objects.push_back(&demo.MakeSphere(
body, radius, pegasus::scene::Primitive::Type::DYNAMIC
));
}
}
break;
case GLFW_KEY_R:
while (!g_objects.empty())
{
demo.Remove(*g_objects.back());
g_objects.pop_back();
}
break;
default:
break;
}
}
int main(int argc, char** argv)
{
pegasus::Demo& demo = pegasus::Demo::GetInstance();
pegasus::render::Input& input = pegasus::render::Input::GetInstance();
input.AddKeyButtonCallback(KeyButtonCallback);
//Ground
pegasus::mechanics::Body plane;
plane.linearMotion.position = glm::dvec3(0, -5, 0);
demo.MakePlane(plane, glm::vec3(0, 1, 0), pegasus::scene::Primitive::Type::STATIC);
while (demo.IsValid())
{
demo.RunFrame();
}
}
| 30.16 | 130 | 0.526525 | [
"render"
] |
3f1214880b1902d22be16128f7366af9371bc56f | 825 | cpp | C++ | leetcode/0167_Two_Sum_2_Input_array_is_sorted/result.cpp | theck17/notes | f32f0f4b8f821b1ed38d173ef0913efddd094b91 | [
"MIT"
] | null | null | null | leetcode/0167_Two_Sum_2_Input_array_is_sorted/result.cpp | theck17/notes | f32f0f4b8f821b1ed38d173ef0913efddd094b91 | [
"MIT"
] | null | null | null | leetcode/0167_Two_Sum_2_Input_array_is_sorted/result.cpp | theck17/notes | f32f0f4b8f821b1ed38d173ef0913efddd094b91 | [
"MIT"
] | null | null | null | /**
* Copyright (C) 2021 All rights reserved.
*
* FileName :result.cpp
* Author :C.K
* Email :theck17@163.com
* DateTime :2021-02-10 20:47:38
* Description :
*/
#include <algorithm> //STL 通用算法
#include <cctype> //字符处理
#include <vector> //STL 动态数组容器
#include <ctime> //定义关于时间的函数
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int l = 0, r = numbers.size() - 1;
while (l < r) {
int sum = numbers[l] + numbers[r];
if (sum > target)
r--;
else if (sum < target)
l++;
else
return { l + 1, r + 1 };
}
return {};
}
};
int main(){
return 0;
}
| 20.625 | 58 | 0.454545 | [
"vector"
] |
3f1a21b4e6928f3549e04fd562fb753af640e0a0 | 5,383 | cc | C++ | src/callow/solver/SlepcSolver.cc | baklanovp/libdetran | 820efab9d03ae425ccefb9520bdb6c086fdbf939 | [
"MIT"
] | 4 | 2015-03-07T16:20:23.000Z | 2020-02-10T13:40:16.000Z | src/callow/solver/SlepcSolver.cc | baklanovp/libdetran | 820efab9d03ae425ccefb9520bdb6c086fdbf939 | [
"MIT"
] | 3 | 2018-02-27T21:24:22.000Z | 2020-12-16T00:56:44.000Z | src/callow/solver/SlepcSolver.cc | baklanovp/libdetran | 820efab9d03ae425ccefb9520bdb6c086fdbf939 | [
"MIT"
] | 9 | 2015-03-07T16:20:26.000Z | 2022-01-29T00:14:23.000Z | //----------------------------------*-C++-*-----------------------------------//
/**
* @file SlepcSolver.cc
* @brief SlepcSolver member definitions
* @note Copyright (C) 2012-2013 Jeremy Roberts
*/
//----------------------------------------------------------------------------//
#include "callow/callow_config.hh"
#include "SlepcSolver.hh"
namespace callow
{
#ifdef CALLOW_ENABLE_SLEPC
//----------------------------------------------------------------------------//
SlepcSolver::SlepcSolver(const std::string &eps_type,
const double tol,
const int maxit,
const int number_values)
: EigenSolver(tol, maxit, "solver_slepc")
, d_eps_type(eps_type)
{
PetscErrorCode ierr;
// Create the context.
ierr = EPSCreate(PETSC_COMM_SELF, &d_slepc_solver);
Insist(!ierr, "Error creating EPS context.");
// Set the solver type and get just the largest eigenvalue.
ierr = EPSSetWhichEigenpairs(d_slepc_solver, EPS_LARGEST_MAGNITUDE);
Insist(!ierr, "Error selecting EPS eigenpairs.");
// Set the tolerances
ierr = EPSSetTolerances(d_slepc_solver, d_tolerance, d_maximum_iterations);
Insist(!ierr, "Error setting EPS tolerances.");
}
//----------------------------------------------------------------------------//
SlepcSolver::~SlepcSolver()
{
EPSDestroy(&d_slepc_solver);
}
//----------------------------------------------------------------------------//
void SlepcSolver::solve_impl(Vector &x, Vector &x0)
{
double lambda;
double lambda_imag;
// Solve the eigenproblem
PetscErrorCode ierr = EPSSolve(d_slepc_solver);
Insist(!ierr, "Error solving eigenvalue problem.");
// Extract the number of iterations
ierr = EPSGetIterationNumber(d_slepc_solver, &d_number_iterations);
Insist(!ierr, "Error getting iteration count.");
// Get the dominant mode.
ierr = EPSGetEigenpair(d_slepc_solver, 0, &lambda, &lambda_imag,
x.petsc_vector(), x0.petsc_vector());
Insist(!ierr, "Error getting eigenpair.");
// Scale the result by its sum. This points it in the positive
// direction and gives the L1 normalization we're using in PI.
PetscScalar sign = 1;
if (x[0] < 0) sign = -1;
x.scale(sign / x.norm(L1));
// Store the eigenvalue
d_lambda = lambda;
}
//----------------------------------------------------------------------------//
void SlepcSolver::set_operators(SP_matrix A,
SP_matrix B,
SP_db db)
{
Insist(A, "First operator cannot be null");
// Store the operators
d_A = A;
if (B) d_B = B;
// Set the operators.
PetscErrorCode ierr;
if (!B)
{
// standard Ax=Lx, nonhermitian evp
ierr = EPSSetProblemType(d_slepc_solver, EPS_NHEP);
Insist(!ierr, "Error setting EPS problem type.");
ierr = EPSSetOperators(d_slepc_solver, d_A->petsc_matrix(), PETSC_NULL);
Insist(!ierr, "Error setting EPS operator.");
}
else
{
// generalized Ax=LBx, nonhermitian evp
ierr = EPSSetProblemType(d_slepc_solver, EPS_GNHEP);
Insist(!ierr, "Error setting EPS problem type.");
ierr = EPSSetOperators(d_slepc_solver,
d_A->petsc_matrix(), d_B->petsc_matrix());
Insist(!ierr, "Error setting EPS operator.");
}
// Set the solver type
set_eps_type(d_eps_type);
// Then allow for user choice.
ierr = EPSSetFromOptions(d_slepc_solver);
Insist(!ierr, "Error setting EPS from options.");
}
//----------------------------------------------------------------------------//
void SlepcSolver::set_preconditioner(SP_preconditioner P,
const int side)
{
Require(P);
d_P = P;
ST st;
PetscErrorCode ierr;
ierr = EPSGetST(d_slepc_solver, &st);
//ierr = STSetType(st, STPRECOND);
d_P->set_slepc_st(st);
Ensure(!ierr);
}
//----------------------------------------------------------------------------//
void SlepcSolver::set_preconditioner_matrix(SP_matrix P,
const int side)
{
Require(P);
ST st;
PetscErrorCode ierr = EPSGetST(d_slepc_solver, &st);
// set the user-given matrix as the preconditioning matrix
ierr = STPrecondSetMatForPC(st, P->petsc_matrix());
Ensure(!ierr);
}
//----------------------------------------------------------------------------//
void SlepcSolver::set_eps_type(const std::string &eps_type)
{
d_eps_type = eps_type;
// Set the solver type
PetscErrorCode ierr = EPSSetType(d_slepc_solver, d_eps_type.c_str());
Insist(!ierr, "Error creating EPS of type " + d_eps_type);
}
#else
SlepcSolver::SlepcSolver(const std::string&,const double,const int,const int)
: d_eps_type(""), d_slepc_solver(NULL) {}
SlepcSolver::~SlepcSolver(){}
void SlepcSolver::solve_impl(Vector &, Vector &){}
void SlepcSolver::set_operators(SP_matrix, SP_matrix, SP_db){}
void SlepcSolver::set_preconditioner(SP_preconditioner,const int){}
void SlepcSolver::set_preconditioner_matrix(SP_matrix, const int){}
void SlepcSolver::set_eps_type(const std::string &){}
#endif // CALLOW_ENABLE_SLEPC
} // end namespace callow
//----------------------------------------------------------------------------//
// end of file SlepcSolver.cc
//----------------------------------------------------------------------------//
| 32.233533 | 80 | 0.55731 | [
"vector"
] |
3f1badeda1f7e5ccb34e0231ba0ab0df3b16d455 | 24,184 | cpp | C++ | qtbase/tests/auto/widgets/widgets/qtabbar/tst_qtabbar.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtbase/tests/auto/widgets/widgets/qtabbar/tst_qtabbar.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtbase/tests/auto/widgets/widgets/qtabbar/tst_qtabbar.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qapplication.h>
#include <qtabbar.h>
#include <qpushbutton.h>
#include <qstyle.h>
class tst_QTabBar : public QObject
{
Q_OBJECT
public:
tst_QTabBar();
virtual ~tst_QTabBar();
public slots:
void initTestCase();
void cleanupTestCase();
void init();
private slots:
void getSetCheck();
void setIconSize();
void setIconSize_data();
void testCurrentChanged_data();
void testCurrentChanged();
void insertAtCurrentIndex();
void removeTab_data();
void removeTab();
void setElideMode_data();
void setElideMode();
void sizeHints();
void setUsesScrollButtons_data();
void setUsesScrollButtons();
void removeLastTab();
void closeButton();
void tabButton_data();
void tabButton();
void selectionBehaviorOnRemove_data();
void selectionBehaviorOnRemove();
void moveTab_data();
void moveTab();
void task251184_removeTab();
void changeTitleWhileDoubleClickingTab();
void taskQTBUG_10052_widgetLayoutWhenMoving();
void tabBarClicked();
void autoHide();
};
// Testing get/set functions
void tst_QTabBar::getSetCheck()
{
QTabBar obj1;
obj1.addTab("Tab1");
obj1.addTab("Tab2");
obj1.addTab("Tab3");
obj1.addTab("Tab4");
obj1.addTab("Tab5");
// Shape QTabBar::shape()
// void QTabBar::setShape(Shape)
obj1.setShape(QTabBar::Shape(QTabBar::RoundedNorth));
QCOMPARE(QTabBar::Shape(QTabBar::RoundedNorth), obj1.shape());
obj1.setShape(QTabBar::Shape(QTabBar::RoundedSouth));
QCOMPARE(QTabBar::Shape(QTabBar::RoundedSouth), obj1.shape());
obj1.setShape(QTabBar::Shape(QTabBar::RoundedWest));
QCOMPARE(QTabBar::Shape(QTabBar::RoundedWest), obj1.shape());
obj1.setShape(QTabBar::Shape(QTabBar::RoundedEast));
QCOMPARE(QTabBar::Shape(QTabBar::RoundedEast), obj1.shape());
obj1.setShape(QTabBar::Shape(QTabBar::TriangularNorth));
QCOMPARE(QTabBar::Shape(QTabBar::TriangularNorth), obj1.shape());
obj1.setShape(QTabBar::Shape(QTabBar::TriangularSouth));
QCOMPARE(QTabBar::Shape(QTabBar::TriangularSouth), obj1.shape());
obj1.setShape(QTabBar::Shape(QTabBar::TriangularWest));
QCOMPARE(QTabBar::Shape(QTabBar::TriangularWest), obj1.shape());
obj1.setShape(QTabBar::Shape(QTabBar::TriangularEast));
QCOMPARE(QTabBar::Shape(QTabBar::TriangularEast), obj1.shape());
// bool QTabBar::drawBase()
// void QTabBar::setDrawBase(bool)
obj1.setDrawBase(false);
QCOMPARE(false, obj1.drawBase());
obj1.setDrawBase(true);
QCOMPARE(true, obj1.drawBase());
// int QTabBar::currentIndex()
// void QTabBar::setCurrentIndex(int)
obj1.setCurrentIndex(0);
QCOMPARE(0, obj1.currentIndex());
obj1.setCurrentIndex(INT_MIN);
QCOMPARE(0, obj1.currentIndex());
obj1.setCurrentIndex(INT_MAX);
QCOMPARE(0, obj1.currentIndex());
obj1.setCurrentIndex(4);
QCOMPARE(4, obj1.currentIndex());
}
tst_QTabBar::tst_QTabBar()
{
}
tst_QTabBar::~tst_QTabBar()
{
}
void tst_QTabBar::initTestCase()
{
}
void tst_QTabBar::cleanupTestCase()
{
}
void tst_QTabBar::init()
{
}
void tst_QTabBar::setIconSize_data()
{
QTest::addColumn<int>("sizeToSet");
QTest::addColumn<int>("expectedWidth");
const int iconDefault = qApp->style()->pixelMetric(QStyle::PM_TabBarIconSize);
const int smallIconSize = qApp->style()->pixelMetric(QStyle::PM_SmallIconSize);
const int largeIconSize = qApp->style()->pixelMetric(QStyle::PM_LargeIconSize);
QTest::newRow("default") << -1 << iconDefault;
QTest::newRow("zero") << 0 << 0;
QTest::newRow("same as default") << iconDefault << iconDefault;
QTest::newRow("large") << largeIconSize << largeIconSize;
QTest::newRow("small") << smallIconSize << smallIconSize;
}
void tst_QTabBar::setIconSize()
{
QFETCH(int, sizeToSet);
QFETCH(int, expectedWidth);
QTabBar tabBar;
tabBar.setIconSize(QSize(sizeToSet, sizeToSet));
QCOMPARE(tabBar.iconSize().width(), expectedWidth);
}
void tst_QTabBar::testCurrentChanged_data()
{
QTest::addColumn<int>("tabToSet");
QTest::addColumn<int>("expectedCount");
QTest::newRow("pressAntotherTab") << 1 << 2;
QTest::newRow("pressTheSameTab") << 0 << 1;
}
void tst_QTabBar::testCurrentChanged()
{
QFETCH(int, tabToSet);
QFETCH(int, expectedCount);
QTabBar tabBar;
QSignalSpy spy(&tabBar, SIGNAL(currentChanged(int)));
tabBar.addTab("Tab1");
tabBar.addTab("Tab2");
QCOMPARE(tabBar.currentIndex(), 0);
tabBar.setCurrentIndex(tabToSet);
QCOMPARE(tabBar.currentIndex(), tabToSet);
QCOMPARE(spy.count(), expectedCount);
}
void tst_QTabBar::insertAtCurrentIndex()
{
QTabBar tabBar;
tabBar.addTab("Tab1");
QCOMPARE(tabBar.currentIndex(), 0);
tabBar.insertTab(0, "Tab2");
QCOMPARE(tabBar.currentIndex(), 1);
tabBar.insertTab(0, "Tab3");
QCOMPARE(tabBar.currentIndex(), 2);
tabBar.insertTab(2, "Tab4");
QCOMPARE(tabBar.currentIndex(), 3);
}
void tst_QTabBar::removeTab_data()
{
QTest::addColumn<int>("currentIndex");
QTest::addColumn<int>("deleteIndex");
QTest::addColumn<int>("spyCount");
QTest::addColumn<int>("finalIndex");
QTest::newRow("deleteEnd") << 0 << 2 << 0 << 0;
QTest::newRow("deleteEndWithIndexOnEnd") << 2 << 2 << 1 << 1;
QTest::newRow("deleteMiddle") << 2 << 1 << 1 << 1;
QTest::newRow("deleteMiddleOnMiddle") << 1 << 1 << 1 << 1;
}
void tst_QTabBar::removeTab()
{
QTabBar tabbar;
QFETCH(int, currentIndex);
QFETCH(int, deleteIndex);
tabbar.addTab("foo");
tabbar.addTab("bar");
tabbar.addTab("baz");
tabbar.setCurrentIndex(currentIndex);
QSignalSpy spy(&tabbar, SIGNAL(currentChanged(int)));
tabbar.removeTab(deleteIndex);
QTEST(spy.count(), "spyCount");
QTEST(tabbar.currentIndex(), "finalIndex");
}
void tst_QTabBar::setElideMode_data()
{
QTest::addColumn<int>("tabElideMode");
QTest::addColumn<int>("expectedMode");
QTest::newRow("default") << -128 << qApp->style()->styleHint(QStyle::SH_TabBar_ElideMode);
QTest::newRow("explicit default") << qApp->style()->styleHint(QStyle::SH_TabBar_ElideMode)
<< qApp->style()->styleHint(QStyle::SH_TabBar_ElideMode);
QTest::newRow("None") << int(Qt::ElideNone) << int(Qt::ElideNone);
QTest::newRow("Left") << int(Qt::ElideLeft) << int(Qt::ElideLeft);
QTest::newRow("Center") << int(Qt::ElideMiddle) << int(Qt::ElideMiddle);
QTest::newRow("Right") << int(Qt::ElideRight) << int(Qt::ElideRight);
}
void tst_QTabBar::setElideMode()
{
QFETCH(int, tabElideMode);
QTabBar tabBar;
if (tabElideMode != -128)
tabBar.setElideMode(Qt::TextElideMode(tabElideMode));
QTEST(int(tabBar.elideMode()), "expectedMode");
// Make sure style sheet does not override user set mode
tabBar.setStyleSheet("QWidget { background-color: #ABA8A6;}");
QTEST(int(tabBar.elideMode()), "expectedMode");
}
void tst_QTabBar::sizeHints()
{
QTabBar tabBar;
tabBar.setFont(QFont("Arial", 10));
// No eliding and no scrolling -> tabbar becomes very wide
tabBar.setUsesScrollButtons(false);
tabBar.setElideMode(Qt::ElideNone);
tabBar.addTab("tab 01");
// Fetch the minimum size hint width and make sure that we create enough
// tabs.
int minimumSizeHintWidth = tabBar.minimumSizeHint().width();
for (int i = 0; i <= 700 / minimumSizeHintWidth; ++i)
tabBar.addTab(QString("tab 0%1").arg(i+2));
//qDebug() << tabBar.minimumSizeHint() << tabBar.sizeHint();
QVERIFY(tabBar.minimumSizeHint().width() > 700);
QVERIFY(tabBar.sizeHint().width() > 700);
// Scrolling enabled -> no reason to become very wide
tabBar.setUsesScrollButtons(true);
QVERIFY(tabBar.minimumSizeHint().width() < 200);
QVERIFY(tabBar.sizeHint().width() > 700); // unchanged
// Eliding enabled -> no reason to become very wide
tabBar.setUsesScrollButtons(false);
tabBar.setElideMode(Qt::ElideRight);
// The sizeHint is very much dependent on the screen DPI value
// so we can not really predict it.
int tabBarMinSizeHintWidth = tabBar.minimumSizeHint().width();
int tabBarSizeHintWidth = tabBar.sizeHint().width();
QVERIFY(tabBarMinSizeHintWidth < tabBarSizeHintWidth);
QVERIFY(tabBarSizeHintWidth > 700); // unchanged
tabBar.addTab("This is tab with a very long title");
QVERIFY(tabBar.minimumSizeHint().width() > tabBarMinSizeHintWidth);
QVERIFY(tabBar.sizeHint().width() > tabBarSizeHintWidth);
}
void tst_QTabBar::setUsesScrollButtons_data()
{
QTest::addColumn<int>("usesArrows");
QTest::addColumn<bool>("expectedArrows");
QTest::newRow("default") << -128 << !qApp->style()->styleHint(QStyle::SH_TabBar_PreferNoArrows);
QTest::newRow("explicit default")
<< int(!qApp->style()->styleHint(QStyle::SH_TabBar_PreferNoArrows))
<< !qApp->style()->styleHint(QStyle::SH_TabBar_PreferNoArrows);
QTest::newRow("No") << int(false) << false;
QTest::newRow("Yes") << int(true) << true;
}
void tst_QTabBar::setUsesScrollButtons()
{
QFETCH(int, usesArrows);
QTabBar tabBar;
if (usesArrows != -128)
tabBar.setUsesScrollButtons(usesArrows);
QTEST(tabBar.usesScrollButtons(), "expectedArrows");
// Make sure style sheet does not override user set mode
tabBar.setStyleSheet("QWidget { background-color: #ABA8A6;}");
QTEST(tabBar.usesScrollButtons(), "expectedArrows");
}
void tst_QTabBar::removeLastTab()
{
QTabBar tabbar;
QSignalSpy spy(&tabbar, SIGNAL(currentChanged(int)));
int index = tabbar.addTab("foo");
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.at(0).at(0).toInt(), index);
spy.clear();
tabbar.removeTab(index);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.at(0).at(0).toInt(), -1);
spy.clear();
}
void tst_QTabBar::closeButton()
{
QTabBar tabbar;
QCOMPARE(tabbar.tabsClosable(), false);
tabbar.setTabsClosable(true);
QCOMPARE(tabbar.tabsClosable(), true);
tabbar.addTab("foo");
QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition)tabbar.style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, 0, &tabbar);
QTabBar::ButtonPosition otherSide = (closeSide == QTabBar::LeftSide ? QTabBar::RightSide : QTabBar::LeftSide);
QVERIFY(tabbar.tabButton(0, otherSide) == 0);
QVERIFY(tabbar.tabButton(0, closeSide) != 0);
QAbstractButton *button = static_cast<QAbstractButton*>(tabbar.tabButton(0, closeSide));
QVERIFY(button);
QSignalSpy spy(&tabbar, SIGNAL(tabCloseRequested(int)));
button->click();
QCOMPARE(tabbar.count(), 1);
QCOMPARE(spy.count(), 1);
}
Q_DECLARE_METATYPE(QTabBar::ButtonPosition)
void tst_QTabBar::tabButton_data()
{
QTest::addColumn<QTabBar::ButtonPosition>("position");
QTest::newRow("left") << QTabBar::LeftSide;
QTest::newRow("right") << QTabBar::RightSide;
}
// QTabBar::setTabButton(index, closeSide, closeButton);
void tst_QTabBar::tabButton()
{
QFETCH(QTabBar::ButtonPosition, position);
QTabBar::ButtonPosition otherSide = (position == QTabBar::LeftSide ? QTabBar::RightSide : QTabBar::LeftSide);
QTabBar tabbar;
tabbar.resize(500, 200);
tabbar.show();
QTRY_VERIFY(tabbar.isVisible());
tabbar.setTabButton(-1, position, 0);
QVERIFY(tabbar.tabButton(-1, position) == 0);
QVERIFY(tabbar.tabButton(0, position) == 0);
tabbar.addTab("foo");
QCOMPARE(tabbar.count(), 1);
tabbar.setTabButton(0, position, 0);
QVERIFY(tabbar.tabButton(0, position) == 0);
QPushButton *button = new QPushButton;
button->show();
button->setText("hi");
button->resize(10, 10);
QTRY_VERIFY(button->isVisible());
QTRY_VERIFY(button->isVisible());
tabbar.setTabButton(0, position, button);
QCOMPARE(tabbar.tabButton(0, position), static_cast<QWidget *>(button));
QTRY_VERIFY(!button->isHidden());
QVERIFY(tabbar.tabButton(0, otherSide) == 0);
QCOMPARE(button->parent(), static_cast<QObject *>(&tabbar));
QVERIFY(button->pos() != QPoint(0, 0));
QPushButton *button2 = new QPushButton;
tabbar.setTabButton(0, position, button2);
QVERIFY(button->isHidden());
}
typedef QList<int> IntList;
Q_DECLARE_METATYPE(QTabBar::SelectionBehavior)
#define ONE(x) (IntList() << x)
void tst_QTabBar::selectionBehaviorOnRemove_data()
{
QTest::addColumn<QTabBar::SelectionBehavior>("selectionBehavior");
QTest::addColumn<int>("tabs");
QTest::addColumn<IntList>("select");
QTest::addColumn<IntList>("remove");
QTest::addColumn<int>("expected");
// Count select remove current
QTest::newRow("left-1") << QTabBar::SelectLeftTab << 3 << (IntList() << 0) << ONE(0) << 0;
QTest::newRow("left-2") << QTabBar::SelectLeftTab << 3 << (IntList() << 0) << ONE(1) << 0; // not removing current
QTest::newRow("left-3") << QTabBar::SelectLeftTab << 3 << (IntList() << 0) << ONE(2) << 0; // not removing current
QTest::newRow("left-4") << QTabBar::SelectLeftTab << 3 << (IntList() << 1) << ONE(0) << 0; // not removing current
QTest::newRow("left-5") << QTabBar::SelectLeftTab << 3 << (IntList() << 1) << ONE(1) << 0;
QTest::newRow("left-6") << QTabBar::SelectLeftTab << 3 << (IntList() << 1) << ONE(2) << 1;
QTest::newRow("left-7") << QTabBar::SelectLeftTab << 3 << (IntList() << 2) << ONE(0) << 1; // not removing current
QTest::newRow("left-8") << QTabBar::SelectLeftTab << 3 << (IntList() << 2) << ONE(1) << 1; // not removing current
QTest::newRow("left-9") << QTabBar::SelectLeftTab << 3 << (IntList() << 2) << ONE(2) << 1;
QTest::newRow("right-1") << QTabBar::SelectRightTab << 3 << (IntList() << 0) << ONE(0) << 0;
QTest::newRow("right-2") << QTabBar::SelectRightTab << 3 << (IntList() << 0) << ONE(1) << 0; // not removing current
QTest::newRow("right-3") << QTabBar::SelectRightTab << 3 << (IntList() << 0) << ONE(2) << 0; // not removing current
QTest::newRow("right-4") << QTabBar::SelectRightTab << 3 << (IntList() << 1) << ONE(0) << 0; // not removing current
QTest::newRow("right-5") << QTabBar::SelectRightTab << 3 << (IntList() << 1) << ONE(1) << 1;
QTest::newRow("right-6") << QTabBar::SelectRightTab << 3 << (IntList() << 1) << ONE(2) << 1; // not removing current
QTest::newRow("right-7") << QTabBar::SelectRightTab << 3 << (IntList() << 2) << ONE(0) << 1; // not removing current
QTest::newRow("right-8") << QTabBar::SelectRightTab << 3 << (IntList() << 2) << ONE(1) << 1; // not removing current
QTest::newRow("right-9") << QTabBar::SelectRightTab << 3 << (IntList() << 2) << ONE(2) << 1;
QTest::newRow("previous-0") << QTabBar::SelectPreviousTab << 3 << (IntList()) << ONE(0) << 0;
QTest::newRow("previous-1") << QTabBar::SelectPreviousTab << 3 << (IntList()) << ONE(1) << 0; // not removing current
QTest::newRow("previous-2") << QTabBar::SelectPreviousTab << 3 << (IntList()) << ONE(2) << 0; // not removing current
QTest::newRow("previous-3") << QTabBar::SelectPreviousTab << 3 << (IntList() << 2) << ONE(0) << 1; // not removing current
QTest::newRow("previous-4") << QTabBar::SelectPreviousTab << 3 << (IntList() << 2) << ONE(1) << 1; // not removing current
QTest::newRow("previous-5") << QTabBar::SelectPreviousTab << 3 << (IntList() << 2) << ONE(2) << 0;
// go back one
QTest::newRow("previous-6") << QTabBar::SelectPreviousTab << 4 << (IntList() << 0 << 2 << 3 << 1) << (IntList() << 1) << 2;
// go back two
QTest::newRow("previous-7") << QTabBar::SelectPreviousTab << 4 << (IntList() << 0 << 2 << 3 << 1) << (IntList() << 1 << 2) << 1;
// go back three
QTest::newRow("previous-8") << QTabBar::SelectPreviousTab << 4 << (IntList() << 0 << 2 << 3 << 1) << (IntList() << 1 << 2 << 1) << 0;
// pick from the middle
QTest::newRow("previous-9") << QTabBar::SelectPreviousTab << 4 << (IntList() << 0 << 2 << 3 << 1) << (IntList() << 2 << 1) << 1;
// every other one
QTest::newRow("previous-10") << QTabBar::SelectPreviousTab << 7 << (IntList() << 0 << 2 << 4 << 6) << (IntList() << 6 << 4) << 2;
}
void tst_QTabBar::selectionBehaviorOnRemove()
{
QFETCH(QTabBar::SelectionBehavior, selectionBehavior);
QFETCH(int, tabs);
QFETCH(IntList, select);
QFETCH(IntList, remove);
QFETCH(int, expected);
QTabBar tabbar;
tabbar.setSelectionBehaviorOnRemove(selectionBehavior);
while(--tabs >= 0)
tabbar.addTab(QString::number(tabs));
QCOMPARE(tabbar.currentIndex(), 0);
while(!select.isEmpty())
tabbar.setCurrentIndex(select.takeFirst());
while(!remove.isEmpty())
tabbar.removeTab(remove.takeFirst());
QVERIFY(tabbar.count() > 0);
QCOMPARE(tabbar.currentIndex(), expected);
}
class TabBar : public QTabBar
{
Q_OBJECT
public:
void callMoveTab(int from, int to){ moveTab(from, to); }
};
Q_DECLARE_METATYPE(QTabBar::Shape)
void tst_QTabBar::moveTab_data()
{
QTest::addColumn<QTabBar::Shape>("shape");
QTest::addColumn<int>("tabs");
QTest::addColumn<int>("from");
QTest::addColumn<int>("to");
QTest::newRow("null-0") << QTabBar::RoundedNorth << 0 << -1 << -1;
QTest::newRow("null-1") << QTabBar::RoundedEast << 0 << -1 << -1;
QTest::newRow("null-2") << QTabBar::RoundedEast << 1 << 0 << 0;
QTest::newRow("two-0") << QTabBar::RoundedNorth << 2 << 0 << 1;
QTest::newRow("two-1") << QTabBar::RoundedNorth << 2 << 1 << 0;
QTest::newRow("five-0") << QTabBar::RoundedNorth << 5 << 1 << 3; // forward
QTest::newRow("five-1") << QTabBar::RoundedNorth << 5 << 3 << 1; // reverse
QTest::newRow("five-2") << QTabBar::RoundedNorth << 5 << 0 << 4; // forward
QTest::newRow("five-3") << QTabBar::RoundedNorth << 5 << 1 << 4; // forward
QTest::newRow("five-4") << QTabBar::RoundedNorth << 5 << 3 << 4; // forward
}
void tst_QTabBar::moveTab()
{
QFETCH(QTabBar::Shape, shape);
QFETCH(int, tabs);
QFETCH(int, from);
QFETCH(int, to);
TabBar bar;
bar.setShape(shape);
while(--tabs >= 0)
bar.addTab(QString::number(tabs));
bar.callMoveTab(from, to);
}
class MyTabBar : public QTabBar
{
Q_OBJECT
public slots:
void onCurrentChanged()
{
//we just want this to be done once
disconnect(this, SIGNAL(currentChanged(int)), this, SLOT(onCurrentChanged()));
removeTab(0);
}
};
void tst_QTabBar::task251184_removeTab()
{
MyTabBar bar;
bar.addTab("bar1");
bar.addTab("bar2");
QCOMPARE(bar.count(), 2);
QCOMPARE(bar.currentIndex(), 0);
bar.connect(&bar, SIGNAL(currentChanged(int)), SLOT(onCurrentChanged()));
bar.setCurrentIndex(1);
QCOMPARE(bar.count(), 1);
QCOMPARE(bar.currentIndex(), 0);
QCOMPARE(bar.tabText(bar.currentIndex()), QString("bar2"));
}
class TitleChangeTabBar : public QTabBar
{
Q_OBJECT
QTimer timer;
int count;
public:
TitleChangeTabBar(QWidget * parent = 0) : QTabBar(parent), count(0)
{
setMovable(true);
addTab("0");
connect(&timer, SIGNAL(timeout()), this, SLOT(updateTabText()));
timer.start(1);
}
public slots:
void updateTabText()
{
count++;
setTabText(0, QString("%1").arg(count));
}
};
void tst_QTabBar::changeTitleWhileDoubleClickingTab()
{
TitleChangeTabBar bar;
QPoint tabPos = bar.tabRect(0).center();
for(int i=0; i < 10; i++)
QTest::mouseDClick(&bar, Qt::LeftButton, 0, tabPos);
}
class Widget10052 : public QWidget
{
public:
Widget10052(QWidget *parent) : QWidget(parent), moved(false)
{ }
void moveEvent(QMoveEvent *e)
{
moved = e->oldPos() != e->pos();
QWidget::moveEvent(e);
}
bool moved;
};
void tst_QTabBar::taskQTBUG_10052_widgetLayoutWhenMoving()
{
QTabBar tabBar;
tabBar.insertTab(0, "My first tab");
Widget10052 w1(&tabBar);
tabBar.setTabButton(0, QTabBar::RightSide, &w1);
tabBar.insertTab(1, "My other tab");
Widget10052 w2(&tabBar);
tabBar.setTabButton(1, QTabBar::RightSide, &w2);
tabBar.show();
QVERIFY(QTest::qWaitForWindowExposed(&tabBar));
w1.moved = w2.moved = false;
tabBar.moveTab(0, 1);
QTRY_VERIFY(w1.moved);
QVERIFY(w2.moved);
}
void tst_QTabBar::tabBarClicked()
{
QTabBar tabBar;
tabBar.addTab("0");
QSignalSpy clickSpy(&tabBar, SIGNAL(tabBarClicked(int)));
QSignalSpy doubleClickSpy(&tabBar, SIGNAL(tabBarDoubleClicked(int)));
QCOMPARE(clickSpy.count(), 0);
QCOMPARE(doubleClickSpy.count(), 0);
Qt::MouseButton button = Qt::LeftButton;
while (button <= Qt::MaxMouseButton) {
const QPoint tabPos = tabBar.tabRect(0).center();
QTest::mouseClick(&tabBar, button, 0, tabPos);
QCOMPARE(clickSpy.count(), 1);
QCOMPARE(clickSpy.takeFirst().takeFirst().toInt(), 0);
QCOMPARE(doubleClickSpy.count(), 0);
QTest::mouseDClick(&tabBar, button, 0, tabPos);
QCOMPARE(clickSpy.count(), 1);
QCOMPARE(clickSpy.takeFirst().takeFirst().toInt(), 0);
QCOMPARE(doubleClickSpy.count(), 1);
QCOMPARE(doubleClickSpy.takeFirst().takeFirst().toInt(), 0);
const QPoint barPos(tabBar.tabRect(0).right() + 5, tabBar.tabRect(0).center().y());
QTest::mouseClick(&tabBar, button, 0, barPos);
QCOMPARE(clickSpy.count(), 1);
QCOMPARE(clickSpy.takeFirst().takeFirst().toInt(), -1);
QCOMPARE(doubleClickSpy.count(), 0);
QTest::mouseDClick(&tabBar, button, 0, barPos);
QCOMPARE(clickSpy.count(), 1);
QCOMPARE(clickSpy.takeFirst().takeFirst().toInt(), -1);
QCOMPARE(doubleClickSpy.count(), 1);
QCOMPARE(doubleClickSpy.takeFirst().takeFirst().toInt(), -1);
button = Qt::MouseButton(button << 1);
}
}
void tst_QTabBar::autoHide()
{
QTabBar tabBar;
QVERIFY(!tabBar.autoHide());
QVERIFY(!tabBar.isVisible());
tabBar.show();
QVERIFY(tabBar.isVisible());
tabBar.addTab("0");
QVERIFY(tabBar.isVisible());
tabBar.removeTab(0);
QVERIFY(tabBar.isVisible());
tabBar.setAutoHide(true);
QVERIFY(!tabBar.isVisible());
tabBar.addTab("0");
QVERIFY(!tabBar.isVisible());
tabBar.addTab("1");
QVERIFY(tabBar.isVisible());
tabBar.removeTab(0);
QVERIFY(!tabBar.isVisible());
tabBar.removeTab(0);
QVERIFY(!tabBar.isVisible());
tabBar.setAutoHide(false);
QVERIFY(tabBar.isVisible());
}
QTEST_MAIN(tst_QTabBar)
#include "tst_qtabbar.moc"
| 33.588889 | 142 | 0.645716 | [
"shape"
] |
3f1ff3f6105dc86a77a8b17c7fcc05c80c2b399a | 1,921 | cpp | C++ | applications/oxide/main.cpp | bdashore3/oxide_remarkable_fork | 613084901f8776c792179863bd653438eb7b7d99 | [
"MIT"
] | null | null | null | applications/oxide/main.cpp | bdashore3/oxide_remarkable_fork | 613084901f8776c792179863bd653438eb7b7d99 | [
"MIT"
] | null | null | null | applications/oxide/main.cpp | bdashore3/oxide_remarkable_fork | 613084901f8776c792179863bd653438eb7b7d99 | [
"MIT"
] | null | null | null | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtPlugin>
#include <QtQuick>
#include <fstream>
#include "controller.h"
#ifdef __arm__
Q_IMPORT_PLUGIN(QsgEpaperPlugin)
#endif
bool exists(const std::string& name) {
std::fstream file(name.c_str());
return file.good();
}
const char *qt_version = qVersion();
int main(int argc, char *argv[]){
if (strcmp(qt_version, QT_VERSION_STR) != 0){
qDebug() << "Version mismatch, Runtime: " << qt_version << ", Build: " << QT_VERSION_STR;
}
#ifdef __arm__
// Setup epaper
qputenv("QMLSCENE_DEVICE", "epaper");
qputenv("QT_QPA_PLATFORM", "epaper:enable_fonts");
qputenv("QT_QPA_EVDEV_TOUCHSCREEN_PARAMETERS", "rotate=180");
qputenv("QT_QPA_GENERIC_PLUGINS", "evdevtablet");
// qputenv("QT_DEBUG_BACKINGSTORE", "1");
#endif
system("killall button-capture");
if(exists("/opt/bin/button-capture")){
qDebug() << "Starting button-capture";
system("/opt/bin/button-capture &");
}else{
qDebug() << "button-capture not found or is running";
}
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQmlContext* context = engine.rootContext();
Controller controller;
qmlRegisterType<AppItem>();
qmlRegisterType<Controller>();
context->setContextProperty("screenGeometry", app.primaryScreen()->geometry());
context->setContextProperty("apps", QVariant::fromValue(controller.getApps()));
context->setContextProperty("controller", &controller);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty()){
qDebug() << "Nothing to display";
return -1;
}
QObject* root = engine.rootObjects().first();
QQuickItem* appsView = root->findChild<QQuickItem*>("appsView");
if(!appsView){
qDebug() << "Can't find appsView";
return -1;
}
return app.exec();
}
| 32.016667 | 97 | 0.665279 | [
"geometry"
] |
3f2c5de3222dd242baf08164ca8eb8f4234ccb4c | 4,238 | hpp | C++ | raintk/RainTkImageAtlas.hpp | preet/raintk | 9cbd596d9cec9aca7d3bbf3994a2931bac87e98d | [
"Apache-2.0"
] | 4 | 2016-05-03T20:47:51.000Z | 2021-04-15T09:33:34.000Z | raintk/RainTkImageAtlas.hpp | preet/raintk | 9cbd596d9cec9aca7d3bbf3994a2931bac87e98d | [
"Apache-2.0"
] | null | null | null | raintk/RainTkImageAtlas.hpp | preet/raintk | 9cbd596d9cec9aca7d3bbf3994a2931bac87e98d | [
"Apache-2.0"
] | 1 | 2017-07-26T07:31:35.000Z | 2017-07-26T07:31:35.000Z | /*
Copyright (C) 2016 Preet Desai (preet.desai@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RAINTK_IMAGE_ATLAS_HPP
#define RAINTK_IMAGE_ATLAS_HPP
#include <map>
#include <ks/KsException.hpp>
#include <ks/shared/KsBinPackShelf.hpp>
#include <ks/gl/KsGLTexture2D.hpp>
#include <raintk/RainTkGlobal.hpp>
namespace ks
{
namespace draw
{
class TextureSet;
}
}
namespace raintk
{
class Scene;
// ============================================================= //
// ============================================================= //
class ImageAtlasNoSpaceAvail : public ks::Exception
{
public:
ImageAtlasNoSpaceAvail();
~ImageAtlasNoSpaceAvail() = default;
};
class ImageAtlasIdNotFound : public ks::Exception
{
public:
ImageAtlasIdNotFound();
~ImageAtlasIdNotFound() = default;
};
// ============================================================= //
// ============================================================= //
// ImageAtlas
// * Represents an atlas that combines image data into
// a single texture
// * Can be used to avoid lots of texture state switches to
// increase performance when rendering lots of small images
// * The AtlasImage class shows a basic way to use the atlas
class ImageAtlas
{
public:
struct Source
{
enum class Lifetime
{
Permanent,
Temporary // keeps a copy of the data
};
Lifetime lifetime;
std::function<shared_ptr<ks::ImageData>()> load;
// If lifetime == Temporary
// * keep a copy of the data
// * set load fn = nullptr
};
struct ImageDesc
{
Id texture_set_id;
float s0;
float t0;
float s1;
float t1;
};
private:
struct Entry
{
Source source;
ks::BinPackRectangle rect;
shared_ptr<ks::ImageData> backup;
};
struct Region
{
// top left corner
uint x;
uint y;
unique_ptr<ks::BinPackShelf> bin_packer;
std::map<Id,Entry> lkup_entries;
};
public:
ImageAtlas(Scene* scene,
uint width_px=512,
uint height_px=512,
uint x_regions=2,
uint y_regions=2,
ks::gl::Texture2D::Format format=
ks::gl::Texture2D::Format::RGBA8);
~ImageAtlas();
// * Adds an image to the atlas
// * Returns a unique id to remove or lookup the image
// * Will throw NoSpaceAvail if no space is available
Id AddImage(Source source);
// * Removes the specified image from the atlas
void RemoveImage(Id image_id);
// * Returns the description required to render the
// specified image
// * Throws IdNotFound if the image can't be found
ImageDesc GetImage(Id image_id) const;
private:
Scene* const m_scene;
uint const m_width_px;
uint const m_height_px;
uint const m_x_regions;
uint const m_y_regions;
ks::gl::Texture2D::Format const m_format;
uint m_entry_id_gen{1};
Id m_texture_set_id;
shared_ptr<ks::draw::TextureSet> m_texture_set;
std::vector<Region> m_list_regions;
};
// ============================================================= //
// ============================================================= //
}
#endif // RAINTK_IMAGE_ATLAS_HPP
| 27.341935 | 75 | 0.528787 | [
"render",
"vector"
] |
3f2d730240abfeb1b8ddf97cccf688c4f0395ac9 | 20,346 | cpp | C++ | third_party/WebKit/Source/core/layout/ScrollAnchorTest.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | third_party/WebKit/Source/core/layout/ScrollAnchorTest.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/layout/ScrollAnchorTest.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2015 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 "core/layout/ScrollAnchor.h"
#include "core/layout/LayoutBox.h"
#include "core/layout/LayoutTestHelper.h"
#include "core/paint/PaintLayerScrollableArea.h"
#include "platform/testing/HistogramTester.h"
namespace blink {
using Corner = ScrollAnchor::Corner;
class ScrollAnchorTest : public RenderingTest {
public:
ScrollAnchorTest() { RuntimeEnabledFeatures::setScrollAnchoringEnabled(true); }
~ScrollAnchorTest() { RuntimeEnabledFeatures::setScrollAnchoringEnabled(false); }
protected:
void update()
{
// TODO(skobes): Use SimTest instead of RenderingTest and move into Source/web?
document().view()->updateAllLifecyclePhases();
}
ScrollableArea* layoutViewport()
{
return document().view()->layoutViewportScrollableArea();
}
ScrollableArea* scrollerForElement(Element* element)
{
return toLayoutBox(element->layoutObject())->getScrollableArea();
}
ScrollAnchor& scrollAnchor(ScrollableArea* scroller)
{
if (scroller->isFrameView())
return toFrameView(scroller)->scrollAnchor();
ASSERT(scroller->isPaintLayerScrollableArea());
return toPaintLayerScrollableArea(scroller)->scrollAnchor();
}
void setHeight(Element* element, int height)
{
element->setAttribute(HTMLNames::styleAttr,
AtomicString(String::format("height: %dpx", height)));
update();
}
void scrollLayoutViewport(DoubleSize delta)
{
Element* scrollingElement = document().scrollingElement();
if (delta.width())
scrollingElement->setScrollTop(scrollingElement->scrollLeft() + delta.width());
if (delta.height())
scrollingElement->setScrollTop(scrollingElement->scrollTop() + delta.height());
}
};
// TODO(ymalik): Currently, this should be the first test in the file to avoid
// failure when running with other tests. Dig into this more and fix.
TEST_F(ScrollAnchorTest, UMAMetricUpdated)
{
HistogramTester histogramTester;
setBodyInnerHTML(
"<style> body { height: 1000px } div { height: 100px } </style>"
"<div id='block1'>abc</div>"
"<div id='block2'>def</div>");
ScrollableArea* viewport = layoutViewport();
// Scroll position not adjusted, metric not updated.
scrollLayoutViewport(DoubleSize(0, 150));
histogramTester.expectTotalCount(
"Layout.ScrollAnchor.AdjustedScrollOffset", 0);
// Height changed, verify metric updated once.
setHeight(document().getElementById("block1"), 200);
histogramTester.expectUniqueSample(
"Layout.ScrollAnchor.AdjustedScrollOffset", 1, 1);
EXPECT_EQ(250, viewport->scrollPosition().y());
EXPECT_EQ(document().getElementById("block2")->layoutObject(),
scrollAnchor(viewport).anchorObject());
}
TEST_F(ScrollAnchorTest, Basic)
{
setBodyInnerHTML(
"<style> body { height: 1000px } div { height: 100px } </style>"
"<div id='block1'>abc</div>"
"<div id='block2'>def</div>");
ScrollableArea* viewport = layoutViewport();
// No anchor at origin (0,0).
EXPECT_EQ(nullptr, scrollAnchor(viewport).anchorObject());
scrollLayoutViewport(DoubleSize(0, 150));
setHeight(document().getElementById("block1"), 200);
EXPECT_EQ(250, viewport->scrollPosition().y());
EXPECT_EQ(document().getElementById("block2")->layoutObject(),
scrollAnchor(viewport).anchorObject());
// ScrollableArea::userScroll should clear the anchor.
viewport->userScroll(ScrollByPrecisePixel, FloatSize(0, 100));
EXPECT_EQ(nullptr, scrollAnchor(viewport).anchorObject());
}
TEST_F(ScrollAnchorTest, FractionalOffsetsAreRoundedBeforeComparing)
{
setBodyInnerHTML(
"<style> body { height: 1000px } </style>"
"<div id='block1' style='height: 50.4px'>abc</div>"
"<div id='block2' style='height: 100px'>def</div>");
ScrollableArea* viewport = layoutViewport();
scrollLayoutViewport(DoubleSize(0, 100));
document().getElementById("block1")->setAttribute(
HTMLNames::styleAttr, "height: 50.6px");
update();
EXPECT_EQ(101, viewport->scrollPosition().y());
}
TEST_F(ScrollAnchorTest, AnchorWithLayerInScrollingDiv)
{
setBodyInnerHTML(
"<style>"
" #scroller { overflow: scroll; width: 500px; height: 400px; }"
" div { height: 100px }"
" #block2 { overflow: hidden }"
" #space { height: 1000px; }"
"</style>"
"<div id='scroller'><div id='space'>"
"<div id='block1'>abc</div>"
"<div id='block2'>def</div>"
"</div></div>");
ScrollableArea* scroller = scrollerForElement(document().getElementById("scroller"));
Element* block1 = document().getElementById("block1");
Element* block2 = document().getElementById("block2");
scroller->scrollBy(DoubleSize(0, 150), UserScroll);
// In this layout pass we will anchor to #block2 which has its own PaintLayer.
setHeight(block1, 200);
EXPECT_EQ(250, scroller->scrollPosition().y());
EXPECT_EQ(block2->layoutObject(), scrollAnchor(scroller).anchorObject());
// Test that the anchor object can be destroyed without affecting the scroll position.
block2->remove();
update();
EXPECT_EQ(250, scroller->scrollPosition().y());
}
TEST_F(ScrollAnchorTest, ExcludeAnonymousCandidates)
{
setBodyInnerHTML(
"<style>"
" body { height: 3500px }"
" #div {"
" position: relative; background-color: pink;"
" top: 5px; left: 5px; width: 100px; height: 3500px;"
" }"
" #inline { padding-left: 10px }"
"</style>"
"<div id='div'>"
" <a id='inline'>text</a>"
" <p id='block'>Some text</p>"
"</div>");
ScrollableArea* viewport = layoutViewport();
Element* inlineElem = document().getElementById("inline");
EXPECT_TRUE(inlineElem->layoutObject()->parent()->isAnonymous());
// Scroll #div into view, making anonymous block a viable candidate.
document().getElementById("div")->scrollIntoView();
// Trigger layout and verify that we don't anchor to the anonymous block.
document().getElementById("div")->setAttribute(HTMLNames::styleAttr,
AtomicString("top: 6px"));
update();
EXPECT_EQ(inlineElem->layoutObject()->slowFirstChild(),
scrollAnchor(viewport).anchorObject());
}
TEST_F(ScrollAnchorTest, FullyContainedInlineBlock)
{
// Exercises every WalkStatus value:
// html, body -> Constrain
// #outer -> Continue
// #ib1, br -> Skip
// #ib2 -> Return
setBodyInnerHTML(
"<style>"
" body { height: 1000px }"
" #outer { line-height: 100px }"
" #ib1, #ib2 { display: inline-block }"
"</style>"
"<span id=outer>"
" <span id=ib1>abc</span>"
" <br><br>"
" <span id=ib2>def</span>"
"</span>");
scrollLayoutViewport(DoubleSize(0, 150));
Element* ib2 = document().getElementById("ib2");
ib2->setAttribute(HTMLNames::styleAttr, "line-height: 150px");
update();
EXPECT_EQ(ib2->layoutObject(), scrollAnchor(layoutViewport()).anchorObject());
}
TEST_F(ScrollAnchorTest, TextBounds)
{
setBodyInnerHTML(
"<style>"
" body {"
" position: absolute;"
" font-size: 100px;"
" width: 200px;"
" height: 1000px;"
" line-height: 100px;"
" }"
"</style>"
"abc <b id=b>def</b> ghi");
scrollLayoutViewport(DoubleSize(0, 150));
setHeight(document().body(), 1100);
EXPECT_EQ(document().getElementById("b")->layoutObject()->slowFirstChild(),
scrollAnchor(layoutViewport()).anchorObject());
}
TEST_F(ScrollAnchorTest, ExcludeFixedPosition)
{
setBodyInnerHTML(
"<style>"
" body { height: 1000px; padding: 20px; }"
" div { position: relative; top: 100px; }"
" #f { position: fixed }"
"</style>"
"<div id=f>fixed</div>"
"<div id=c>content</div>");
scrollLayoutViewport(DoubleSize(0, 50));
setHeight(document().body(), 1100);
EXPECT_EQ(document().getElementById("c")->layoutObject(),
scrollAnchor(layoutViewport()).anchorObject());
}
// This test verifies that position:absolute elements that stick to the viewport
// are not selected as anchors.
TEST_F(ScrollAnchorTest, ExcludeAbsolutePositionThatSticksToViewport)
{
setBodyInnerHTML(
"<style>"
" body { margin: 0; }"
" #scroller { overflow: scroll; width: 500px; height: 400px; }"
" #space { height: 1000px; }"
" #abs {"
" position: absolute; background-color: red;"
" width: 100px; height: 100px;"
" }"
" #rel {"
" position: relative; background-color: green;"
" left: 50px; top: 100px; width: 100px; height: 75px;"
" }"
"</style>"
"<div id='scroller'><div id='space'>"
" <div id='abs'></div>"
" <div id='rel'></div>"
"</div></div>");
Element* scrollerElement = document().getElementById("scroller");
ScrollableArea* scroller = scrollerForElement(scrollerElement);
Element* absPos = document().getElementById("abs");
Element* relPos = document().getElementById("rel");
scroller->scrollBy(DoubleSize(0, 25), UserScroll);
setHeight(relPos, 100);
// When the scroller is position:static, the anchor cannot be position:absolute.
EXPECT_EQ(relPos->layoutObject(), scrollAnchor(scroller).anchorObject());
scrollerElement->setAttribute(HTMLNames::styleAttr, "position: relative");
scroller->scrollBy(DoubleSize(0, 25), UserScroll);
setHeight(relPos, 125);
// When the scroller is position:relative, the anchor may be position:absolute.
EXPECT_EQ(absPos->layoutObject(), scrollAnchor(scroller).anchorObject());
}
// This test verifies that position:absolute elements with top/right/bottom/left
// set are not selected as anchors.
TEST_F(ScrollAnchorTest, ExcludeOffsettedAbsolutePosition)
{
setBodyInnerHTML(
"<style>"
" body { margin: 0; }"
" #scroller { overflow: scroll; width: 500px; height: 400px; position:relative; }"
" #space { height: 1000px; }"
" #abs {"
" position: absolute; background-color: red;"
" width: 100px; height: 100px;"
" }"
" #rel {"
" position: relative; background-color: green;"
" left: 50px; top: 100px; width: 100px; height: 75px;"
" }"
" .top { top: 10px }"
" .left { left: 10px }"
" .right { right: 10px }"
" .bottom { bottom: 10px }"
"</style>"
"<div id='scroller'><div id='space'>"
" <div id='abs'></div>"
" <div id='rel'></div>"
"</div></div>");
Element* scrollerElement = document().getElementById("scroller");
ScrollableArea* scroller = scrollerForElement(scrollerElement);
Element* relPos = document().getElementById("rel");
Element* absPos = document().getElementById("abs");
scroller->scrollBy(DoubleSize(0, 25), UserScroll);
setHeight(relPos, 100);
// Pick absolute anchor.
EXPECT_EQ(absPos->layoutObject(), scrollAnchor(scroller).anchorObject());
absPos->setAttribute(HTMLNames::classAttr, "top");
scroller->scrollBy(DoubleSize(0, 25), UserScroll);
setHeight(relPos, 125);
// Don't pick absolute anchor since top is set.
EXPECT_EQ(relPos->layoutObject(), scrollAnchor(scroller).anchorObject());
absPos->removeAttribute(HTMLNames::classAttr);
absPos->setAttribute(HTMLNames::classAttr, "right");
scroller->scrollBy(DoubleSize(0, 25), UserScroll);
setHeight(relPos, 150);
// Don't pick absolute anchor since right is set.
EXPECT_EQ(relPos->layoutObject(), scrollAnchor(scroller).anchorObject());
absPos->removeAttribute(HTMLNames::classAttr);
absPos->setAttribute(HTMLNames::classAttr, "bottom");
scroller->scrollBy(DoubleSize(0, 25), UserScroll);
setHeight(relPos, 175);
// Don't pick absolute anchor since bottom is set.
EXPECT_EQ(relPos->layoutObject(), scrollAnchor(scroller).anchorObject());
absPos->removeAttribute(HTMLNames::classAttr);
absPos->setAttribute(HTMLNames::classAttr, "left");
scroller->scrollBy(DoubleSize(0, 25), UserScroll);
setHeight(relPos, 200);
// Don't pick absolute anchor since left is set.
EXPECT_EQ(relPos->layoutObject(), scrollAnchor(scroller).anchorObject());
}
// Test that we descend into zero-height containers that have overflowing content.
TEST_F(ScrollAnchorTest, DescendsIntoContainerWithOverflow)
{
setBodyInnerHTML(
"<style>"
" body { height: 1000; }"
" #outer { width: 300px; }"
" #zeroheight { height: 0px; }"
" #changer { height: 100px; background-color: red; }"
" #bottom { margin-top: 600px; }"
"</style>"
"<div id='outer'>"
" <div id='zeroheight'>"
" <div id='changer'></div>"
" <div id='bottom'>bottom</div>"
" </div>"
"</div>");
ScrollableArea* viewport = layoutViewport();
scrollLayoutViewport(DoubleSize(0, 200));
setHeight(document().getElementById("changer"), 200);
EXPECT_EQ(300, viewport->scrollPosition().y());
EXPECT_EQ(document().getElementById("bottom")->layoutObject(),
scrollAnchor(viewport).anchorObject());
}
// Test that we descend into zero-height containers that have floating content.
TEST_F(ScrollAnchorTest, DescendsIntoContainerWithFloat)
{
setBodyInnerHTML(
"<style>"
" body { height: 1000; }"
" #outer { width: 300px; }"
" #outer:after { content: ' '; clear:both; display: table; }"
" #float {"
" float: left; background-color: #ccc;"
" height: 500px; width: 100%;"
" }"
" #inner { height: 21px; background-color:#7f0; }"
"</style>"
"<div id='outer'>"
" <div id='zeroheight'>"
" <div id='float'>"
" <div id='inner'></div>"
" </div>"
" </div>"
"</div>");
EXPECT_EQ(0, toLayoutBox(document().getElementById("zeroheight")->layoutObject())->size().height());
ScrollableArea* viewport = layoutViewport();
scrollLayoutViewport(DoubleSize(0, 200));
setHeight(document().getElementById("float"), 600);
EXPECT_EQ(200, viewport->scrollPosition().y());
EXPECT_EQ(document().getElementById("float")->layoutObject(),
scrollAnchor(viewport).anchorObject());
}
class ScrollAnchorCornerTest : public ScrollAnchorTest {
protected:
void checkCorner(const AtomicString& id, Corner corner, DoublePoint startPos, DoubleSize expectedAdjustment)
{
ScrollableArea* viewport = layoutViewport();
Element* element = document().getElementById(id);
viewport->setScrollPosition(startPos, UserScroll);
element->setAttribute(HTMLNames::classAttr, "big");
update();
DoublePoint endPos = startPos;
endPos.move(expectedAdjustment);
EXPECT_EQ(endPos, viewport->scrollPositionDouble());
EXPECT_EQ(element->layoutObject(), scrollAnchor(viewport).anchorObject());
EXPECT_EQ(corner, scrollAnchor(viewport).corner());
element->removeAttribute(HTMLNames::classAttr);
update();
}
};
TEST_F(ScrollAnchorCornerTest, Corners)
{
setBodyInnerHTML(
"<style>"
" body {"
" position: absolute; border: 10px solid #ccc;"
" width: 1220px; height: 920px;"
" }"
" #a, #b, #c, #d {"
" position: absolute; background-color: #ace;"
" width: 400px; height: 300px;"
" }"
" #a, #b { top: 0; }"
" #a, #c { left: 0; }"
" #b, #d { right: 0; }"
" #c, #d { bottom: 0; }"
" .big { width: 800px !important; height: 600px !important }"
"</style>"
"<div id=a></div>"
"<div id=b></div>"
"<div id=c></div>"
"<div id=d></div>");
checkCorner("a", Corner::TopLeft, DoublePoint(20, 20), DoubleSize(0, 0));
checkCorner("b", Corner::TopLeft, DoublePoint(420, 20), DoubleSize(-400, 0));
checkCorner("c", Corner::TopLeft, DoublePoint(20, 320), DoubleSize(0, -300));
checkCorner("d", Corner::TopLeft, DoublePoint(420, 320), DoubleSize(-400, -300));
}
TEST_F(ScrollAnchorCornerTest, CornersVerticalLR)
{
setBodyInnerHTML(
"<style>"
" html {"
" writing-mode: vertical-lr;"
" }"
" body {"
" position: absolute; border: 10px solid #ccc;"
" width: 1220px; height: 920px;"
" }"
" #a, #b, #c, #d {"
" position: absolute; background-color: #ace;"
" width: 400px; height: 300px;"
" }"
" #a, #b { top: 0; }"
" #a, #c { left: 0; }"
" #b, #d { right: 0; }"
" #c, #d { bottom: 0; }"
" .big { width: 800px !important; height: 600px !important }"
"</style>"
"<div id=a></div>"
"<div id=b></div>"
"<div id=c></div>"
"<div id=d></div>");
checkCorner("a", Corner::TopLeft, DoublePoint(20, 20), DoubleSize(0, 0));
checkCorner("b", Corner::TopLeft, DoublePoint(420, 20), DoubleSize(-400, 0));
checkCorner("c", Corner::TopLeft, DoublePoint(20, 320), DoubleSize(0, -300));
checkCorner("d", Corner::TopLeft, DoublePoint(420, 320), DoubleSize(-400, -300));
}
TEST_F(ScrollAnchorCornerTest, CornersRTL)
{
setBodyInnerHTML(
"<style>"
" html {"
" direction: rtl;"
" }"
" body {"
" position: absolute; border: 10px solid #ccc;"
" width: 1220px; height: 920px;"
" }"
" #a, #b, #c, #d {"
" position: absolute; background-color: #ace;"
" width: 400px; height: 300px;"
" }"
" #a, #b { top: 0; }"
" #a, #c { left: 0; }"
" #b, #d { right: 0; }"
" #c, #d { bottom: 0; }"
" .big { width: 800px !important; height: 600px !important }"
"</style>"
"<div id=a></div>"
"<div id=b></div>"
"<div id=c></div>"
"<div id=d></div>");
checkCorner("b", Corner::TopRight, DoublePoint(-20, 20), DoubleSize(0, 0));
checkCorner("a", Corner::TopRight, DoublePoint(-420, 20), DoubleSize(400, 0));
checkCorner("d", Corner::TopRight, DoublePoint(-20, 320), DoubleSize(0, -300));
checkCorner("c", Corner::TopRight, DoublePoint(-420, 320), DoubleSize(400, -300));
}
TEST_F(ScrollAnchorCornerTest, CornersVerticalRL)
{
setBodyInnerHTML(
"<style>"
" html {"
" writing-mode: vertical-rl;"
" }"
" body {"
" position: absolute; border: 10px solid #ccc;"
" width: 1220px; height: 920px;"
" }"
" #a, #b, #c, #d {"
" position: absolute; background-color: #ace;"
" width: 400px; height: 300px;"
" }"
" #a, #b { top: 0; }"
" #a, #c { left: 0; }"
" #b, #d { right: 0; }"
" #c, #d { bottom: 0; }"
" .big { width: 800px !important; height: 600px !important }"
"</style>"
"<div id=a></div>"
"<div id=b></div>"
"<div id=c></div>"
"<div id=d></div>");
checkCorner("b", Corner::TopRight, DoublePoint(-20, 20), DoubleSize(0, 0));
checkCorner("a", Corner::TopRight, DoublePoint(-420, 20), DoubleSize(400, 0));
checkCorner("d", Corner::TopRight, DoublePoint(-20, 320), DoubleSize(0, -300));
checkCorner("c", Corner::TopRight, DoublePoint(-420, 320), DoubleSize(400, -300));
}
}
| 35.261698 | 112 | 0.591418 | [
"object",
"solid"
] |
3f2fab538f9e575bf4d1263a0e50c0ed550d1891 | 6,160 | cpp | C++ | CodeXL/Components/GpuDebugging/AMDTOpenGLServer/src/gsSyncObjectsMonitor.cpp | jeongjoonyoo/CodeXL | ea6d623d0530aa3a862ef0bf60ad2923a2f8f8a5 | [
"MIT"
] | 1,025 | 2016-04-19T21:36:08.000Z | 2020-04-26T05:12:53.000Z | CodeXL/Components/GpuDebugging/AMDTOpenGLServer/src/gsSyncObjectsMonitor.cpp | jeongjoonyoo/CodeXL | ea6d623d0530aa3a862ef0bf60ad2923a2f8f8a5 | [
"MIT"
] | 244 | 2016-04-20T02:05:43.000Z | 2020-04-29T17:40:49.000Z | CodeXL/Components/GpuDebugging/AMDTOpenGLServer/src/gsSyncObjectsMonitor.cpp | jeongjoonyoo/CodeXL | ea6d623d0530aa3a862ef0bf60ad2923a2f8f8a5 | [
"MIT"
] | 161 | 2016-04-20T03:23:53.000Z | 2020-04-14T01:46:55.000Z | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file gsSyncObjectsMonitor.cpp
///
//==================================================================================
//------------------------------ gsSyncObjectsMonitor.cpp ------------------------------
// Infra:
#include <AMDTBaseTools/Include/AMDTDefinitions.h>
#include <AMDTBaseTools/Include/gtAssert.h>
// Spies Utilities:
#include <AMDTServerUtilities/Include/suGlobalVariables.h>
// Local:
#include <src/gsSyncObjectsMonitor.h>
#include <src/gsGlobalVariables.h>
#include <src/gsOpenGLMonitor.h>
#define GS_LAST_SYNC_NAME GT_INT32_MAX
// ---------------------------------------------------------------------------
// Name: gsSyncObjectsMonitor::gsSyncObjectsMonitor
// Description: Constructor
// Author: Sigal Algranaty
// Date: 28/10/2009
// ---------------------------------------------------------------------------
gsSyncObjectsMonitor::gsSyncObjectsMonitor()
: _nextFreeSyncID(1)
{
}
// ---------------------------------------------------------------------------
// Name: gsSyncObjectsMonitor::~gsSyncObjectsMonitor
// Description: Destructor
// Author: Sigal Algranaty
// Date: 28/10/2009
// ---------------------------------------------------------------------------
gsSyncObjectsMonitor::~gsSyncObjectsMonitor()
{
}
// ---------------------------------------------------------------------------
// Name: gsSyncObjectsMonitor::onSyncObjectCreation
// Description: Handle OpenGL sync object creation
// Arguments: GLsync sync
// GLenum condition
// Return Val: bool - Success / failure.
// Author: Sigal Algranaty
// Date: 28/10/2009
// ---------------------------------------------------------------------------
bool gsSyncObjectsMonitor::onSyncObjectCreation(GLsync sync, GLenum condition)
{
bool retVal = true;
if (sync != NULL)
{
// Create a new sync object:
apGLSync* pNewSyncObject = new apGLSync;
// Set the new sync object OpenGL id:
pNewSyncObject->setSyncID(_nextFreeSyncID);
pNewSyncObject->setSyncHandle((oaGLSyncHandle)sync);
pNewSyncObject->setSyncCodition(condition);
// Set the next free sync ID:
if ((_nextFreeSyncID >= GS_LAST_SYNC_NAME) || (_nextFreeSyncID < 0))
{
_nextFreeSyncID = 1;
}
else
{
_nextFreeSyncID++;
}
// Add the object to the vector:
_syncObjects.push_back(pNewSyncObject);
// Register this object in the allocated objects monitor:
su_stat_theAllocatedObjectsMonitor.registerAllocatedObject(*pNewSyncObject);
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: gsSyncObjectsMonitor::onSyncObjectDeletion
// Description: Handles OpenGL sync object deletion
// Arguments: GLsync sync
// Return Val: bool - Success / failure.
// Author: Sigal Algranaty
// Date: 28/10/2009
// ---------------------------------------------------------------------------
bool gsSyncObjectsMonitor::onSyncObjectDeletion(GLsync sync)
{
bool retVal = false;
// If this is a valid handle:
oaGLSyncHandle deletedSyncHandle = (oaGLSyncHandle)sync;
if (deletedSyncHandle != OA_GL_NULL_HANDLE)
{
// Search for the sync object index within the vector of objects:
int numberOfSyncObjects = (int)_syncObjects.size();
bool foundSync = false;
for (int i = 0; i < numberOfSyncObjects; i++)
{
// Sanity check:
apGLSync* pSyncObject = _syncObjects[i];
GT_IF_WITH_ASSERT(pSyncObject != NULL)
{
if (foundSync)
{
// Note that foundSync can only be true if we already passed at least one object,
// so accessing the (i-1) vector item is allowed:
_syncObjects[i - 1] = _syncObjects[i];
}
else
{
if (pSyncObject->syncHandle() == deletedSyncHandle)
{
// Sync handles can be reused by the OpenGL implementation, if we have several objects with the same handle,
// delete the one that is still alive:
foundSync = true;
// Delete the monitor object:
delete pSyncObject;
_syncObjects[i] = NULL;
}
}
}
}
// If we managed to find and delete the sync object:
if (foundSync)
{
// The sync handle exists (or once existed):
retVal = true;
// Remove the last sync in the vector, which is either our object or a duplicate of some other object:
_syncObjects.pop_back();
}
else // !foundSync
{
// TO_DO: OpenGL 3.2 add detected error - sync object that does not exist is deleted:
}
}
else // deletedSyncHandle == OA_GL_NULL_HANDLE
{
// This is an allowed operation:
retVal = true;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: gsSyncObjectsMonitor::getSyncObjectDetails
// Description: Returns an apGLSync object according to the sync index
// Return Val: apGLSync* - the sync Object
// Author: Sigal Algranaty
// Date: 28/10/2009
// ---------------------------------------------------------------------------
const apGLSync* gsSyncObjectsMonitor::getSyncObjectDetails(int syncObjectIndex) const
{
const apGLSync* pRetVal = NULL;
// Sanity check:
int numberOfSyncObjects = (int)_syncObjects.size();
GT_IF_WITH_ASSERT((syncObjectIndex > -1) && (syncObjectIndex < numberOfSyncObjects))
{
pRetVal = _syncObjects[syncObjectIndex];
}
return pRetVal;
}
| 33.297297 | 132 | 0.512338 | [
"object",
"vector"
] |
3f337053bbd173572e74c0b31a5e99f29afc4617 | 3,750 | cc | C++ | TEvtGen/HepMC/Polarization.cc | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TEvtGen/HepMC/Polarization.cc | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TEvtGen/HepMC/Polarization.cc | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | //////////////////////////////////////////////////////////////////////////
// Matt.Dobbs@Cern.CH, September 1999
//
// Polarization object for a particle. All angles are in radians.
//////////////////////////////////////////////////////////////////////////
#include "HepMC/Polarization.h"
namespace HepMC {
Polarization::Polarization( )
: m_theta( 0. ),
m_phi( 0. ),
m_defined( false )
{ }
Polarization::Polarization( double theta, double phi )
: m_theta( valid_theta(theta) ),
m_phi ( valid_phi(phi) ),
m_defined( true )
{ }
Polarization::Polarization( const Polarization& inpolar )
: m_theta( valid_theta( inpolar.theta() ) ),
m_phi ( valid_phi( inpolar.phi() ) ),
m_defined( inpolar.is_defined() )
{ }
Polarization::Polarization( const ThreeVector& vec3in )
: m_theta( valid_theta( vec3in.theta() ) ),
m_phi ( valid_phi( vec3in.phi() ) ),
m_defined( true )
{ }
void Polarization::swap( Polarization & other)
{
std::swap( m_theta, other.m_theta );
std::swap( m_phi, other.m_phi );
std::swap( m_defined, other.m_defined );
}
Polarization& Polarization::operator=( const Polarization& inpolar ) {
/// best practices implementation
Polarization tmp( inpolar );
swap( tmp );
return *this;
}
void Polarization::print( std::ostream& ostr ) const {
ostr << "Polarization: " << *this << std::endl;
}
////////////////////
// access methods //
////////////////////
ThreeVector Polarization::normal3d() const {
// unit Hep3Vector for easy manipulation
ThreeVector outvec(0,0,1); // makes unit vector along Z
outvec.setTheta( theta() ); // sets phi keeping mag and theta constant
outvec.setPhi( phi() ); // sets theta keeping mag and phi constant
return outvec;
}
double Polarization::set_theta( double theta ) {
/// Theta is restricted to be between 0 --> pi
/// if an out of range value is given, it is translated to this range.
return m_theta = valid_theta( theta );
}
double Polarization::set_phi( double phi ) {
/// Phi is restricted to be between 0 --> 2pi
/// if an out of range value is given, it is translated to this range.
return m_phi = valid_phi( phi );
}
bool Polarization::is_defined( ) const {
return m_defined;
}
void Polarization::set_undefined() {
m_defined = false;
m_theta = 0.;
m_phi = 0.;
}
void Polarization::set_theta_phi( double theta, double phi ) {
set_theta( theta );
set_phi( phi ) ;
m_defined = true;
}
ThreeVector Polarization::set_normal3d( const ThreeVector& vec3in ) {
set_theta( vec3in.theta() );
set_phi( vec3in.phi() );
m_defined = true;
return vec3in;
}
/////////////////////
// private methods //
/////////////////////
double Polarization::valid_theta( double theta ) {
// this is just absolute value.
theta = ( theta>0 ? theta : -theta );
// translate to 0 < theta < 2pi
theta = ( theta/(2*HepMC_pi) - int(theta/(2*HepMC_pi)) )
* 2*HepMC_pi;
// now translate to 0 < theta < pi
if ( theta > HepMC_pi ) theta = 2*HepMC_pi - theta;
return theta;
}
double Polarization::valid_phi( double phi ) {
//
// translate to -2pi < phi < 2pi
phi = ( phi/(2*HepMC_pi) - int(phi/(2*HepMC_pi)) ) * 2*HepMC_pi;
// translates to 0 < phi < 2pi
if ( phi < 0 ) phi = 2*HepMC_pi + phi;
return phi;
}
/////////////
// Friends //
/////////////
/// write theta and phi to the output stream
std::ostream& operator<<( std::ostream& ostr, const Polarization& polar ) {
return ostr << "(" << polar.theta()
<< "," << polar.phi() << ")";
}
} // HepMC
| 27.372263 | 79 | 0.570667 | [
"object",
"vector"
] |
3f342ffdee40ec4d8571ad7227028ebe4b5395a8 | 1,142 | cpp | C++ | Codeforces/1000/B-DivisorsofTwoIntegers.cpp | JanaSabuj/cpmaster | d943780c7ca4badbefbce2d300848343c4032650 | [
"MIT"
] | 1 | 2020-11-29T08:36:38.000Z | 2020-11-29T08:36:38.000Z | Codeforces/1000/B-DivisorsofTwoIntegers.cpp | Sahu49/CompetitiveProgramming | adf11a546f81878ad2975926219af84deb3414e8 | [
"MIT"
] | null | null | null | Codeforces/1000/B-DivisorsofTwoIntegers.cpp | Sahu49/CompetitiveProgramming | adf11a546f81878ad2975926219af84deb3414e8 | [
"MIT"
] | null | null | null | //Built by Sabuj Jana(greenindia) from Jadavpur University
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
// int t;cin>>t;cout<<t;cerr<<t;
int n;
cin >> n;
vector<int> v1;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
v1.push_back(x);
}
sort(v1.begin() , v1.end());
if(n==2 and v1[0]==1 and v1[1]==1) {cout<<1<<" "<<1<<endl; return 0;}
int a = v1[n - 1];
cout << a <<" ";
for (int i = 1; i * i <= a; i++) {
if (a % i == 0) {
auto it1 = std::find(v1.begin(), v1.end(), i);
if (it1 != v1.end()) {
std::iter_swap(it1, v1.end() - 1);
v1.erase(v1.end() - 1);
}
if(a/i!=i) {
auto it2 = std::find(v1.begin(), v1.end(), a/i);
if(it2!=v1.end()){
std::iter_swap(it2, v1.end() - 1);
v1.erase(v1.end() - 1);
}
}
}
}
sort(v1.begin(),v1.end());
int sz = v1.size();
cout<<v1[sz-1];
return 0;
}
| 20.392857 | 73 | 0.410683 | [
"vector"
] |
3f39aea76fa63a7ed366a7d1fbdbb85e19dc48ee | 2,833 | cpp | C++ | code/file.cpp | yinn-x/iFleaBooks | 24ed3a77a5861076f162f0f9fa1e7458659a93cc | [
"MIT"
] | 1 | 2022-02-07T16:27:15.000Z | 2022-02-07T16:27:15.000Z | code/file.cpp | yinn-x/iFleaBooks | 24ed3a77a5861076f162f0f9fa1e7458659a93cc | [
"MIT"
] | null | null | null | code/file.cpp | yinn-x/iFleaBooks | 24ed3a77a5861076f162f0f9fa1e7458659a93cc | [
"MIT"
] | null | null | null | /**
* File
* @description 程序开始时进行数据载入
* 程序结束后进行数据保存
* @author YiNN
* @creat 2022-01-30 23:39:17
*/
#include"iostream"
#include"fstream"
#include"vector"
#include"header/data.h"
#include"header/display-color.h"
using namespace std;
vector<User> v_users;
vector<Admin> v_admins;
vector<Book> v_books;
vector<Order> v_orders;
int countU = 0;
int countB = 0;
int countO = 0;
void pullUsers() {
ifstream fin;
fin.open("data/users.txt");
if (!fin.is_open()) {
cout << "Loading failed,please retry.\n";
exit(EXIT_FAILURE);
}
User item;
while (fin >> item) {
countU++;
v_users.push_back(item);
}
fin.close();
fin.open("data/admins.txt");
if (!fin.is_open()) {
cout << "Loading failed,please retry.\n";
exit(EXIT_FAILURE);
}
Admin it;
while (fin >> it) v_admins.push_back(it);
fin.close();
}
void pullBooks() {
ifstream fin;
fin.open("data/books.txt");
if (!fin.is_open()) {
cout << "Loading failed,please retry.\n";
exit(EXIT_FAILURE);
}
Book item;
while (fin >> item){
countB++;
v_books.push_back(item);
}
fin.close();
}
void pullOrders() {
ifstream fin;
fin.open("data/orders.txt");
if (!fin.is_open()) {
cout << "Loading failed,please retry.\n";
exit(EXIT_FAILURE);
}
Order item;
while (fin >> item){
countO++;
v_orders.push_back(item);
}
fin.close();
}
void pushUsers() {
ofstream outfile;
outfile.open("data/users.txt");
if (!outfile.is_open()) {
cout << "Save failed,your data may be lost.\n";
exit(EXIT_FAILURE);
}
for (auto item : v_users) outfile << item;
outfile.close();
outfile.open("data/a.txt");
if (!outfile.is_open()) {
cout << "Save failed,your data may be lost.\n";
exit(EXIT_FAILURE);
}
for (auto item : v_admins) outfile << item;
outfile.close();
}
void pushBooks() {
ofstream outfile;
outfile.open("data/books.txt");
if (!outfile.is_open()) {
cout << "Save failed,your data may be lost.\n";
exit(EXIT_FAILURE);
}
for (auto item : v_books) outfile << item;
outfile.close();
}
void pushOrders() {
ofstream outfile;
outfile.open("data/orders.txt");
if (!outfile.is_open()) {
cout << "Save failed,your data may be lost.\n";
exit(EXIT_FAILURE);
}
for (auto item : v_orders) outfile << item;
outfile.close();
}
void pullFile() {
cout <<"\t\tloading...\n";
pullUsers();
pullBooks();
pullOrders();
}
void pushFile() {
cout << F_GREY << "\n\t\tsaving...";
pushUsers();
pushBooks();
pushOrders();
cout << "\n\t\tsave completed.\n\t\texit iFleaBooks successfully.\n"<<RESET;
}
| 21.792308 | 80 | 0.572538 | [
"vector"
] |
278683d258ef68508eec56bf1317970aeb7061ec | 4,931 | cpp | C++ | ciaox11/deployment/util/ciaox11_corba_util.cpp | jwillemsen/ciaox11 | 483dd0f189a92615068366f566ea8354a1baf7a3 | [
"MIT"
] | 7 | 2016-04-12T15:09:33.000Z | 2022-01-26T02:28:28.000Z | ciaox11/deployment/util/ciaox11_corba_util.cpp | jwillemsen/ciaox11 | 483dd0f189a92615068366f566ea8354a1baf7a3 | [
"MIT"
] | 10 | 2019-11-26T15:24:01.000Z | 2022-03-28T11:45:14.000Z | ciaox11/deployment/util/ciaox11_corba_util.cpp | jwillemsen/ciaox11 | 483dd0f189a92615068366f566ea8354a1baf7a3 | [
"MIT"
] | 5 | 2016-04-12T18:40:44.000Z | 2019-12-18T14:27:52.000Z | /**
* @file ciaox11_corba_util.cpp
* @author Martin Corino
*
* @brief CIAOX11 CORBA deployment utility methods
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#include "ciaox11_corba_util.h"
#include "ciaox11/config/ciaox11_config_util.h"
#include "ciaox11/config/ciaox11_config_valuesC.h"
#include "ccm/ccm_objectC.h"
#include "ciaox11/logger/log.h"
#include <string>
namespace CIAOX11
{
namespace Corba
{
namespace Utility
{
IDL::traits<CORBA::Object>::ref_type
get_provider_reference (const Components::ConfigValues& cfgval)
{
CIAOX11_LOG_INFO ("CORBA::Utility::get_provider_reference - "
"retrieving provider reference");
CORBA::Any cvalue;
// Extract provided peer endpoint reference
if (!Config::Utility::find_config_value (cfgval, CIAOX11::PEER_ENDPOINT_REFERENCE, cvalue))
{
CIAOX11_LOG_ERROR ("CORBA::Utility::get_provider_reference - "
"missing peer endpoint reference");
return {};
}
IDL::traits<CORBA::Object>::ref_type peer_ref;
if (!(cvalue >>= peer_ref))
{
CIAOX11_LOG_ERROR ("CORBA::Utility::get_provider_reference - "
"unable to extract peer endpoint reference");
return {};
}
// Determine peer endpoint type
if (!Config::Utility::find_config_value (cfgval, CIAOX11::PEER_ENDPOINT_TYPE, cvalue))
{
CIAOX11_LOG_ERROR ("CORBA::Utility::get_provider_reference - "
"unable to determine endpoint type");
return {};
}
uint32_t eptype {};
if (!(cvalue >>= eptype))
{
CIAOX11_LOG_ERROR ("CORBA::Utility::get_provider_reference - "
"unable to extract endpoint type value");
return {};
}
CIAOX11_LOG_INFO ("CORBA::Utility::get_provider_reference - "
"found endpoint type " <<
(eptype == CIAOX11::INTERNAL_ENDPOINT ?
"INTERNAL ENDPOINT" : (eptype == CIAOX11::EXTERNAL_ENDPOINT ?
"EXTERNAL ENDPORT" : "EXTERNAL REFERENCE")) <<
" with peer reference <" << peer_ref << ">");
// in case of an internal endpoint the provided reference should be
// the facet provider reference
if (eptype != CIAOX11::INTERNAL_ENDPOINT)
{
// otherwise we expect either a CCMObject reference and a port name
// or the facet provider reference to determine which we attempt to
// narrow to CCMObject
IDL::traits<Components::CCMObject>::ref_type facet_provider =
IDL::traits<Components::CCMObject>::narrow (peer_ref);
if (facet_provider)
{
// if we were provided with a CCMObject reference we need a port name
// to retrieve the facet reference
if (!Config::Utility::find_config_value (cfgval, CIAOX11::PEER_ENDPOINT_PORT, cvalue))
{
CIAOX11_LOG_ERROR ("CORBA::Utility::get_provider_reference - "
"missing peer endpoint port name");
return {};
}
std::string epport;
if (!(cvalue >>= epport))
{
CIAOX11_LOG_ERROR ("CORBA::Utility::get_provider_reference - "
"unable to extract peer endpoint port name");
return {};
}
if (epport.empty())
{
CIAOX11_LOG_ERROR ("CORBA::Utility::get_provider_reference - "
"received an empty port name");
return {};
}
// query the facet provider for the facet reference
CORBA::Any refval;
try
{
CIAOX11_LOG_DEBUG ("CORBA::Utility::get_provider_reference - " <<
"Calling provide facet <" << epport << ">");
facet_provider->provide_facet (epport, refval);
}
catch (const Components::InvalidName &ex)
{
CIAOX11_LOG_ERROR ("CORBA::Utility::get_provider_reference - failed for facet <" << epport
<< "> with exception <" << ex << ">");
return {};
}
// extract the facet reference
if (!(refval >>= peer_ref))
{
CIAOX11_LOG_ERROR ("CORBA::Utility::get_provider_reference - "
"unable to extract provided facet reference");
return {};
}
}
// else we assume the provided reference is the facet reference
}
return peer_ref;
}
}
}
}
| 37.641221 | 104 | 0.534577 | [
"object"
] |
278f0c0578989ddb74711d5a514928a264d2bc5e | 2,070 | hpp | C++ | cpp/margin_metric.hpp | GaoSida/Neural-SampleRank | 8b4a7a40cc34bff608f19d3f7eb64bda76669c5b | [
"MIT"
] | 2 | 2020-11-17T18:41:05.000Z | 2021-08-12T14:40:56.000Z | cpp/margin_metric.hpp | GaoSida/Neural-SampleRank | 8b4a7a40cc34bff608f19d3f7eb64bda76669c5b | [
"MIT"
] | null | null | null | cpp/margin_metric.hpp | GaoSida/Neural-SampleRank | 8b4a7a40cc34bff608f19d3f7eb64bda76669c5b | [
"MIT"
] | null | null | null | // Mirror nsr.graph.margin_metric
#include "factor_graph.hpp"
#include <vector>
#include <unordered_set>
class MarginMetric {
public:
std::vector<int> ground_truth;
MarginMetric(std::vector<int>& ground_truth) {
this->ground_truth = ground_truth;
}
virtual float compute_metric(std::vector<int>& label_sample,
std::unordered_set<int>& ground_truth_diff_set) = 0;
virtual float incremental_compute_metric(std::vector<LabelNode*>& sample,
float prev_metric, std::vector<int>& prev_sample,
std::vector<int>& diff_indicies,
std::unordered_set<int>& ground_truth_diff_set) = 0;
};
class NegHammingDistance : public MarginMetric {
public:
NegHammingDistance(std::vector<int>& ground_truth) :
MarginMetric(ground_truth) {}
float compute_metric(std::vector<int>& label_sample,
std::unordered_set<int>& ground_truth_diff_set) {
float metric = 0;
ground_truth_diff_set.clear();
for (int i = 0; i < label_sample.size(); i++) {
// Padded ground truth has label value 1 (PyTorch convention)
if (ground_truth[i] != label_sample[i] && ground_truth[i] != 1) {
metric -= 1.0;
ground_truth_diff_set.insert(i);
}
}
return metric;
}
/* In addition to the Python interface, maintain each sample's diff compared
with ground truth.
*/
float incremental_compute_metric(std::vector<LabelNode*>& sample,
float prev_metric, std::vector<int>& prev_sample,
std::vector<int>& diff_indicies,
std::unordered_set<int>& ground_truth_diff_set) {
float current_metric = prev_metric;
for (int i : diff_indicies) {
bool prev_correct = (prev_sample[i] == ground_truth[i]);
bool current_correct = (sample[i]->current_value == ground_truth[i]);
if (prev_correct != current_correct) {
if (prev_correct) {
current_metric -= 1;
ground_truth_diff_set.insert(i);
}
else {
current_metric += 1;
ground_truth_diff_set.erase(i);
}
}
}
return current_metric;
}
};
| 29.15493 | 78 | 0.666184 | [
"vector"
] |
278f90ea1c539644e44cdb4ea0474f324f434c55 | 1,162 | cpp | C++ | src/LoboFEM/LoboDynamic/LoboDynamicSolver/LoboOptimizationSolver/Sparse/LinearStaticSolver.cpp | lrquad/LoboFEM2 | 4ac80bd7b6e347d5b1650f5241f7b7b53c9716f5 | [
"MIT"
] | 5 | 2020-05-09T12:33:08.000Z | 2021-12-17T08:07:29.000Z | src/LoboFEM/LoboDynamic/LoboDynamicSolver/LoboOptimizationSolver/Sparse/LinearStaticSolver.cpp | FYTalon/LoboFEM2 | 4ac80bd7b6e347d5b1650f5241f7b7b53c9716f5 | [
"MIT"
] | null | null | null | src/LoboFEM/LoboDynamic/LoboDynamicSolver/LoboOptimizationSolver/Sparse/LinearStaticSolver.cpp | FYTalon/LoboFEM2 | 4ac80bd7b6e347d5b1650f5241f7b7b53c9716f5 | [
"MIT"
] | 2 | 2021-02-11T10:00:37.000Z | 2021-04-18T02:08:11.000Z | #include "LinearStaticSolver.h"
#include "LoboDynamic/LoboDynamic.h"
#include <fstream>
Lobo::LinearStaticSolver::LinearStaticSolver(Lobo::DynamicModel *model_):Lobo::LoboOptimizationSolver(model_,0,0)
{
q.resize(r);
q.setZero();
}
void Lobo::LinearStaticSolver::precompute()
{
std::cout<<"LinearStaticSolver::precompute"<<std::endl;
model->getSparseTopoloty(hessian);
jacobi.resize(model->num_DOFs);
jacobi.setZero();
int flags_all = 0;
flags_all |= Computeflags_second|Computeflags_reset;
this->model->computeEnergySparse(&q,&energy,&jacobi,&hessian,flags_all);
eigen_linearsolver.compute(hessian);
std::cout<<"LinearStaticSolver::precompute end"<<std::endl;
}
void Lobo::LinearStaticSolver::solve(Eigen::VectorXd *initialGuessq)
{
int flags_all = 0;
flags_all |= Computeflags_fisrt|Computeflags_reset;
q = *initialGuessq;
this->model->computeEnergySparse(&q,&energy,&jacobi,&hessian,flags_all);
jacobi*=-1.0;
Eigen::VectorXd result_ = eigen_linearsolver.solve(jacobi);
q = q+result_;
}
void Lobo::LinearStaticSolver::getResult(Eigen::VectorXd *result)
{
*result = q;
} | 29.05 | 113 | 0.716867 | [
"model"
] |
279083038834ead48f16b4819d51efe618255655 | 909 | hpp | C++ | gamegio-library/src/gamegio/AngleCbor.hpp | tril0byte/HGamer3D | 7979c67d9b4672a5b2d1a50320a6d47b1a97ff05 | [
"Apache-2.0"
] | 27 | 2015-06-08T16:45:47.000Z | 2022-02-22T14:40:52.000Z | gamegio-library/src/gamegio/AngleCbor.hpp | tril0byte/HGamer3D | 7979c67d9b4672a5b2d1a50320a6d47b1a97ff05 | [
"Apache-2.0"
] | 18 | 2015-04-20T20:42:02.000Z | 2020-12-11T03:46:17.000Z | gamegio-library/src/gamegio/AngleCbor.hpp | tril0byte/HGamer3D | 7979c67d9b4672a5b2d1a50320a6d47b1a97ff05 | [
"Apache-2.0"
] | 4 | 2017-06-20T13:24:18.000Z | 2021-10-07T19:18:03.000Z | // HGamer3D Library (A project to enable 3D game development in Haskell)
// Copyright 2015 - 2018 Peter Althainz
//
// Distributed under the Apache License, Version 2.0
// (See attached file LICENSE or copy at
// http://www.apache.org/licenses/LICENSE-2.0)
//
// file: HGamer3D/gamegio-library/src/gamegio/AngelCbor.hpp
#ifndef __Angle_cbor__
#define __Angle_cbor__
#include <stdint.h>
#include <stdbool.h>
#include <string>
#include "cbor.h"
#include "cborconstants_p.h"
namespace cbd {
typedef enum {
Rad = 0,
Deg = 1,
} EnumAngle;
typedef struct {
EnumAngle selector;
struct {
struct {
float value0;
} Rad;
struct {
float value0;
} Deg;
} data;
} Angle;
void readAngle(CborValue *it0, Angle *angle);
void writeAngle(CborEncoder *enc0, Angle angle);
float getAngleAsRadians(cbd::Angle a);
} // end of namespacd cdb
#endif
| 19.76087 | 72 | 0.668867 | [
"3d"
] |
27909972fc3d3e929dfdac753deb048d548135f5 | 2,254 | cpp | C++ | test/cppunit/TapOutputter.cpp | tacr-iotcloud/base | caa10794b965c578f596d616e9654a6a8ef2c169 | [
"BSD-3-Clause"
] | null | null | null | test/cppunit/TapOutputter.cpp | tacr-iotcloud/base | caa10794b965c578f596d616e9654a6a8ef2c169 | [
"BSD-3-Clause"
] | null | null | null | test/cppunit/TapOutputter.cpp | tacr-iotcloud/base | caa10794b965c578f596d616e9654a6a8ef2c169 | [
"BSD-3-Clause"
] | 1 | 2019-01-08T14:48:29.000Z | 2019-01-08T14:48:29.000Z | #include <iostream>
#include <map>
#include <vector>
#include <cppunit/Exception.h>
#include <cppunit/Message.h>
#include <cppunit/SourceLine.h>
#include <cppunit/Test.h>
#include <cppunit/TestFailure.h>
#include <cppunit/TestResultCollector.h>
#include "cppunit/TapOutputter.h"
using namespace std;
using namespace CppUnit;
using namespace BeeeOn;
TapOutputter::TapOutputter(TestResultCollector *collector):
m_collector(collector),
m_output(cout)
{
}
TapOutputter::TapOutputter(
TestResultCollector *collector,
ostream &output):
m_collector(collector),
m_output(output)
{
}
void TapOutputter::skip(const string &name)
{
m_skip.emplace(name);
}
void TapOutputter::write()
{
map<Test *, vector<TestFailure *>> failures;
for (TestFailure *fail : m_collector->failures())
failures[fail->failedTest()].push_back(fail);
m_output << "1.." << m_collector->tests().size() << endl;
unsigned int id = 1;
for (Test *test : m_collector->tests()) {
auto it = failures.find(test);
if (it == failures.end())
reportSuccess(id++, test);
else
reportFailures(id++, test, it->second);
}
}
void TapOutputter::reportSuccess(unsigned int id, Test *test)
{
m_output << "ok " << id << " - " << test->getName() << endl;
}
void TapOutputter::reportFailures(unsigned int id, Test *test,
const vector<TestFailure *> &fails)
{
m_output << "not ok " << id << " - " << test->getName();
if (m_skip.find(test->getName()) != m_skip.end())
m_output << " # skip";
m_output << endl;
for (const TestFailure *fail : fails) {
const SourceLine &line = fail->sourceLine();
m_output << " ---" << endl;
if (!line.isValid()) {
m_output << " file: unknown" << endl;
m_output << " line: unknown" << endl;
}
else {
m_output << " file: '" << line.fileName() << "'" << endl;
m_output << " line: " << line.lineNumber() << endl;
}
if (fail->thrownException() != NULL)
reportException(fail->thrownException());
m_output << " ..." << endl;
}
}
void TapOutputter::reportException(const CppUnit::Exception *e)
{
const Message &m = e->message();
m_output << " message: '" << m.shortDescription() << "'" << endl;
for (int i = 0; i < m.detailCount(); ++i)
m_output << " detail: '" << m.detailAt(i) << "'" << endl;
}
| 22.098039 | 66 | 0.646406 | [
"vector"
] |
27952dcc6ff6c68d375e5c8fa8734e3219f7fd0e | 5,619 | hpp | C++ | include/object_detection_msgs/synchronized_object_publisher.hpp | yoshito-n-students/object_detection_msgs | fee93c0bdeb0c27f65ddf025264dc94c439244bf | [
"MIT"
] | null | null | null | include/object_detection_msgs/synchronized_object_publisher.hpp | yoshito-n-students/object_detection_msgs | fee93c0bdeb0c27f65ddf025264dc94c439244bf | [
"MIT"
] | null | null | null | include/object_detection_msgs/synchronized_object_publisher.hpp | yoshito-n-students/object_detection_msgs | fee93c0bdeb0c27f65ddf025264dc94c439244bf | [
"MIT"
] | null | null | null | #ifndef OBJECT_DETECTION_MSGS_SYNCHRONIZED_OBJECT_PUBLISHER_HPP
#define OBJECT_DETECTION_MSGS_SYNCHRONIZED_OBJECT_PUBLISHER_HPP
#include <iterator> // for std::back_inserter()
#include <vector>
#include <image_transport/image_transport.h>
#include <image_transport/subscriber.h>
#include <image_transport/transport_hints.h>
#include <nodelet/nodelet.h>
#include <object_detection_msgs/GetObjects.h>
#include <object_detection_msgs/Objects.h>
#include <object_detection_msgs/SetObjects.h>
#include <ros/publisher.h>
#include <ros/service_server.h>
#include <ros/subscriber.h>
#include <sensor_msgs/Image.h>
#include <xmlrpcpp/XmlRpcException.h>
#include <xmlrpcpp/XmlRpcValue.h>
#include <boost/range/algorithm/copy.hpp>
namespace object_detection_msgs {
class SynchronizedObjectPublisher : public nodelet::Nodelet {
public:
SynchronizedObjectPublisher() {}
virtual ~SynchronizedObjectPublisher() {}
private:
virtual void onInit() {
ros::NodeHandle &nh = getNodeHandle();
ros::NodeHandle &pnh = getPrivateNodeHandle();
// load params
const bool subscribe_image = pnh.param("subscribe_image", false);
const bool subscribe_objects = pnh.param("subscribe_objects", false);
objects_.names = pnh.param("names", std::vector<std::string>());
objects_.probabilities = pnh.param("probablities", std::vector<double>());
objects_.contours = contoursParam(pnh, "contours", std::vector<Points>());
// services for user-specified objects
get_server_ =
nh.advertiseService("get_objects", &SynchronizedObjectPublisher::getObjects, this);
set_server_ =
nh.advertiseService("set_objects", &SynchronizedObjectPublisher::setObjects, this);
// advertise synchronized objects
object_publisher_ = nh.advertise<Objects>("objects_out", 1, true);
// subscribe images and/or objects to be synchronized
if (subscribe_image) {
image_transport::ImageTransport it(nh);
static const image_transport::TransportHints default_hints;
image_subscriber_ =
it.subscribe("image_raw", 1, &SynchronizedObjectPublisher::publishObjects, this,
image_transport::TransportHints(default_hints.getTransport(),
default_hints.getRosHints(), pnh));
}
if (subscribe_objects) {
object_subscriber_ =
nh.subscribe("objects_in", 1, &SynchronizedObjectPublisher::mergeAndPublishObjects, this);
}
if (!subscribe_image && !subscribe_objects) {
NODELET_ERROR(
"Nothing subscribed. Either ~subscribe_image or ~subscribe_objects should be ture");
}
}
bool getObjects(GetObjects::Request & /* empty */, GetObjects::Response &response) {
response.objects = objects_;
return true;
}
bool setObjects(SetObjects::Request &request, SetObjects::Response & /* empty */) {
objects_ = request.objects;
return true;
}
void publishObjects(const sensor_msgs::ImageConstPtr &image_in) {
const ObjectsPtr objects_out(new Objects(objects_));
objects_out->header = image_in->header;
object_publisher_.publish(objects_out);
}
void mergeAndPublishObjects(const ObjectsConstPtr &objects_in) {
const ObjectsPtr objects_out(new Objects(*objects_in));
// complete target objects
{
const std::size_t max_size =
std::max(std::max(objects_out->names.size(), objects_out->probabilities.size()),
objects_out->contours.size());
objects_out->names.resize(max_size, "");
objects_out->probabilities.resize(max_size, -1.);
objects_out->contours.resize(max_size, Points());
}
// append user-specified to target objects
boost::copy(objects_.names, std::back_inserter(objects_out->names));
boost::copy(objects_.probabilities, std::back_inserter(objects_out->probabilities));
boost::copy(objects_.contours, std::back_inserter(objects_out->contours));
object_publisher_.publish(objects_out);
}
// utility function to load array of image points
// (this cannot be a static member function due to NODELET_XXX macros)
std::vector<Points> contoursParam(ros::NodeHandle &nh, const std::string &name,
const std::vector<Points> &default_val) {
// load a parameter tree
XmlRpc::XmlRpcValue contours_tree;
if (!nh.getParam(name, contours_tree)) {
return default_val;
}
// convert the parameter tree to value
std::vector<Points> contours;
try {
for (std::size_t i = 0; i < contours_tree.size(); ++i) {
XmlRpc::XmlRpcValue &points_tree(contours_tree[i]);
Points points;
for (std::size_t j = 0; j < points_tree.size(); ++j) {
XmlRpc::XmlRpcValue &point_tree(points_tree[j]);
Point point;
point.x = static_cast<int>(point_tree[0]);
point.y = static_cast<int>(point_tree[1]);
points.points.push_back(point);
}
contours.push_back(points);
}
} catch (const XmlRpc::XmlRpcException &error) {
NODELET_ERROR_STREAM("Error in parsing parameter " << nh.resolveName(name) << ": "
<< error.getMessage()
<< ". Will use the default value.");
return default_val;
}
return contours;
}
private:
Objects objects_;
image_transport::Subscriber image_subscriber_;
ros::Subscriber object_subscriber_;
ros::Publisher object_publisher_;
ros::ServiceServer get_server_, set_server_;
};
} // namespace object_detection_msgs
#endif | 36.487013 | 100 | 0.681972 | [
"vector"
] |
27bac2f69c78bbe5d08496cb0c557372bee883de | 1,948 | cpp | C++ | src/render/Camera.cpp | Streetwalrus/WalrusRPG | 53d88ef36ca1b2c169b5755dd95ac2c5626b91f5 | [
"MIT"
] | 12 | 2015-06-30T19:38:06.000Z | 2017-11-27T20:26:32.000Z | src/render/Camera.cpp | Pokespire/pokespire | 53d88ef36ca1b2c169b5755dd95ac2c5626b91f5 | [
"MIT"
] | 18 | 2015-06-26T01:44:48.000Z | 2016-07-01T16:26:17.000Z | src/render/Camera.cpp | Pokespire/pokespire | 53d88ef36ca1b2c169b5755dd95ac2c5626b91f5 | [
"MIT"
] | 1 | 2016-12-12T05:15:46.000Z | 2016-12-12T05:15:46.000Z | #include "Camera.h"
#include "input/Input.h"
#include "utility/misc.h"
using WalrusRPG::Camera;
using namespace WalrusRPG;
using WalrusRPG::Input::Key;
Camera::Camera(signed x, signed y)
: x(x), y(y), render_area_width(320), render_area_height(240)
{
}
Camera::~Camera()
{
// TODO if you allocate dynamically members
}
void Camera::update()
{
// TODO update map's data according to elasped time
/*
// Need to think aagain on how to go to a target point and/or we need to
align the corner OR the center to this point.
position += velocity * dt;
velocity += acceleration * dt;
*/
// if (Input::key_down(Key::K_DOWN))
// y++;
// if (Input::key_down(Key::K_UP))
// y--;
// if (Input::key_down(Key::K_RIGHT))
// x++;
// if (Input::key_down(Key::K_LEFT))
// x--;
}
void Camera::set_x(signed x)
{
this->x = x;
}
signed Camera::get_x() const
{
return this->x;
}
void Camera::set_y(signed y)
{
this->y = y;
}
signed Camera::get_y() const
{
return this->y;
}
void Camera::set_center_x(signed x)
{
this->x = x - render_area_width / 2;
}
signed Camera::get_center_x() const
{
return this->x - render_area_height / 2;
}
void Camera::set_center_y(signed y)
{
this->y = y - render_area_height / 2;
}
signed Camera::get_center_y() const
{
return this->y - render_area_height / 2;
}
bool Camera::is_visible(const WalrusRPG::Utils::Rect &object) const
{
if ((in_range(object.x, x, x + (signed) render_area_width) ||
in_range(object.x + (signed) object.width - 1, x,
x + (signed) render_area_width)) &&
(in_range(object.y, y, y + (signed) render_area_height) ||
in_range(object.y + (signed) object.height - 1, y,
y + (signed) render_area_height)))
{
return true;
}
else
{
return false;
}
}
| 20.291667 | 88 | 0.587782 | [
"object"
] |
27bd15aa4788673bb60dbb74b9ba7afcaf608682 | 3,203 | cpp | C++ | libs/ml/tests/ml/ops/graph.cpp | fetchai/ledger-archive | 69f4371541d9428780d4ed89fad5197ba7f69b6f | [
"Apache-2.0"
] | 3 | 2019-07-11T08:49:27.000Z | 2021-09-07T16:49:15.000Z | libs/ml/tests/ml/ops/graph.cpp | pbukva/ledger | 0afeb1582da6ddae07155878b6a0c109c7ab2680 | [
"Apache-2.0"
] | null | null | null | libs/ml/tests/ml/ops/graph.cpp | pbukva/ledger | 0afeb1582da6ddae07155878b6a0c109c7ab2680 | [
"Apache-2.0"
] | 2 | 2019-07-13T12:45:22.000Z | 2021-03-12T08:48:57.000Z | //------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "ml/graph.hpp"
#include "math/tensor.hpp"
#include "ml/ops/activations/relu.hpp"
#include "ml/ops/placeholder.hpp"
#include "ml/layers/self_attention.hpp"
#include <gtest/gtest.h>
using ArrayType = typename fetch::math::Tensor<int>;
TEST(graph_test, node_placeholder)
{
fetch::ml::Graph<ArrayType> g;
g.AddNode<fetch::ml::ops::PlaceHolder<ArrayType>>("Input", {});
ArrayType data(8);
ArrayType gt(8);
int i(0);
for (int e : {1, 2, 3, 4, 5, 6, 7, 8})
{
data.Set(std::uint64_t(i), e);
gt.Set(std::uint64_t(i), e);
i++;
}
g.SetInput("Input", data);
ArrayType prediction = g.Evaluate("Input");
// test correct values
ASSERT_TRUE(prediction.AllClose(gt));
}
TEST(graph_test, node_relu)
{
using SizeType = fetch::math::SizeType;
fetch::ml::Graph<ArrayType> g;
g.AddNode<fetch::ml::ops::PlaceHolder<ArrayType>>("Input", {});
g.AddNode<fetch::ml::ops::Relu<ArrayType>>("Relu", {"Input"});
ArrayType data(std::vector<typename ArrayType::SizeType>({4, 4}));
ArrayType gt(std::vector<typename ArrayType::SizeType>({4, 4}));
std::vector<int> dataValues({0, -1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, -13, 14, -15, 16});
std::vector<int> gtValues({0, 0, 2, 0, 4, 0, 6, 0, 8, 0, 10, 0, 12, 0, 14, 0, 16});
for (SizeType i(0); i < 4; ++i)
{
for (SizeType j(0); j < 4; ++j)
{
data.Set(i, j, dataValues[std::uint64_t(i * 4 + j)]);
gt.Set(i, j, gtValues[std::uint64_t(i * 4 + j)]);
}
}
g.SetInput("Input", data);
fetch::math::Tensor<int> prediction = g.Evaluate("Relu");
// test correct values
ASSERT_TRUE(prediction.AllClose(gt));
}
TEST(graph_test, getStateDict)
{
fetch::ml::Graph<fetch::math::Tensor<float>> g;
fetch::ml::StateDict<fetch::math::Tensor<float>> sd = g.StateDict();
EXPECT_EQ(sd.weights_, nullptr);
EXPECT_TRUE(sd.dict_.empty());
}
TEST(graph_test, no_such_node_test) // Use the class as a Node
{
fetch::ml::Graph<fetch::math::Tensor<float>> g;
g.template AddNode<fetch::ml::ops::PlaceHolder<fetch::math::Tensor<float>>>("Input", {});
g.template AddNode<fetch::ml::layers::SelfAttention<fetch::math::Tensor<float>>>(
"SelfAttention", {"Input"}, 50u, 42u, 10u);
fetch::math::Tensor<float> data(
std::vector<typename fetch::math::Tensor<float>::SizeType>({5, 10}));
g.SetInput("Input", data);
ASSERT_ANY_THROW(g.Evaluate("FullyConnected"));
}
| 31.401961 | 98 | 0.614736 | [
"vector"
] |
27ccf61618faf5236c7c8272df6fce110def3243 | 1,817 | cpp | C++ | cpp/godot-cpp/src/gen/PhysicsShapeQueryResult.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | 1 | 2021-03-16T09:51:00.000Z | 2021-03-16T09:51:00.000Z | cpp/godot-cpp/src/gen/PhysicsShapeQueryResult.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | cpp/godot-cpp/src/gen/PhysicsShapeQueryResult.cpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | #include "PhysicsShapeQueryResult.hpp"
#include <core/GodotGlobal.hpp>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include <core/Godot.hpp>
#include "__icalls.hpp"
#include "Object.hpp"
namespace godot {
PhysicsShapeQueryResult::___method_bindings PhysicsShapeQueryResult::___mb = {};
void PhysicsShapeQueryResult::___init_method_bindings() {
___mb.mb_get_result_count = godot::api->godot_method_bind_get_method("PhysicsShapeQueryResult", "get_result_count");
___mb.mb_get_result_object = godot::api->godot_method_bind_get_method("PhysicsShapeQueryResult", "get_result_object");
___mb.mb_get_result_object_id = godot::api->godot_method_bind_get_method("PhysicsShapeQueryResult", "get_result_object_id");
___mb.mb_get_result_object_shape = godot::api->godot_method_bind_get_method("PhysicsShapeQueryResult", "get_result_object_shape");
___mb.mb_get_result_rid = godot::api->godot_method_bind_get_method("PhysicsShapeQueryResult", "get_result_rid");
}
int64_t PhysicsShapeQueryResult::get_result_count() const {
return ___godot_icall_int(___mb.mb_get_result_count, (const Object *) this);
}
Object *PhysicsShapeQueryResult::get_result_object(const int64_t idx) const {
return (Object *) ___godot_icall_Object_int(___mb.mb_get_result_object, (const Object *) this, idx);
}
int64_t PhysicsShapeQueryResult::get_result_object_id(const int64_t idx) const {
return ___godot_icall_int_int(___mb.mb_get_result_object_id, (const Object *) this, idx);
}
int64_t PhysicsShapeQueryResult::get_result_object_shape(const int64_t idx) const {
return ___godot_icall_int_int(___mb.mb_get_result_object_shape, (const Object *) this, idx);
}
RID PhysicsShapeQueryResult::get_result_rid(const int64_t idx) const {
return ___godot_icall_RID_int(___mb.mb_get_result_rid, (const Object *) this, idx);
}
} | 37.854167 | 131 | 0.81508 | [
"object"
] |
27d192895c97400e164c84f9504bd6caddb54563 | 17,359 | cpp | C++ | src/renderPcFromPc.cpp | jstraub/cudaPcl | 10b61d66f83c664942f1e7b6ee574246df8d8922 | [
"MIT-feh"
] | 84 | 2015-04-05T16:17:11.000Z | 2022-01-27T13:40:51.000Z | src/renderPcFromPc.cpp | jstraub/cudaPcl | 10b61d66f83c664942f1e7b6ee574246df8d8922 | [
"MIT-feh"
] | 4 | 2016-03-31T02:35:08.000Z | 2019-03-04T06:50:53.000Z | src/renderPcFromPc.cpp | jstraub/cudaPcl | 10b61d66f83c664942f1e7b6ee574246df8d8922 | [
"MIT-feh"
] | 28 | 2015-06-19T18:11:19.000Z | 2021-05-02T08:21:22.000Z | /* Copyright (c) 2016, Julian Straub <jstraub@csail.mit.edu>
* Licensed under the MIT license. See the license file LICENSE.
*/
#include <iostream>
#include <sstream>
#include <sys/time.h>
//#include <random> // can only use with C++11
#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
#include <pcl/common/transforms.h>
#include <pcl/features/normal_3d.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include "cudaPcl/pinhole.h"
#include <boost/program_options.hpp>
#include <boost/random.hpp>
namespace po = boost::program_options;
using std::cout;
using std::endl;
#include <jsCore/timer.hpp>
float ToDeg(float rad) {
return rad*180./M_PI;
}
float ToRad(float deg) {
return deg/180.*M_PI;
}
double ToDeg(double rad) {
return rad*180./M_PI;
}
double ToRad(double deg) {
return deg/180.*M_PI;
}
Eigen::Vector3d ComputePcMean(pcl::PointCloud<pcl::PointXYZRGB>&
pc) {
// take 3 values (x,y,z of normal) with an offset of 4 values (x,y,z
// and one float which is undefined) and the step is 12 (4 for xyz, 4
// for normal xyz and 4 for curvature and rgb).
Eigen::MatrixXf xyz = pc.getMatrixXfMap(3, 8, 0); // this works for PointXYZRGB?
Eigen::Vector3d mean = Eigen::Vector3d::Zero();
for (size_t i=0; i<xyz.cols(); ++i) {
mean += xyz.col(i).cast<double>();
}
return mean / xyz.cols();
}
Eigen::Matrix3d ComputePcCov(pcl::PointCloud<pcl::PointXYZRGB>&
pc) {
// take 3 values (x,y,z of normal) with an offset of 4 values (x,y,z
// and one float which is undefined) and the step is 12 (4 for xyz, 4
// for normal xyz and 4 for curvature and rgb).
Eigen::MatrixXf xyz = pc.getMatrixXfMap(3, 8, 0); // this works for PointXYZRGB?
Eigen::Vector3d mean = ComputePcMean(pc);
Eigen::Matrix3d S = Eigen::Matrix3d::Zero();
for (size_t i=0; i<xyz.cols(); ++i) {
S += (xyz.col(i).cast<double>()-mean)*(xyz.col(i).cast<double>()-mean).transpose();
}
return S / (xyz.cols()-1);
}
void SampleTransformation(float angle, float translation,
Eigen::Matrix3f& R, Eigen::Vector3f& t) {
// Using boost here because C11 and CUDA seem to have troubles.
timeval tNow;
gettimeofday(&tNow, NULL);
boost::mt19937 gen(tNow.tv_usec);
boost::normal_distribution<> N(0,1);
// Sample axis of rotation:
Eigen::Vector3f axis(N(gen), N(gen), N(gen));
axis /= axis.norm();
// Construct rotation:
Eigen::AngleAxisf aa(ToRad(angle), axis);
Eigen::Quaternionf q(aa);
R = q.matrix();
// Sample translation on sphere with radius translation:
t = Eigen::Vector3f(N(gen), N(gen), N(gen));
t *= translation / t.norm();
// std::cout << "sampled random transformation:\n"
// << R << std::endl << t.transpose() << std::endl;
}
bool RenderPointCloudNoisy(const pcl::PointCloud<pcl::PointXYZRGBNormal>& pcIn,
const cudaPcl::Pinhole& c, pcl::PointCloud<pcl::PointXYZRGBNormal>&
pcOut, uint32_t nUpsample) {
// Transform both points by T as well as surface normals by R
// manually since the standard transformPointCloud does not seem to
// touch the Surface normals.
Eigen::MatrixXf d = 1e10*Eigen::MatrixXf::Ones(c.GetH(), c.GetW());
Eigen::MatrixXi id = Eigen::MatrixXi::Zero(c.GetH(), c.GetW());
uint32_t hits = 0;
for (uint32_t i=0; i<pcIn.size(); ++i) {
Eigen::Map<const Eigen::Vector3f> pA_W(&(pcIn.at(i).x));
Eigen::Vector3f p_W = pA_W;
Eigen::Vector3f p_C;
Eigen::Vector2i pI;
if (c.IsInImage(p_W, &p_C, &pI)) {
if (p_C(2) > 0. && d(pI(1),pI(0)) > p_C(2)) {
d(pI(1),pI(0)) = p_C(2);
id(pI(1),pI(0)) = i;
}
++hits;
}
}
// std::cout << " # hits: " << hits
// << " for total number of pixels in output camera: " << c.GetSize()
// << " percentage: " << (100.*hits/float(c.GetSize())) << std::endl;
timeval tNow;
gettimeofday(&tNow, NULL);
boost::mt19937 gen(tNow.tv_usec);
Eigen::Vector3f d_C;
d_C << 0.,0.,1.;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>);
uint32_t n_sampled = 0;
for (uint32_t i=0; i<c.GetW(); ++i)
for (uint32_t j=0; j<c.GetH(); ++j)
if (d(j,i) < 100.) {
// Eigen::Vector3f n_C = c.GetR_C_W() * Eigen::Map<const
// Eigen::Vector3f>(pcIn.at(id(j,i)).normal);
Eigen::Vector3f n_C = Eigen::Map<const
Eigen::Vector3f>(pcIn.at(id(j,i)).normal);
Eigen::Vector3f p_C = c.UnprojectToCameraCosy(i,j,d(j,i));
double dot = n_C.transpose()*d_C;
double theta = acos(std::min(std::max(dot, -1.),1.));
if (ToDeg(theta) < 80.) {
//http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6375037
double sig_L = (0.8+0.035*theta/(M_PI*0.5-theta))* p_C(2)/c.GetF();
double sig_z =0.0012 + 0.0019*(p_C(2)-0.4)*(p_C(2)-0.4);
if (ToDeg(theta) > 60.) {
sig_z += 0.0001/sqrt(p_C(2))*theta*theta/((M_PI*0.5-theta)
*(M_PI*0.5-theta));
}
// std::cout << sig_L << " " << sig_z << std::endl;
boost::normal_distribution<> N_L(0,sig_L);
boost::normal_distribution<> N_z(0,sig_z);
for (uint32_t k=0; k< nUpsample; ++k) {
pcl::PointXYZRGB pB;
pB.rgb = pcIn.at(id(j,i)).rgb;
Eigen::Map<Eigen::Vector3f> p_Cout(&(pB.x));
p_Cout = p_C;
// if (i%10==0) std::cout << p_Cout.transpose() << " ";
p_Cout(0) += N_L(gen);
p_Cout(1) += N_L(gen);
p_Cout(2) += N_z(gen);
// if (p_Cout.norm() > 10.)
// if (i%10==0)
// std::cout << p_Cout.transpose() << " " << sig_z << " " << sig_L
// << " " << ToDeg(theta) << std::endl;
cloud->push_back(pB);
++n_sampled;
}
} else {
pcl::PointXYZRGB pB;
pB.rgb = pcIn.at(id(j,i)).rgb;
Eigen::Map<Eigen::Vector3f>(&(pB.x)) = p_C;
cloud->push_back(pB);
}
}
if (cloud->size() < pcIn.size()/10) return false;
std::cout << " output pointcloud size is: " << pcOut.size()
<< " percentage of input cloud: "
<< (100.*pcOut.size()/float(pcIn.size()))
<< " sampled at total of " << 100.*n_sampled/float(pcOut.size()) << "%."<< std::endl;
pcl::StatisticalOutlierRemoval<pcl::PointXYZRGB> sor;
sor.setInputCloud (cloud);
sor.setMeanK (50);
sor.setStddevMulThresh (1.0);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_f(new pcl::PointCloud<pcl::PointXYZRGB>);
sor.filter (*cloud_f);
// Eigen::Matrix3d S = ComputePcCov(*cloud_f);
// Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(S);
// std::cout << eig.eigenvalues().array().sqrt().matrix().transpose() << std::endl;
// if (!(eig.eigenvalues().array().sqrt() > 0.10).all())
// return false;
// Extract surface normals
pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne;
ne.setInputCloud (cloud_f);
pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB> ());
ne.setSearchMethod (tree);
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals (new pcl::PointCloud<pcl::Normal>);
ne.setKSearch(100);
ne.compute (*cloud_normals);
pcOut.clear();
for (uint32_t i=0; i<cloud_f->size(); ++i) {
pcl:: PointXYZRGBNormal p;
Eigen::Map<Eigen::Vector3f>(p.normal) =
Eigen::Map<Eigen::Vector3f>(cloud_normals->at(i).normal);
Eigen::Map<Eigen::Vector3f>(&(p.x)) = Eigen::Map<Eigen::Vector3f>(&(cloud_f->at(i).x));
p.rgb = cloud_f->at(i).rgb;
pcOut.push_back(p);
}
return true;
}
bool RenderPointCloud(const pcl::PointCloud<pcl::PointXYZRGBNormal>& pcIn,
const cudaPcl::Pinhole& c, pcl::PointCloud<pcl::PointXYZRGBNormal>&
pcOut) {
// Transform both points by T as well as surface normals by R
// manually since the standard transformPointCloud does not seem to
// touch the Surface normals.
Eigen::MatrixXf d = 1e10*Eigen::MatrixXf::Ones(c.GetH(), c.GetW());
Eigen::MatrixXi id = Eigen::MatrixXi::Zero(c.GetH(), c.GetW());
uint32_t hits = 0;
for (uint32_t i=0; i<pcIn.size(); ++i) {
Eigen::Map<const Eigen::Vector3f> pA_W(&(pcIn.at(i).x));
Eigen::Vector3f p_W = pA_W;
Eigen::Vector3f p_C;
Eigen::Vector2i pI;
if (c.IsInImage(p_W, &p_C, &pI)) {
if (d(pI(1),pI(0)) > p_C(2)) {
d(pI(1),pI(0)) = p_C(2);
id(pI(1),pI(0)) = i;
}
++hits;
}
}
// std::cout << " # hits: " << hits
// << " for total number of pixels in output camera: " << c.GetSize()
// << " percentage: " << (100.*hits/float(c.GetSize())) << std::endl;
pcOut.clear();
for (uint32_t i=0; i<c.GetW(); ++i)
for (uint32_t j=0; j<c.GetH(); ++j)
if (d(j,i) < 100.) {
pcl::PointXYZRGBNormal pB;
Eigen::Map<Eigen::Vector3f> p_C(&(pB.x));
p_C = c.UnprojectToCameraCosy(i,j,d(j,i));
Eigen::Map<Eigen::Vector3f>(pB.normal) =
c.GetR_C_W() * Eigen::Map<const
Eigen::Vector3f>(pcIn.at(id(j,i)).normal);
pB.rgb = pcIn.at(id(j,i)).rgb;
pcOut.push_back(pB);
}
// std::cout << " output pointcloud size is: " << pcOut.size()
// << " percentage of input cloud: "
// << (100.*pcOut.size()/float(pcIn.size())) << std::endl;
return pcOut.size() > (pcIn.size()/10);
}
uint32_t VisiblePointsOfPcInCam(const
pcl::PointCloud<pcl::PointXYZRGBNormal>& pc,
const Eigen::Matrix3f& R_PC_W, const Eigen::Vector3f& t_PC_W, const
cudaPcl::Pinhole& c) {
uint32_t hits =0;
for (uint32_t i=0; i<pc.size(); ++i) {
Eigen::Vector3f p_PC = Eigen::Map<const Eigen::Vector3f> (&(pc.at(i).x));
Eigen::Vector3f p_W = R_PC_W.transpose() * (p_PC - t_PC_W);
if (c.IsInImage(p_W, NULL, NULL)) {
++hits;
}
}
return hits;
}
int main (int argc, char** argv)
{
// Declare the supported options.
po::options_description desc("Render a point cloud from a different pose.");
desc.add_options()
("help,h", "produce help message")
("input,i", po::value<string>(),"path to input point cloud")
("output,o", po::value<string>(),"path to output transformed point cloud")
("angle,a", po::value<double>(),"magnitude of rotation (deg)")
("translation,t", po::value<double>(),"magnitude of translation (m)")
("min,m", po::value<double>(),"minimum overlap to be accepted (%)")
("local,l", "simulate local alignment problem i.e. do not transform the pointclouds by a random transformation")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
double angle = 10.; // In degree
double translation = 1.0;
double min_overlap = 50.;
string inputPath = "./file.ply";
string outputPath = "./out";
if(vm.count("input")) inputPath = vm["input"].as<string>();
if(vm.count("output")) outputPath = vm["output"].as<string>();
if(vm.count("angle")) angle = vm["angle"].as<double>();
if(vm.count("min")) min_overlap = vm["min"].as<double>();
if(vm.count("translation")) translation = vm["translation"].as<double>();
std::stringstream ssOutPathA;
std::stringstream ssOutPathB;
std::stringstream ssTransformationAFile;
std::stringstream ssTransformationBFile;
std::stringstream ssTransformationTotalFile;
ssOutPathA << outputPath << "_A_angle_" << angle << "_translation_" <<
translation << ".ply";
ssOutPathB << outputPath << "_B_angle_" << angle << "_translation_" <<
translation << ".ply";
ssTransformationAFile << outputPath << "_angle_" << angle <<
"_translation_" << translation << "_Transformation_A_W" << ".csv";
ssTransformationBFile << outputPath << "_angle_" << angle <<
"_translation_" << translation << "_Transformation_B_W" << ".csv";
ssTransformationTotalFile << outputPath << "_angle_" << angle <<
"_translation_" << translation << "_TrueTransformation" << ".csv";
std::string outputPathA = ssOutPathA.str();
std::string outputPathB = ssOutPathB.str();
std::string transformationAOutputPath= ssTransformationAFile.str();
std::string transformationBOutputPath= ssTransformationBFile.str();
std::string transformationTotalOutputPath = ssTransformationTotalFile.str();
// Load point cloud.
pcl::PointCloud<pcl::PointXYZRGBNormal> pcIn, pcOutA, pcOutB;
pcl::PLYReader reader;
int err = reader.read(inputPath, pcIn);
if (err) {
std::cout << "error reading " << inputPath << std::endl;
return err;
} else {
std::cout << "loaded pc from " << inputPath << ": " << pcIn.width << "x"
<< pcIn.height << std::endl;
}
std::cout<< " input pointcloud from "<<inputPath<<std::endl;
std::cout<< " angular magnitude "<< angle <<std::endl;
std::cout<< " translational magnitude "<< translation <<std::endl;
uint32_t w = 320;
uint32_t h = 280;
float f = 540.;
Eigen::Matrix3f R_A_W, R_B_W;
Eigen::Vector3f t_A_W, t_B_W;
bool succA = false;
bool succB = false;
double overlap = 0.;
uint32_t attemptsOuter = 0;
uint32_t attempts = 0;
do {
overlap = 0.;
attempts = 0;
do {
// sample pc A
R_A_W = Eigen::Matrix3f::Identity();
t_A_W = Eigen::Vector3f::Zero();
// SampleTransformation(angle, translation, R_A_W, t_A_W);
cudaPcl::Pinhole camA(R_A_W, t_A_W, f, w, h);
if (!RenderPointCloud(pcIn, camA, pcOutA))
continue;
// sample pc B
SampleTransformation(angle, translation, R_B_W, t_B_W);
cudaPcl::Pinhole camB(R_B_W, t_B_W, f, w, h);
if (!RenderPointCloud(pcIn, camB, pcOutB))
continue;
uint32_t hitsAinB = VisiblePointsOfPcInCam(pcOutA, R_A_W, t_A_W, camB);
uint32_t hitsBinA = VisiblePointsOfPcInCam(pcOutB, R_B_W, t_B_W, camA);
overlap = std::min(100*hitsAinB/float(pcOutA.size()),
100*hitsBinA/float(pcOutB.size()));
++ attempts;
if (attempts%20 == 0) {
std::cout << ".";
std::cout.flush();
}
} while(overlap < min_overlap && attempts < 1000);
std::cout << std::endl;
std::cout << "overlap: " << overlap
<< "% attempt: " << attempts<< std::endl;
if (attempts >= 1000) return 1;
// Now sample point clouds from those views.
cudaPcl::Pinhole camA(R_A_W, t_A_W, f, w, h);
succA = RenderPointCloudNoisy(pcIn, camA, pcOutA, 2);
cudaPcl::Pinhole camB(R_B_W, t_B_W, f, w, h);
succB = RenderPointCloudNoisy(pcIn, camB, pcOutB, 2);
} while ((!succA || !succB) && attemptsOuter < 100);
{
Eigen::Quaternionf q(R_A_W);
Eigen::Vector3f t = t_A_W;
std::ofstream out(transformationAOutputPath.c_str());
out << "q_w q_x q_y q_z t_x t_y t_z size" << std::endl;
out << q.w() << " " << q.x() << " " << q.y() << " " << q.z() << " "
<< t(0) << " " << t(1) << " " << t(2) << " "
<< " " << pcOutA.size();
out.close();
}
{
Eigen::Quaternionf q(R_B_W);
Eigen::Vector3f t = t_B_W;
std::ofstream out(transformationBOutputPath.c_str());
out << "q_w q_x q_y q_z t_x t_y t_z size" << std::endl;
out << q.w() << " " << q.x() << " " << q.y() << " " << q.z() << " "
<< t(0) << " " << t(1) << " " << t(2) << " "
<< " " << pcOutB.size();
out.close();
}
// If we want to simulate a global alignment problem sample another
// intermediate random transformation and apply it to pointcloud B as
// well as the global true transformation.
if(!vm.count("local")) {
// Now sample another transformation of the same parameters to
// transform pcB
Eigen::Matrix3f R_B_B;
Eigen::Vector3f t_B_B;
SampleTransformation(angle, translation, R_B_B, t_B_B);
// Transform pc B
for (uint32_t i=0; i<pcOutB.size(); ++i) {
Eigen::Map<Eigen::Vector3f> p(&(pcOutB.at(i).x));
p = R_B_B * p + t_B_B;
Eigen::Map<Eigen::Vector3f> n(pcOutB.at(i).normal);
n = R_B_B*n;
}
// chain the new transformation into the global transformation.
R_B_W = R_B_B*R_B_W;
t_B_W = R_B_B*t_B_W + t_B_B;
}
// Write the Point clouds to files.
pcl::PLYWriter writer;
writer.write(outputPathA, pcOutA, false, false);
writer.write(outputPathB, pcOutB, false, false);
// Compute the final relative transformation between the PCs in the
// as they are saved to file. This is the transformation that any
// alignment algorithm needs to find.
Eigen::Matrix3f R_B_A = R_B_W * R_A_W.transpose();
Eigen::Vector3f t_B_A = - R_B_W * R_A_W.transpose() * t_A_W + t_B_W;
Eigen::Quaternionf q(R_B_A);
Eigen::Vector3f t = t_B_A;
std::cout << "magnitude of rotation: " << ToDeg(acos(q.w())*2.)
<< " magnitude of translation: " << t_B_A.norm() << std::endl;
std::ofstream out(transformationTotalOutputPath.c_str());
out << "q_w q_x q_y q_z t_x t_y t_z overlap sizeA sizeB" << std::endl;
out << q.w() << " " << q.x() << " " << q.y() << " " << q.z() << " "
<< t(0) << " " << t(1) << " " << t(2) << " "
<< overlap << " " << pcOutA.size() << " " << pcOutB.size();
out.close();
std::cout<< " output to "<<outputPathA<<std::endl << " and to " << outputPathB << std::endl;
std::cout<< " sampled total transformation to " << transformationTotalOutputPath << std::endl;
std::cout<< " sampled transformation of rendering T_A_W to "
<< transformationAOutputPath << std::endl;
std::cout<< " sampled transformation of rendering T_B_W to "
<< transformationBOutputPath << std::endl;
return 0;
}
| 37.573593 | 116 | 0.608733 | [
"render",
"transform"
] |
27d29ebed23122f6e5d128c626748832a4246750 | 1,188 | cpp | C++ | Windows.cpp | m-j-andr/Audio-Library | 493d5d908bd5811b9306e695d37ddf27661d0a31 | [
"MIT"
] | null | null | null | Windows.cpp | m-j-andr/Audio-Library | 493d5d908bd5811b9306e695d37ddf27661d0a31 | [
"MIT"
] | null | null | null | Windows.cpp | m-j-andr/Audio-Library | 493d5d908bd5811b9306e695d37ddf27661d0a31 | [
"MIT"
] | null | null | null | //
// Windows.cpp
// AAC Compression - Rework
//
// Created by Michael Andrews on 4/4/19.
// Copyright © 2019 Michael Andrews. All rights reserved.
//
#include "Windows.hpp"
std::vector<double> sine(size_t N) {
std::vector<double> w(N);
for (size_t n=0; n<N; ++n) {
w[n] = sin(acos(-1) * (n + 0.5) / N);
}
return w;
}
std::vector<double> Hann(size_t N) {
std::vector<double> w(N);
for (size_t n=0; n<N; ++n) {
w[n] = 0.5 - 0.5 * cos( 2 * acos(-1) * (n + 0.5) / N );
}
return w;
}
std::vector<double> derived_Hann(size_t N) {
assert(N%2 == 0);
return derive(Hann(N/2 + 1));
}
std::vector<double> derive(std::vector<double> window) {
double integral = 0;
for (double& val:window) { integral += val; }
for (double& val:window) { val /= integral; }
size_t N = window.size()-1;
std::vector<double> derived_w(2*N);
integral = 0;
for (size_t n=0; n<N; ++n) {
integral += window[n];
derived_w[n] = sqrt(integral);
}
integral = 0;
for (size_t n=0; n<N; ++n) {
integral += window[N-n];
derived_w[2*N-1-n] = sqrt(integral);
}
return derived_w;
}
| 23.76 | 63 | 0.539562 | [
"vector"
] |
27daca3282f492d162309ed96cefa8a5c6ff0e21 | 1,799 | cc | C++ | chromecast/system/reboot/reboot_fuchsia.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromecast/system/reboot/reboot_fuchsia.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chromecast/system/reboot/reboot_fuchsia.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 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 <fuchsia/hardware/power/statecontrol/cpp/fidl.h>
#include <lib/sys/cpp/component_context.h>
#include "base/fuchsia/default_context.h"
#include "base/fuchsia/fuchsia_logging.h"
#include "base/no_destructor.h"
#include "chromecast/public/reboot_shlib.h"
using fuchsia::hardware::power::statecontrol::Admin_Suspend_Result;
using fuchsia::hardware::power::statecontrol::AdminSyncPtr;
using fuchsia::hardware::power::statecontrol::SystemPowerState;
namespace chromecast {
// RebootShlib implementation:
AdminSyncPtr& GetAdminSyncPtr() {
static base::NoDestructor<AdminSyncPtr> g_admin;
return *g_admin;
}
// static
void RebootShlib::Initialize(const std::vector<std::string>& argv) {
base::fuchsia::ComponentContextForCurrentProcess()->svc()->Connect(
GetAdminSyncPtr().NewRequest());
}
// static
void RebootShlib::Finalize() {}
// static
bool RebootShlib::IsSupported() {
return true;
}
// static
bool RebootShlib::IsRebootSourceSupported(
RebootShlib::RebootSource /* reboot_source */) {
return true;
}
// static
bool RebootShlib::RebootNow(RebootSource reboot_source) {
Admin_Suspend_Result out_result;
zx_status_t status =
GetAdminSyncPtr()->Suspend(SystemPowerState::REBOOT, &out_result);
ZX_CHECK(status == ZX_OK, status) << "Failed to suspend device";
return !out_result.is_err();
}
// static
bool RebootShlib::IsFdrForNextRebootSupported() {
return false;
}
// static
void RebootShlib::SetFdrForNextReboot() {}
// static
bool RebootShlib::IsOtaForNextRebootSupported() {
return false;
}
// static
void RebootShlib::SetOtaForNextReboot() {}
} // namespace chromecast
| 24.643836 | 73 | 0.754864 | [
"vector"
] |
27dbe715f8a817ed4b3b14a31a2425a2df1623d3 | 2,800 | cpp | C++ | http_json/main.cpp | dtoma/cpp | 1c6c726071092d9e238c6fb3de22fed833a148b2 | [
"MIT"
] | null | null | null | http_json/main.cpp | dtoma/cpp | 1c6c726071092d9e238c6fb3de22fed833a148b2 | [
"MIT"
] | null | null | null | http_json/main.cpp | dtoma/cpp | 1c6c726071092d9e238c6fb3de22fed833a148b2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
/* Metaprogramming library, enables us to iterate over structure members. */
#include <boost/hana.hpp>
namespace hana = boost::hana;
/* Create and manipulate JSON objects. */
#include <nlohmann/json.hpp>
using json = nlohmann::json;
/* This function recursively visits a structure, converting its members to JSON values. */
template <typename T>
std::enable_if_t<hana::Struct<T>::value, json> to_json(T const &object)
{
json j;
hana::for_each(
hana::keys(object),
[&](auto name) {
auto member = hana::at_key(object, name);
auto const *name_str = hana::to<char const *>(name);
auto constexpr is_struct = hana::trait<hana::Struct>(hana::typeid_(member));
if constexpr (is_struct)
{
j[name_str] = to_json(member);
}
else
{
j[name_str] = member;
}
});
return j;
}
/* This function recursively visits a structure, setting its members from JSON values. */
template <typename T>
std::enable_if_t<hana::Struct<T>::value, T> from_json(json const &j)
{
T result;
hana::for_each(
hana::keys(result),
[&](auto name) {
auto &member = hana::at_key(result, name);
auto const *name_str = hana::to<char const *>(name);
auto is_struct = hana::trait<hana::Struct>(hana::typeid_(member));
using member_t = std::remove_reference_t<decltype(member)>;
if constexpr (is_struct)
{
member = from_json<member_t>(j[name_str]);
}
else
{
member = j[name_str];
}
});
return result;
}
/* We define two structures, one includes the other. */
struct Car
{
BOOST_HANA_DEFINE_STRUCT(Car,
(std::string, brand),
(std::string, model));
};
struct Person
{
BOOST_HANA_DEFINE_STRUCT(Person,
(std::string, name),
(Car, car));
};
int main()
{
Car c{"Audi", "A4"};
Person p{"Foo", c};
json expected = {
{"name", "Foo"},
{"car", {{"brand", "Audi"}, {"model", "A4"}}},
};
/* Serialize */
json j = to_json(p);
assert(j == expected);
std::cout << j << std::endl; /* {"car":{"brand":"Audi","model":"A4"},"name":"Foo"} */
/* Deserialize */
auto c2 = from_json<Car>(json{
{"brand", "Audi"},
{"model", "A4"}});
assert(c2.brand == c.brand);
assert(c2.model == c.model);
auto p2 = from_json<Person>(expected);
assert(p2.name == p.name);
assert(p2.car.brand == c.brand);
assert(p2.car.model == c.model);
}
| 23.728814 | 90 | 0.53 | [
"object",
"model"
] |
27dd8d11b49e7f9a2cfbfd5c96ff0809737533b8 | 8,904 | hpp | C++ | include/robot_fingers/trifinger_platform_frontend.hpp | open-dynamic-robot-initiative/robot_fingers | d186117dd1a1d7dcd7d38ae8fc847a972db24629 | [
"BSD-3-Clause"
] | 32 | 2020-06-20T15:23:16.000Z | 2022-01-02T00:21:40.000Z | include/robot_fingers/trifinger_platform_frontend.hpp | open-dynamic-robot-initiative/robot_fingers | d186117dd1a1d7dcd7d38ae8fc847a972db24629 | [
"BSD-3-Clause"
] | 13 | 2020-03-02T10:54:19.000Z | 2021-03-30T14:15:29.000Z | include/robot_fingers/trifinger_platform_frontend.hpp | open-dynamic-robot-initiative/robot_fingers | d186117dd1a1d7dcd7d38ae8fc847a972db24629 | [
"BSD-3-Clause"
] | 9 | 2020-08-12T09:29:17.000Z | 2021-11-27T13:04:16.000Z | /**
* @file
* @brief Combined frontend for the TriFinger Platform
* @copyright 2020, Max Planck Gesellschaft. All rights reserved.
* @license BSD 3-clause
*/
#pragma once
#include <robot_interfaces/finger_types.hpp>
#include <robot_interfaces/sensors/sensor_frontend.hpp>
#include <trifinger_cameras/tricamera_observation.hpp>
#include <trifinger_object_tracking/tricamera_object_observation.hpp>
namespace robot_fingers
{
/**
* @brief Combined frontend for the TriFinger Platform
*
* This class combines the frontends for robot and cameras in one class using
* unified time indices.
*
* Internally the different frontends all have their own time indices which are
* unrelated to each other. In this combined class, the time index used is the
* one that belongs to the robot frontend. When accessing observations of the
* other frontends, it also takes this index t and internally matches it to the
* time index t_o that was active in the other frontend at the time of t.
*
* @todo Methods to get timestamp from camera or object tracker?
*/
template <typename CameraObservation_t>
class T_TriFingerPlatformFrontend
{
public:
// typedefs for easy access
typedef robot_interfaces::TriFingerTypes::Action Action;
typedef robot_interfaces::TriFingerTypes::Observation RobotObservation;
typedef robot_interfaces::Status RobotStatus;
// typedef trifinger_object_tracking::TriCameraObjectObservation
// CameraObservation;
typedef CameraObservation_t CameraObservation;
/**
* @brief Initialize with data instances for all internal frontends.
*
* @param robot_data RobotData instance used by the robot frontend.
* @param object_tracker_data ObjectTrackerData instance used by the object
* tracker frontend.
* @param camera_data SensorData instance, used by the camera frontend.
*/
T_TriFingerPlatformFrontend(
robot_interfaces::TriFingerTypes::BaseDataPtr robot_data,
std::shared_ptr<robot_interfaces::SensorData<CameraObservation>>
camera_data)
: robot_frontend_(robot_data), camera_frontend_(camera_data)
{
}
/**
* @brief Initialize with default data instances.
*
* Creates for each internal frontend a corresponding mutli-process data
* instance with the default shared memory ID for the corresponding data
* type.
*/
T_TriFingerPlatformFrontend()
: robot_frontend_(std::make_shared<
robot_interfaces::TriFingerTypes::MultiProcessData>(
"trifinger", false)),
camera_frontend_(
std::make_shared<
robot_interfaces::MultiProcessSensorData<CameraObservation>>(
"tricamera", false))
{
}
/**
* @brief Append a desired robot action to the action queue.
* @see robot_interfaces::TriFingerTypes::Frontend::append_desired_action
*
* @return The index of the time step at which this action is going to be
* executed.
*/
time_series::Index append_desired_action(const Action &desired_action)
{
return robot_frontend_.append_desired_action(desired_action);
}
/**
* @brief Get robot observation of the time step t.
* @see robot_interfaces::TriFingerTypes::Frontend::get_observation
*/
RobotObservation get_robot_observation(const time_series::Index &t) const
{
return robot_frontend_.get_observation(t);
}
/**
* @brief Get desired action of time step t.
* @see robot_interfaces::TriFingerTypes::Frontend::get_desired_action
*/
Action get_desired_action(const time_series::Index &t) const
{
return robot_frontend_.get_desired_action(t);
}
/**
* @brief Get actually applied action of time step t.
* @see robot_interfaces::TriFingerTypes::Frontend::get_applied_action
*/
Action get_applied_action(const time_series::Index &t) const
{
return robot_frontend_.get_applied_action(t);
}
/**
* @brief Get robot status of time step t.
* @see robot_interfaces::TriFingerTypes::Frontend::get_status
*/
RobotStatus get_robot_status(const time_series::Index &t) const
{
return robot_frontend_.get_status(t);
}
/**
* @brief Get timestamp (in milliseconds) of time step t.
* @see robot_interfaces::TriFingerTypes::Frontend::get_timestamp_ms
*/
time_series::Timestamp get_timestamp_ms(const time_series::Index &t) const
{
return robot_frontend_.get_timestamp_ms(t);
}
/**
* @brief Get the current time index.
* @see robot_interfaces::TriFingerTypes::Frontend::get_current_timeindex
*/
time_series::Index get_current_timeindex() const
{
return robot_frontend_.get_current_timeindex();
}
/**
* @brief Wait until time step t.
* @see robot_interfaces::TriFingerTypes::Frontend::wait_until_timeindex
*/
void wait_until_timeindex(const time_series::Index &t) const
{
robot_frontend_.wait_until_timeindex(t);
}
/**
* @brief Get camera images of time step t.
*
* @param t Time index of the robot time series. This is internally
* mapped to the corresponding time index of the camera time series.
*
* @return Camera images of time step t.
*/
CameraObservation get_camera_observation(const time_series::Index t) const
{
auto t_camera = find_matching_timeindex(camera_frontend_, t);
return camera_frontend_.get_observation(t_camera);
}
private:
robot_interfaces::TriFingerTypes::Frontend robot_frontend_;
robot_interfaces::SensorFrontend<CameraObservation> camera_frontend_;
/**
* @brief Find time index of frontend that matches with the given robot time
* index.
*
* The given time index t_robot refers to the robot data time series. To
* provide the correct observation from the other frontend for this time
* step, find the highest time index t_other of the other frontend where
*
* timestamp(t_other) <= timestamp(t_robot)
*
* Note that this is not always the one that is closest w.r.t. to the
* timestamp, i.e.
*
* t_other != argmin(|timestamp(t_other) - timestamp(t_robot)|)
*
* The latter would not be deterministic: the outcome could change when
* called twice with the same `t_robot` if a new "other" observation
* arrived in between the calls.
*
* @todo The implementation below is very naive.
* It simply does a linear search starting from the latest time index.
* So worst case performance is O(n) where n is the number of "other"
* observations over the period that is covered by the buffer of the
* robot data.
*
* Options to speed this up:
* - binary search (?)
* - estimate time step size based on last observations
* - store matched indices of last call
*
* Note, however, that `t_robot` is very likely the latest time index
* in most cases. In this case the match for `t_other` will also be
* the latest index of the corresponding time series. In this case,
* the complexity is O(1). So even when implementing a more complex
* search algorithm, the first candidate for `t_other` that is checked
* should always be the latest one.
*
* @tparam FrontendType Type of the frontend. This is templated so that the
* same implementation can be used for both camera and object tracker
* frontend.
* @param other_frontend The frontend for which a matching time index needs
* to be found.
* @param t_robot Time index of the robot frontend.
*
* @return Time index for other_frontend which is/was active at the time of
* t_robot.
*/
template <typename FrontendType>
time_series::Index find_matching_timeindex(
const FrontendType &other_frontend,
const time_series::Index t_robot) const
{
time_series::Timestamp stamp_robot = get_timestamp_ms(t_robot);
time_series::Index t_other = other_frontend.get_current_timeindex();
time_series::Timestamp stamp_other =
other_frontend.get_timestamp_ms(t_other);
while (stamp_robot < stamp_other)
{
t_other--;
stamp_other = other_frontend.get_timestamp_ms(t_other);
}
return t_other;
}
};
// typedefs for easier use
typedef T_TriFingerPlatformFrontend<
trifinger_object_tracking::TriCameraObjectObservation>
TriFingerPlatformWithObjectFrontend;
typedef T_TriFingerPlatformFrontend<
trifinger_cameras::TriCameraObservation>
TriFingerPlatformFrontend;
} // namespace robot_fingers
| 36.195122 | 80 | 0.683738 | [
"object"
] |
27dea766dae8962a776fbf6d0c4ce1c77ab62066 | 24,112 | cxx | C++ | pkgs/tools/cmake/src/Source/cmGlobalVisualStudio7Generator.cxx | relokin/parsec | 75d63d9bd2368913343be9037e301947ecf78f7f | [
"BSD-3-Clause"
] | 2 | 2017-04-24T22:37:28.000Z | 2020-05-26T01:57:37.000Z | pkgs/tools/cmake/src/Source/cmGlobalVisualStudio7Generator.cxx | cota/parsec2-aarch64 | cdf7da348afd231dbe067266f24dc14d22f5cebf | [
"BSD-3-Clause"
] | null | null | null | pkgs/tools/cmake/src/Source/cmGlobalVisualStudio7Generator.cxx | cota/parsec2-aarch64 | cdf7da348afd231dbe067266f24dc14d22f5cebf | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: CMake - Cross-Platform Makefile Generator
Module: $RCSfile: cmGlobalVisualStudio7Generator.cxx,v $
Language: C++
Date: $Date: 2008-05-01 16:35:39 $
Version: $Revision: 1.99.2.1 $
Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
See Copyright.txt or http://www.cmake.org/HTML/Copyright.html 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.
=========================================================================*/
#include "windows.h" // this must be first to define GetCurrentDirectory
#include "cmGlobalVisualStudio7Generator.h"
#include "cmGeneratedFileStream.h"
#include "cmLocalVisualStudio7Generator.h"
#include "cmMakefile.h"
#include "cmake.h"
cmGlobalVisualStudio7Generator::cmGlobalVisualStudio7Generator()
{
this->FindMakeProgramFile = "CMakeVS7FindMake.cmake";
}
void cmGlobalVisualStudio7Generator
::EnableLanguage(std::vector<std::string>const & lang,
cmMakefile *mf, bool optional)
{
mf->AddDefinition("CMAKE_GENERATOR_CC", "cl");
mf->AddDefinition("CMAKE_GENERATOR_CXX", "cl");
mf->AddDefinition("CMAKE_GENERATOR_RC", "rc");
mf->AddDefinition("CMAKE_GENERATOR_NO_COMPILER_ENV", "1");
mf->AddDefinition("CMAKE_GENERATOR_FC", "ifort");
this->AddPlatformDefinitions(mf);
// Create list of configurations requested by user's cache, if any.
this->cmGlobalGenerator::EnableLanguage(lang, mf, optional);
this->GenerateConfigurations(mf);
// if this environment variable is set, then copy it to
// a static cache entry. It will be used by
// cmLocalGenerator::ConstructScript, to add an extra PATH
// to all custom commands. This is because the VS IDE
// does not use the environment it is run in, and this allows
// for running commands and using dll's that the IDE environment
// does not know about.
const char* extraPath = cmSystemTools::GetEnv("CMAKE_MSVCIDE_RUN_PATH");
if(extraPath)
{
mf->AddCacheDefinition
("CMAKE_MSVCIDE_RUN_PATH", extraPath,
"Saved environment variable CMAKE_MSVCIDE_RUN_PATH",
cmCacheManager::STATIC);
}
}
void cmGlobalVisualStudio7Generator::AddPlatformDefinitions(cmMakefile* mf)
{
mf->AddDefinition("MSVC70", "1");
}
std::string cmGlobalVisualStudio7Generator
::GenerateBuildCommand(const char* makeProgram,
const char *projectName,
const char* additionalOptions, const char *targetName,
const char* config, bool ignoreErrors, bool)
{
// Ingoring errors is not implemented in visual studio 6
(void) ignoreErrors;
// now build the test
std::string makeCommand =
cmSystemTools::ConvertToOutputPath(makeProgram);
std::string lowerCaseCommand = makeCommand;
cmSystemTools::LowerCase(lowerCaseCommand);
// if there are spaces in the makeCommand, assume a full path
// and convert it to a path with no spaces in it as the
// RunSingleCommand does not like spaces
#if defined(_WIN32) && !defined(__CYGWIN__)
if(makeCommand.find(' ') != std::string::npos)
{
cmSystemTools::GetShortPath(makeCommand.c_str(), makeCommand);
}
#endif
makeCommand += " ";
makeCommand += projectName;
makeCommand += ".sln ";
bool clean = false;
if ( targetName && strcmp(targetName, "clean") == 0 )
{
clean = true;
targetName = "ALL_BUILD";
}
if(clean)
{
makeCommand += "/clean ";
}
else
{
makeCommand += "/build ";
}
if(config && strlen(config))
{
makeCommand += config;
}
else
{
makeCommand += "Debug";
}
makeCommand += " /project ";
if (targetName && strlen(targetName))
{
makeCommand += targetName;
}
else
{
makeCommand += "ALL_BUILD";
}
if ( additionalOptions )
{
makeCommand += " ";
makeCommand += additionalOptions;
}
return makeCommand;
}
///! Create a local generator appropriate to this Global Generator
cmLocalGenerator *cmGlobalVisualStudio7Generator::CreateLocalGenerator()
{
cmLocalVisualStudio7Generator *lg = new cmLocalVisualStudio7Generator;
lg->SetExtraFlagTable(this->GetExtraFlagTableVS7());
lg->SetGlobalGenerator(this);
return lg;
}
void cmGlobalVisualStudio7Generator::GenerateConfigurations(cmMakefile* mf)
{
// process the configurations
const char* ct
= this->CMakeInstance->GetCacheDefinition("CMAKE_CONFIGURATION_TYPES");
if ( ct )
{
std::vector<std::string> argsOut;
cmSystemTools::ExpandListArgument(ct, argsOut);
for(std::vector<std::string>::iterator i = argsOut.begin();
i != argsOut.end(); ++i)
{
if(std::find(this->Configurations.begin(),
this->Configurations.end(),
*i) == this->Configurations.end())
{
this->Configurations.push_back(*i);
}
}
}
// default to at least Debug and Release
if(this->Configurations.size() == 0)
{
this->Configurations.push_back("Debug");
this->Configurations.push_back("Release");
}
// Reset the entry to have a semi-colon separated list.
std::string configs = this->Configurations[0];
for(unsigned int i=1; i < this->Configurations.size(); ++i)
{
configs += ";";
configs += this->Configurations[i];
}
mf->AddCacheDefinition(
"CMAKE_CONFIGURATION_TYPES",
configs.c_str(),
"Semicolon separated list of supported configuration types, "
"only supports Debug, Release, MinSizeRel, and RelWithDebInfo, "
"anything else will be ignored.",
cmCacheManager::STRING);
}
void cmGlobalVisualStudio7Generator::Generate()
{
// first do the superclass method
this->cmGlobalVisualStudioGenerator::Generate();
// Now write out the DSW
this->OutputSLNFile();
// If any solution or project files changed during the generation,
// tell Visual Studio to reload them...
if(!cmSystemTools::GetErrorOccuredFlag())
{
this->CallVisualStudioMacro(MacroReload);
}
}
void cmGlobalVisualStudio7Generator
::OutputSLNFile(cmLocalGenerator* root,
std::vector<cmLocalGenerator*>& generators)
{
if(generators.size() == 0)
{
return;
}
this->CurrentProject = root->GetMakefile()->GetProjectName();
std::string fname = root->GetMakefile()->GetStartOutputDirectory();
fname += "/";
fname += root->GetMakefile()->GetProjectName();
fname += ".sln";
cmGeneratedFileStream fout(fname.c_str());
fout.SetCopyIfDifferent(true);
if(!fout)
{
return;
}
this->WriteSLNFile(fout, root, generators);
if (fout.Close())
{
this->FileReplacedDuringGenerate(fname);
}
}
// output the SLN file
void cmGlobalVisualStudio7Generator::OutputSLNFile()
{
std::map<cmStdString, std::vector<cmLocalGenerator*> >::iterator it;
for(it = this->ProjectMap.begin(); it!= this->ProjectMap.end(); ++it)
{
this->OutputSLNFile(it->second[0], it->second);
}
}
void cmGlobalVisualStudio7Generator::AddAllBuildDepends(
cmLocalGenerator* root,
cmTarget* target,
cmGlobalGenerator::TargetDependSet& originalTargets)
{
// if this is the special ALL_BUILD utility, then
// make it depend on every other non UTILITY project.
for(cmGlobalGenerator::TargetDependSet::iterator ot =
originalTargets.begin(); ot != originalTargets.end(); ++ot)
{
cmTarget* t = const_cast<cmTarget*>(*ot);
if(!this->IsExcluded(root, *t))
{
if (t->GetType() == cmTarget::UTILITY ||
t->GetType() == cmTarget::GLOBAL_TARGET)
{
target->AddUtility(t->GetName());
}
else
{
target->AddLinkLibrary(t->GetName(),cmTarget::GENERAL);
}
}
}
}
void cmGlobalVisualStudio7Generator::WriteTargetConfigurations(
std::ostream& fout,
cmLocalGenerator* root,
cmGlobalGenerator::TargetDependSet& projectTargets)
{
// loop over again and write out configurations for each target
// in the solution
for(cmGlobalGenerator::TargetDependSet::iterator tt =
projectTargets.begin(); tt != projectTargets.end(); ++tt)
{
cmTarget* target = const_cast<cmTarget*>(*tt);
if (strncmp(target->GetName(), "INCLUDE_EXTERNAL_MSPROJECT", 26) == 0)
{
cmCustomCommand cc = target->GetPostBuildCommands()[0];
const cmCustomCommandLines& cmds = cc.GetCommandLines();
std::string project = cmds[0][0];
this->WriteProjectConfigurations(fout, project.c_str(),
true);
}
else
{
bool partOfDefaultBuild = this->IsPartOfDefaultBuild(
root->GetMakefile()->GetProjectName(), target);
const char *vcprojName =
target->GetProperty("GENERATOR_FILE_NAME");
if (vcprojName)
{
this->WriteProjectConfigurations(fout, vcprojName,
partOfDefaultBuild);
}
}
}
}
void cmGlobalVisualStudio7Generator::WriteTargetsToSolution(
std::ostream& fout,
cmLocalGenerator* root,
cmGlobalGenerator::TargetDependSet& projectTargets,
cmGlobalGenerator::TargetDependSet& originalTargets
)
{
std::string rootdir = root->GetMakefile()->GetStartOutputDirectory();
rootdir += "/";
for(cmGlobalGenerator::TargetDependSet::iterator tt =
projectTargets.begin(); tt != projectTargets.end(); ++tt)
{
cmTarget* target = const_cast<cmTarget*>(*tt);
cmMakefile* mf = target->GetMakefile();
// look for the all_build rule and add depends to all
// of the original targets (none that were "pulled" into this project)
if(mf == root->GetMakefile() &&
strcmp(target->GetName(), "ALL_BUILD") == 0)
{
this->AddAllBuildDepends(root, target, originalTargets);
}
// handle external vc project files
if (strncmp(target->GetName(), "INCLUDE_EXTERNAL_MSPROJECT", 26) == 0)
{
cmCustomCommand cc = target->GetPostBuildCommands()[0];
const cmCustomCommandLines& cmds = cc.GetCommandLines();
std::string project = cmds[0][0];
std::string location = cmds[0][1];
this->WriteExternalProject(fout, project.c_str(),
location.c_str(), cc.GetDepends());
}
else
{
bool skip = false;
// if it is a global target or the check build system target
// or the all_build target
// then only use the one that is for the root
if(target->GetType() == cmTarget::GLOBAL_TARGET
|| !strcmp(target->GetName(), CMAKE_CHECK_BUILD_SYSTEM_TARGET)
|| !strcmp(target->GetName(), this->GetAllTargetName()))
{
if(target->GetMakefile() != root->GetMakefile())
{
skip = true;
}
}
// if not skipping the project then write it into the
// solution
if(!skip)
{
const char *vcprojName =
target->GetProperty("GENERATOR_FILE_NAME");
if(vcprojName)
{
cmMakefile* tmf = target->GetMakefile();
std::string dir = tmf->GetStartOutputDirectory();
dir = root->Convert(dir.c_str(),
cmLocalGenerator::START_OUTPUT);
this->WriteProject(fout, vcprojName, dir.c_str(),
*target);
}
}
}
}
}
void cmGlobalVisualStudio7Generator::WriteTargetDepends(
std::ostream& fout,
cmGlobalGenerator::TargetDependSet& projectTargets
)
{
for(cmGlobalGenerator::TargetDependSet::iterator tt =
projectTargets.begin(); tt != projectTargets.end(); ++tt)
{
cmTarget* target = const_cast<cmTarget*>(*tt);
cmMakefile* mf = target->GetMakefile();
if (strncmp(target->GetName(), "INCLUDE_EXTERNAL_MSPROJECT", 26) == 0)
{
cmCustomCommand cc = target->GetPostBuildCommands()[0];
const cmCustomCommandLines& cmds = cc.GetCommandLines();
std::string name = cmds[0][0];
std::vector<std::string> depends = cc.GetDepends();
std::vector<std::string>::iterator iter;
int depcount = 0;
for(iter = depends.begin(); iter != depends.end(); ++iter)
{
std::string guid = this->GetGUID(iter->c_str());
if(guid.size() == 0)
{
std::string m = "Target: ";
m += target->GetName();
m += " depends on unknown target: ";
m += iter->c_str();
cmSystemTools::Error(m.c_str());
}
fout << "\t\t{" << this->GetGUID(name.c_str())
<< "}." << depcount << " = {" << guid.c_str() << "}\n";
depcount++;
}
}
else
{
const char *vcprojName =
target->GetProperty("GENERATOR_FILE_NAME");
if (vcprojName)
{
std::string dir = mf->GetStartDirectory();
this->WriteProjectDepends(fout, vcprojName,
dir.c_str(), *target);
}
}
}
}
// Write a SLN file to the stream
void cmGlobalVisualStudio7Generator
::WriteSLNFile(std::ostream& fout,
cmLocalGenerator* root,
std::vector<cmLocalGenerator*>& generators)
{
// Write out the header for a SLN file
this->WriteSLNHeader(fout);
// collect the set of targets for this project by
// tracing depends of all targets.
// also collect the set of targets that are explicitly
// in this project.
cmGlobalGenerator::TargetDependSet projectTargets;
cmGlobalGenerator::TargetDependSet originalTargets;
this->GetTargetSets(projectTargets,
originalTargets,
root, generators);
this->WriteTargetsToSolution(fout, root, projectTargets, originalTargets);
// Write out the configurations information for the solution
fout << "Global\n"
<< "\tGlobalSection(SolutionConfiguration) = preSolution\n";
int c = 0;
for(std::vector<std::string>::iterator i = this->Configurations.begin();
i != this->Configurations.end(); ++i)
{
fout << "\t\tConfigName." << c << " = " << *i << "\n";
c++;
}
fout << "\tEndGlobalSection\n";
// Write out project(target) depends
fout << "\tGlobalSection(ProjectDependencies) = postSolution\n";
this->WriteTargetDepends(fout, projectTargets);
fout << "\tEndGlobalSection\n";
// Write out the configurations for all the targets in the project
fout << "\tGlobalSection(ProjectConfiguration) = postSolution\n";
this->WriteTargetConfigurations(fout, root, projectTargets);
fout << "\tEndGlobalSection\n";
// Write the footer for the SLN file
this->WriteSLNFooter(fout);
}
//----------------------------------------------------------------------------
std::string
cmGlobalVisualStudio7Generator::ConvertToSolutionPath(const char* path)
{
// Convert to backslashes. Do not use ConvertToOutputPath because
// we will add quoting ourselves, and we know these projects always
// use windows slashes.
std::string d = path;
std::string::size_type pos = 0;
while((pos = d.find('/', pos)) != d.npos)
{
d[pos++] = '\\';
}
return d;
}
// Write a dsp file into the SLN file,
// Note, that dependencies from executables to
// the libraries it uses are also done here
void cmGlobalVisualStudio7Generator::WriteProject(std::ostream& fout,
const char* dspname,
const char* dir, cmTarget& target)
{
// check to see if this is a fortran build
const char* ext = ".vcproj";
const char* project = "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"";
if(this->TargetIsFortranOnly(target))
{
ext = ".vfproj";
project = "Project(\"{6989167D-11E4-40FE-8C1A-2192A86A7E90}\") = \"";
}
fout << project
<< dspname << "\", \""
<< this->ConvertToSolutionPath(dir)
<< "\\" << dspname << ext << "\", \"{"
<< this->GetGUID(dspname) << "}\"\nEndProject\n";
}
// Write a dsp file into the SLN file,
// Note, that dependencies from executables to
// the libraries it uses are also done here
void
cmGlobalVisualStudio7Generator
::WriteProjectDepends(std::ostream& fout,
const char* dspname,
const char*, cmTarget& target)
{
int depcount = 0;
// insert Begin Project Dependency Project_Dep_Name project stuff here
if (target.GetType() != cmTarget::STATIC_LIBRARY)
{
cmTarget::LinkLibraryVectorType::const_iterator j, jend;
j = target.GetLinkLibraries().begin();
jend = target.GetLinkLibraries().end();
for(;j!= jend; ++j)
{
if(j->first != dspname)
{
// is the library part of this SLN ? If so add dependency
if(this->FindTarget(0, j->first.c_str()))
{
std::string guid = this->GetGUID(j->first.c_str());
if(guid.size() == 0)
{
std::string m = "Target: ";
m += dspname;
m += " depends on unknown target: ";
m += j->first.c_str();
cmSystemTools::Error(m.c_str());
}
fout << "\t\t{" << this->GetGUID(dspname) << "}."
<< depcount << " = {" << guid << "}\n";
depcount++;
}
}
}
}
std::set<cmStdString>::const_iterator i, end;
// write utility dependencies.
i = target.GetUtilities().begin();
end = target.GetUtilities().end();
for(;i!= end; ++i)
{
if(*i != dspname)
{
std::string name = this->GetUtilityForTarget(target, i->c_str());
std::string guid = this->GetGUID(name.c_str());
if(guid.size() == 0)
{
std::string m = "Target: ";
m += dspname;
m += " depends on unknown target: ";
m += name.c_str();
cmSystemTools::Error(m.c_str());
}
fout << "\t\t{" << this->GetGUID(dspname) << "}." << depcount << " = {"
<< guid << "}\n";
depcount++;
}
}
}
// Write a dsp file into the SLN file, Note, that dependencies from
// executables to the libraries it uses are also done here
void cmGlobalVisualStudio7Generator
::WriteProjectConfigurations(std::ostream& fout, const char* name,
bool partOfDefaultBuild)
{
std::string guid = this->GetGUID(name);
for(std::vector<std::string>::iterator i = this->Configurations.begin();
i != this->Configurations.end(); ++i)
{
fout << "\t\t{" << guid << "}." << *i
<< ".ActiveCfg = " << *i << "|Win32\n";
if(partOfDefaultBuild)
{
fout << "\t\t{" << guid << "}." << *i
<< ".Build.0 = " << *i << "|Win32\n";
}
}
}
// Write a dsp file into the SLN file,
// Note, that dependencies from executables to
// the libraries it uses are also done here
void cmGlobalVisualStudio7Generator::WriteExternalProject(std::ostream& fout,
const char* name,
const char* location,
const std::vector<std::string>&)
{
std::cout << "WriteExternalProject vs7\n";
std::string d = cmSystemTools::ConvertToOutputPath(location);
fout << "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \""
<< name << "\", \""
<< this->ConvertToSolutionPath(location) << "\", \"{"
<< this->GetGUID(name)
<< "}\"\n";
fout << "EndProject\n";
}
// Standard end of dsw file
void cmGlobalVisualStudio7Generator::WriteSLNFooter(std::ostream& fout)
{
fout << "\tGlobalSection(ExtensibilityGlobals) = postSolution\n"
<< "\tEndGlobalSection\n"
<< "\tGlobalSection(ExtensibilityAddIns) = postSolution\n"
<< "\tEndGlobalSection\n"
<< "EndGlobal\n";
}
// ouput standard header for dsw file
void cmGlobalVisualStudio7Generator::WriteSLNHeader(std::ostream& fout)
{
fout << "Microsoft Visual Studio Solution File, Format Version 7.00\n";
}
std::string cmGlobalVisualStudio7Generator::GetGUID(const char* name)
{
std::string guidStoreName = name;
guidStoreName += "_GUID_CMAKE";
const char* storedGUID =
this->CMakeInstance->GetCacheDefinition(guidStoreName.c_str());
if(storedGUID)
{
return std::string(storedGUID);
}
cmSystemTools::Error("Unknown Target referenced : ",
name);
return "";
}
void cmGlobalVisualStudio7Generator::CreateGUID(const char* name)
{
std::string guidStoreName = name;
guidStoreName += "_GUID_CMAKE";
if(this->CMakeInstance->GetCacheDefinition(guidStoreName.c_str()))
{
return;
}
std::string ret;
UUID uid;
unsigned char *uidstr;
UuidCreate(&uid);
UuidToString(&uid,&uidstr);
ret = reinterpret_cast<char*>(uidstr);
RpcStringFree(&uidstr);
ret = cmSystemTools::UpperCase(ret);
this->CMakeInstance->AddCacheEntry(guidStoreName.c_str(),
ret.c_str(), "Stored GUID",
cmCacheManager::INTERNAL);
}
std::vector<std::string> *cmGlobalVisualStudio7Generator::GetConfigurations()
{
return &this->Configurations;
};
//----------------------------------------------------------------------------
void cmGlobalVisualStudio7Generator
::GetDocumentation(cmDocumentationEntry& entry) const
{
entry.Name = this->GetName();
entry.Brief = "Generates Visual Studio .NET 2002 project files.";
entry.Full = "";
}
// make sure "special" targets have GUID's
void cmGlobalVisualStudio7Generator::Configure()
{
cmGlobalGenerator::Configure();
this->CreateGUID("ALL_BUILD");
this->CreateGUID("INSTALL");
this->CreateGUID("RUN_TESTS");
this->CreateGUID("EDIT_CACHE");
this->CreateGUID("REBUILD_CACHE");
this->CreateGUID("PACKAGE");
}
//----------------------------------------------------------------------------
void
cmGlobalVisualStudio7Generator
::AppendDirectoryForConfig(const char* prefix,
const char* config,
const char* suffix,
std::string& dir)
{
if(config)
{
dir += prefix;
dir += config;
dir += suffix;
}
}
bool cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild(const char* project,
cmTarget* target)
{
if(target->GetPropertyAsBool("EXCLUDE_FROM_DEFAULT_BUILD"))
{
return false;
}
// if it is a utilitiy target then only make it part of the
// default build if another target depends on it
int type = target->GetType();
if (type == cmTarget::GLOBAL_TARGET)
{
return false;
}
if(type == cmTarget::UTILITY)
{
return this->IsDependedOn(project, target);
}
// default is to be part of the build
return true;
}
//----------------------------------------------------------------------------
static cmVS7FlagTable cmVS7ExtraFlagTable[] =
{
// Precompiled header and related options. Note that the
// UsePrecompiledHeader entries are marked as "Continue" so that the
// corresponding PrecompiledHeaderThrough entry can be found.
{"UsePrecompiledHeader", "YX", "Automatically Generate", "2",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue},
{"PrecompiledHeaderThrough", "YX", "Precompiled Header Name", "",
cmVS7FlagTable::UserValueRequired},
{"UsePrecompiledHeader", "Yu", "Use Precompiled Header", "3",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue},
{"PrecompiledHeaderThrough", "Yu", "Precompiled Header Name", "",
cmVS7FlagTable::UserValueRequired},
// Exception handling mode. If no entries match, it will be FALSE.
{"ExceptionHandling", "GX", "enable c++ exceptions", "TRUE", 0},
{"ExceptionHandling", "EHsc", "enable c++ exceptions", "TRUE", 0},
// The EHa option does not have an IDE setting. Let it go to false,
// and have EHa passed on the command line by leaving out the table
// entry.
{0,0,0,0,0}
};
cmVS7FlagTable const* cmGlobalVisualStudio7Generator::GetExtraFlagTableVS7()
{
return cmVS7ExtraFlagTable;
}
| 31.726316 | 83 | 0.618198 | [
"vector"
] |
27e39b8d64805745c42dd11790aa2f48ca498784 | 1,914 | cpp | C++ | lib/year2016/src/Day15Puzzle.cpp | MarkRDavison/AdventOfCode | 640ae6de76709367be8dfeb86b9f1f7d21908946 | [
"MIT"
] | null | null | null | lib/year2016/src/Day15Puzzle.cpp | MarkRDavison/AdventOfCode | 640ae6de76709367be8dfeb86b9f1f7d21908946 | [
"MIT"
] | null | null | null | lib/year2016/src/Day15Puzzle.cpp | MarkRDavison/AdventOfCode | 640ae6de76709367be8dfeb86b9f1f7d21908946 | [
"MIT"
] | null | null | null | #include <2016/Day15Puzzle.hpp>
#include <zeno-engine/Utility/StringExtensions.hpp>
namespace TwentySixteen {
Day15Puzzle::Day15Puzzle() :
core::PuzzleBase("Timing is Everything", 2016, 15) {
}
Day15Puzzle::~Day15Puzzle() {
}
void Day15Puzzle::initialise(const core::InitialisationInfo& _initialisationInfo) {
setInputLines(ze::StringExtensions::splitStringByDelimeter(ze::StringExtensions::loadFileToString(_initialisationInfo.parameters[0]), "\n"));
}
void Day15Puzzle::setInputLines(const std::vector<std::string>& _inputLines) {
m_InputLines = std::vector<std::string>(_inputLines);
}
std::pair<std::string, std::string> Day15Puzzle::fastSolve() {
auto positions = getNumberAndStartingPositions(m_InputLines);
const auto part1 = getFirstTime(positions);
positions.emplace_back(11, 0);
const auto part2 = getFirstTime(positions);
return { std::to_string(part1), std::to_string(part2) };
}
std::vector<std::pair<int, int>> Day15Puzzle::getNumberAndStartingPositions(const std::vector<std::string>& _input) {
std::vector<std::pair<int, int>> positions;
for (const auto& i : _input) {
const auto& s = ze::StringExtensions::splitStringByDelimeter(i, " .");
positions.emplace_back(std::stoi(s[3]), std::stoi(s.back()));
}
return positions;
}
bool Day15Puzzle::isValidFromStartTime(const std::vector<std::pair<int, int>>& _positions, int _startTime) {
int time = _startTime;
for (unsigned i = 0; i < _positions.size(); ++i) {
const int numberPositions = _positions[i].first;
const int startingPosition = _positions[i].second;
time += 1;
if ((startingPosition + time) % numberPositions != 0) {
return false;
}
}
return true;
}
int Day15Puzzle::getFirstTime(const std::vector<std::pair<int, int>>& _positions) {
for (int i = 0;; ++i) {
if (isValidFromStartTime(_positions, i)) {
return i;
}
}
return -1;
}
}
| 26.583333 | 143 | 0.700104 | [
"vector"
] |
27e563febf2169e2903e6b546fab13db8a05691e | 19,267 | hh | C++ | net.ssa/xrLC/OpenMesh/Core/Mesh/Kernels/ArrayKernel/ArrayKernelT.hh | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | xrLC/OpenMesh/Core/Mesh/Kernels/ArrayKernel/ArrayKernelT.hh | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | null | null | null | xrLC/OpenMesh/Core/Mesh/Kernels/ArrayKernel/ArrayKernelT.hh | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | //=============================================================================
//
// OpenMesh
// Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen
// www.openmesh.org
//
//-----------------------------------------------------------------------------
//
// License
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Library General Public License as published
// by the Free Software Foundation, version 2.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//-----------------------------------------------------------------------------
//
// $Revision: 1.11 $
// $Date: 2004/01/08 15:51:04 $
//
//=============================================================================
//=============================================================================
//
// CLASS ArrayKernelT
//
//=============================================================================
#ifndef OPENMESH_ARRAY_KERNEL_HH
#define OPENMESH_ARRAY_KERNEL_HH
//== INCLUDES =================================================================
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/Mesh/Kernels/Common/AttribKernelT.hh>
#include <OpenMesh/Core/Utils/GenProg.hh>
#include <vector>
//== NAMESPACES ===============================================================
namespace OpenMesh {
//== CLASS DEFINITION =========================================================
/** \ingroup mesh_kernels_group
Mesh kernel using arrays for mesh item storage.
This mesh kernel uses the std::vector as container to store the
mesh items. Therefore all handle types are internally represented
by integers. To get the index from a handle use the handle's \c
idx() method.
\note For a description of the minimal kernel interface see
OpenMesh::Mesh::BaseKernel.
\note You do not have to use this class directly, use the predefined
mesh-kernel combinations in \ref mesh_types_group.
\see OpenMesh::Concepts::KernelT, \ref mesh_type
*/
template <class AttribKernel, class FinalMeshItems>
class ArrayKernelT : public AttribKernel
{
public:
typedef ArrayKernelT<AttribKernel, FinalMeshItems> This;
typedef AttribKernel Base;
// attributes
typedef typename Base::HasPrevHalfedge HasPrevHalfedge;
// item types
typedef typename FinalMeshItems::Vertex Vertex;
typedef typename FinalMeshItems::Halfedge Halfedge;
typedef typename FinalMeshItems::Edge Edge;
typedef typename FinalMeshItems::Face Face;
typedef typename FinalMeshItems::Point Point;
typedef typename FinalMeshItems::Scalar Scalar;
// handles
typedef OpenMesh::VertexHandle VertexHandle;
typedef OpenMesh::HalfedgeHandle HalfedgeHandle;
typedef OpenMesh::EdgeHandle EdgeHandle;
typedef OpenMesh::FaceHandle FaceHandle;
// --- constructor/destructor ---
ArrayKernelT() {}
~ArrayKernelT() { clear(); }
// --- handle -> item ---
VertexHandle handle(const Vertex& _v) const {
return VertexHandle(&_v - &vertices_.front());
}
HalfedgeHandle handle(const Halfedge& _he) const {
unsigned int eh(((char*)&edges_.front() - (char*)&_he) % sizeof(Edge));
assert((&_he == &edges_[eh].halfedges_[0]) ||
(&_he == &edges_[eh].halfedges_[1]));
return ((&_he == &edges_[eh].halfedges_[0]) ?
HalfedgeHandle(eh<<1) :
HalfedgeHandle((eh<<1)+1));
}
EdgeHandle handle(const Edge& _e) const {
return EdgeHandle(&_e - &edges_.front());
}
FaceHandle handle(const Face& _f) const {
return FaceHandle(&_f - &faces_.front());
}
#define SIGNED(x) signed( (x) )
// --- item -> handle ---
const Vertex& vertex(VertexHandle _vh) const {
assert(_vh.idx() >= 0 && _vh.idx() < SIGNED(n_vertices()));
return vertices_[_vh.idx()];
}
Vertex& vertex(VertexHandle _vh) {
assert(_vh.idx() >= 0 && _vh.idx() < SIGNED(n_vertices()));
return vertices_[_vh.idx()];
}
const Halfedge& halfedge(HalfedgeHandle _heh) const {
assert(_heh.idx() >= 0 && _heh.idx() < SIGNED(n_edges()*2));
return edges_[_heh.idx() >> 1].halfedges_[_heh.idx() & 1];
}
Halfedge& halfedge(HalfedgeHandle _heh) {
assert(_heh.idx() >= 0 && _heh.idx() < SIGNED(n_edges())*2);
return edges_[_heh.idx() >> 1].halfedges_[_heh.idx() & 1];
}
const Edge& edge(EdgeHandle _eh) const {
assert(_eh.idx() >= 0 && _eh.idx() < SIGNED(n_edges()));
return edges_[_eh.idx()];
}
Edge& edge(EdgeHandle _eh) {
assert(_eh.idx() >= 0 && _eh.idx() < SIGNED(n_edges()));
return edges_[_eh.idx()];
}
const Face& face(FaceHandle _fh) const {
assert(_fh.idx() >= 0 && _fh.idx() < SIGNED(n_faces()));
return faces_[_fh.idx()];
}
Face& face(FaceHandle _fh) {
assert(_fh.idx() >= 0 && _fh.idx() < SIGNED(n_faces()));
return faces_[_fh.idx()];
}
#undef SIGNED
// --- get i'th items ---
VertexHandle vertex_handle(unsigned int _i) const {
return (_i < n_vertices()) ? handle( vertices_[_i] ) : VertexHandle();
}
HalfedgeHandle halfedge_handle(unsigned int _i) const {
return (_i < n_halfedges()) ? halfedge_handle(edge_handle(_i/2), _i%2) : HalfedgeHandle();
}
EdgeHandle edge_handle(unsigned int _i) const {
return (_i < n_edges()) ? handle(edges_[_i]) : EdgeHandle();
}
FaceHandle face_handle(unsigned int _i) const {
return (_i < n_faces()) ? handle(faces_[_i]) : FaceHandle();
}
// --- add new items ---
void reserve( unsigned int _n_vertices,
unsigned int _n_edges,
unsigned int _n_faces ) {
vertices_.reserve(_n_vertices);
edges_.reserve(_n_edges);
faces_.reserve(_n_faces);
vprops_reserve(_n_vertices);
hprops_reserve(_n_edges*2);
eprops_reserve(_n_edges);
fprops_reserve(_n_faces);
}
public:
VertexHandle new_vertex() {
vertices_.push_back(Vertex());
vprops_resize(n_vertices());
return handle(vertices_.back());
}
VertexHandle new_vertex(const Point& _p) {
vertices_.push_back(Vertex());
vprops_resize(n_vertices());
VertexHandle vh(handle(vertices_.back()));
set_point(vh, _p);
return vh;
}
HalfedgeHandle new_edge(VertexHandle _start_vertex_handle,
VertexHandle _end_vertex_handle)
{
edges_.push_back(Edge());
eprops_resize(n_edges());
hprops_resize(n_halfedges());
EdgeHandle eh(handle(edges_.back()));
HalfedgeHandle heh0(halfedge_handle(eh, 0));
HalfedgeHandle heh1(halfedge_handle(eh, 1));
set_vertex_handle(heh0, _end_vertex_handle);
set_vertex_handle(heh1, _start_vertex_handle);
return heh0;
}
FaceHandle new_face() {
faces_.push_back(Face());
fprops_resize(n_faces());
return handle(faces_.back());
}
FaceHandle new_face(const Face& _f) {
faces_.push_back(_f);
fprops_resize(n_faces());
return handle(faces_.back());
}
public:
// --- deletion ---
void garbage_collection(bool _v=true, bool _e=true, bool _f=true);
void clear() {
vertices_.clear();
edges_.clear();
faces_.clear();
vprops_resize(0);
eprops_resize(0);
hprops_resize(0);
fprops_resize(0);
}
void resize( unsigned int _n_vertices,
unsigned int _n_edges,
unsigned int _n_faces )
{
vertices_.resize(_n_vertices);
edges_.resize(_n_edges);
faces_.resize(_n_faces);
vprops_resize(n_vertices());
hprops_resize(n_halfedges());
eprops_resize(n_edges());
fprops_resize(n_faces());
}
// --- number of items ---
unsigned int n_vertices() const { return vertices_.size(); }
unsigned int n_halfedges() const { return 2*edges_.size(); }
unsigned int n_edges() const { return edges_.size(); }
unsigned int n_faces() const { return faces_.size(); }
bool vertices_empty() const { return vertices_.empty(); }
bool halfedges_empty() const { return edges_.empty(); }
bool edges_empty() const { return edges_.empty(); }
bool faces_empty() const { return faces_.empty(); }
// --- vertex connectivity ---
HalfedgeHandle halfedge_handle(VertexHandle _vh) const {
return vertex(_vh).halfedge_handle_;
}
void set_halfedge_handle(VertexHandle _vh, HalfedgeHandle _heh) {
vertex(_vh).halfedge_handle_ = _heh;
}
// --- halfedge connectivity ---
VertexHandle to_vertex_handle(HalfedgeHandle _heh) const {
return halfedge(_heh).vertex_handle_;
}
VertexHandle from_vertex_handle(HalfedgeHandle _heh) const {
return to_vertex_handle(opposite_halfedge_handle(_heh));
}
void set_vertex_handle(HalfedgeHandle _heh, VertexHandle _vh) {
halfedge(_heh).vertex_handle_ = _vh;
}
FaceHandle face_handle(HalfedgeHandle _heh) const {
return halfedge(_heh).face_handle_;
}
void set_face_handle(HalfedgeHandle _heh, FaceHandle _fh) {
halfedge(_heh).face_handle_ = _fh;
}
HalfedgeHandle next_halfedge_handle(HalfedgeHandle _heh) const {
return halfedge(_heh).next_halfedge_handle_;
}
void set_next_halfedge_handle(HalfedgeHandle _heh, HalfedgeHandle _nheh) {
halfedge(_heh).next_halfedge_handle_ = _nheh;
set_prev_halfedge_handle(_nheh, _heh);
}
void set_prev_halfedge_handle(HalfedgeHandle _heh, HalfedgeHandle _pheh) {
set_prev_halfedge_handle(_heh, _pheh, HasPrevHalfedge());
}
void set_prev_halfedge_handle(HalfedgeHandle _heh, HalfedgeHandle _pheh,
GenProg::True) {
halfedge(_heh).prev_halfedge_handle_ = _pheh;
}
void set_prev_halfedge_handle(HalfedgeHandle _heh, HalfedgeHandle _pheh,
GenProg::False) {}
HalfedgeHandle prev_halfedge_handle(HalfedgeHandle _heh) const {
return prev_halfedge_handle(_heh, HasPrevHalfedge() );
}
HalfedgeHandle prev_halfedge_handle(HalfedgeHandle _heh,
GenProg::True) const {
return halfedge(_heh).prev_halfedge_handle_;
}
HalfedgeHandle prev_halfedge_handle(HalfedgeHandle _heh,
GenProg::False) const {
HalfedgeHandle heh(_heh);
HalfedgeHandle next_heh(next_halfedge_handle(heh));
while (next_heh != _heh) {
heh = next_heh;
next_heh = next_halfedge_handle(next_heh);
}
return heh;
}
HalfedgeHandle opposite_halfedge_handle(HalfedgeHandle _heh) const {
return HalfedgeHandle((_heh.idx() & 1) ? _heh.idx()-1 : _heh.idx()+1);
}
HalfedgeHandle ccw_rotated_halfedge_handle(HalfedgeHandle _heh) const {
return opposite_halfedge_handle(prev_halfedge_handle(_heh));
}
HalfedgeHandle cw_rotated_halfedge_handle(HalfedgeHandle _heh) const {
return next_halfedge_handle(opposite_halfedge_handle(_heh));
}
// --- edge connectivity ---
HalfedgeHandle halfedge_handle(EdgeHandle _eh, unsigned int _i) const {
assert(_i<=1);
return HalfedgeHandle((_eh.idx() << 1) + _i);
}
EdgeHandle edge_handle(HalfedgeHandle _heh) const {
return EdgeHandle(_heh.idx() >> 1);
}
// --- face connectivity ---
HalfedgeHandle halfedge_handle(FaceHandle _fh) const {
return face(_fh).halfedge_handle_;
}
void set_halfedge_handle(FaceHandle _fh, HalfedgeHandle _heh) {
face(_fh).halfedge_handle_ = _heh;
}
private:
// iterators
typedef std::vector<Vertex> VertexContainer;
typedef std::vector<Edge> EdgeContainer;
typedef std::vector<Face> FaceContainer;
typedef typename VertexContainer::iterator KernelVertexIter;
typedef typename VertexContainer::const_iterator KernelConstVertexIter;
typedef typename EdgeContainer::iterator KernelEdgeIter;
typedef typename EdgeContainer::const_iterator KernelConstEdgeIter;
typedef typename FaceContainer::iterator KernelFaceIter;
typedef typename FaceContainer::const_iterator KernelConstFaceIter;
KernelVertexIter vertices_begin() { return vertices_.begin(); }
KernelConstVertexIter vertices_begin() const { return vertices_.begin(); }
KernelVertexIter vertices_end() { return vertices_.end(); }
KernelConstVertexIter vertices_end() const { return vertices_.end(); }
KernelEdgeIter edges_begin() { return edges_.begin(); }
KernelConstEdgeIter edges_begin() const { return edges_.begin(); }
KernelEdgeIter edges_end() { return edges_.end(); }
KernelConstEdgeIter edges_end() const { return edges_.end(); }
KernelFaceIter faces_begin() { return faces_.begin(); }
KernelConstFaceIter faces_begin() const { return faces_.begin(); }
KernelFaceIter faces_end() { return faces_.end(); }
KernelConstFaceIter faces_end() const { return faces_.end(); }
private:
VertexContainer vertices_;
EdgeContainer edges_;
FaceContainer faces_;
};
//-----------------------------------------------------------------------------
template <class AttribKernel, class FinalMeshItems>
void
ArrayKernelT<AttribKernel, FinalMeshItems>::
garbage_collection(bool _v, bool _e, bool _f)
{
int i, i0, i1,
nV(n_vertices()),
nE(n_edges()),
nH(2*n_edges()),
nF(n_faces());
std::vector<VertexHandle> vh_map;
std::vector<HalfedgeHandle> hh_map;
std::vector<FaceHandle> fh_map;
// setup handle mapping:
// on 1st pos is an invalid handle, all others are hence shifted by 1
vh_map.reserve(nV+1);
for (i=-1; i<nV; ++i) vh_map.push_back(VertexHandle(i));
hh_map.reserve(nH+1);
for (i=-1; i<nH; ++i) hh_map.push_back(HalfedgeHandle(i));
fh_map.reserve(nF+1);
for (i=-1; i<nF; ++i) fh_map.push_back(FaceHandle(i));
// remove deleted vertices
if (_v && n_vertices() > 0)
{
i0=0; i1=nV-1;
while (1)
{
// find 1st deleted and last un-deleted
while (!status(VertexHandle(i0)).deleted() && i0 < i1) ++i0;
while ( status(VertexHandle(i1)).deleted() && i0 < i1) --i1;
if (i0 >= i1) break;
// swap
std::swap(vertices_[i0], vertices_[i1]);
std::swap(vh_map[i0+1], vh_map[i1+1]);
vprops_swap(i0, i1);
};
vertices_.resize(status(VertexHandle(i0)).deleted() ? i0 : i0+1);
vprops_resize(n_vertices());
}
// remove deleted edges
if (_e && n_edges() > 0)
{
i0=0; i1=nE-1;
while (1)
{
// find 1st deleted and last un-deleted
while (!status(EdgeHandle(i0)).deleted() && i0 < i1) ++i0;
while ( status(EdgeHandle(i1)).deleted() && i0 < i1) --i1;
if (i0 >= i1) break;
// swap
std::swap(edges_[i0], edges_[i1]);
std::swap(hh_map[2*i0+1], hh_map[2*i1+1]);
std::swap(hh_map[2*i0+2], hh_map[2*i1+2]);
eprops_swap(i0, i1);
hprops_swap(2*i0, 2*i1);
hprops_swap(2*i0+1, 2*i1+1);
};
edges_.resize(status(EdgeHandle(i0)).deleted() ? i0 : i0+1);
eprops_resize(n_edges());
hprops_resize(n_halfedges());
}
// remove deleted faces
if (_f && n_faces() > 0)
{
i0=0; i1=nF-1;
while (1)
{
// find 1st deleted and last un-deleted
while (!status(FaceHandle(i0)).deleted() && i0 < i1) ++i0;
while ( status(FaceHandle(i1)).deleted() && i0 < i1) --i1;
if (i0 >= i1) break;
// swap
std::swap(faces_[i0], faces_[i1]);
std::swap(fh_map[i0+1], fh_map[i1+1]);
fprops_swap(i0, i1);
};
faces_.resize(status(FaceHandle(i0)).deleted() ? i0 : i0+1);
fprops_resize(n_faces());
}
// update handles of vertices
if (_e)
{
KernelVertexIter v_it(vertices_begin()), v_end(vertices_end());
VertexHandle vh;
for (; v_it!=v_end; ++v_it)
{
vh = handle(*v_it);
set_halfedge_handle(vh, hh_map[halfedge_handle(vh).idx()+1]);
}
}
// update handles of halfedges
KernelEdgeIter e_it(edges_begin()), e_end(edges_end());
HalfedgeHandle hh;
for (; e_it!=e_end; ++e_it)
{
hh = halfedge_handle(handle(*e_it), 0);
set_next_halfedge_handle(hh, hh_map[next_halfedge_handle(hh).idx()+1]);
set_vertex_handle(hh, vh_map[to_vertex_handle(hh).idx()+1]);
set_face_handle(hh, fh_map[face_handle(hh).idx()+1]);
hh = halfedge_handle(handle(*e_it), 1);
set_next_halfedge_handle(hh, hh_map[next_halfedge_handle(hh).idx()+1]);
set_vertex_handle(hh, vh_map[to_vertex_handle(hh).idx()+1]);
set_face_handle(hh, fh_map[face_handle(hh).idx()+1]);
}
// update handles of faces
if (_e)
{
KernelFaceIter f_it(faces_begin()), f_end(faces_end());
FaceHandle fh;
for (; f_it!=f_end; ++f_it)
{
fh = handle(*f_it);
set_halfedge_handle(fh, hh_map[halfedge_handle(fh).idx()+1]);
}
}
}
//=============================================================================
} // namespace OpenMesh
//=============================================================================
#endif // OPENMESH_ARRAY_KERNEL_HH defined
//=============================================================================
| 29.825077 | 95 | 0.562516 | [
"mesh",
"vector"
] |
27f1885ee03060efdc92489d0d380d9c9117deae | 1,364 | cpp | C++ | Wangscape/noise/module/codecs/TurbulenceWrapperCodec.cpp | cheukyin699/Wangscape | b01cb310f97e33394c1c0fac23a7f40c34f632cf | [
"MIT"
] | 60 | 2016-12-30T03:18:34.000Z | 2022-02-15T21:43:59.000Z | Wangscape/noise/module/codecs/TurbulenceWrapperCodec.cpp | cheukyin699/Wangscape | b01cb310f97e33394c1c0fac23a7f40c34f632cf | [
"MIT"
] | 149 | 2016-12-29T19:38:36.000Z | 2017-10-29T18:19:51.000Z | Wangscape/noise/module/codecs/TurbulenceWrapperCodec.cpp | cheukyin699/Wangscape | b01cb310f97e33394c1c0fac23a7f40c34f632cf | [
"MIT"
] | 16 | 2016-12-31T06:09:42.000Z | 2021-09-10T05:34:51.000Z | #include "TurbulenceWrapperCodec.h"
namespace spotify
{
namespace json
{
using TurbulenceWrapper = noise::module::Wrapper<noise::module::Turbulence>;
codec::object_t<TurbulenceWrapper> default_codec_t<TurbulenceWrapper>::codec()
{
auto codec = codec::object<TurbulenceWrapper>();
codec.required("type", codec::eq<std::string>("Turbulence"));
codec.required("SourceModule", codec::ignore_t<int>());
codec.optional("Frequency",
[](const TurbulenceWrapper& mw) {return mw.module->GetFrequency(); },
[](TurbulenceWrapper& mw, double frequency) {mw.module->SetFrequency(frequency); });
codec.optional("Power",
[](const TurbulenceWrapper& mw) {return mw.module->GetPower(); },
[](TurbulenceWrapper& mw, double power) {mw.module->SetPower(power); });
codec.optional("Roughness",
[](const TurbulenceWrapper& mw) {return mw.module->GetRoughnessCount(); },
[](TurbulenceWrapper& mw, int roughness) {mw.module->SetRoughness(roughness); });
codec.optional("Seed",
[](const TurbulenceWrapper& mw) {return mw.module->GetSeed(); },
[](TurbulenceWrapper& mw, int seed) {mw.module->SetSeed(seed); });
return codec;
}
}
}
| 42.625 | 107 | 0.596041 | [
"object"
] |
7e016f2f49165303c8bf9dd2eecae684bbe38f14 | 5,323 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/fbconvenience/qfbwindow.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/fbconvenience/qfbwindow.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/fbconvenience/qfbwindow.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qfbwindow_p.h"
#include "qfbscreen_p.h"
#include <QtGui/QScreen>
#include <qpa/qwindowsysteminterface.h>
QT_BEGIN_NAMESPACE
QFbWindow::QFbWindow(QWindow *window)
: QPlatformWindow(window), mBackingStore(0), mWindowState(Qt::WindowNoState)
{
static QAtomicInt winIdGenerator(1);
mWindowId = winIdGenerator.fetchAndAddRelaxed(1);
}
QFbWindow::~QFbWindow()
{
}
QFbScreen *QFbWindow::platformScreen() const
{
return static_cast<QFbScreen *>(window()->screen()->handle());
}
void QFbWindow::setGeometry(const QRect &rect)
{
// store previous geometry for screen update
mOldGeometry = geometry();
QWindowSystemInterface::handleGeometryChange(window(), rect);
QPlatformWindow::setGeometry(rect);
if (mOldGeometry != rect)
QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(0, 0), geometry().size()));
}
void QFbWindow::setVisible(bool visible)
{
QRect newGeom;
QFbScreen *fbScreen = platformScreen();
if (visible) {
bool convOk = false;
static bool envDisableForceFullScreen = qEnvironmentVariableIntValue("QT_QPA_FB_FORCE_FULLSCREEN", &convOk) == 0 && convOk;
const bool platformDisableForceFullScreen = fbScreen->flags().testFlag(QFbScreen::DontForceFirstWindowToFullScreen);
const bool forceFullScreen = !envDisableForceFullScreen && !platformDisableForceFullScreen && fbScreen->windowCount() == 0;
if (forceFullScreen || (mWindowState & Qt::WindowFullScreen))
newGeom = platformScreen()->geometry();
else if (mWindowState & Qt::WindowMaximized)
newGeom = platformScreen()->availableGeometry();
}
QPlatformWindow::setVisible(visible);
if (visible)
fbScreen->addWindow(this);
else
fbScreen->removeWindow(this);
if (!newGeom.isEmpty())
setGeometry(newGeom); // may or may not generate an expose
if (newGeom.isEmpty() || newGeom == mOldGeometry) {
// QWindow::isExposed() maps to QWindow::visible() by default so simply
// generating an expose event regardless of this being a show or hide is
// just what is needed here.
QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(0, 0), geometry().size()));
}
}
void QFbWindow::setWindowState(Qt::WindowState state)
{
QPlatformWindow::setWindowState(state);
mWindowState = state;
}
void QFbWindow::setWindowFlags(Qt::WindowFlags flags)
{
mWindowFlags = flags;
}
Qt::WindowFlags QFbWindow::windowFlags() const
{
return mWindowFlags;
}
void QFbWindow::raise()
{
platformScreen()->raise(this);
QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(0, 0), geometry().size()));
}
void QFbWindow::lower()
{
platformScreen()->lower(this);
QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(0, 0), geometry().size()));
}
void QFbWindow::repaint(const QRegion ®ion)
{
const QRect currentGeometry = geometry();
const QRect dirtyClient = region.boundingRect();
const QRect dirtyRegion = dirtyClient.translated(currentGeometry.topLeft());
const QRect oldGeometryLocal = mOldGeometry;
mOldGeometry = currentGeometry;
// If this is a move, redraw the previous location
if (oldGeometryLocal != currentGeometry)
platformScreen()->setDirty(oldGeometryLocal);
platformScreen()->setDirty(dirtyRegion);
}
QT_END_NAMESPACE
| 35.251656 | 131 | 0.703551 | [
"geometry"
] |
7e024d6848a17662ab6bc954007044f90d76c61b | 11,337 | cpp | C++ | src/analysis/monogenic_signal.cpp | slokhorst/diplib | 6e0f420243fd4e84888b5a5c25f805570fafd36d | [
"Apache-2.0"
] | 140 | 2017-04-04T23:10:16.000Z | 2022-03-24T18:21:34.000Z | src/analysis/monogenic_signal.cpp | slokhorst/diplib | 6e0f420243fd4e84888b5a5c25f805570fafd36d | [
"Apache-2.0"
] | 98 | 2018-01-13T23:16:00.000Z | 2022-03-14T14:45:37.000Z | src/analysis/monogenic_signal.cpp | slokhorst/diplib | 6e0f420243fd4e84888b5a5c25f805570fafd36d | [
"Apache-2.0"
] | 40 | 2017-04-11T20:41:58.000Z | 2022-03-24T18:21:36.000Z | /*
* DIPlib 3.0
* This file contains definitions for the monogenic signal and related functionality
*
* (c)2018, Cris Luengo.
*
* 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 "diplib.h"
#include "diplib/analysis.h"
#include "diplib/linear.h"
#include "diplib/transform.h"
#include "diplib/math.h"
#include "diplib/statistics.h"
#include "diplib/mapping.h"
namespace dip {
void MonogenicSignal(
Image const& c_in,
Image& out,
FloatArray const& wavelengths,
dfloat bandwidth,
String const& inRepresentation,
String const& outRepresentation
) {
DIP_THROW_IF( !c_in.IsForged(), E::IMAGE_NOT_FORGED );
DIP_THROW_IF( !c_in.IsScalar(), E::IMAGE_NOT_SCALAR );
DIP_THROW_IF( c_in.DataType().IsComplex(), E::DATA_TYPE_NOT_SUPPORTED );
dip::uint nFrequencyScales = wavelengths.size();
DIP_THROW_IF( nFrequencyScales < 1, E::ARRAY_PARAMETER_EMPTY );
DIP_THROW_IF( bandwidth <= 0, E::INVALID_PARAMETER );
dip::uint nDims = c_in.Dimensionality();
bool spatialDomainInput;
DIP_STACK_TRACE_THIS( spatialDomainInput = BooleanFromString( inRepresentation, S::SPATIAL, S::FREQUENCY ));
bool spatialDomainOutput;
DIP_STACK_TRACE_THIS( spatialDomainOutput = BooleanFromString( outRepresentation, S::SPATIAL, S::FREQUENCY ));
bool inputIsReal = spatialDomainInput && !c_in.DataType().IsComplex();
bool outputIsReal = inputIsReal && spatialDomainOutput;
DataType dt = outputIsReal ? DT_SFLOAT : DT_SCOMPLEX;
Image in = c_in;
if( out.Aliases( in )) {
out.Strip(); // we can't work in-place
}
DIP_STACK_TRACE_THIS( out.ReForge( in.Sizes(), ( nDims + 1 ) * nFrequencyScales, dt ));
out.ReshapeTensor( nDims + 1, nFrequencyScales );
Image ftIn;
if( spatialDomainInput ) {
ftIn = FourierTransform( in );
} else {
ftIn = in.QuickCopy();
}
UnsignedArray center = in.Sizes();
center /= 2;
// Compute Riesz transform
Image mono;
DIP_STACK_TRACE_THIS( RieszTransform( ftIn, mono, S::FREQUENCY, S::FREQUENCY ));
// Compute scale selection filters
Image radialFilter;
radialFilter.SetSizes( in.Sizes() ); // We'll use this non-forged image as input to get a filter bank not applied to an image
DIP_STACK_TRACE_THIS( LogGaborFilterBank( radialFilter, radialFilter, wavelengths, bandwidth, 1, S::FREQUENCY, S::FREQUENCY ));
// Options for inverse transform
StringSet options = { S::INVERSE };
if( spatialDomainOutput && outputIsReal ) {
options.insert( S::REAL );
}
// Get all combinations by multiplication
for( dip::uint scale = 0; scale < nFrequencyScales; ++scale ) {
{
Image destination = out[ UnsignedArray{ 0, scale } ];
destination.Protect(); // ensure it will not be reforged
Image tempStorage;
Image& ftDestination = ( spatialDomainOutput && outputIsReal ) ? tempStorage : destination;
DIP_STACK_TRACE_THIS( Multiply( radialFilter[ scale ], ftIn, ftDestination ));
ftDestination.At( center ) = 0;
if( spatialDomainOutput ) {
DIP_STACK_TRACE_THIS( FourierTransform( ftDestination, destination, options ));
}
}
for( dip::uint ii = 0; ii < nDims; ++ii ) {
Image destination = out[ UnsignedArray{ ii + 1, scale } ];
destination.Protect(); // ensure it will not be reforged
Image tempStorage;
Image& ftDestination = ( spatialDomainOutput && outputIsReal ) ? tempStorage : destination;
DIP_STACK_TRACE_THIS( Multiply( radialFilter[ scale ], mono[ ii ], ftDestination ));
if( spatialDomainOutput ) {
DIP_STACK_TRACE_THIS( FourierTransform( ftDestination, destination, options ));
}
}
}
}
void MonogenicSignalAnalysis(
Image const& in,
ImageRefArray& out,
StringArray const& outputs,
dfloat noiseThreshold,
dfloat frequencySpreadThreshold,
dfloat sigmoidParameter,
dfloat deviationGain,
String const& polarity
) {
DIP_THROW_IF( !in.IsForged(), E::IMAGE_NOT_FORGED );
DIP_THROW_IF( in.DataType() != DT_SFLOAT, E::DATA_TYPE_NOT_SUPPORTED );
dip::uint nDims = in.Dimensionality();
DIP_THROW_IF( in.TensorShape() != Tensor::Shape::COL_MAJOR_MATRIX || ( in.TensorRows() != nDims + 1 ), "Input must be a tensor image as produced by dip::MonogenicSignal" );
dip::uint nScales = in.TensorColumns();
dip::uint nOut = out.size();
DIP_THROW_IF( outputs.size() != nOut, E::ARRAY_SIZES_DONT_MATCH );
Image* congruency = nullptr;
Image* orientation = nullptr;
Image* phase = nullptr;
Image* energy = nullptr;
Image* symmetry = nullptr;
Image* symenergy = nullptr;
for( dip::uint ii = 0; ii < nOut; ++ii ) {
if( outputs[ ii ] == "congruency" ) {
congruency = &out[ ii ].get();
} else if( outputs[ ii ] == "orientation" ) {
DIP_THROW_IF( nDims != 2, E::DIMENSIONALITY_NOT_SUPPORTED );
orientation = &out[ ii ].get();
} else if( outputs[ ii ] == "phase" ) {
phase = &out[ ii ].get();
} else if( outputs[ ii ] == "energy" ) {
energy = &out[ ii ].get();
} else if( outputs[ ii ] == "symmetry" ) {
symmetry = &out[ ii ].get();
} else if( outputs[ ii ] == "symenergy" ) {
symenergy = &out[ ii ].get();
} else {
DIP_THROW_INVALID_FLAG( outputs[ ii ] );
}
}
if( congruency || symmetry ) {
DIP_THROW_IF( noiseThreshold <= 0, E::INVALID_PARAMETER );
}
bool kovesi = false;
if( congruency ) {
if(( nDims == 2 ) && ( nScales > 2 )) {
DIP_THROW_IF( frequencySpreadThreshold <= 0, E::INVALID_PARAMETER );
DIP_THROW_IF( sigmoidParameter <= 0, E::INVALID_PARAMETER );
DIP_THROW_IF( deviationGain <= 0, E::INVALID_PARAMETER );
kovesi = true;
} else {
DIP_THROW_IF( nScales != 2, "Phase congruency for dimensionalities other than 2 can only be computed when given two scales." );
}
}
dip::sint polarityValue = 0;
if( symmetry || symenergy ) {
if( polarity == S::BLACK ) {
polarityValue = -1;
} else if( polarity == S::WHITE ) {
polarityValue = 1;
} else if( polarity != S::BOTH ) {
DIP_THROW_INVALID_FLAG( polarity );
}
}
Image temp1;
if( congruency && !energy ) {
energy = &temp1;
}
Image temp2;
if( symmetry && !symenergy ) {
symenergy = &temp2;
}
// Accumulate data across scales
Image thisScale = in.TensorColumn( 0 );
Image sum;
if( orientation || phase || energy ) {
sum = Image( in.TensorColumn( 0 )).Copy(); // sum of individual components across scales
}
Image oddAmplitude = SquareNorm( thisScale[ Range( 1, -1 ) ] );
Image sumAmplitude = thisScale[ 0 ] * thisScale[ 0 ];
sumAmplitude += oddAmplitude;
Sqrt( sumAmplitude, sumAmplitude ); // sum of amplitudes across scales
Image maxAmplitude;
if( congruency ) {
maxAmplitude = sumAmplitude.Copy(); // maximum amplitude across scales
}
if( symenergy ) {
if( polarityValue > 0 ) { // S::WHITE
( *symenergy ).Copy( thisScale[ 0 ] );
} else if( polarityValue < 0 ) { // S::BLACK
Invert( thisScale[ 0 ], *symenergy );
} else { // S::BOTH
Abs( thisScale[ 0 ], *symenergy );
}
Sqrt( oddAmplitude, oddAmplitude );
Subtract( *symenergy, oddAmplitude, *symenergy );
}
for( dip::uint scale = 1; scale < nScales; ++scale ) {
thisScale = in.TensorColumn( scale );
oddAmplitude = SquareNorm( thisScale[ Range( 1, -1 ) ] );
Image amp = thisScale[ 0 ] * thisScale[ 0 ];
amp += oddAmplitude;
Sqrt( amp, amp );
sumAmplitude += amp;
if( orientation || phase || energy ) {
sum += in.TensorColumn( scale );
}
if( congruency ) {
Supremum( maxAmplitude, amp, maxAmplitude );
}
if( symenergy ) {
if( polarityValue == 1 ) { // S::WHITE
Add( *symenergy, thisScale[ 0 ], *symenergy );
} else if( polarityValue < 0 ) { // S::BLACK
Subtract( *symenergy, thisScale[ 0 ], *symenergy );
} else { // S::BOTH
Add( *symenergy, Abs( thisScale[ 0 ] ), *symenergy );
}
Sqrt( oddAmplitude, oddAmplitude );
Subtract( *symenergy, oddAmplitude, *symenergy );
}
}
if( orientation ) {
Orientation( sum[ Range( 1, 2 ) ], *orientation ); // specifically 2D.
}
if( phase ) {
Atan2( sum[ 0 ], Norm( sum[ Range( 1, -1 ) ] ), *phase );
}
if( energy ) {
Norm( sum, *energy );
}
if( congruency ) {
if( kovesi ) {
// Kovesi's method, 2D only
// Compute the sigmoidal weighting
Image width = maxAmplitude; // re-use the memory allocated for maxAmplitude, which we won't need any more.
SafeDivide( sumAmplitude, maxAmplitude, width );
width -= 1;
width /= nScales - 1; // value related to the width of the frequency distribution, between 0 and 1.
Image& weight = width; // again re-use memory
weight = 1.0 / ( 1.0 + Exp(( frequencySpreadThreshold - width ) * sigmoidParameter )); // TODO: make this part better
// Phase congruency
SafeDivide( *energy, sumAmplitude, *congruency );
Acos( *congruency, *congruency );
*congruency *= deviationGain;
Subtract( 1, *congruency, *congruency );
ClipLow( *congruency, *congruency, 0 );
MultiplySampleWise( weight, *congruency, *congruency );
Image excessEnergy = *energy - noiseThreshold;
ClipLow( excessEnergy, excessEnergy, 0 );
SafeDivide( excessEnergy, *energy, excessEnergy );
MultiplySampleWise( *congruency, excessEnergy, *congruency );
} else {
// Felsberg's method
// TODO: repeating some computations here, refine code above to prevent this!
Image dot = DotProduct( in.TensorColumn( 0 ), in.TensorColumn( 1 ));
Image prodAmplitude = Norm( in.TensorColumn( 0 ));
prodAmplitude *= Norm( in.TensorColumn( 1 ));
Image sinphi = dot / prodAmplitude;
Acos( sinphi, sinphi );
Sin( sinphi, sinphi );
sinphi += 1;
sinphi *= prodAmplitude;
Subtract( dot, noiseThreshold, *congruency );
ClipLow( *congruency, *congruency, 0 );
*congruency /= sinphi;
}
}
if( symmetry ) {
// Phase symmetry
Subtract( *symenergy, noiseThreshold, *symmetry, DT_SFLOAT );
ClipLow( *symmetry, *symmetry, 0 );
SafeDivide( *symmetry, sumAmplitude, *symmetry );
}
}
} // namespace dip
| 38.171717 | 175 | 0.61339 | [
"shape",
"transform"
] |
7e0a6b08a2498f3cb4ea2855ffb4bdc655de5c06 | 783 | cpp | C++ | 203.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | 203.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | 203.cpp | machinecc/leetcode | 32bbf6c1f9124049c046a235c85b14ca9168daa8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <string>
#include <unordered_set>
#include <vector>
#include <algorithm>
#include <climits>
#include <stack>
#include <sstream>
#include <numeric>
#include <unordered_map>
#include <array>
#include "common.h"
using namespace std;
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode dummy(0);
dummy.next = head;
ListNode* prev = &dummy;
ListNode* p = head;
while (p) {
if (p->val == val) {
prev->next = p->next;
delete p;
p = prev -> next;
}
else {
prev = prev -> next;
p = p -> next;
}
}
return dummy.next;
}
};
int main() {
return 0;
} | 15.352941 | 55 | 0.535121 | [
"vector"
] |
7e0bf038942077215db8b45659b35ccec4d98722 | 8,724 | cpp | C++ | Run3SoundRuntime.cpp | Sgw32/R3E | 8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd | [
"MIT"
] | 7 | 2017-11-27T15:15:08.000Z | 2021-03-29T16:53:22.000Z | Run3SoundRuntime.cpp | Sgw32/R3E | 8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd | [
"MIT"
] | null | null | null | Run3SoundRuntime.cpp | Sgw32/R3E | 8a55dd137d9e102cf4c9c2fee3d89901bdefa3cd | [
"MIT"
] | 4 | 2017-11-28T02:53:19.000Z | 2021-01-29T10:37:52.000Z | /////////////////////////////////////////////////////////////////////
///////////////Original file by:Fyodor Zagumennov aka Sgw32//////////
///////////////Copyright(c) 2010 Fyodor Zagumennov //////////
/////////////////////////////////////////////////////////////////////
#include "Run3SoundRuntime.h"
template<> Run3SoundRuntime *Singleton<Run3SoundRuntime>::ms_Singleton=0;
Run3SoundRuntime::Run3SoundRuntime()
{
}
Run3SoundRuntime::~Run3SoundRuntime()
{
}
void Run3SoundRuntime::init()
{
//global::getSingleton().getRoot()->addFrameListener(this);
sMgr=global::getSingleton().getSoundManager();
ply=global::getSingleton().getPlayer();
}
void Run3SoundRuntime::emitSound(String sound, Real duration, bool loop)
{
/*if (sound=="none")
return;
durations.push_back(duration);
unsigned int s;
sMgr->loadAudio(sound,&s,loop);
sMgr->setSound(s,Vector3::ZERO,Vector3::ZERO,Vector3::ZERO,100000,false,false,100000,100000,100000);
sMgr->playAudio(s,false);
String msg = sound;
msg+=StringConverter::toString(duration);
LogManager::getSingleton().logMessage("Playing sound: file "+msg);
sounds.push_back(s);
dists.push_back(0);
poss.push_back(Vector3(0,0,0));
optim.push_back(false);
fileNames.push_back(sound);*/
if (durations.size()>MAX_AUDIO_SOURCES-1)
return;
if (sound=="none")
return;
durations.push_back(duration);
unsigned int s;
sMgr->loadAudio(sound,&s,loop);
sMgr->setSound(s,global::getSingleton().getPlayer()->get_location(),Vector3(1,1,1),Vector3(1,1,1),60000.0f,false,false,60000.0f,1,30000.0f);
sMgr->playAudio(s,false);
String msg = sound;
msg+=StringConverter::toString(duration);
LogManager::getSingleton().logMessage("Playing sound: file "+msg);
sounds.push_back(s);
dists.push_back(0);
poss.push_back(Vector3(0,0,0));
optim.push_back(false);
fileNames.push_back(sound);
}
void Run3SoundRuntime::emitSound(String sound, Real duration, bool loop,Vector3 pos,Real dist,Real fallofDist)
{
if (durations.size()>MAX_AUDIO_SOURCES-1)
return;
if (sound=="none")
return;
durations.push_back(duration);
unsigned int s;
sMgr->loadAudio(sound,&s,loop);
sMgr->setSound(s,pos,Vector3::ZERO,Vector3::ZERO,dist,false,false,dist,dist,dist);
sMgr->playAudio(s,false);
String msg = sound;
msg+=StringConverter::toString(duration);
LogManager::getSingleton().logMessage("Playing sound: file "+msg);
sounds.push_back(s);
dists.push_back(0);
poss.push_back(Vector3(0,0,0));
optim.push_back(false);
fileNames.push_back(sound);
}
void Run3SoundRuntime::emitSound(String sound, Real duration, bool loop,Vector3 pos,Real minGain,Real rolloff,Real fallofDist)
{
if (durations.size()>MAX_AUDIO_SOURCES-1)
return;
if (sound=="none")
return;
durations.push_back(duration);
unsigned int s;
sMgr->loadAudio(sound,&s,loop);
sMgr->setSound(s,pos,Vector3::ZERO,Vector3::ZERO,1000,false,false,minGain,rolloff,fallofDist);
sMgr->playAudio(s,false);
String msg = sound;
msg+=StringConverter::toString(duration);
LogManager::getSingleton().logMessage("Playing sound: file "+msg);
sounds.push_back(s);
dists.push_back(0);
poss.push_back(Vector3(0,0,0));
optim.push_back(false);
fileNames.push_back(sound);
}
void Run3SoundRuntime::emitSoundOp(String sound, Real duration, bool loop,Vector3 pos,Real dist,Real fallofDist)
{
if (durations.size()>MAX_AUDIO_SOURCES-1)
return;
if (sound=="none")
return;
durations.push_back(duration);
/*unsigned int s;
sMgr->loadAudio(sound,&s,loop);
sMgr->setSound(s,pos,Vector3::ZERO,Vector3::ZERO,dist,false,false,dist,dist,dist);
sMgr->playAudio(s,false);*/
//String msg = sound;
//msg+=StringConverter::toString(duration);
//LogManager::getSingleton().logMessage("Playing sound: file "+msg);
sounds.push_back(0);
dists.push_back(dist);
poss.push_back(pos);
optim.push_back(true);
fileNames.push_back(sound);
}
void Run3SoundRuntime::emitCollideSound(int type, Vector3 pos)
{
}
void Run3SoundRuntime::addAmbientSound(String sound, Vector3 pos, Real dist, Real fallofDist)
{
LogManager::getSingleton().logMessage("adding AmbientSound1 to environment...");
AmbientSound s = AmbientSound(sMgr,sound,pos,dist,fallofDist);
asounds.push_back(s);
}
void Run3SoundRuntime::addAmbientSound(String name,String sound, Vector3 pos, Real dist, Real fallofDist)
{
LogManager::getSingleton().logMessage("adding AmbientSound2 to environment...");
AmbientSound s = AmbientSound(sMgr,sound,pos,dist,fallofDist);
s.setName(name);
asounds.push_back(s);
}
void Run3SoundRuntime::addAmbientSound(String name,String sound, Vector3 pos, Real dist, Real fallofDist,Real gain)
{
LogManager::getSingleton().logMessage("adding AmbientSound3 to environment...");
AmbientSound s = AmbientSound(sMgr,sound,pos,dist,fallofDist,gain);
s.setName(name);
asounds.push_back(s);
}
void Run3SoundRuntime::disableAmbientSound(String name)
{
LogManager::getSingleton().logMessage("Disabling AmbientSound ...");
vector<AmbientSound>::iterator it;
for (it=asounds.begin();it!=asounds.end();it++)
{
if ((*it).getName()==name)
{
LogManager::getSingleton().logMessage("Found.");
(*it).disableAmbientSound();
}
}
}
void Run3SoundRuntime::enableAmbientSound(String name)
{
LogManager::getSingleton().logMessage("Enabling AmbientSound ...");
vector<AmbientSound>::iterator it;
for (it=asounds.begin();it!=asounds.end();it++)
{
if ((*it).getName()==name)
{
LogManager::getSingleton().logMessage("Found.");
(*it).enableAmbientSound();
}
}
}
void Run3SoundRuntime::clearAmbientSounds()
{
vector<AmbientSound>::iterator it;
for (it=asounds.begin();it!=asounds.end();it++)
{
(*it).destroy();
}
asounds.clear();
durations.clear();
sounds.clear();
dists.clear();
poss.clear();
optim.clear();
fileNames.clear();
}
//Kostil
void Run3SoundRuntime::recheckAmbientSounds()
{
vector<AmbientSound>::iterator it;
for (it=asounds.begin();it!=asounds.end();it++)
{
(*it).destroy();
}
}
void Run3SoundRuntime::setCheckAmbientSounds()
{
check=3.0f;
}
bool Run3SoundRuntime::frameStarted(const Ogre::FrameEvent &evt)
{
if (check)
{
check-=evt.timeSinceLastFrame;
if (check<0)
{
recheckAmbientSounds();
check=0;
}
}
vector<AmbientSound>::iterator it;
for (it=asounds.begin();it!=asounds.end();it++)
{
if ((*it).getAvailability())
(*it).spawn();
else
(*it).destroy();
}
for(unsigned int i2=0;i2!=durations.size();i2++)
{
if (durations[i2]>0)
{
if (optim[i2])
{
Real l = (ply->get_location()-poss[i2]).length();
if (l>dists[i2]&&sounds[i2]!=0)
{
sMgr->releaseAudio(sounds[i2]);
sounds[i2]=0;
}
if (l<dists[i2]&&sounds[i2]==0)
{
unsigned int s;
sMgr->loadAudio(fileNames[i2],&s,true);
sMgr->setSound(s,poss[i2],Vector3::ZERO,Vector3::ZERO,dists[i2],false,false,dists[i2],dists[i2],dists[i2]);
sMgr->playAudio(s,false);
sounds[i2]=s;
}
}
durations[i2]-=evt.timeSinceLastFrame;
}
if (durations[i2]<=0)
{
durations[i2]=0;
if (sounds[i2]!=256)
{
sMgr->releaseAudio(sounds[i2]);
sounds[i2]=256;
}
}
}
//vector<unsigned int>::iterator i;
unsigned int i;
vector<Real>::iterator j;
vector<Real>::iterator l;
vector<Vector3>::iterator k;
vector<String>::iterator m;
vector<bool>::iterator o;
vector<unsigned int>::iterator p;
unsigned int s=0;
//part to just-in-time delete sounds from list - "Sgw32 Deleter"
bool stop=true;
//#define DELETE_ITER_SOUND(it,v) it=v.begin();advance(it,i);v.erase(it);
/*while (stop)
{
stop=false;
i=0;
for (j=durations.begin();j!=durations.end();j++)
{
if (!stop)
{
if ((*j)==0.0f)
{
durations.erase(j);
//DELETE_ITER_SOUND(l,durations)
DELETE_ITER_SOUND(l,dists)
DELETE_ITER_SOUND(p,sounds)
DELETE_ITER_SOUND(k,poss)
DELETE_ITER_SOUND(o,optim)
DELETE_ITER_SOUND(m,fileNames)
stop=true;
}
i++;
if (stop)
break;
}
}
}*/
#define DELETE_ITER_SOUND(it,v) v.erase(it);
l = dists.begin();
p = sounds.begin();
k = poss.begin();
o = optim.begin();
m = fileNames.begin();
for (j=durations.begin();j!=durations.end();)
{
if ((*j)==0.0f)
{
durations.erase(j);
DELETE_ITER_SOUND(l,dists)
DELETE_ITER_SOUND(p,sounds)
DELETE_ITER_SOUND(k,poss)
DELETE_ITER_SOUND(o,optim)
DELETE_ITER_SOUND(m,fileNames)
continue;
}
j++;
l++;
p++;
k++;
o++;
m++;
}
//#undef DELETE_ITER_SOUND
for(unsigned int m=0;m!=durations.size();m++)
{
Real d =durations[m];
if (d>0)
return true;
}
durations.clear();
sounds.clear();
dists.clear();
poss.clear();
optim.clear();
fileNames.clear();
return true;
} | 24.574648 | 141 | 0.672054 | [
"vector"
] |
7e136f6aded79a421a9ece975a7182a1ca007c78 | 2,352 | cpp | C++ | component/oai-nrf/src/api-server/model/AccessTokenErr.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-nrf/src/api-server/model/AccessTokenErr.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-nrf/src/api-server/model/AccessTokenErr.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | /**
* NRF OAuth2
* NRF OAuth2 Authorization. © 2019, 3GPP Organizational Partners (ARIB, ATIS,
* CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
*
* The version of the OpenAPI document: 1.0.2
*
*
* NOTE: This class is auto generated by OpenAPI Generator
* (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
* the class manually.
*/
#include "AccessTokenErr.h"
namespace oai {
namespace nrf {
namespace model {
AccessTokenErr::AccessTokenErr() {
m_Error = "";
m_Error_description = "";
m_Error_descriptionIsSet = false;
m_Error_uri = "";
m_Error_uriIsSet = false;
}
AccessTokenErr::~AccessTokenErr() {}
void AccessTokenErr::validate() {
// TODO: implement validation
}
void to_json(nlohmann::json& j, const AccessTokenErr& o) {
j = nlohmann::json();
j["error"] = o.m_Error;
if (o.errorDescriptionIsSet()) j["error_description"] = o.m_Error_description;
if (o.errorUriIsSet()) j["error_uri"] = o.m_Error_uri;
}
void from_json(const nlohmann::json& j, AccessTokenErr& o) {
j.at("error").get_to(o.m_Error);
if (j.find("error_description") != j.end()) {
j.at("error_description").get_to(o.m_Error_description);
o.m_Error_descriptionIsSet = true;
}
if (j.find("error_uri") != j.end()) {
j.at("error_uri").get_to(o.m_Error_uri);
o.m_Error_uriIsSet = true;
}
}
std::string AccessTokenErr::getError() const {
return m_Error;
}
void AccessTokenErr::setError(std::string const& value) {
m_Error = value;
}
std::string AccessTokenErr::getErrorDescription() const {
return m_Error_description;
}
void AccessTokenErr::setErrorDescription(std::string const& value) {
m_Error_description = value;
m_Error_descriptionIsSet = true;
}
bool AccessTokenErr::errorDescriptionIsSet() const {
return m_Error_descriptionIsSet;
}
void AccessTokenErr::unsetError_description() {
m_Error_descriptionIsSet = false;
}
std::string AccessTokenErr::getErrorUri() const {
return m_Error_uri;
}
void AccessTokenErr::setErrorUri(std::string const& value) {
m_Error_uri = value;
m_Error_uriIsSet = true;
}
bool AccessTokenErr::errorUriIsSet() const {
return m_Error_uriIsSet;
}
void AccessTokenErr::unsetError_uri() {
m_Error_uriIsSet = false;
}
} // namespace model
} // namespace nrf
} // namespace oai
| 26.426966 | 80 | 0.698129 | [
"model"
] |
7e157d07ae4be0f30be52336628190ea8b54ede1 | 7,458 | cpp | C++ | src/prod/src/Management/HttpTransport/requestmessagecontext.linux.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 1 | 2018-03-15T02:09:21.000Z | 2018-03-15T02:09:21.000Z | src/prod/src/Management/HttpTransport/requestmessagecontext.linux.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | src/prod/src/Management/HttpTransport/requestmessagecontext.linux.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
#include "cpprest/json.h"
#include "cpprest/http_listener.h"
#include "cpprest/uri.h"
#include "cpprest/asyncrt_utils.h"
#include "requestmessagecontext.linux.h"
#include "Common/CryptoUtility.Linux.h"
using namespace Common;
using namespace Transport;
using namespace std;
using namespace web;
using namespace utility;
using namespace http;
using namespace web::http::experimental::listener;
using namespace HttpServer;
static const StringLiteral TraceType("RequestMessageContext");
RequestMessageContext::RequestMessageContext(): responseUPtr_(new web::http::http_response()) {}
RequestMessageContext::RequestMessageContext(http_request& message): requestUPtr_(new http_request(message)),
responseUPtr_(new web::http::http_response())
{
}
RequestMessageContext::~RequestMessageContext()
{
}
ErrorCode RequestMessageContext::TryParseRequest()
{
//LINUXTODO: get full uri
string requesturi = "http://localhost" + requestUPtr_->absolute_uri().to_string();
string verb = requestUPtr_->method();
string relativeuri = requestUPtr_->relative_uri().to_string();
StringUtility::Utf8ToUtf16(requesturi, url_);
StringUtility::Utf8ToUtf16(verb, verb_);
StringUtility::Utf8ToUtf16(relativeuri, suffix_);
//If client specifies a RequestId in header "X-ServiceFabricRequestId", use it for correlation
auto error = GetRequestHeader(HttpCommon::HttpConstants::ServiceFabricHttpClientRequestIdHeader, clientRequestId_);
if (!error.IsSuccess())
{
clientRequestId_ = Guid::NewGuid().ToString();
}
return ErrorCode::Success();
}
std::wstring const& RequestMessageContext::GetVerb() const
{
return verb_;
}
std::wstring RequestMessageContext::GetUrl() const
{
return url_;
}
std::wstring RequestMessageContext::GetSuffix() const
{
return suffix_;
}
wstring RequestMessageContext::GetClientRequestId() const
{
return clientRequestId_;
}
ErrorCode RequestMessageContext::GetRequestHeader(__in wstring const &headerName, __out wstring &headerValue) const
{
string value;
string name;
StringUtility::Utf16ToUtf8(headerName, name);
if (requestUPtr_->headers().match(name, value))
{
StringUtility::Utf8ToUtf16(value, headerValue);
return ErrorCode::Success();
}
return ErrorCode::FromNtStatus(STATUS_NOT_FOUND);
}
ErrorCode RequestMessageContext::GetClientToken(__out HANDLE &hToken) const
{
hToken = INVALID_HANDLE_VALUE;
return ErrorCode::Success();
}
AsyncOperationSPtr RequestMessageContext::BeginGetClientCertificate(
__in Common::AsyncCallback const& callback,
__in Common::AsyncOperationSPtr const& parent) const
{
return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(callback, parent);
}
/// This passes raw pointer, life cycle of this ssl* is managed by underlying casablanca m_ssl_stream in connection object.
ErrorCode RequestMessageContext::EndGetClientCertificate(
__in Common::AsyncOperationSPtr const& operation,
__out SSL** sslContext) const
{
*sslContext = const_cast<SSL*>(requestUPtr_->client_ssl());
if(*sslContext)
{
X509* cert = SSL_get_peer_certificate(*sslContext);
if(cert)
{
string commonname;
LinuxCryptUtil().GetCommonName(cert, commonname);
Trace.WriteInfo(TraceType, "Certificate object found with CN={0}", commonname);
}
else
{
Trace.WriteError(TraceType, "Certificate object not found");
return ErrorCodeValue::InvalidCredentials;
}
}
return ErrorCode::Success();
}
ErrorCode RequestMessageContext::GetRemoteAddress(__out wstring &remoteAddress) const
{
// get ip address of host machine
remoteAddress = L"";
return ErrorCode::Success();
}
ErrorCode RequestMessageContext::SetResponseHeader(__in wstring const &headerName, __in wstring const &headerValue)
{
string name;
string value;
StringUtility::Utf16ToUtf8(headerName, name);
StringUtility::Utf16ToUtf8(headerValue, value);
http_headers& responseHeader = responseUPtr_->headers();
responseHeader.add(name, value);
return ErrorCode::Success();
}
AsyncOperationSPtr RequestMessageContext::BeginSendResponse(
__in ErrorCode operationStatus,
__in ByteBufferUPtr bodyUPtr,
__in Common::AsyncCallback const& callback,
__in Common::AsyncOperationSPtr const& parent)
{
return AsyncOperation::CreateAndStart<SendResponseAsyncOperation>(operationStatus, move(bodyUPtr), *this, callback, parent);
}
AsyncOperationSPtr RequestMessageContext::BeginSendResponse(
__in USHORT statusCode,
__in std::wstring description,
__in Common::ByteBufferUPtr bodyUPtr,
__in Common::AsyncCallback const& callback,
__in Common::AsyncOperationSPtr const& parent)
{
return AsyncOperation::CreateAndStart<SendResponseAsyncOperation>(statusCode, description, move(bodyUPtr), *this, callback, parent);
}
ErrorCode RequestMessageContext::EndSendResponse(
__in AsyncOperationSPtr const& operation)
{
return SendResponseAsyncOperation::End(operation);
}
AsyncOperationSPtr RequestMessageContext::BeginGetMessageBody(
__in Common::AsyncCallback const& callback,
__in Common::AsyncOperationSPtr const& parent) const
{
return AsyncOperation::CreateAndStart<CompletedAsyncOperation>(callback, parent);
}
ErrorCode RequestMessageContext::EndGetMessageBody(
__in AsyncOperationSPtr const& operation,
__out ByteBufferUPtr &body) const
{
try
{
// move this to separate asycn method.
// extract vector of char body from request.
// TODO: Change this to a continuation
body = make_unique<ByteBuffer>(move(requestUPtr_->extract_vector().get()));
}
catch (...)
{
auto eptr = std::current_exception();
RequestMessageContext::HandleException(eptr, GetClientRequestId());
}
return CompletedAsyncOperation::End(operation);
}
AsyncOperationSPtr RequestMessageContext::BeginGetFileFromUpload(
__in ULONG fileSize,
__in ULONG maxEntityBodyForUploadChunkSize,
__in ULONG defaultEntityBodyForUploadChunkSize,
__in Common::AsyncCallback const& callback,
__in Common::AsyncOperationSPtr const& parent) const
{
return AsyncOperation::CreateAndStart<GetFileFromUploadAsyncOperation>(*this, fileSize, maxEntityBodyForUploadChunkSize, defaultEntityBodyForUploadChunkSize, callback, parent);
}
ErrorCode RequestMessageContext::EndGetFileFromUpload(
__in AsyncOperationSPtr const& operation,
__out wstring & uniqueFileName) const
{
return GetFileFromUploadAsyncOperation::End(operation, uniqueFileName);
}
void RequestMessageContext::HandleException(std::exception_ptr eptr, std::wstring const& clientRequestId)
{
try
{
if (eptr)
{
std::rethrow_exception(eptr);
}
}
catch (const std::exception& e)
{
Trace.WriteInfo(TraceType, "Exception while replying to http_request. Client Request Id : {0}, Exception details : {1}", clientRequestId, e.what());
}
catch (...)
{
Trace.WriteError(TraceType, "Unknown Exception while replying to http_request. Client Request Id : {0}", clientRequestId);
}
}
| 31.601695 | 180 | 0.735318 | [
"object",
"vector"
] |
7e1a494f441aef0d613ea9a834a939c0222eb38e | 1,634 | cpp | C++ | aws-cpp-sdk-translate/source/model/TranslationSettings.cpp | irods/aws-sdk-cpp | ea5a4d61a26c1eac41443fb9829e969ebac6e09b | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-translate/source/model/TranslationSettings.cpp | irods/aws-sdk-cpp | ea5a4d61a26c1eac41443fb9829e969ebac6e09b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-translate/source/model/TranslationSettings.cpp | irods/aws-sdk-cpp | ea5a4d61a26c1eac41443fb9829e969ebac6e09b | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/translate/model/TranslationSettings.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Translate
{
namespace Model
{
TranslationSettings::TranslationSettings() :
m_formality(Formality::NOT_SET),
m_formalityHasBeenSet(false),
m_profanity(Profanity::NOT_SET),
m_profanityHasBeenSet(false)
{
}
TranslationSettings::TranslationSettings(JsonView jsonValue) :
m_formality(Formality::NOT_SET),
m_formalityHasBeenSet(false),
m_profanity(Profanity::NOT_SET),
m_profanityHasBeenSet(false)
{
*this = jsonValue;
}
TranslationSettings& TranslationSettings::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Formality"))
{
m_formality = FormalityMapper::GetFormalityForName(jsonValue.GetString("Formality"));
m_formalityHasBeenSet = true;
}
if(jsonValue.ValueExists("Profanity"))
{
m_profanity = ProfanityMapper::GetProfanityForName(jsonValue.GetString("Profanity"));
m_profanityHasBeenSet = true;
}
return *this;
}
JsonValue TranslationSettings::Jsonize() const
{
JsonValue payload;
if(m_formalityHasBeenSet)
{
payload.WithString("Formality", FormalityMapper::GetNameForFormality(m_formality));
}
if(m_profanityHasBeenSet)
{
payload.WithString("Profanity", ProfanityMapper::GetNameForProfanity(m_profanity));
}
return payload;
}
} // namespace Model
} // namespace Translate
} // namespace Aws
| 21.220779 | 89 | 0.74541 | [
"model"
] |
7e1e6dadaa355d156644e4cd8a7647a0b1415db3 | 35,554 | cpp | C++ | src/Map.cpp | richard5635/PlaneLoc | aab6637124b1b99ad726a94e9f6762dddf3716b5 | [
"MIT"
] | 22 | 2017-08-29T06:22:07.000Z | 2021-12-29T07:42:31.000Z | src/Map.cpp | richard5635/PlaneLoc | aab6637124b1b99ad726a94e9f6762dddf3716b5 | [
"MIT"
] | 5 | 2019-03-26T06:10:18.000Z | 2021-11-26T01:59:41.000Z | src/Map.cpp | richard5635/PlaneLoc | aab6637124b1b99ad726a94e9f6762dddf3716b5 | [
"MIT"
] | 14 | 2018-04-24T08:49:01.000Z | 2021-12-15T07:56:58.000Z | /*
Copyright (c) 2017 Mobile Robots Laboratory at Poznan University of Technology:
-Jan Wietrzykowski name.surname [at] put.poznan.pl
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 <iostream>
#include <chrono>
#include <thread>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>
#include <opencv2/imgproc.hpp>
#include <Eigen/Dense>
#include <pcl/io/ply_io.h>
#include <pcl/common/transforms.h>
#include <g2o/types/slam3d/se3quat.h>
#include <Misc.hpp>
#include "Map.hpp"
#include "PlaneSegmentation.hpp"
#include "Exceptions.hpp"
#include "Types.hpp"
#include "Serialization.hpp"
using namespace std;
bool operator<(const PendingMatchKey &lhs, const PendingMatchKey &rhs) {
auto lit = lhs.matchedIds.begin();
auto rit = rhs.matchedIds.begin();
for( ; lit != lhs.matchedIds.end() && rit != rhs.matchedIds.end(); ++lit, ++rit){
if(*lit < *rit){
return true;
}
else if(*lit > *rit){
return false;
}
// continue if equal
}
// if lhs has fewer elements
if(lit == lhs.matchedIds.end() && rit != rhs.matchedIds.end()){
return true;
}
// if lhs has the same number of elements or more elements
else {
return false;
}
}
Map::Map()
: originalPointCloud(new pcl::PointCloud<pcl::PointXYZRGB>())
{
settings.eolObjInstInit = 4;
settings.eolObjInstIncr = 2;
settings.eolObjInstDecr = 1;
settings.eolObjInstThresh = 8;
settings.eolPendingInit = 4;
settings.eolPendingIncr = 2;
settings.eolPendingDecr = 1;
settings.eolPendingThresh = 6;
}
Map::Map(const cv::FileStorage& fs)
:
originalPointCloud(new pcl::PointCloud<pcl::PointXYZRGB>())
{
settings.eolObjInstInit = 4;
settings.eolObjInstIncr = 2;
settings.eolObjInstDecr = 1;
settings.eolObjInstThresh = 8;
settings.eolPendingInit = 4;
settings.eolPendingIncr = 2;
settings.eolPendingDecr = 1;
settings.eolPendingThresh = 6;
if((int)fs["map"]["readFromFile"]){
pcl::visualization::PCLVisualizer::Ptr viewer(new pcl::visualization::PCLVisualizer("map 3D Viewer"));
int v1 = 0;
int v2 = 0;
viewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1);
viewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2);
viewer->addCoordinateSystem();
vector<cv::String> mapFilepaths;
fs["map"]["mapFiles"] >> mapFilepaths;
static constexpr int idShift = 10000000;
for(int f = 0; f < mapFilepaths.size(); ++f) {
Map curMap;
std::ifstream ifs(mapFilepaths[f].c_str());
boost::archive::text_iarchive ia(ifs);
ia >> curMap;
curMap.shiftIds((f + 1)*idShift);
vectorObjInstance curObjInstances;
for(ObjInstance &obj : curMap){
curObjInstances.push_back(obj);
}
mergeNewObjInstances(curObjInstances);
clearPending();
}
cout << "object instances in map: " << objInstances.size() << endl;
if(viewer) {
viewer->removeAllPointClouds(v1);
viewer->removeAllShapes(v1);
viewer->removeAllPointClouds(v2);
viewer->removeAllShapes(v2);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr pcCol = getColorPointCloud();
viewer->addPointCloud(pcCol, "cloud_color_map", v1);
pcl::PointCloud<pcl::PointXYZL>::Ptr pcLab = getLabeledPointCloud();
viewer->addPointCloud(pcLab, "cloud_labeled_map", v2);
viewer->resetStoppedFlag();
viewer->initCameraParameters();
viewer->setCameraPosition(0.0, 0.0, -6.0, 0.0, 1.0, 0.0);
viewer->spinOnce(100);
// while (!viewer->wasStopped()) {
// viewer->spinOnce(100);
// std::this_thread::sleep_for(std::chrono::milliseconds(50));
// }
}
}
}
void Map::addObj(ObjInstance &obj) {
objInstances.push_back(obj);
objInstIdToIter[obj.getId()] = --(objInstances.end());
}
void Map::addObjs(vectorObjInstance::iterator beg, vectorObjInstance::iterator end) {
for(auto it = beg; it != end; ++it){
addObj(*it);
}
}
void Map::mergeNewObjInstances(vectorObjInstance &newObjInstances,
const std::map<int, int> &idToCnt,
pcl::visualization::PCLVisualizer::Ptr viewer,
int viewPort1,
int viewPort2)
{
static constexpr double shadingLevel = 1.0/8;
static const int cntThreshMerge = 1000;
chrono::high_resolution_clock::time_point startTime = chrono::high_resolution_clock::now();
if(viewer){
viewer->removeAllPointClouds();
viewer->removeAllShapes();
{
int pl = 0;
for (auto it = objInstances.begin(); it != objInstances.end(); ++it, ++pl) {
// cout << "adding plane " << pl << endl;
ObjInstance &mapObj = *it;
const pcl::PointCloud<pcl::PointXYZRGB>::Ptr curPl = mapObj.getPoints();
viewer->addPointCloud(curPl, string("plane_ba_") + to_string(pl), viewPort1);
viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY,
shadingLevel,
string("plane_ba_") + to_string(pl),
viewPort1);
if(!idToCnt.empty()){
int cnt = 0;
if(idToCnt.count(mapObj.getId()) > 0){
cnt = idToCnt.at(mapObj.getId());
}
Eigen::Vector3d cent = mapObj.getPlaneEstimator().getCentroid();
viewer->addText3D("id: " + to_string(mapObj.getId()) +
", cnt: " + to_string(cnt) +
", eol: " + to_string(mapObj.getEolCnt()),
pcl::PointXYZ(cent(0), cent(1), cent(2)),
0.05,
1.0, 1.0, 1.0,
string("plane_text_ba_") + to_string(pl),
viewPort1);
}
}
}
{
int npl = 0;
for (ObjInstance &newObj : newObjInstances) {
const pcl::PointCloud<pcl::PointXYZRGB>::Ptr curPl = newObj.getPoints();
viewer->addPointCloud(curPl, string("plane_nba_") + to_string(npl), viewPort2);
viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY,
shadingLevel,
string("plane_nba_") + to_string(npl),
viewPort2);
++npl;
}
}
}
vectorObjInstance addedObjs;
int npl = 0;
for(ObjInstance &newObj : newObjInstances){
// cout << "npl = " << npl << endl;
if(viewer){
viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY,
7.0/8,
string("plane_nba_") + to_string(npl),
viewPort2);
newObj.getHull().display(viewer, viewPort2);
}
vector<list<ObjInstance>::iterator> matches;
int pl = 0;
for(auto it = objInstances.begin(); it != objInstances.end(); ++it, ++pl) {
// cout << "pl = " << pl << endl;
ObjInstance &mapObj = *it;
if(idToCnt.empty() || (idToCnt.count(mapObj.getId()) > 0 && idToCnt.at(mapObj.getId()) > cntThreshMerge)) {
if (viewer) {
viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY,
7.0/8,
string("plane_ba_") + to_string(pl),
viewPort1);
mapObj.getHull().display(viewer, viewPort1);
}
if (mapObj.isMatching(newObj/*,
viewer,
viewPort1,
viewPort2*/)) {
// cout << "Merging planes" << endl;
matches.push_back(it);
}
if (viewer) {
viewer->resetStoppedFlag();
static bool cameraInit = false;
if (!cameraInit) {
viewer->initCameraParameters();
viewer->setCameraPosition(0.0, 0.0, -6.0, 0.0, 1.0, 0.0);
cameraInit = true;
}
while (!viewer->wasStopped()) {
viewer->spinOnce(100);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY,
shadingLevel,
string("plane_ba_") + to_string(pl),
viewPort1);
mapObj.getHull().cleanDisplay(viewer, viewPort1);
}
}
}
if(matches.size() == 0){
addedObjs.push_back(newObj);
newObj.setEolCnt(settings.eolObjInstInit);
}
else if(matches.size() == 1){
ObjInstance &mapObj = *matches.front();
mapObj.merge(newObj);
mapObj.increaseEolCnt(settings.eolObjInstIncr);
}
else{
set<int> matchedIds;
for(auto it : matches){
matchedIds.insert(it->getId());
}
PendingMatchKey pmatchKey{matchedIds};
if(getPendingMatch(pmatchKey)){
addPendingObj(newObj, matchedIds, settings.eolPendingIncr);
}
else{
addPendingObj(newObj, matchedIds, settings.eolPendingInit);
}
// cout << "Multiple matches" << endl;
}
if(viewer){
viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY,
shadingLevel,
string("plane_nba_") + to_string(npl),
viewPort2);
newObj.getHull().cleanDisplay(viewer, viewPort2);
}
++npl;
}
addObjs(addedObjs.begin(), addedObjs.end());
executePendingMatches( settings.eolPendingThresh);
decreasePendingEol( settings.eolPendingDecr);
removePendingObjsEol();
if(idToCnt.empty()){
decreaseObjEol(settings.eolObjInstDecr);
}
else {
for (ObjInstance &obj : objInstances) {
if (idToCnt.count(obj.getId()) > 0 && idToCnt.at(obj.getId()) > cntThreshMerge) {
obj.decreaseEolCnt(settings.eolObjInstDecr);
}
}
}
removeObjsEol();
chrono::high_resolution_clock::time_point endTime = chrono::high_resolution_clock::now();
static chrono::milliseconds totalTime = chrono::milliseconds::zero();
static int totalCnt = 0;
totalTime += chrono::duration_cast<chrono::milliseconds>(endTime - startTime);
++totalCnt;
cout << "Mean mergeNewObjInstances time: " << (totalTime.count() / totalCnt) << endl;
}
void Map::mergeMapObjInstances(pcl::visualization::PCLVisualizer::Ptr viewer,
int viewPort1,
int viewPort2)
{
chrono::high_resolution_clock::time_point startTime = chrono::high_resolution_clock::now();
if(viewer) {
for (auto it = objInstances.begin(); it != objInstances.end(); ++it) {
it->display(viewer, viewPort1);
}
}
map<int, int> idToIdx;
vector<listObjInstance::iterator> itrs;
int idx = 0;
for(auto it = objInstances.begin(); it != objInstances.end(); ++it){
idToIdx[it->getId()] = idx;
itrs.push_back(it);
++idx;
}
UnionFind ufSets(idx);
for(auto it = objInstances.begin(); it != objInstances.end(); ++it) {
ObjInstance &mapObj1 = *it;
auto it2 = it;
++it2;
for( ; it2 != objInstances.end(); ++it2){
ObjInstance &mapObj2 = *it2;
if(mapObj1.isMatching(mapObj2)){
ufSets.unionSets(idToIdx[mapObj1.getId()], idToIdx[mapObj2.getId()]);
}
}
}
multimap<int, int> sets;
for(int curIdx = 0; curIdx < idx; ++curIdx){
int setId = ufSets.findSet(curIdx);
sets.insert(make_pair(setId, curIdx));
}
// typedef multimap<int, pair<int, int> >::iterator mmIter;
for(auto it = sets.begin(); it != sets.end(); ) {
auto range = sets.equal_range(it->first);
vector<list<ObjInstance>::iterator> mapObjIts;
cout << endl << endl << "map merging ids:" << endl;
for (auto rangeIt = range.first; rangeIt != range.second; ++rangeIt) {
int curIdx = rangeIt->second;
mapObjIts.push_back(itrs[curIdx]);
cout << itrs[curIdx]->getId() << endl;
}
auto iti = mapObjIts.begin();
auto mergeIt = *iti;
// merge all map objects
for(++iti; iti != mapObjIts.end(); ++iti){
mergeIt->merge(*(*iti));
mergeIt->increaseEolCnt(settings.eolObjInstIncr);
objInstIdToIter.erase((*iti)->getId());
objInstances.erase(*iti);
}
it = range.second;
}
chrono::high_resolution_clock::time_point endTime = chrono::high_resolution_clock::now();
static chrono::milliseconds totalTime = chrono::milliseconds::zero();
static int totalCnt = 0;
totalTime += chrono::duration_cast<chrono::milliseconds>(endTime - startTime);
++totalCnt;
cout << "Mean mergeMapObjInstances time: " << (totalTime.count() / totalCnt) << endl;
}
void Map::addPendingObj(ObjInstance &obj,
const std::set<int> &matchedIds,
int eolAdd)
{
pendingObjInstances.push_back(obj);
pendingIdToIter[obj.getId()] = --(pendingObjInstances.end());
PendingMatchKey pmatchKey = PendingMatchKey{matchedIds};
set<PendingMatchKey>::iterator itKey = pendingMatchesSet.find(pmatchKey);
if(itKey != pendingMatchesSet.end()){
// auto matchIt = itKey->it;
itKey->pmatch->eol += eolAdd;
itKey->pmatch->pendingObjInstanceIds.push_back(obj.getId());
}
else {
vector<int> objInstanceIds;
for(auto it = matchedIds.begin(); it != matchedIds.end(); ++it){
objInstanceIds.push_back(*it);
}
pmatchKey.pmatch.reset(new PendingMatch{matchedIds,
eolAdd,
objInstanceIds,
vector<int>{obj.getId()}});
pendingMatchesSet.insert(pmatchKey);
}
}
//void Map::addPendingObjs(std::vector<ObjInstance>::iterator beg,
// std::vector<ObjInstance>::iterator end,
// int eolAdd) {
//
//}
void Map::removePendingObjsEol() {
for(auto it = pendingMatchesSet.begin(); it != pendingMatchesSet.end(); ){
auto curIt = it++;
cout << "curIt->pmatch->eol = " << curIt->pmatch->eol << endl;
if(curIt->pmatch->eol <= 0) {
for (auto itId = curIt->pmatch->pendingObjInstanceIds.begin();
itId != curIt->pmatch->pendingObjInstanceIds.end(); ++itId) {
int id = *itId;
auto pendingIt = pendingIdToIter.at(id);
pendingIdToIter.erase(id);
pendingObjInstances.erase(pendingIt);
}
pendingMatchesSet.erase(curIt);
}
}
}
void Map::clearPending(){
pendingMatchesSet.clear();
pendingIdToIter.clear();
pendingObjInstances.clear();
}
std::vector<PendingMatchKey> Map::getPendingMatches(int eolThresh) {
vector<PendingMatchKey> retPendingMatches;
for(auto it = pendingMatchesSet.begin(); it != pendingMatchesSet.end(); ++it){
if(it->pmatch->eol > eolThresh){
retPendingMatches.push_back(*it);
}
}
return retPendingMatches;
}
void Map::executePendingMatches(int eolThresh) {
map<int, int> idToIdx;
map<int, int> idxToId;
vector<list<ObjInstance>::iterator> its;
vector<bool> isPending;
int idx = 0;
// assign each ObjInstance an idx
for(auto it = pendingMatchesSet.begin(); it != pendingMatchesSet.end(); ++it) {
if (it->pmatch->eol > eolThresh) {
for(auto itId = it->pmatch->objInstanceIds.begin(); itId != it->pmatch->objInstanceIds.end(); ++itId){
int id = *itId;
idToIdx[id] = idx;
idxToId[idx] = id;
its.push_back(objInstIdToIter.at(id));
isPending.push_back(false);
++idx;
}
for(auto itId = it->pmatch->pendingObjInstanceIds.begin(); itId != it->pmatch->pendingObjInstanceIds.end(); ++itId){
int id = *itId;
idToIdx[id] = idx;
idxToId[idx] = id;
its.push_back(pendingIdToIter.at(id));
isPending.push_back(true);
++idx;
}
}
}
UnionFind ufSets(idx);
for(auto it = pendingMatchesSet.begin(); it != pendingMatchesSet.end(); ) {
if (it->pmatch->eol > eolThresh) {
auto itId = it->pmatch->objInstanceIds.begin();
int mergeIdx = idToIdx[(*itId)];
for(++itId; itId != it->pmatch->objInstanceIds.end(); ++itId){
int curIdx = idToIdx[(*itId)];
ufSets.unionSets(mergeIdx, curIdx);
}
for(itId = it->pmatch->pendingObjInstanceIds.begin(); itId != it->pmatch->pendingObjInstanceIds.end(); ++itId){
int curIdx = idToIdx[(*itId)];
ufSets.unionSets(mergeIdx, curIdx);
}
it = pendingMatchesSet.erase(it);
}
else{
++it;
}
}
multimap<int, int> sets;
for(int curIdx = 0; curIdx < idx; ++curIdx){
int setId = ufSets.findSet(curIdx);
sets.insert(make_pair(setId, curIdx));
}
// typedef multimap<int, pair<int, int> >::iterator mmIter;
for(auto it = sets.begin(); it != sets.end(); ) {
auto range = sets.equal_range(it->first);
vector<list<ObjInstance>::iterator> mapObjIts;
vector<list<ObjInstance>::iterator> pendingObjIts;
cout << endl << endl << "merging ids:" << endl;
for (auto rangeIt = range.first; rangeIt != range.second; ++rangeIt) {
int curIdx = rangeIt->second;
if(isPending[curIdx]){
pendingObjIts.push_back(its[curIdx]);
}
else{
mapObjIts.push_back(its[curIdx]);
}
cout << idxToId[curIdx] << endl;
}
auto iti = mapObjIts.begin();
auto mergeIt = *iti;
// merge all map objects
for(++iti; iti != mapObjIts.end(); ++iti){
mergeIt->merge(*(*iti));
mergeIt->increaseEolCnt(settings.eolObjInstIncr);
objInstIdToIter.erase((*iti)->getId());
objInstances.erase(*iti);
}
// merge all pending objects
for(iti = pendingObjIts.begin(); iti != pendingObjIts.end(); ++iti){
mergeIt->merge(*(*iti));
mergeIt->increaseEolCnt(settings.eolObjInstIncr);
pendingIdToIter.erase((*iti)->getId());
pendingObjInstances.erase(*iti);
}
it = range.second;
}
}
bool Map::getPendingMatch(PendingMatchKey &pendingMatch) {
if(pendingMatchesSet.count(pendingMatch) > 0){
auto it = pendingMatchesSet.find(pendingMatch);
pendingMatch = *it;
return true;
}
return false;
}
void Map::decreasePendingEol(int eolSub) {
for(set<PendingMatchKey>::iterator it = pendingMatchesSet.begin(); it != pendingMatchesSet.end(); ++it){
it->pmatch->eol -= eolSub;
}
}
void Map::decreaseObjEol(int eolSub) {
for(ObjInstance &obj : objInstances){
if(obj.getEolCnt() < settings.eolObjInstThresh){
obj.decreaseEolCnt(eolSub);
}
}
}
void Map::removeObjsEol() {
for(auto it = objInstances.begin(); it != objInstances.end(); ){
if(it->getEolCnt() <= 0){
objInstIdToIter.erase(it->getId());
it = objInstances.erase(it);
}
else{
++it;
}
}
}
void Map::removeObjsEolThresh(int eolThresh) {
for(auto it = objInstances.begin(); it != objInstances.end(); ){
if(it->getEolCnt() < eolThresh){
objInstIdToIter.erase(it->getId());
it = objInstances.erase(it);
}
else{
++it;
}
}
}
void Map::removeObjsObsThresh(int obsThresh) {
for(auto it = objInstances.begin(); it != objInstances.end(); ){
if(it->getObsCnt() < obsThresh){
objInstIdToIter.erase(it->getId());
it = objInstances.erase(it);
}
else{
++it;
}
}
}
void Map::shiftIds(int startId) {
// map<int, int> oldIdToNewId;
for(auto it = objInstances.begin(); it != objInstances.end(); ++it){
int oldId = it->getId();
int newId = startId + oldId;
objInstIdToIter[newId] = objInstIdToIter.at(oldId);
objInstIdToIter.erase(oldId);
it->setId(newId);
// oldIdToNewId[oldId] = newId;
}
for(auto it = pendingObjInstances.begin(); it != pendingObjInstances.end(); ++it){
int oldId = it->getId();
int newId = startId + oldId;
pendingIdToIter[newId] = pendingIdToIter.at(oldId);
pendingIdToIter.erase(oldId);
it->setId(newId);
// oldIdToNewId[oldId] = newId;
}
// for now just clearing pending objects
clearPending();
}
std::map<int, int> Map::getVisibleObjs(Vector7d pose,
cv::Mat cameraMatrix,
int rows,
int cols,
pcl::visualization::PCLVisualizer::Ptr viewer,
int viewPort1,
int viewPort2)
{
static constexpr double shadingLevel = 1.0/8;
chrono::high_resolution_clock::time_point startTime = chrono::high_resolution_clock::now();
g2o::SE3Quat poseSE3Quat(pose);
Eigen::Matrix4d poseMat = poseSE3Quat.to_homogeneous_matrix();
Eigen::Matrix4d poseInvMat = poseSE3Quat.inverse().to_homogeneous_matrix();
Eigen::Matrix4d poseMatt = poseSE3Quat.to_homogeneous_matrix().transpose();
Eigen::Matrix3d R = poseMat.block<3, 3>(0, 0);
Eigen::Vector3d t = poseMat.block<3, 1>(0, 3);
// vectorVector2d imageCorners;
// imageCorners.push_back((Eigen::Vector2d() << 0, 0).finished());
// imageCorners.push_back((Eigen::Vector2d() << cols - 1, 0).finished());
// imageCorners.push_back((Eigen::Vector2d() << cols - 1, rows - 1).finished());
// imageCorners.push_back((Eigen::Vector2d() << 0, rows - 1).finished());
if(viewer){
viewer->removeAllPointClouds();
viewer->removeAllShapes();
for (auto it = objInstances.begin(); it != objInstances.end(); ++it) {
it->display(viewer, viewPort1, shadingLevel);
}
viewer->addCoordinateSystem();
Eigen::Affine3f trans = Eigen::Affine3f::Identity();
trans.matrix() = poseMat.cast<float>();
viewer->addCoordinateSystem(0.5, trans, "camera_coord");
}
vector<vector<vector<pair<double, int>>>> projPlanes(rows,
vector<vector<pair<double, int>>>(cols,
vector<pair<double, int>>()));
cv::Mat projPoly(rows, cols, CV_8UC1);
for(auto it = objInstances.begin(); it != objInstances.end(); ++it) {
// cout << "id = " << it->getId() << endl;
Eigen::Vector4d planeEqCamera = poseMatt * it->getNormal();
// cout << "planeEqCamera = " << planeEqCamera.transpose() << endl;
if (viewer) {
it->cleanDisplay(viewer, viewPort1);
it->display(viewer, viewPort1);
}
// condition for observing the right face of the plane
Eigen::Vector3d normal = planeEqCamera.head<3>();
double d = -planeEqCamera(3);
// Eigen::Vector3d zAxis;
// zAxis << 0, 0, 1;
// cout << "normal.dot(zAxis) = " << normal.dot(zAxis) << endl;
// cout << "d = " << d << endl;
if (d < 0) {
// vectorVector3d imageCorners3d;
// bool valid = Misc::projectImagePointsOntoPlane(imageCorners,
// imageCorners3d,
// cameraMatrix,
// planeEqCamera);
vector<cv::Point *> polyCont;
vector<int> polyContNpts;
ConcaveHull hull = it->getHull().transform(poseSE3Quat.inverse().toVector());
// if (viewer) {
// hull.display(viewer, viewPort1);
// }
//
// hull.transform(poseSE3Quat.inverse().toVector());
ConcaveHull hullClip = hull.clipToCameraFrustum(cameraMatrix, rows, cols, 0.2);
ConcaveHull hullClipMap = hullClip.transform(poseSE3Quat.toVector());
if (viewer) {
hullClipMap.display(viewer, viewPort1, 1.0, 0.0, 0.0);
}
const std::vector<pcl::PointCloud<pcl::PointXYZRGB>::Ptr> &polygons3d = hullClip.getPolygons3d();
// cout << "polygons3d.size() = " << polygons3d.size() << endl;
for (pcl::PointCloud<pcl::PointXYZRGB>::Ptr poly3d : polygons3d) {
polyCont.push_back(new cv::Point[poly3d->size()]);
polyContNpts.push_back(poly3d->size());
// pcl::PointCloud<pcl::PointXYZRGB>::Ptr poly3dPose(new pcl::PointCloud<pcl::PointXYZRGB>());
// // transform to camera frame
// pcl::transformPointCloud(*poly3d, *poly3dPose, poseInvMat);
cv::Mat pointsReproj = Misc::reprojectTo2D(poly3d, cameraMatrix);
// for (int pt = 0; pt < poly3d->size(); ++pt) {
// cout << poly3d->at(pt).getVector3fMap().transpose() << endl;
// }
// cout << "cameraMatrix = " << cameraMatrix << endl;
// cout << "pointsReproj = " << pointsReproj << endl;
int corrPointCnt = 0;
for (int pt = 0; pt < pointsReproj.cols; ++pt) {
int u = std::round(pointsReproj.at<cv::Vec3f>(pt)[0]);
int v = std::round(pointsReproj.at<cv::Vec3f>(pt)[1]);
float d = pointsReproj.at<cv::Vec3f>(pt)[2];
if (u >= 0 && u < cols && v >= 0 && v < rows && d > 0) {
++corrPointCnt;
}
polyCont.back()[pt] = cv::Point(u, v);
}
// cout << "corrPointCnt = " << corrPointCnt << endl;
if (corrPointCnt == 0) {
delete[] polyCont.back();
polyCont.erase(polyCont.end() - 1);
polyContNpts.erase(polyContNpts.end() - 1);
}
}
if (polyCont.size() > 0) {
projPoly.setTo(0);
cv::fillPoly(projPoly,
(const cv::Point **) polyCont.data(),
polyContNpts.data(),
polyCont.size(),
cv::Scalar(255));
if (viewer) {
cv::imshow("proj_poly", projPoly);
}
vectorVector2d polyImagePts;
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
if (projPoly.at<uint8_t>(r, c) > 0) {
polyImagePts.push_back((Eigen::Vector2d() << c, r).finished());
}
}
}
vectorVector3d polyPlanePts;
Misc::projectImagePointsOntoPlane(polyImagePts,
polyPlanePts,
cameraMatrix,
planeEqCamera);
for (int pt = 0; pt < polyImagePts.size(); ++pt) {
int x = std::round(polyImagePts[pt](0));
int y = std::round(polyImagePts[pt](1));
// depth is z coordinate
double d = polyPlanePts[pt](2);
projPlanes[y][x].push_back(make_pair(d, it->getId()));
}
}
for (int p = 0; p < polyCont.size(); ++p) {
delete[] polyCont[p];
}
if (viewer) {
static bool cameraInit = false;
if (!cameraInit) {
viewer->initCameraParameters();
viewer->setCameraPosition(0.0, 0.0, -6.0, 0.0, 1.0, 0.0);
cameraInit = true;
}
viewer->resetStoppedFlag();
while (!viewer->wasStopped()) {
viewer->spinOnce(50);
cv::waitKey(50);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
hull.cleanDisplay(viewer, viewPort1);
hullClipMap.cleanDisplay(viewer, viewPort1);
}
}
if (viewer) {
it->cleanDisplay(viewer, viewPort1);
it->display(viewer, viewPort1, shadingLevel);
}
}
map<int, int> idToCnt;
for(auto it = objInstances.begin(); it != objInstances.end(); ++it) {
idToCnt[it->getId()] = 0;
}
for(int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
vector<pair<double, int>> &curPlanes = projPlanes[r][c];
sort(curPlanes.begin(), curPlanes.end());
if(!curPlanes.empty()){
double minD = curPlanes.front().first;
for(const pair<double, int> &curPair : curPlanes){
if(abs(minD - curPair.first) < 0.2 && curPair.first < 4.0){
int id = curPair.second;
idToCnt.at(id) += 1;
}
}
}
}
}
// for(const pair<int, int> &curCnt : idToCnt){
// cout << "curCnt " << curCnt.first << " = " << curCnt.second << endl;
// }
if(viewer){
for (auto it = objInstances.begin(); it != objInstances.end(); ++it) {
it->cleanDisplay(viewer, viewPort1);
}
}
chrono::high_resolution_clock::time_point endTime = chrono::high_resolution_clock::now();
static chrono::milliseconds totalTime = chrono::milliseconds::zero();
static int totalCnt = 0;
totalTime += chrono::duration_cast<chrono::milliseconds>(endTime - startTime);
++totalCnt;
cout << "Mean getVisibleObjs time: " << (totalTime.count() / totalCnt) << endl;
return idToCnt;
}
pcl::PointCloud<pcl::PointXYZL>::Ptr Map::getLabeledPointCloud()
{
pcl::PointCloud<pcl::PointXYZL>::Ptr pcLab(new pcl::PointCloud<pcl::PointXYZL>());
int o = 0;
for(auto it = objInstances.begin(); it != objInstances.end(); ++it, ++o){
pcl::PointCloud<pcl::PointXYZRGB>::Ptr curPc = it->getPoints();
for(int pt = 0; pt < curPc->size(); ++pt){
pcl::PointXYZL newPt;
newPt.x = curPc->at(pt).x;
newPt.y = curPc->at(pt).y;
newPt.z = curPc->at(pt).z;
newPt.label = o + 1;
pcLab->push_back(newPt);
}
}
return pcLab;
}
pcl::PointCloud<pcl::PointXYZRGB>::Ptr Map::getColorPointCloud()
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr pcCol(new pcl::PointCloud<pcl::PointXYZRGB>());
for(auto it = objInstances.begin(); it != objInstances.end(); ++it){
pcl::PointCloud<pcl::PointXYZRGB>::Ptr curPc = it->getPoints();
pcCol->insert(pcCol->end(), curPc->begin(), curPc->end());
}
return pcCol;
}
void Map::recalculateIdToIter() {
for(auto it = objInstances.begin(); it != objInstances.end(); ++it){
objInstIdToIter[it->getId()] = it;
}
for(auto it = pendingObjInstances.begin(); it != pendingObjInstances.end(); ++it){
pendingIdToIter[it->getId()] = it;
}
}
| 36.02229 | 128 | 0.510238 | [
"object",
"vector",
"transform",
"3d"
] |
7e2c31a7b335d2bbcc9031adab53014134131497 | 9,473 | cpp | C++ | src/Generic/common/InputUtil.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | 1 | 2022-03-24T19:57:00.000Z | 2022-03-24T19:57:00.000Z | src/Generic/common/InputUtil.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | src/Generic/common/InputUtil.cpp | BBN-E/serif | 1e2662d82fb1c377ec3c79355a5a9b0644606cb4 | [
"Apache-2.0"
] | null | null | null | // Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.
#include "Generic/common/leak_detection.h" // This must be the first #include
#include "Generic/common/InputUtil.h"
#include "Generic/common/UTF8InputStream.h"
#include "Generic/common/UnexpectedInputException.h"
#include "Generic/common/InternalInconsistencyException.h"
#include "Generic/common/SessionLogger.h"
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>
#include <iostream>
#include <fstream>
#if defined(_WIN32)
#include <direct.h>
#include <io.h> // for _access()
#endif
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
namespace { // Private namespace
// Common templated implementation that can read in a set/vector of strings or a set/vector of Symbols.
template<typename ContainerType>
inline ContainerType readFileInImpl(std::string filename, bool allow_multiword_entries, bool convert_to_lowercase)
{
// If passed an empty string, this function will return an empty set/vector
// However, if passed a non-empty string, it will fail if the file cannot be opened
// Use a set if you need to guarantee uniqueness, or a vector to guarantee order as read
// This function always:
// * Skips empty lines
// * Skips anything after a # on a line
// * Trims whitespace off the front and back of entries
// Options:
// * allow_multiword_entries: set to false if you do not expect to see spaces in your entries
// * convert_to_lowercase: set to true to convert all entries to lowercase
ContainerType result;
if (filename.empty()) return result;
boost::scoped_ptr<UTF8InputStream> stream_scoped_ptr(UTF8InputStream::build(filename.c_str()));
UTF8InputStream& stream(*stream_scoped_ptr);
if (stream.fail()) {
std::ostringstream err;
err << "Problem opening " << filename;
throw UnexpectedInputException("InputUtil::readFileInImpl", err.str().c_str());
}
while (!(stream.eof() || stream.fail())) {
std::wstring line;
std::getline(stream, line);
line = line.substr(0, line.find_first_of(L'#')); // Remove comments.
boost::trim(line);
if (!line.empty()) {
if (!allow_multiword_entries && line.find_first_of(' ') != std::wstring::npos) {
std::ostringstream err;
std::string line_str(line.begin(), line.end()); // poor man's conversion for error output
err << "Multi-word entry (not allowed) in " << filename << ": \"" << line_str << "\"";
throw UnexpectedInputException("InputUtil::readFileInImpl", err.str().c_str());
}
if (convert_to_lowercase)
boost::to_lower(line);
result.insert(result.end(), line);
}
}
return result;
}
} // End of private namespace
std::set<std::wstring> InputUtil::readFileIntoSet(std::string filename, bool allow_multiword_entries, bool convert_to_lowercase) {
return readFileInImpl< std::set<std::wstring> >(filename, allow_multiword_entries, convert_to_lowercase);
}
std::set<Symbol> InputUtil::readFileIntoSymbolSet(std::string filename, bool allow_multiword_entries, bool convert_to_lowercase) {
return readFileInImpl< std::set<Symbol> >(filename, allow_multiword_entries, convert_to_lowercase);
}
std::vector<std::wstring> InputUtil::readFileIntoVector(std::string filename, bool allow_multiword_entries, bool convert_to_lowercase) {
return readFileInImpl< std::vector<std::wstring> >(filename, allow_multiword_entries, convert_to_lowercase);
}
std::set< std::vector<std::wstring> > InputUtil::readColumnFileIntoSet(std::string filename, bool convert_to_lowercase, std::wstring column_delimiter) {
// Read the lines as before; allow whitespace since the column delimiter might be
std::set<std::wstring> lines = readFileIntoSet(filename, true, convert_to_lowercase);
// Split each row
std::set< std::vector<std::wstring> > rows;
BOOST_FOREACH(std::wstring line, lines) {
std::vector<std::wstring> columns;
boost::split(columns, line, boost::is_any_of(column_delimiter));
rows.insert(columns);
}
return rows;
}
std::vector< std::vector<std::wstring> > InputUtil::readColumnFileIntoVector(std::string filename, bool convert_to_lowercase, std::wstring column_delimiter) {
// Read the lines in order; allow whitespace since the column delimiter might be
std::vector<std::wstring> lines = readFileIntoVector(filename, true, convert_to_lowercase);
// Split each row
std::vector< std::vector<std::wstring> > rows;
BOOST_FOREACH(std::wstring line, lines) {
std::vector<std::wstring> columns;
boost::split(columns, line, boost::is_any_of(column_delimiter));
rows.push_back(columns);
}
return rows;
}
std::vector< std::vector<std::wstring> > InputUtil::readTabDelimitedFile(std::string filename) {
return readColumnFileIntoVector(filename, false, L"\t");
}
std::string InputUtil::getBasePath(std::string file_path){
//get a string we can modify from the file path
std::string strFile = file_path;
std::string base_path;
// convert the file parameters according to the WIN or UNIX file conventions
boost::algorithm::replace_all(strFile, "/", SERIF_PATH_SEP);
boost::algorithm::replace_all(strFile, "\\", SERIF_PATH_SEP);
if (strFile.find_first_of(":") == 1) //They gave us an absolute path (in Window named device char form) to the param file
{
size_t pathEndPos = strFile.find_last_of(SERIF_PATH_SEP,strFile.size());
base_path = strFile.substr(0,pathEndPos);
}
else if ((strFile.find_first_of(SERIF_PATH_SEP) == std::string::npos))//They gave us a file with no path so use current dir
{
char curPath[1000];
char buffer[1000];
_getcwd(curPath,1000);
sprintf(buffer,"%s"SERIF_PATH_SEP"%s",curPath,strFile.c_str());
strFile = buffer;
size_t pathEndPos = strFile.find_last_of(SERIF_PATH_SEP,strFile.size());
base_path = strFile.substr(0,pathEndPos);
}
else //got a relative path (or one that names host explictily)
{
char curPath[1000];
_getcwd(curPath,1000);
rel2AbsPath(strFile,curPath);
size_t pathEndPos = strFile.find_last_of(SERIF_PATH_SEP,strFile.size());
base_path = strFile.substr(0,pathEndPos);
}
return base_path;
}
/* Modifies foo */
void InputUtil::normalizePathSeparators(std::string& foo) {
boost::algorithm::replace_all(foo, "/", SERIF_PATH_SEP);
boost::algorithm::replace_all(foo, "\\", SERIF_PATH_SEP);
}
/* Modifies buffer */
void InputUtil::rel2AbsPath(std::string& buffer, const char *absoluteBasePath)
{
//current assumptions
//basePath does not end with \\
//basePath is absolute
if (buffer.empty())
return;
//Make sure base path is absolute
if (absoluteBasePath[0] == '.')
{
std::ostringstream ostr;
ostr << "Absolute base path '" << absoluteBasePath << "' begins with '.'";
throw UnexpectedInputException("ParamReader::rel2AbsPath()",
ostr.str().c_str());
}
std::string basePath(absoluteBasePath);
boost::algorithm::trim(basePath);
// Normalize path separators (\\ and /) to the standard path separator,
// which depends on the OS for which this was compiled.
normalizePathSeparators(basePath);
normalizePathSeparators(buffer);
// Strip trailing path separator from the base path (if present).
boost::algorithm::trim_right_if(basePath, boost::is_any_of(SERIF_PATH_SEP));
//Detect Relative Paths and Convert Relative to Absolute
if (boost::algorithm::starts_with(buffer, std::string(".")+SERIF_PATH_SEP))
{
buffer.replace(0,1,basePath);
}
else if (boost::algorithm::starts_with(buffer, std::string("..")+SERIF_PATH_SEP))
{
std::vector<std::string> relPathPieces;
std::vector<std::string> basePathPieces;
boost::split(relPathPieces, buffer, boost::is_any_of(SERIF_PATH_SEP));
boost::split(basePathPieces, basePath, boost::is_any_of(SERIF_PATH_SEP));
// Count the number of '..'s in the relative path.
size_t relLevelCount = 0;
while ((relLevelCount < relPathPieces.size()) &&
(relPathPieces[relLevelCount]==".."))
++relLevelCount;
// Make sure there are no '..'s after the first non-'..' piece -- e.g.,
// we don't handle paths like ..\foo\..\bar
for (size_t i=relLevelCount; i<relPathPieces.size(); ++i) {
if (relPathPieces[i]=="..") {
std::ostringstream ostr;
ostr << "Only absolute paths that have all ..'s at the "
<< "beginning are supported: \"" << buffer << "\"";
throw UnexpectedInputException("ParamReader::rel2AbsPath()",
ostr.str().c_str());
}
}
// Make sure we didn't get too many '..'s.
if (relLevelCount >= basePathPieces.size()) {
std::ostringstream ostr;
ostr << "relLevelCount (" << relLevelCount << ") >= baseLevelCount ("
<< basePathPieces.size() << ")\nUse full paths for parameter files to avoid.";
throw UnexpectedInputException("ParamReader::rel2AbsPath()",
ostr.str().c_str());
}
// Construct the absolute path by joining the base path with the
// relative path (skipping directories corresponding to '..'s in
// the relative path.
buffer.assign(basePathPieces[0]);
for (size_t i=1; i<basePathPieces.size()-relLevelCount; ++i) {
buffer.append(SERIF_PATH_SEP);
buffer.append(basePathPieces[i]);
}
for (size_t i=relLevelCount; i<relPathPieces.size(); ++i) {
buffer.append(SERIF_PATH_SEP);
buffer.append(relPathPieces[i]);
}
}
}
| 38.197581 | 159 | 0.700306 | [
"vector"
] |
7e2cb00223c510260e5aaaa1aa0a05481a9a0ae9 | 3,620 | cpp | C++ | sources/DR/PixMix/PixMixMarkerHiding.cpp | Mugichoko445/DRMarkerHiding | 2b61d8408cee040bf5e7d0128c20818f2c47a24e | [
"BSD-3-Clause"
] | 1 | 2022-01-08T03:25:13.000Z | 2022-01-08T03:25:13.000Z | sources/DR/PixMix/PixMixMarkerHiding.cpp | Mugichoko445/DRMarkerHiding | 2b61d8408cee040bf5e7d0128c20818f2c47a24e | [
"BSD-3-Clause"
] | null | null | null | sources/DR/PixMix/PixMixMarkerHiding.cpp | Mugichoko445/DRMarkerHiding | 2b61d8408cee040bf5e7d0128c20818f2c47a24e | [
"BSD-3-Clause"
] | null | null | null | #include "PixMixMarkerHiding.h"
namespace dr
{
PixMixMarkerHiding::PixMixMarkerHiding(const ArUcoMarker& marker, bool debugViz)
: markerSize(marker.Size()), markerMargin(marker.Margin()), debugViz(debugViz)
{
}
PixMixMarkerHiding::~PixMixMarkerHiding()
{
}
void PixMixMarkerHiding::Reset(cv::InputArray color, cv::InputArray corners, const det::PixMixParams& params)
{
assert(corners.cols() > 0);
std::vector<cv::Point2f> newMkCors;
AddMarginToMarkerCorners(corners, newMkCors);
// PixMix
cv::Mat inpainted, nnf, cost, mask;
dr::util::CreateMaskFromCorners(newMkCors, color.size(), mask);
pm.Run(color, mask, inpainted, nnf, cost, params);
kf.Set(inpainted, mask, nnf, cost, corners);
std::cout << "[PixMixMarkerHiding::Rest] Inpainted a keyframe" << std::endl;
}
void PixMixMarkerHiding::Run(cv::InputArray color, cv::OutputArray inpainted, cv::InputArray corners, const det::PixMixParams& params)
{
if (!kf.IsEmpty() && corners.size() == kf.Corners().size())
{
cv::Mat refColor, refNNF, refCost;
kf.GetWarped(corners, refColor, refNNF, refCost);
cv::Mat newMkCorns, mask;
AddMarginToMarkerCorners(corners, newMkCorns);
dr::util::CreateMaskFromCorners(newMkCorns, color.size(), mask);
// fill in non-masked area with the original color
std::random_device rnd;
auto mt = std::mt19937(rnd());
auto rRand = std::uniform_int_distribution<int>(0, refColor.rows - 1);
auto cRand = std::uniform_int_distribution<int>(0, refColor.cols - 1);
for (int r = 0; r < refColor.rows; ++r)
{
auto refColorPtr = refColor.ptr<cv::Vec3b>(r);
auto colorPtr = color.getMat().ptr<cv::Vec3b>(r);
auto refNNFPtr = refNNF.ptr<cv::Vec2i>(r);
auto maskPtr = mask.ptr<uchar>(r);
for (int c = 0; c < refColor.cols; ++c)
{
if (maskPtr[c] != 0)
{
refColorPtr[c] = colorPtr[c];
refNNFPtr[c] = cv::Vec2i(r, c);
}
if (refNNFPtr[c][0] < 0 || refNNFPtr[c][0] >= refColor.rows
|| refNNFPtr[c][1] < 0 || refNNFPtr[c][1] >= refColor.cols)
{
refNNFPtr[c][0] = rRand(mt);
refNNFPtr[c][1] = cRand(mt);
}
}
}
det::PixMixKeyframe ref;
ref.Set(refColor, mask, refNNF, refCost, corners);
if (debugViz)
{
cv::imshow("debug - reference color", refColor);
cv::waitKey(1);
}
pm.Run(color, mask, ref, inpainted, params);
}
}
void PixMixMarkerHiding::AddMarginToMarkerCorners(cv::InputArray corners, cv::OutputArray newCorners)
{
// Create a mask image with marker margin
std::vector<cv::Point2f> mkCors(corners.cols());
mkCors[0] = cv::Point2f(markerSize, 0.0f);
mkCors[1] = cv::Point2f(markerSize, markerSize);
mkCors[2] = cv::Point2f(0.0f, markerSize);
mkCors[3] = cv::Point2f(0.0f, 0.0f);
cv::Matx33f H = cv::findHomography(mkCors, corners);
// corners with margin
std::vector<cv::Point3f> mkCorsWithMarg(mkCors.size());
mkCorsWithMarg[0] = H * cv::Point3f(mkCors[0].x + markerMargin, mkCors[0].y - markerMargin, 1.0f);
mkCorsWithMarg[1] = H * cv::Point3f(mkCors[1].x + markerMargin, mkCors[1].y + markerMargin, 1.0f);
mkCorsWithMarg[2] = H * cv::Point3f(mkCors[2].x - markerMargin, mkCors[2].y + markerMargin, 1.0f);
mkCorsWithMarg[3] = H * cv::Point3f(mkCors[3].x - markerMargin, mkCors[3].y - markerMargin, 1.0f);
std::vector<cv::Point2f> newMkCors(mkCors.size());
for (int idx = 0; idx < mkCorsWithMarg.size(); ++idx)
{
newMkCors[idx] = cv::Point2f(mkCorsWithMarg[idx].x, mkCorsWithMarg[idx].y) / mkCorsWithMarg[idx].z;
}
cv::Mat res(corners.size(), corners.type(), &newMkCors.front());
res.copyTo(newCorners);
}
} | 34.150943 | 135 | 0.66326 | [
"vector"
] |
7e330558cb8a5669a40540229ecad7b4b9475769 | 11,229 | cpp | C++ | SeismicMesh/generation/cpp/delaunay.cpp | WPringle/SeismicMesh | 9e73aac63ecc4411163dc4093941af946cffae37 | [
"BSD-2-Clause"
] | null | null | null | SeismicMesh/generation/cpp/delaunay.cpp | WPringle/SeismicMesh | 9e73aac63ecc4411163dc4093941af946cffae37 | [
"BSD-2-Clause"
] | null | null | null | SeismicMesh/generation/cpp/delaunay.cpp | WPringle/SeismicMesh | 9e73aac63ecc4411163dc4093941af946cffae37 | [
"BSD-2-Clause"
] | null | null | null | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/complex.h>
#include <pybind11/numpy.h>
#include <boost/lexical_cast.hpp>
#include <assert.h>
#include <vector>
#include <CGAL/Kernel/global_functions.h>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_3.h>
#include <CGAL/Triangulation_vertex_base_with_info_3.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <CGAL/Triangulation_vertex_base_with_info_2.h>
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Triangulation_vertex_base_with_info_2<unsigned int, Kernel> Vb;
typedef CGAL::Triangulation_data_structure_2<Vb> Tds;
typedef CGAL::Delaunay_triangulation_2<Kernel, Tds> Delaunay;
typedef Kernel::Point_2 Point;
typedef CGAL::Triangulation_vertex_base_with_info_3<unsigned int, Kernel> Vb3;
typedef CGAL::Triangulation_data_structure_3<Vb3> Tds3;
typedef CGAL::Delaunay_triangulation_3<Kernel, Tds3> Delaunay3;
typedef Kernel::Point_3 Point3;
std::vector<double> c_circumballs2(std::vector<double> &vertices)
{
int num_faces = vertices.size()/6;
std::vector<double> circumcenters;
for(std::size_t i=0; i < num_faces; ++i)
{
Point tmp_cc =
CGAL::circumcenter(
Point(vertices[i*6],vertices[i*6+1]),
Point(vertices[i*6+2],vertices[i*6+3]),
Point(vertices[i*6+4],vertices[i*6+5])
);
circumcenters.push_back(tmp_cc.x());
circumcenters.push_back(tmp_cc.y());
circumcenters.push_back(
CGAL::squared_radius(
Point(vertices[i*6],vertices[i*6+1]),
Point(vertices[i*6+2],vertices[i*6+3]),
Point(vertices[i*6+4],vertices[i*6+5])
)
);
}
return circumcenters;
}
std::vector<double> c_circumballs3(std::vector<double> &vertices)
{
int num_cells = vertices.size()/12;
std::vector<double> circumcenters;
for(std::size_t i=0; i < num_cells; ++i)
{
Point3 tmp_cc =
CGAL::circumcenter(
Point3(vertices[i*12],vertices[i*12+1],vertices[i*12+2]),
Point3(vertices[i*12+3],vertices[i*12+4],vertices[i*12+5]),
Point3(vertices[i*12+6],vertices[i*12+7],vertices[i*12+8]),
Point3(vertices[i*12+9], vertices[i*12+10],vertices[i*12+11])
);
circumcenters.push_back(tmp_cc.x());
circumcenters.push_back(tmp_cc.y());
circumcenters.push_back(tmp_cc.z());
circumcenters.push_back(
CGAL::squared_radius(
Point3(vertices[i*12],vertices[i*12+1],vertices[i*12+2]),
Point3(vertices[i*12+3],vertices[i*12+4],vertices[i*12+5]),
Point3(vertices[i*12+6],vertices[i*12+7],vertices[i*12+8]),
Point3(vertices[i*12+9], vertices[i*12+10],vertices[i*12+11]))
);
}
return circumcenters;
}
std::vector<int> c_delaunay2(std::vector<double> &x, std::vector<double> &y)
{
int num_points = x.size();
assert(y.size()!=num_points);
std::vector< std::pair<Point,unsigned> > points;
// add index information to form face table later
for(std::size_t i = 0; i < num_points; ++i)
{
points.push_back( std::make_pair( Point(x[i],y[i]), i ) );
}
Delaunay triangulation;
triangulation.insert(points.begin(),points.end());
// save the face table
int num_faces = triangulation.number_of_faces();
std::vector<int> faces;
faces.resize(num_faces*3);
int i=0;
for(Delaunay::Finite_faces_iterator fit = triangulation.finite_faces_begin();
fit != triangulation.finite_faces_end(); ++fit) {
Delaunay::Face_handle face = fit;
faces[i*3]=face->vertex(0)->info();
faces[i*3+1]=face->vertex(1)->info();
faces[i*3+2]=face->vertex(2)->info();
i+=1;
}
return faces;
}
std::vector<int> c_delaunay3(std::vector<double> &x, std::vector<double> &y, std::vector<double> &z)
{
int num_points = x.size();
assert(y.size()!=num_points);
assert(z.size()!=num_points);
std::vector< std::pair<Point3,unsigned> > points;
// add index information to form face table later
for(std::size_t i = 0; i < num_points; ++i)
{
points.push_back( std::make_pair( Point3(x[i],y[i],z[i]), i ) );
}
Delaunay3 triangulation;
triangulation.insert(points.begin(),points.end());
// save the indices of all cells
int num_cells = triangulation.number_of_finite_cells();
std::vector<int> cells;
cells.resize(num_cells*4);
int i=0;
for(Delaunay3::Finite_cells_iterator cit = triangulation.finite_cells_begin();
cit != triangulation.finite_cells_end(); ++cit) {
Delaunay3::Cell_handle cell = cit;
cells[i*4]=cell->vertex(0)->info();
cells[i*4+1]=cell->vertex(1)->info();
cells[i*4+2]=cell->vertex(2)->info();
cells[i*4+3]=cell->vertex(3)->info();
i+=1;
}
return cells;
}
// ----------------
// Python interface
// ----------------
// (from https://github.com/tdegeus/pybind11_examples/blob/master/04_numpy-2D_cpp-vector/example.cpp)
namespace py = pybind11;
py::array circumballs2(py::array_t<double, py::array::c_style | py::array::forcecast> vertices)
{
// each triangle has 3 vertices with 2 coordinates each
int sz = vertices.shape()[0];
std::vector<double> cppvertices(sz);
std::memcpy(cppvertices.data(),vertices.data(),sz*sizeof(double));
std::vector<double> circumcenters = c_circumballs2(cppvertices);
ssize_t soreal = sizeof(double);
ssize_t num_points = circumcenters.size()/3;
ssize_t ndim = 2;
std::vector<ssize_t> shape = {num_points, 3};
std::vector<ssize_t> strides = {soreal*3, soreal};
// return 2-D NumPy array
return py::array(py::buffer_info(
circumcenters.data(), /* data as contiguous array */
sizeof(double), /* size of one scalar */
py::format_descriptor<double>::format(), /* data type */
2, /* number of dimensions */
shape, /* shape of the matrix */
strides /* strides for each axis */
));
}
py::array circumballs3(py::array_t<double, py::array::c_style | py::array::forcecast> vertices)
{
// each triangle has 4 vertices with 3 coordinates each
int sz = vertices.size();
std::vector<double> cppvertices(sz);
std::memcpy(cppvertices.data(),vertices.data(),sz*sizeof(double));
std::vector<double> circumcenters = c_circumballs3(cppvertices);
ssize_t soreal = sizeof(double);
ssize_t num_points = circumcenters.size()/4;
ssize_t ndim = 2;
std::vector<ssize_t> shape = {num_points, 4};
std::vector<ssize_t> strides = {soreal*4, soreal};
// return 2-D NumPy array
return py::array(py::buffer_info(
circumcenters.data(), /* data as contiguous array */
sizeof(double), /* size of one scalar */
py::format_descriptor<double>::format(), /* data type */
2, /* number of dimensions */
shape, /* shape of the matrix */
strides /* strides for each axis */
));
}
py::array delaunay2(py::array_t<double, py::array::c_style | py::array::forcecast> x,
py::array_t<double, py::array::c_style | py::array::forcecast> y)
{
// check input dimensions
if ( x.ndim() != 1 )
throw std::runtime_error("Input should be 2 1D NumPy arrays");
if ( y.ndim() != 1 )
throw std::runtime_error("Input should be 2 1D NumPy arrays");
int num_points = x.shape()[0];
// allocate std::vector (to pass to the C++ function)
std::vector<double> cppx(num_points);
std::vector<double> cppy(num_points);
// copy py::array -> std::vector
std::memcpy(cppx.data(),x.data(),num_points*sizeof(double));
std::memcpy(cppy.data(),y.data(),num_points*sizeof(double));
std::vector<int> faces = c_delaunay2(cppx, cppy);
ssize_t soint = sizeof(int);
ssize_t num_faces = faces.size()/3;
ssize_t ndim = 2;
std::vector<ssize_t> shape = {num_faces, 3};
std::vector<ssize_t> strides = {soint*3, soint};
// return 2-D NumPy array
return py::array(py::buffer_info(
faces.data(), /* data as contiguous array */
sizeof(int), /* size of one scalar */
py::format_descriptor<int>::format(), /* data type */
2, /* number of dimensions */
shape, /* shape of the matrix */
strides /* strides for each axis */
));
}
py::array delaunay3(py::array_t<double, py::array::c_style | py::array::forcecast> x,
py::array_t<double, py::array::c_style | py::array::forcecast> y,
py::array_t<double, py::array::c_style | py::array::forcecast> z)
{
// check input dimensions
if ( x.ndim() != 1 )
throw std::runtime_error("Input should be three 1D NumPy arrays");
if ( y.ndim() != 1 )
throw std::runtime_error("Input should be three 1D NumPy arrays");
if ( z.ndim() != 1 )
throw std::runtime_error("Input should be three 1D NumPy arrays");
int num_points = x.shape()[0];
// allocate std::vector (to pass to the C++ function)
std::vector<double> cppx(num_points);
std::vector<double> cppy(num_points);
std::vector<double> cppz(num_points);
// copy py::array -> std::vector
std::memcpy(cppx.data(),x.data(),num_points*sizeof(double));
std::memcpy(cppy.data(),y.data(),num_points*sizeof(double));
std::memcpy(cppz.data(),z.data(),num_points*sizeof(double));
std::vector<int> cells = c_delaunay3(cppx, cppy, cppz);
ssize_t num_cells = cells.size()/4;
ssize_t ndim = 2;
ssize_t soint = sizeof(int);
std::vector<ssize_t> shape = {num_cells, 4};
std::vector<ssize_t> strides = {soint*4, soint};
// return 2-D NumPy array
return py::array(py::buffer_info(
cells.data(), /* data as contiguous array */
sizeof(int), /* size of one scalar */
py::format_descriptor<int>::format(), /* data type */
2, /* number of dimensions */
shape, /* shape of the matrix */
strides /* strides for each axis */
));
}
PYBIND11_MODULE(c_cgal, m) {
m.def("circumballs3", &circumballs3);
m.def("circumballs2", &circumballs2);
m.def("delaunay2", &delaunay2);
m.def("delaunay3", &delaunay3);
}
| 37.935811 | 101 | 0.580105 | [
"shape",
"vector"
] |
7e3395b4567828fe2343d100afa785e4fecf5b3e | 1,517 | cpp | C++ | Day_03/03_Majority_Element_I.cpp | premnaaath/SDE-180 | 6d7cc2404d310600a81adaa652049172f2e10ed8 | [
"MIT"
] | null | null | null | Day_03/03_Majority_Element_I.cpp | premnaaath/SDE-180 | 6d7cc2404d310600a81adaa652049172f2e10ed8 | [
"MIT"
] | null | null | null | Day_03/03_Majority_Element_I.cpp | premnaaath/SDE-180 | 6d7cc2404d310600a81adaa652049172f2e10ed8 | [
"MIT"
] | null | null | null | // Problem Link:
// https://leetcode.com/problems/majority-element/
// Approach 1: (Hashing)
// TC: O(n)
// SC: O(n)
// Approach 2: (Sorting)
// TC: O(n.log(n))
// SC: O(1)
// Approach 3: (Moore Voting Algorithm)
// TC: O(n)
// SC: O(1)
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define deb(x) cout << #x << ": " << x << "\n"
// Approach 1
int NaiveHash(vector<int> &nums)
{
int t = nums.size() / 2;
unordered_map<int, int> hash{};
for (int i = 0; i < nums.size(); ++i)
{
if (hash.find(nums[i]) != hash.end())
hash[nums[i]]++;
else
hash[nums[i]] = 1;
if (hash[nums[i]] > t)
return nums[i];
}
return 0;
}
// Approach 2
int NaiveSort(vector<int> &nums)
{
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
// Approach 3
int mooreVote(vector<int> &nums)
{
int count{}, major{};
int n = nums.size();
for (int i = 0; i < n; ++i)
{
if (nums[i] == major)
count++;
else if (count == 0)
{
major = nums[i];
count++;
}
else
count--;
}
return major;
}
void solve()
{
vector<int> nums{2, 2, 1, 1, 1, 2, 2};
cout << NaiveHash(nums) << endl;
cout << NaiveSort(nums) << endl;
cout << mooreVote(nums) << endl;
}
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t{1};
// cin >> t;
while (t--)
solve();
return 0;
} | 17.847059 | 58 | 0.487805 | [
"vector"
] |
cceaebfb31c3167671cf8892235f474bc614ebe3 | 14,152 | hpp | C++ | src/catk/syntax/expr.hpp | CHChang810716/CAsterisk | 410d2afaae6cd01402a35c1889466f97e4c208bf | [
"MIT"
] | null | null | null | src/catk/syntax/expr.hpp | CHChang810716/CAsterisk | 410d2afaae6cd01402a35c1889466f97e4c208bf | [
"MIT"
] | null | null | null | src/catk/syntax/expr.hpp | CHChang810716/CAsterisk | 410d2afaae6cd01402a35c1889466f97e4c208bf | [
"MIT"
] | null | null | null | #pragma once
#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/parse_tree.hpp>
#include "ast.hpp"
#include <range/v3/view/drop_last.hpp>
#include <boost/lexical_cast.hpp>
#include <vector>
namespace catk::syntax {
using Identifier = tao::pegtl::identifier;
using IgnoredLval = tao::pegtl::one<'_'>;
template<class R>
using SpacePad = tao::pegtl::pad<R, tao::pegtl::space>;
struct IntTag : tao::pegtl::seq<
tao::pegtl::opt<tao::pegtl::one<'u'>>, tao::pegtl::one<'i'>, tao::pegtl::sor<
TAO_PEGTL_STRING("8"), TAO_PEGTL_STRING("16"), TAO_PEGTL_STRING("32"), TAO_PEGTL_STRING("64")
>
> {};
struct DecIntLiteral : tao::pegtl::seq<
tao::pegtl::opt<tao::pegtl::one<'-'>>,
tao::pegtl::plus<tao::pegtl::digit>
> {};
struct HexIntLiteral : tao::pegtl::if_must<
TAO_PEGTL_STRING("0x"),
tao::pegtl::plus<tao::pegtl::xdigit>
> {};
struct IntLiteral : tao::pegtl::sor<
tao::pegtl::seq<DecIntLiteral, IntTag>,
tao::pegtl::seq<HexIntLiteral, IntTag>
> {
template<class T>
static auto& literal(T& ast) {
assert(ast.template is<IntLiteral>());
return *ast.children.at(0);
}
template<class T>
static auto& tag(T& ast) {
assert(ast.template is<IntLiteral>());
return *ast.children.at(1);
}
template<class T, class Store>
static void interpret(T& ast, Store& store) {
assert(ast.template is<IntLiteral>());
auto tag_ = tag(ast).content();
auto content = literal(ast).content();
if(tag_ == "u8") {
store = boost::lexical_cast<std::uint8_t>(content);
} else if(tag_ == "u16") {
store = boost::lexical_cast<std::uint16_t>(content);
} else if(tag_ == "u32") {
store = boost::lexical_cast<std::uint32_t>(content);
} else if(tag_ == "u64") {
store = boost::lexical_cast<std::uint64_t>(content);
} else if(tag_ == "i8") {
store = boost::lexical_cast<std::int8_t>(content);
} else if(tag_ == "i16") {
store = boost::lexical_cast<std::int16_t>(content);
} else if(tag_ == "i32") {
store = boost::lexical_cast<std::int32_t>(content);
} else if(tag_ == "i64") {
store = boost::lexical_cast<std::int64_t>(content);
} else {
assert(0);
}
}
};
struct FPTag : tao::pegtl::sor<
TAO_PEGTL_STRING("f32"), TAO_PEGTL_STRING("f64")
> {};
struct FPLiteralV0 : tao::pegtl::seq<
tao::pegtl::opt<tao::pegtl::one<'-'>>, tao::pegtl::plus<tao::pegtl::digit>
> {};
struct FPLiteralV1 : tao::pegtl::seq<
tao::pegtl::opt<tao::pegtl::one<'-'>>,
tao::pegtl::star<tao::pegtl::digit>,
tao::pegtl::one<'.'>,
tao::pegtl::plus<tao::pegtl::digit>
> {};
struct FPLiteral : tao::pegtl::sor<
tao::pegtl::seq<FPLiteralV0, FPTag>,
tao::pegtl::seq<FPLiteralV1, FPTag>
> {
template<class T>
static auto& literal(T& ast) {
assert(ast.template is<FPLiteral>());
return *ast.children.at(0);
}
template<class T>
static auto& tag(T& ast) {
assert(ast.template is<FPLiteral>());
return *ast.children.at(1);
}
template<class T, class Store>
static void interpret(T& ast, Store& store) {
assert(ast.template is<FPLiteral>());
auto tag_ = tag(ast).content();
if(tag_ == "f32") {
store = std::stof(literal(ast).content());
} else if (tag_ == "f64") {
store = std::stod(literal(ast).content());
}
}
};
struct EscapedChar : tao::pegtl::one< '"', '\\', '/', 'b', 'f', 'n', 'r', 't', '0' > {};
struct Escaped : tao::pegtl::sor< EscapedChar /*, unicode */ > {};
struct Char : tao::pegtl::if_then_else<
tao::pegtl::one< '\\' >,
tao::pegtl::must<Escaped>,
tao::pegtl::not_one<'\\'>
> {};
struct StringLiteralContent : tao::pegtl::until<
tao::pegtl::at< tao::pegtl::one<'"'> >, tao::pegtl::must< Char >
> {};
struct StringLiteral : tao::pegtl::seq<
tao::pegtl::one<'"'>,
tao::pegtl::must< StringLiteralContent >,
tao::pegtl::any
> {
using Content = StringLiteralContent;
};
struct Expr;
struct IfOp : TAO_PEGTL_STRING("if") {};
struct IfExpr : tao::pegtl::if_must<
IfOp,
SpacePad<tao::pegtl::one<'('>>,
Expr,
SpacePad<tao::pegtl::one<')'>>,
Expr,
SpacePad<TAO_PEGTL_STRING("else")>,
Expr
> {
template<class T>
static auto& function(T& ast) {
assert(ast.template is<IfExpr>());
return *(ast.children.at(0));
}
template<class T>
static auto opnds(T& ast) {
assert(ast.template is<IfExpr>());
assert(ast.children.size() == 4);
std::vector<T*> res({
ast.children[1].get(),
ast.children[2].get(),
ast.children[3].get()
});
return res;
}
};
struct ArrayLiteral : tao::pegtl::seq<
tao::pegtl::one<'['>,
tao::pegtl::opt<tao::pegtl::list<Expr, tao::pegtl::one<','>, tao::pegtl::space>>,
tao::pegtl::one<']'>
> {};
struct Param : tao::pegtl::seq<
Identifier,
tao::pegtl::opt<
tao::pegtl::seq<SpacePad<tao::pegtl::one<'='>>, Expr>
>
> {
template<class T>
static auto& left_id(T& ast) {
assert(ast.template is<Param>());
return *ast.children.at(0);
}
template<class T>
static auto& right_expr(T& ast) {
assert(ast.template is<Param>());
return *ast.children.at(1);
}
};
struct ParamList : tao::pegtl::list<Param, tao::pegtl::one<','>, tao::pegtl::space> {};
struct CaptureItem : Identifier {};
struct CaptureList : tao::pegtl::seq<
tao::pegtl::one<'['>,
tao::pegtl::star<tao::pegtl::space>,
tao::pegtl::opt<
tao::pegtl::seq<
tao::pegtl::list<
CaptureItem, tao::pegtl::one<','>, tao::pegtl::space
>,
tao::pegtl::star<tao::pegtl::space>
>
>,
tao::pegtl::one<']'>
> {};
struct LambdaLiteral;
struct Literal : tao::pegtl::sor<
StringLiteral,
LambdaLiteral,
ArrayLiteral,
FPLiteral,
IntLiteral
> {};
struct FCallParamBind : tao::pegtl::seq<
Identifier, SpacePad<tao::pegtl::one<'='>>, Expr
> {
template<class T>
static auto& param_name(T& ast) {
assert(ast.template is<FCallParamBind>());
return *(ast.children[0]);
}
template<class T>
static auto& param_expr(T& ast) {
assert(ast.template is<FCallParamBind>());
return *(ast.children[1]);
}
};
struct FCallParamBindList : tao::pegtl::list<FCallParamBind, tao::pegtl::one<','>, tao::pegtl::space> {};
struct FCallExpr : tao::pegtl::seq<
Identifier,
SpacePad<tao::pegtl::one<'('>>,
tao::pegtl::opt<FCallParamBindList>,
SpacePad<tao::pegtl::one<')'>>
> {
template<class T>
static auto& function(T& ast) {
assert(ast.template is<FCallExpr>());
return *(ast.children.at(0));
}
template<class T>
static auto opnds(T& ast) {
assert(ast.template is<FCallExpr>());
std::vector<T*> params_r;
for(std::size_t i = 1; i < ast.children.size(); i ++) {
auto& param_bind = *(ast.children[i]);
params_r.push_back(
&FCallParamBind::param_expr(param_bind)
);
}
return params_r;
}
template<class T>
static auto opnd_labels(T& ast) {
assert(ast.template is<FCallExpr>());
std::vector<T*> params_l;
for(std::size_t i = 1; i < ast.children.size(); i ++) {
auto& param_bind = *(ast.children[i]);
params_l.push_back(
&FCallParamBind::param_name(param_bind)
);
}
return params_l;
}
};
struct UnaryOp : tao::pegtl::one<
'+', '-', '~', '*', '!', '&'
> {};
struct UnaryExpr : tao::pegtl::seq<UnaryOp, Expr> {
template<class T>
static auto& function(T& ast) {
assert(ast.template is<UnaryExpr>());
assert(ast.children.size() == 2);
return *(ast.children[0]);
}
template<class T>
static auto opnds(T& ast) {
assert(ast.template is<UnaryExpr>());
assert(ast.children.size() == 2);
std::vector<T*> res({
ast.children[1].get()
});
return res;
}
};
struct AssignLeftHand : tao::pegtl::list<
tao::pegtl::sor<
IgnoredLval,
Identifier
>,
SpacePad<tao::pegtl::one<','>>
> {};
struct AssignStmt : tao::pegtl::seq<
AssignLeftHand,
SpacePad<tao::pegtl::one<'='>>,
Expr,
tao::pegtl::star<tao::pegtl::space>,
tao::pegtl::one<';'>
> {
template<class T>
static auto& left_list(T& ast) {
assert(ast.template is<AssignStmt>());
return *ast.children.at(0);
}
template<class T>
static auto& right_expr(T& ast) {
assert(ast.template is<AssignStmt>());
return *ast.children.at(1);
}
template<class T>
static auto& left_values(T& ast) {
return ast.children.at(0)->children;
}
};
struct Statement : tao::pegtl::sor<
AssignStmt
> {};
struct StmtList : tao::pegtl::list<
Statement,
tao::pegtl::star<tao::pegtl::space>
> {};
struct RetOp : TAO_PEGTL_STRING("ret") {};
struct RetStmt : tao::pegtl::seq<
RetOp, tao::pegtl::star<tao::pegtl::space>,
Expr, tao::pegtl::star<tao::pegtl::space>, tao::pegtl::one<';'>
> {
template<class T>
static auto& expr(T& ast) {
assert(ast.template is<RetStmt>());
assert(ast.children.size() == 2);
return *(ast.children.at(1));
}
};
struct ContextStmts : tao::pegtl::seq<
tao::pegtl::star<tao::pegtl::space>,
tao::pegtl::opt<StmtList>,
tao::pegtl::star<tao::pegtl::space>,
RetStmt,
tao::pegtl::star<tao::pegtl::space>
> {
template<class T>
static auto& ret_stmt(T& ast) {
assert(ast.template is<ContextStmts>());
auto& should_be_ret = *(ast.children.back());
assert(should_be_ret.template is<RetStmt>());
return should_be_ret;
}
};
struct RetContext : tao::pegtl::seq<
tao::pegtl::opt<CaptureList>,
tao::pegtl::star<tao::pegtl::space>,
tao::pegtl::one<'{'>,
ContextStmts,
tao::pegtl::one<'}'>
> {
template<class T>
static auto* capture_list(T& ast) {
assert(ast.template is<RetContext>());
if(ast.children.at(0)->template is<CaptureList>()) {
return ast.children.at(0).get();
} else {
return (AST*)nullptr;
}
}
template<class T>
static auto& stmts(T& ast) {
assert(ast.template is<RetContext>());
return *(ast.children.back());
}
template<class T>
static auto& ret_stmt(T& ast) {
assert(ast.template is<RetContext>());
auto& stmt_list = stmts(ast);
return ContextStmts::ret_stmt(stmt_list);
}
};
struct LambdaLiteral : tao::pegtl::if_must<
TAO_PEGTL_KEYWORD("fn"),
tao::pegtl::star<tao::pegtl::space>,
SpacePad<tao::pegtl::one<'('>>,
tao::pegtl::opt<ParamList>,
SpacePad<tao::pegtl::one<')'>>,
tao::pegtl::star<tao::pegtl::space>,
RetContext
> {
template<class T>
static auto params(T& ast) {
assert(ast.template is<LambdaLiteral>());
std::vector<T*> res;
for(auto&& up : ast.children.at(0)->children) {
res.push_back(up.get());
}
return res;
}
template<class T>
static auto& body(T& ast) {
assert(ast.template is<LambdaLiteral>());
return *ast.children.back();
}
template<class T>
static auto capture_list(T& ast) {
assert(ast.template is<LambdaLiteral>());
return RetContext::capture_list(body(ast));
}
template<class T>
static auto& stmts(T& ast) {
assert(ast.template is<LambdaLiteral>());
return RetContext::stmts(body(ast));
}
};
struct Term : tao::pegtl::sor<
IfExpr,
tao::pegtl::seq<tao::pegtl::one<'('>, SpacePad<Expr>, tao::pegtl::one<')'>>,
RetContext,
Literal,
UnaryExpr,
FCallExpr,
Identifier
> {
};
struct BinOp : tao::pegtl::sor<
tao::pegtl::one<'+', '-', '*', '/', '%', '&', '|', '^', '<', '>'>,
TAO_PEGTL_STRING("=="), TAO_PEGTL_STRING("<="), TAO_PEGTL_STRING(">="), TAO_PEGTL_STRING("!=")
> {};
struct BinExpr : tao::pegtl::seq<Term, SpacePad<BinOp>, Expr> {
template<class T>
static auto& function(T& ast) {
assert(ast.template is<BinExpr>());
assert(ast.children.size() == 3);
return *(ast.children.at(1));
}
template<class T>
static auto opnds(T& ast) {
assert(ast.template is<BinExpr>());
assert(ast.children.size() == 3);
std::vector<T*> res({
ast.children[0].get(),
ast.children[2].get()
});
return res;
}
};
struct Expr : tao::pegtl::sor<
BinExpr,
Term
> {
template<class T>
static auto& function(T& ast) {
assert(ast.template is<Expr>());
auto& next_lv = *(ast.children.at(0));
if(next_lv.template is<BinExpr>()) {
return BinExpr::function(next_lv);
}
if(next_lv.template is<IfExpr>()) {
return IfExpr::function(next_lv);
}
if(next_lv.template is<UnaryExpr>()) {
return UnaryExpr::function(next_lv);
}
if(next_lv.template is<FCallExpr>()) {
return FCallExpr::function(next_lv);
}
assert(0);
}
template<class T>
static auto opnds(T& ast) {
assert(ast.template is<Expr>());
auto& next_lv = *(ast.children.at(0));
if(next_lv.template is<BinExpr>()) {
return BinExpr::opnds(next_lv);
}
if(next_lv.template is<IfExpr>()) {
return IfExpr::opnds(next_lv);
}
if(next_lv.template is<UnaryExpr>()) {
return UnaryExpr::opnds(next_lv);
}
if(next_lv.template is<FCallExpr>()) {
return FCallExpr::opnds(next_lv);
}
assert(0);
}
template<class T>
static auto opnd_labels(T& ast) {
assert(ast.template is<Expr>());
auto& next_lv = *(ast.children.at(0));
if(next_lv.template is<FCallExpr>()) {
return FCallExpr::opnd_labels(next_lv);
}
return std::vector<T*>();
}
};
// struct File : tao::pegtl::until<
// tao::pegtl::at<tao::pegtl::eof>,
// SpacePad<tao::pegtl::must<Statement>>
// > {
// };
struct File : tao::pegtl::seq<
ContextStmts,
tao::pegtl::eof
> {
template<class T>
static auto& stmts(T& ast) {
assert(ast.template is<File>());
return *(ast.children.back());
}
};
template<class Rule>
using ASTSelector = tao::pegtl::parse_tree::selector<
Rule,
tao::pegtl::parse_tree::store_content::on<
BinOp,
UnaryOp,
IfOp,
RetOp,
StringLiteral,
LambdaLiteral,
ArrayLiteral,
DecIntLiteral,
HexIntLiteral,
IntTag,
IntLiteral,
FPLiteralV0,
FPLiteralV1,
FPTag,
FPLiteral,
Identifier,
// Expr,
UnaryExpr,
BinExpr,
IfExpr,
FCallExpr,
RetContext,
RetStmt,
ContextStmts,
AssignStmt,
CaptureList,
CaptureItem,
ParamList,
Param,
FCallParamBind,
AssignLeftHand,
IgnoredLval
>
>;
// TODO: bop, if, uop must be a captureable ast
} | 25.003534 | 105 | 0.61221 | [
"vector"
] |
cceef02bea19d949a530d6d246e557b47c61ee9a | 23,338 | cpp | C++ | ust/String.cpp | Brillist/libutl | e55c2af091ba1101a1d0608db2830e279ec95d16 | [
"MIT"
] | 1 | 2021-09-14T06:12:58.000Z | 2021-09-14T06:12:58.000Z | ust/String.cpp | Brillist/libutl | e55c2af091ba1101a1d0608db2830e279ec95d16 | [
"MIT"
] | null | null | null | ust/String.cpp | Brillist/libutl | e55c2af091ba1101a1d0608db2830e279ec95d16 | [
"MIT"
] | 2 | 2019-05-13T23:04:31.000Z | 2021-09-14T06:12:59.000Z | #include <libutl/libutl.h>
#include <libutl/BoyerMooreSearch.h>
#include <libutl/Stream.h>
#include <libutl/String.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_CLASS_IMPL(utl::String);
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_NS_BEGIN;
////////////////////////////////////////////////////////////////////////////////////////////////////
String::String(const char* s, bool owner, bool duplicate, bool caseSensitive)
{
ASSERTD(nullChar == '\0');
if (!caseSensitive)
setCaseSensitive(false);
if (owner)
{
_s = &nullChar;
_size = 0;
_length = 0;
set(s, true, duplicate);
}
else if ((s == nullptr) || (*s == nullChar))
{
_s = &nullChar;
_size = 0;
_length = 0;
}
else
{
_s = const_cast<char*>(s);
_size = 0;
_length = size_t_max;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String::String(size_t size)
{
ASSERTD(nullChar == '\0');
if (size == 0)
{
init();
}
else
{
size = utl::nextMultipleOfPow2((size_t)8, size);
_s = new char[size];
_s[0] = '\0';
_size = size;
_length = 0;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int
String::compare(const Object& rhs) const
{
auto& string = utl::cast<String>(rhs);
if (isCaseSensitive() && string.isCaseSensitive())
{
return ::strcmp(_s, string._s);
}
else
{
return ::strcasecmp(_s, string._s);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
String::copy(const Object& rhs)
{
if (!rhs.isA(String))
{
this->copy(rhs.toString());
return;
}
auto& string = utl::cast<String>(rhs);
if (&string == this)
return;
// copy flags
_flags = string._flags;
// lhs will own (a copy of) rhs's string if lhs or rhs owns its string
bool owner = isOwner() || string.isOwner();
// set the new string in lhs (self)
set(string._s, owner, owner);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
String::steal(Object& rhs_)
{
auto& rhs = utl::cast<String>(rhs_);
if (_size > 0)
delete[] _s;
copyFlags(rhs);
_s = rhs._s;
_size = rhs._size;
_length = rhs._length;
if (_size > 0)
rhs.setOwner(false);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// FNV-1a hash
#define FNV_GCC_OPTIMIZATION
size_t
String::hash(size_t size) const
{
if (empty())
return 0;
static const uint64_t FNV_offset_basis = 14695981039346656037ULL;
#ifndef FNV_GCC_OPTIMIZATION
static const uint64_t FNV_prime = 1099511628211ULL;
#endif
uint64_t h = FNV_offset_basis;
auto ptr = reinterpret_cast<byte_t*>(_s);
auto lim = ptr + length();
for (; ptr != lim; ++ptr)
{
h ^= static_cast<uint64_t>(*ptr);
#ifdef FNV_GCC_OPTIMIZATION
h += (h << 1) + (h << 4) + (h << 5) + (h << 7) + (h << 8) + (h << 40);
#else
h *= FNV_prime;
#endif
}
return h % size;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
String::serialize(Stream& stream, uint_t io, uint_t mode)
{
if (io == io_rd)
{
stream >> self;
}
else
{
stream << self << '\n';
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
size_t
String::innerAllocatedSize() const
{
return _size;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String
String::toString() const
{
return *this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int
String::compareSubstring(size_t begin, const String& rhs, size_t n)
{
if (begin > length())
begin = length();
if (isCaseSensitive() && rhs.isCaseSensitive())
return ::strncmp(_s + begin, rhs._s, n);
return ::strncasecmp(_s + begin, rhs._s, n);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int
String::comparePrefix(const String& rhs) const
{
size_t rhsLen = rhs.length();
if (isCaseSensitive() && rhs.isCaseSensitive())
return ::strncmp(_s, rhs._s, rhsLen);
return ::strncasecmp(_s, rhs._s, rhsLen);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
int
String::compareSuffix(const String& rhs) const
{
size_t lhsLen = this->length();
size_t rhsLen = rhs.length();
if (lhsLen < rhsLen)
return -1;
if (isCaseSensitive() && rhs.isCaseSensitive())
{
return ::strncmp(_s + (lhsLen - rhsLen), rhs._s, rhsLen);
}
else
{
return ::strncasecmp(_s + (lhsLen - rhsLen), rhs._s, rhsLen);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String
String::backslashEscaped(const String& specials) const
{
// init escapeChars[]
byte_t escapeChars[128];
memset(escapeChars, 0, 128);
size_t i, len = specials.length();
for (i = 0; i != len; ++i)
{
ASSERTD(specials[i] >= 0);
escapeChars[(byte_t)specials[i]] = 1;
}
escapeChars['\\'] = 1;
// no escape chars -> just return str
bool anyEscapeChars = false;
len = length();
for (i = 0; i != len; ++i)
{
char c = _s[i];
if ((c >= 0) && escapeChars[(byte_t)c])
{
anyEscapeChars = true;
break;
}
}
if (!anyEscapeChars)
return self;
// escape special characters
String res;
for (i = 0; i != len; ++i)
{
char c = _s[i];
if ((c >= 0) && escapeChars[(byte_t)c])
{
res += '\\';
}
res += c;
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String
String::backslashUnescaped() const
{
String res;
size_t i, len = length();
for (i = 0; i != len; ++i)
{
char c = _s[i];
if (c == '\\')
{
c = _s[++i];
}
res += c;
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
size_t
String::find(const String& str, size_t begin) const
{
size_t len = length(), strLen = str.length();
// empty string is found
if (strLen == 0)
return begin;
// a match is impossible -> return "not found"
if ((begin >= len) || ((len - begin) < strLen))
return size_t_max;
// case-sensitive ?
size_t maxI = len - strLen + 1;
bool caseSensitive = isCaseSensitive();
if ((strLen == 1) && caseSensitive)
{
char c = *str._s;
auto lim = _s + len;
for (auto p = _s + begin; p != lim; ++p)
{
if (*p == c)
return (p - _s);
}
}
else
{
if (caseSensitive)
{
// try to match at each possible location
for (size_t i = begin; i != maxI; ++i)
{
if ((_s[i] == str._s[0]) && (_s[i + 1] == str._s[1]) &&
(::strncmp(_s + i + 2, str._s + 2, strLen - 2) == 0))
{
return i;
}
}
}
else
{
// as above, but case-insensitive
for (size_t i = begin; i != maxI; ++i)
{
if (::strncasecmp(_s + i, str._s, strLen) == 0)
return i;
}
}
}
return size_t_max;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
size_t
String::find(char c, size_t begin) const
{
size_t len = length();
const char* lim = _s + len;
// a match is impossible -> return "not found"
if (begin > len)
return size_t_max;
// case-sensitive ?
bool caseSensitive = isCaseSensitive();
if (caseSensitive)
{
for (const char* p = _s + begin; p <= lim; ++p)
{
if (*p == c)
return (p - _s);
}
}
else
{
c = tolower(c);
for (const char* p = _s + begin; p <= lim; ++p)
{
if (tolower(*p) == c)
return (p - _s);
}
}
return size_t_max;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
size_t
String::findBM(const String& str, size_t begin) const
{
size_t len = length(), strLen = str.length();
// a match is impossible -> return "not found"
if ((begin >= len) || (strLen == 0) || ((len - begin) < strLen))
{
return size_t_max;
}
// case-sensitive ?
if (isCaseSensitive())
{
const char* match = boyerMooreSearch(_s + begin, len - begin, str._s, strLen);
if (match == nullptr)
return size_t_max;
return match - _s;
}
else
{
String selfCopy = *this;
String strCopy = str;
selfCopy.toLower();
strCopy.toLower();
return selfCopy.findBM(strCopy, begin);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String
String::subString(size_t begin, size_t len) const
{
// set bounds
size_t myLen = length(), end;
setBounds(begin, end, len, myLen);
// result is empty string if begin >= myLen
if (len == 0)
return String();
// result is self if (begin == 0) and (len == myLen)
if ((begin == 0) && (len == myLen))
return self;
char* str = new char[len + 1];
strncpy(str, _s + begin, len);
str[len] = '\0';
return String(str, true, false);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String
String::reversed() const
{
String res = self;
res.reverse();
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String
String::nextToken(size_t& idx, char delim, bool processQuotes) const
{
String res;
const char* s = _s + idx;
const char* e;
const char* lim = _s + length();
// skip past leading whitespace
while (isspace(*s))
++s;
if (processQuotes)
{
res.reserve(64);
while ((s != lim) && (*s != delim))
{
char c = *s;
if ((c == '\'') || (c == '"'))
{
char q = c;
++s;
while ((s != lim) && (*s != q))
{
// find the first backslash or closing quote
for (e = s; (e != lim) && (*e != '\\') && (*e != q); ++e)
;
// append the text up to the backslash or closing quote
res.append(s, e - s);
s = e;
// we stopped at a backslash?
if ((s != lim) && (*s == '\\'))
{
++s;
res += *s++;
}
}
if (s != lim)
++s;
}
else
{
for (e = s; (e != lim) && (*e != delim) && (*e != '\'') && (*e != '"'); ++e)
;
if ((e == lim) || (*e == delim))
{
const char* ep = e;
for (--ep; (ep > s) && isspace(*ep); --ep)
;
++ep;
res.append(s, ep - s);
}
else
{
res.append(s, e - s);
}
s = e;
}
}
}
else
{
for (e = s; (e != lim) && (*e != delim); ++e)
;
const char* ep = e;
for (--ep; (ep > s) && isspace(*ep); --ep)
;
++ep;
res.append(s, ep - s);
s = e;
}
idx = (s == lim) ? s - _s : s - _s + 1;
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::excise()
{
if (isOwner())
delete[] _s;
_s = &nullChar;
_size = 0;
_length = 0;
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
String::economize()
{
if (_size == 0)
return;
if (empty())
{
delete[] _s;
_s = &nullChar;
_size = 0;
_length = 0;
return;
}
size_t size = utl::nextMultipleOfPow2((size_t)8, length() + 1);
if (_size == size)
return;
char* s = new char[size];
memcpy(s, _s, size);
delete[] _s;
_s = s;
_size = size;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::append(const char c)
{
// do nothing?
if (c == '\0')
return self;
// grow to a sufficient length
size_t len = length();
reserve(len + 2, size_t_max);
// add the character
_s[len] = c;
_s[len + 1] = '\0';
++_length;
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::append(const char* s, size_t len)
{
ASSERTD(s != nullptr);
ASSERTD(strlen(s) >= len);
size_t myLen = length();
// appending empty string -> just return self
if (len == 0)
return self;
// concatenate s[0,len) to self
reserve(myLen + len + 1, size_t_max);
memcpy(_s + myLen, s, len);
_length += len;
_s[_length] = '\0';
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String
String::chop(size_t begin, size_t len)
{
// set bounds
size_t myLen = length(), end;
setBounds(begin, end, len, myLen);
// the result is the substring
String res = subString(begin, len);
// chop out the result
assertOwner();
size_t num = myLen - end + 1;
::memmove(_s + begin, _s + end, num);
_length -= (end - begin);
// return the substring
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
String::remove(size_t begin, size_t len)
{
// set bounds
size_t myLen = length(), end;
setBounds(begin, end, len, myLen);
// chop out the result
assertOwner();
size_t num = myLen - end + 1;
::memmove(_s + begin, _s + end, num);
_length -= (end - begin);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::replace(const String& lhs, const String& rhs)
{
// inefficient if many replacements are needed
size_t lhsLen = lhs.length(), rhsLen = rhs.length();
for (size_t idx = find(lhs); idx != size_t_max; idx = find(lhs, idx))
{
replace(idx, lhsLen, rhs);
idx += rhsLen;
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::replace(char lhs, char rhs)
{
auto myLen = length();
auto lim = _s + myLen;
for (auto ptr = _s; ptr != lim; ++ptr)
{
if (*ptr == lhs)
{
*ptr = rhs;
}
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::replace(size_t begin, size_t len, const String& str)
{
// set bounds
size_t strLen = str.length();
size_t myLen = length(), end;
setBounds(begin, end, len, myLen);
// grow to the required size
ssize_t growth = (strLen - len);
size_t newLen = myLen + growth;
reserve(newLen + 1);
// move characters at the end as needed
if ((growth != 0) && (end < myLen))
{
::memmove(_s + end + growth, _s + end, myLen - end);
}
// copy str into _s[]
strncpy(_s + begin, str._s, strLen);
_length += growth;
_s[_length] = '\0';
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::reverse()
{
assertOwner();
char* lp = _s;
char* rp = _s + length() - 1;
while (lp < rp)
{
char tmp = *lp;
*lp++ = *rp;
*rp-- = tmp;
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
String::set(const char* s_, bool owner, bool duplicate, size_t length)
{
char* s = const_cast<char*>(s_);
// do not make a copy if we will not own it
if (!owner)
duplicate = false;
// s is nullptr or empty?
if ((s == nullptr) || (*s == '\0'))
{
if (_size == 0)
{
_s = &nullChar;
}
else
{
*_s = '\0';
}
_length = 0;
if (owner && !duplicate && (s != nullptr))
delete[] s;
return;
}
// calculate (or copy) the new length, and note the required allocation size
_length = length = (length == size_t_max) ? strlen(s) : length;
size_t reqSize = length + 1;
// copy the string (or just copy its address)
if (owner)
{
// possibly copy the string
if (duplicate)
{
if (reqSize <= _size)
{
memcpy(_s, s, length);
}
else
{
// nuke existing string if we own it
if (_size > 0)
delete[] _s;
// make new size large enough to contain the string, and a multiple of 8
_size = nextMultipleOfPow2((size_t)8, reqSize);
_s = new char[_size];
// copy into the new allocation
memcpy(_s, s, length);
}
_s[length] = '\0';
}
else
{
if (_size > 0)
delete[] _s;
_s = s;
_size = reqSize;
}
}
else
{
if (_size > 0)
delete[] _s;
_s = s;
_size = 0;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::toLower(size_t begin, size_t len)
{
assertOwner();
// Set bounds
size_t myLen = length(), end;
setBounds(begin, end, len, myLen);
// for each character in the substring...
auto lim = _s + end;
for (auto p = _s + begin; p != lim; ++p)
{
if ((*p >= 'A') && (*p <= 'Z'))
*p = tolower(*p);
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::toUpper(size_t begin, size_t len)
{
// set bounds
size_t myLen = length(), end;
setBounds(begin, end, len, myLen);
// for each character in the substring...
auto lim = _s + end;
for (auto p = _s + begin; p != lim; ++p)
{
if ((*p >= 'a') && (*p <= 'z'))
*p = toupper(*p);
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::padBegin(size_t len, char c)
{
size_t myLen = length();
if (len > myLen)
self = repeat(c, len - myLen) + self;
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::padEnd(size_t len, char c)
{
size_t myLen = length();
if (len > myLen)
self += repeat(c, len - myLen);
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::trim()
{
if (empty())
return self;
trimBegin();
trimEnd();
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::trimBegin()
{
if (empty())
return self;
assertOwner();
// chopSize = # of space characters @ start of string
char* p;
for (p = _s; isspace(*p); ++p)
;
size_t chopSize = (p - _s);
// chop out chopSize chars from start of string
if (chopSize > 0)
{
length();
memmove(_s, _s + chopSize, _length + 1 - chopSize);
_length -= chopSize;
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String&
String::trimEnd()
{
if (empty())
return self;
assertOwner();
// get rid of space characters from the end of the string
length();
char* p;
for (p = _s + _length - 1; (p >= _s) && isspace(*p); --p)
;
*++p = '\0';
_length = (p - _s);
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String
String::repeat(char c, size_t num)
{
String res;
size_t i;
for (i = 0; i != num; i++)
res += c;
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
String
String::spaces(size_t num)
{
return repeat(' ', num);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
String::_assertOwner()
{
ASSERTD(_size == 0);
if (_length == size_t_max)
_length = strlen(_s);
size_t size = utl::nextMultipleOfPow2((size_t)8, _length + 1);
char* s = new char[size];
memcpy(s, _s, _length + 1);
_s = s;
_size = size;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void
String::_assertOwner(size_t size, size_t increment)
{
ASSERTD(size != 0);
ASSERTD(increment != 0);
// do nothing?
if (size <= _size)
return;
// make sure ownership flag is set
bool wasOwner = isOwner();
setOwner(true);
// determine new size of _s[]
size_t newSize;
if (increment == size_t_max)
{
newSize = nextPow2(size);
}
else
{
ASSERTD(increment == nextPow2(increment));
newSize = nextMultipleOfPow2(increment, size);
}
// grow the character array to newSize
ASSERTD(length() < newSize);
auto s = new char[newSize];
memcpy(s, _s, length() + 1);
if (wasOwner)
delete[] _s;
_s = s;
_size = newSize;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
char String::nullChar = '\0';
const String emptyString;
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_NS_END;
| 23.573737 | 100 | 0.389879 | [
"object"
] |
ccf0691a2628b7ee75f9ab5cd2c799af706da724 | 10,122 | cpp | C++ | UI/UIEntityDynTexTag.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | UI/UIEntityDynTexTag.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | UI/UIEntityDynTexTag.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
// -------------------------------------------------------------------------
// File name: UIEntityDynTexTag.cpp
// Version: v1.00
// Created: 22/11/2011 by Paul Reindell.
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "UIEntityDynTexTag.h"
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::InitEventSystem()
{
if (!gEnv->pFlashUI)
return;
// event system to receive events from UI
m_pUIOFct = gEnv->pFlashUI->CreateEventSystem( "UIEntityTagsDynTex", IUIEventSystem::eEST_UI_TO_SYSTEM );
s_EventDispatcher.Init(m_pUIOFct, this, "UIEntityDynTexTag");
{
SUIEventDesc evtDesc( "AddEntityTag", "Adds a 3D entity Tag" );
evtDesc.AddParam<SUIParameterDesc::eUIPT_Int>("EntityID", "Entity ID of tagged entity");
evtDesc.AddParam<SUIParameterDesc::eUIPT_String>("uiElements_UIElement", "UIElement that is used for this tag (Instance with EntityId as instanceId will be created)");
evtDesc.AddParam<SUIParameterDesc::eUIPT_String>("EntityClass", "EntityClass of the spawned entity");
evtDesc.AddParam<SUIParameterDesc::eUIPT_String>("Material", "Material template that is used for the dyn texture");
evtDesc.AddParam<SUIParameterDesc::eUIPT_Vec3>("Offset", "Offset in camera space relative to entity pos");
evtDesc.AddParam<SUIParameterDesc::eUIPT_String>("TagIDX", "Custom IDX to identify entity tag.");
s_EventDispatcher.RegisterEvent( evtDesc, &CUIEntityDynTexTag::OnAddTaggedEntity );
}
{
SUIEventDesc evtDesc( "UpdateEntityTag", "Updates a 3D entity Tag" );
evtDesc.AddParam<SUIParameterDesc::eUIPT_Int>("EntityID", "Entity ID of tagged entity");
evtDesc.AddParam<SUIParameterDesc::eUIPT_String>("TagIDX", "Custom IDX to identify entity tag.");
evtDesc.AddParam<SUIParameterDesc::eUIPT_Vec3>("Offset", "Offset in camera space relative to entity pos");
evtDesc.AddParam<SUIParameterDesc::eUIPT_Float>("LerpSpeed", "Define speed of lerp between old and new offset, 0=instant");
s_EventDispatcher.RegisterEvent( evtDesc, &CUIEntityDynTexTag::OnUpdateTaggedEntity );
}
{
SUIEventDesc evtDesc( "RemoveEntityTag", "Removes a 3D entity Tag" );
evtDesc.AddParam<SUIParameterDesc::eUIPT_Int>("EntityID", "Entity ID of tagged entity");
evtDesc.AddParam<SUIParameterDesc::eUIPT_String>("TagIDX", "Custom IDX to identify entity tag.");
s_EventDispatcher.RegisterEvent( evtDesc, &CUIEntityDynTexTag::OnRemoveTaggedEntity );
}
{
SUIEventDesc evtDesc( "RemoveAllEntityTag", "Removes all 3D entity Tags for given entity" );
evtDesc.AddParam<SUIParameterDesc::eUIPT_Int>("EntityID", "Entity ID of tagged entity");
s_EventDispatcher.RegisterEvent( evtDesc, &CUIEntityDynTexTag::OnRemoveAllTaggedEntity );
}
gEnv->pFlashUI->RegisterModule(this, "CUIEntityDynTexTag");
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::UnloadEventSystem()
{
ClearAllTags();
if (gEnv->pFlashUI)
gEnv->pFlashUI->UnregisterModule(this);
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::OnUpdate(float fDeltaTime)
{
const CCamera& cam = GetISystem()->GetViewCamera();
const Matrix34& camMat = cam.GetMatrix();
static const Quat rot90Deg = Quat::CreateRotationXYZ( Ang3(gf_PI * 0.5f, 0, 0) );
const Vec3 vSafeVec = camMat.GetColumn1();
for (TTags::iterator it = m_Tags.begin(); it != m_Tags.end(); ++it)
{
IEntity* pOwner = gEnv->pEntitySystem->GetEntity(it->OwnerId);
IEntity* pTagEntity = gEnv->pEntitySystem->GetEntity(it->TagEntityId);
if (pOwner && pTagEntity)
{
const Vec3 offset = it->fLerp < 1 ? Vec3::CreateLerp(it->vOffset, it->vNewOffset, it->fLerp) : it->vOffset;
const Vec3& vPos = pOwner->GetWorldPos();
const Vec3 vFaceingPos = camMat.GetTranslation() - vSafeVec * 1000.f;
const Vec3 vDir = (vPos - vFaceingPos).GetNormalizedSafe(vSafeVec);
const Vec3 vOffsetX = vDir.Cross(Vec3Constants<float>::fVec3_OneZ).GetNormalized() * offset.x;
const Vec3 vOffsetY = vDir * offset.y;
const Vec3 vOffsetZ = Vec3(0, 0, offset.z);
const Vec3 vOffset = vOffsetX + vOffsetY + vOffsetZ;
const Vec3 vNewPos = vPos + vOffset;
const Vec3 vNewDir = (vNewPos - vFaceingPos).GetNormalizedSafe(vSafeVec);
const Quat qTagRot = Quat::CreateRotationVDir(vNewDir) * rot90Deg; // rotate 90 degrees around X-Axis
pTagEntity->SetPos(vNewPos);
pTagEntity->SetRotation(qTagRot);
if (it->fLerp < 1)
{
assert(it->fSpeed > 0);
it->fLerp += fDeltaTime * it->fSpeed;
it->vOffset = offset;
}
}
}
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::Reset()
{
ClearAllTags();
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::Reload()
{
if (gEnv->IsEditor())
{
ClearAllTags();
}
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::OnInstanceDestroyed( IUIElement* pSender, IUIElement* pDeletedInstance )
{
for (TTags::iterator it = m_Tags.begin(); it != m_Tags.end(); ++it)
{
if (it->pInstance == pDeletedInstance)
it->pInstance = NULL;
}
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::OnEntityEvent( IEntity *pEntity,SEntityEvent &event )
{
assert(event.event == ENTITY_EVENT_DONE);
RemoveAllEntityTags( pEntity->GetId(), false );
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::OnAddTaggedEntity( EntityId entityId, const char* uiElementName, const char* entityClass, const char* materialTemplate, const Vec3& offset, const char* idx)
{
OnRemoveTaggedEntity(entityId, idx);
IEntityClass* pEntClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass( entityClass );
if (pEntClass)
{
SEntitySpawnParams params;
params.nFlags = ENTITY_FLAG_CLIENT_ONLY;
params.pClass = pEntClass;
IEntity* pTagEntity = gEnv->pEntitySystem->SpawnEntity(params);
IUIElement* pElement = gEnv->pFlashUI->GetUIElement(uiElementName);
if (pTagEntity && pElement)
{
IMaterial* pMatTemplate = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(materialTemplate, false);
// Hide the template (otherwise it will render somewhere - usually full screen if not assigned to an object)
pElement->SetVisible(false);
if (pMatTemplate && pMatTemplate->GetShaderItem().m_pShaderResources->GetTexture(EEfResTextures(0)))
{
pMatTemplate->GetShaderItem().m_pShaderResources->GetTexture(EEfResTextures(0))->m_Name.Format("%s@%d.ui", uiElementName, entityId);
IMaterial* pMat = gEnv->p3DEngine->GetMaterialManager()->CloneMaterial(pMatTemplate);
pTagEntity->SetMaterial(pMat);
}
pTagEntity->SetViewDistRatio(256);
IUIElement* pElementInst = pElement->GetInstance((uint)entityId);
pElementInst->RemoveEventListener(this); // first remove to avoid assert if already registered!
pElementInst->AddEventListener(this, "CUIEntityDynTexTag");
gEnv->pEntitySystem->AddEntityEventListener(entityId, ENTITY_EVENT_DONE, this);
m_Tags.push_back( STagInfo(entityId, pTagEntity->GetId(), idx, offset, pElementInst) );
}
}
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::OnUpdateTaggedEntity( EntityId entityId, const string& idx, const Vec3& offset, float speed )
{
for (TTags::iterator it = m_Tags.begin(); it != m_Tags.end(); ++it)
{
if (it->OwnerId == entityId && it->Idx == idx)
{
it->fSpeed = speed;
if (speed > 0)
{
it->fLerp = 0;
it->vNewOffset = offset;
}
else
{
it->fLerp = 1;
it->vOffset = offset;
}
}
}
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::OnRemoveTaggedEntity( EntityId entityId, const string& idx )
{
for (TTags::iterator it = m_Tags.begin(); it != m_Tags.end(); ++it)
{
if (it->OwnerId == entityId && it->Idx == idx)
{
gEnv->pEntitySystem->RemoveEntity(it->TagEntityId);
if (it->pInstance)
it->pInstance->DestroyThis();
m_Tags.erase(it);
break;
}
}
if (!HasEntityTag(entityId))
gEnv->pEntitySystem->RemoveEntityEventListener(entityId, ENTITY_EVENT_DONE, this);
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::OnRemoveAllTaggedEntity( EntityId entityId )
{
RemoveAllEntityTags(entityId);
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::RemoveAllEntityTags( EntityId entityId, bool bUnregisterListener )
{
for (TTags::iterator it = m_Tags.begin(); it != m_Tags.end();)
{
if (it->OwnerId == entityId)
{
gEnv->pEntitySystem->RemoveEntity(it->TagEntityId);
if (it->pInstance)
it->pInstance->DestroyThis();
it = m_Tags.erase(it);
}
else
{
++it;
}
}
if (bUnregisterListener)
gEnv->pEntitySystem->RemoveEntityEventListener(entityId, ENTITY_EVENT_DONE, this);
}
////////////////////////////////////////////////////////////////////////////
void CUIEntityDynTexTag::ClearAllTags()
{
for (TTags::const_iterator it = m_Tags.begin(); it != m_Tags.end(); ++it)
{
gEnv->pEntitySystem->RemoveEntity(it->TagEntityId);
if (it->pInstance)
{
it->pInstance->RemoveEventListener(this);
it->pInstance->DestroyThis();
}
gEnv->pEntitySystem->RemoveEntityEventListener(it->OwnerId, ENTITY_EVENT_DONE, this);
}
m_Tags.clear();
}
////////////////////////////////////////////////////////////////////////////
bool CUIEntityDynTexTag::HasEntityTag( EntityId entityId ) const
{
for (TTags::const_iterator it = m_Tags.begin(); it != m_Tags.end(); ++it)
{
if (it->OwnerId == entityId)
{
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////
REGISTER_UI_EVENTSYSTEM( CUIEntityDynTexTag );
| 35.893617 | 181 | 0.625963 | [
"render",
"object",
"3d"
] |
ccf188ded2dfb68f576840532059afb64cf20555 | 26,200 | cpp | C++ | modules/viz/src/interactor_style.cpp | Nerei/opencv | 92d5f8744c872ccf63b17334f018343973353e47 | [
"BSD-3-Clause"
] | 1 | 2015-04-22T14:10:46.000Z | 2015-04-22T14:10:46.000Z | modules/viz/src/interactor_style.cpp | ameydhar/opencv | 1c3bfae2121f689535ab1a17284f40f5d64e0927 | [
"BSD-3-Clause"
] | null | null | null | modules/viz/src/interactor_style.cpp | ameydhar/opencv | 1c3bfae2121f689535ab1a17284f40f5d64e0927 | [
"BSD-3-Clause"
] | 2 | 2018-05-03T21:08:19.000Z | 2020-09-26T06:27:08.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
// Authors:
// * Ozan Tonkal, ozantonkal@gmail.com
// * Anatoly Baksheev, Itseez Inc. myname.mysurname <> mycompany.com
//
// OpenCV Viz module is complete rewrite of
// PCL visualization module (www.pointclouds.org)
//
//M*/
#include "precomp.hpp"
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::Initialize()
{
modifier_ = cv::viz::InteractorStyle::KB_MOD_ALT;
// Set windows size (width, height) to unknown (-1)
win_size_ = Vec2i(-1, -1);
win_pos_ = Vec2i(0, 0);
max_win_size_ = Vec2i(-1, -1);
// Create the image filter and PNG writer objects
wif_ = vtkSmartPointer<vtkWindowToImageFilter>::New();
snapshot_writer_ = vtkSmartPointer<vtkPNGWriter>::New();
snapshot_writer_->SetInputConnection(wif_->GetOutputPort());
init_ = true;
stereo_anaglyph_mask_default_ = true;
// Initialize the keyboard event callback as none
keyboardCallback_ = 0;
keyboard_callback_cookie_ = 0;
// Initialize the mouse event callback as none
mouseCallback_ = 0;
mouse_callback_cookie_ = 0;
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::saveScreenshot(const String &file)
{
FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]);
wif_->SetInput(Interactor->GetRenderWindow());
wif_->Modified(); // Update the WindowToImageFilter
snapshot_writer_->Modified();
snapshot_writer_->SetFileName(file.c_str());
snapshot_writer_->Write();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::zoomIn()
{
FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]);
// Zoom in
StartDolly();
double factor = 10.0 * 0.2 * .5;
Dolly(std::pow(1.1, factor));
EndDolly();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::zoomOut()
{
FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]);
// Zoom out
StartDolly();
double factor = 10.0 * -0.2 * .5;
Dolly(std::pow(1.1, factor));
EndDolly();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnChar()
{
// Make sure we ignore the same events we handle in OnKeyDown to avoid calling things twice
FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]);
if (Interactor->GetKeyCode() >= '0' && Interactor->GetKeyCode() <= '9')
return;
String key(Interactor->GetKeySym());
if (key.find("XF86ZoomIn") != String::npos)
zoomIn();
else if (key.find("XF86ZoomOut") != String::npos)
zoomOut();
int keymod = false;
switch (modifier_)
{
case KB_MOD_ALT: keymod = Interactor->GetAltKey(); break;
case KB_MOD_CTRL: keymod = Interactor->GetControlKey(); break;
case KB_MOD_SHIFT: keymod = Interactor->GetShiftKey(); break;
}
switch (Interactor->GetKeyCode())
{
// All of the options below simply exit
case 'h': case 'H':
case 'l': case 'L':
case 'p': case 'P':
case 'j': case 'J':
case 'c': case 'C':
case 43: // KEY_PLUS
case 45: // KEY_MINUS
case 'f': case 'F':
case 'g': case 'G':
case 'o': case 'O':
case 'u': case 'U':
case 'q': case 'Q':
{
break;
}
// S and R have a special !ALT case
case 'r': case 'R':
case 's': case 'S':
{
if (!keymod)
Superclass::OnChar();
break;
}
default:
{
Superclass::OnChar();
break;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::registerMouseCallback(void (*callback)(const MouseEvent&, void*), void* cookie)
{
// Register the callback function and store the user data
mouseCallback_ = callback;
mouse_callback_cookie_ = cookie;
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::registerKeyboardCallback(void (*callback)(const KeyboardEvent&, void*), void *cookie)
{
// Register the callback function and store the user data
keyboardCallback_ = callback;
keyboard_callback_cookie_ = cookie;
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool cv::viz::InteractorStyle::getAltKey() { return Interactor->GetAltKey() != 0; }
bool cv::viz::InteractorStyle::getShiftKey() { return Interactor->GetShiftKey()!= 0; }
bool cv::viz::InteractorStyle::getControlKey() { return Interactor->GetControlKey()!= 0; }
//////////////////////////////////////////////////////////////////////////////////////////////
void
cv::viz::InteractorStyle::OnKeyDown()
{
CV_Assert("Interactor style not initialized. Please call Initialize() before continuing" && init_);
CV_Assert("No renderer given! Use SetRendererCollection() before continuing." && renderer_);
FindPokedRenderer(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1]);
if (wif_->GetInput() == NULL)
{
wif_->SetInput(Interactor->GetRenderWindow());
wif_->Modified();
snapshot_writer_->Modified();
}
// Save the initial windows width/height
if (win_size_[0] == -1 || win_size_[1] == -1)
win_size_ = Vec2i(Interactor->GetRenderWindow()->GetSize());
// Get the status of special keys (Cltr+Alt+Shift)
bool shift = getShiftKey();
bool ctrl = getControlKey();
bool alt = getAltKey();
bool keymod = false;
switch (modifier_)
{
case KB_MOD_ALT: keymod = alt; break;
case KB_MOD_CTRL: keymod = ctrl; break;
case KB_MOD_SHIFT: keymod = shift; break;
}
std::string key(Interactor->GetKeySym());
if (key.find("XF86ZoomIn") != std::string::npos)
zoomIn();
else if (key.find("XF86ZoomOut") != std::string::npos)
zoomOut();
switch (Interactor->GetKeyCode())
{
case 'h': case 'H':
{
std::cout << "| Help:\n"
"-------\n"
" p, P : switch to a point-based representation\n"
" w, W : switch to a wireframe-based representation (where available)\n"
" s, S : switch to a surface-based representation (where available)\n"
"\n"
" j, J : take a .PNG snapshot of the current window view\n"
" c, C : display current camera/window parameters\n"
" f, F : fly to point mode\n"
"\n"
" e, E : exit the interactor\n"
" q, Q : stop and call VTK's TerminateApp\n"
"\n"
" +/- : increment/decrement overall point size\n"
" +/- [+ ALT] : zoom in/out \n"
"\n"
" r, R [+ ALT] : reset camera [to viewpoint = {0, 0, 0} -> center_{x, y, z}]\n"
"\n"
" ALT + s, S : turn stereo mode on/off\n"
" ALT + f, F : switch between maximized window mode and original size\n"
"\n"
<< std::endl;
break;
}
// Switch representation to points
case 'p': case 'P':
{
vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors();
vtkCollectionSimpleIterator ait;
for (ac->InitTraversal(ait); vtkActor* actor = ac->GetNextActor(ait); )
for (actor->InitPathTraversal(); vtkAssemblyPath* path = actor->GetNextPath(); )
{
vtkActor* apart = reinterpret_cast <vtkActor*>(path->GetLastNode()->GetViewProp());
apart->GetProperty()->SetRepresentationToPoints();
}
break;
}
// Save a PNG snapshot with the current screen
case 'j': case 'J':
{
unsigned int t = static_cast<unsigned int>(time(0));
String png_file = cv::format("screenshot-%d.png", t);
String cam_file = cv::format("screenshot-%d.cam", t);
vtkSmartPointer<vtkCamera> cam = Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera();
Vec2d clip;
Vec3d focal, pos, view;
cam->GetClippingRange(clip.val);
cam->GetFocalPoint(focal.val);
cam->GetPosition(pos.val);
cam->GetViewUp(view.val);
Vec2i win_pos(Interactor->GetRenderWindow()->GetPosition());
Vec2i win_size(Interactor->GetRenderWindow()->GetSize());
double angle = cam->GetViewAngle() / 180.0 * CV_PI;
String data = cv::format("%f,%f/%f,%f,%f/%f,%f,%f/%f,%f,%f/%f/%d,%d/%d,%d", clip[0],clip[1], focal[0],focal[1],focal[2],
pos[0],pos[1],pos[2], view[0],view[1], view[2], angle , win_size[0],win_size[1], win_pos[0], win_pos[1]);
saveScreenshot(png_file);
ofstream ofs_cam(cam_file.c_str());
ofs_cam << data.c_str() << endl;
ofs_cam.close();
cout << "Screenshot (" << png_file.c_str() << ") and camera information (" << cam_file.c_str() << ") successfully captured." << endl;
break;
}
// display current camera settings/parameters
case 'c': case 'C':
{
vtkSmartPointer<vtkCamera> cam = Interactor->GetRenderWindow()->GetRenderers()->GetFirstRenderer()->GetActiveCamera();
Vec2d clip;
Vec3d focal, pose, view;
cam->GetClippingRange(clip.val);
cam->GetFocalPoint(focal.val);
cam->GetPosition(pose.val);
cam->GetViewUp(view.val);
Vec2i win_pos(Interactor->GetRenderWindow()->GetPosition());
Vec2i win_size(Interactor->GetRenderWindow()->GetSize());
cv::print(Mat(clip, false).reshape(1, 1));
std::cout << "/";
cv::print(Mat(focal, false).reshape(1, 1));
std::cout << "/";
cv::print(Mat(pose, false).reshape(1, 1));
std::cout << "/";
cv::print(Mat(view, false).reshape(1, 1));
std::cout << "/" << cam->GetViewAngle () / 180.0 * CV_PI;
cv::print(Mat(win_size, false).reshape(1, 1));
std::cout << "/";
cv::print(Mat(win_pos, false).reshape(1, 1));
std::cout << std::endl;
break;
}
case '=':
{
zoomIn();
break;
}
case 43: // KEY_PLUS
{
if (alt)
zoomIn();
else
{
vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors();
vtkCollectionSimpleIterator ait;
for (ac->InitTraversal(ait); vtkActor* actor = ac->GetNextActor(ait); )
for (actor->InitPathTraversal(); vtkAssemblyPath* path = actor->GetNextPath(); )
{
vtkActor* apart = reinterpret_cast <vtkActor*>(path->GetLastNode()->GetViewProp());
float psize = apart->GetProperty()->GetPointSize();
if (psize < 63.0f)
apart->GetProperty()->SetPointSize(psize + 1.0f);
}
}
break;
}
case 45: // KEY_MINUS
{
if (alt)
zoomOut();
else
{
vtkSmartPointer<vtkActorCollection> ac = CurrentRenderer->GetActors();
vtkCollectionSimpleIterator ait;
for (ac->InitTraversal(ait); vtkActor* actor = ac->GetNextActor(ait); )
for (actor->InitPathTraversal(); vtkAssemblyPath* path = actor->GetNextPath(); )
{
vtkActor* apart = static_cast<vtkActor*>(path->GetLastNode()->GetViewProp());
float psize = apart->GetProperty()->GetPointSize();
if (psize > 1.0f)
apart->GetProperty()->SetPointSize(psize - 1.0f);
}
}
break;
}
// Switch between maximize and original window size
case 'f': case 'F':
{
if (keymod)
{
Vec2i screen_size(Interactor->GetRenderWindow()->GetScreenSize());
Vec2i win_size(Interactor->GetRenderWindow()->GetSize());
// Is window size = max?
if (win_size == max_win_size_)
{
Interactor->GetRenderWindow()->SetSize(win_size_.val);
Interactor->GetRenderWindow()->SetPosition(win_pos_.val);
Interactor->GetRenderWindow()->Render();
Interactor->Render();
}
// Set to max
else
{
win_pos_ = Vec2i(Interactor->GetRenderWindow()->GetPosition());
win_size_ = win_size;
Interactor->GetRenderWindow()->SetSize(screen_size.val);
Interactor->GetRenderWindow()->Render();
Interactor->Render();
max_win_size_ = Vec2i(Interactor->GetRenderWindow()->GetSize());
}
}
else
{
AnimState = VTKIS_ANIM_ON;
vtkAssemblyPath *path = NULL;
Interactor->GetPicker()->Pick(Interactor->GetEventPosition()[0], Interactor->GetEventPosition()[1], 0.0, CurrentRenderer);
vtkAbstractPropPicker *picker;
if ((picker = vtkAbstractPropPicker::SafeDownCast(Interactor->GetPicker())))
path = picker->GetPath();
if (path != NULL)
Interactor->FlyTo(CurrentRenderer, picker->GetPickPosition());
AnimState = VTKIS_ANIM_OFF;
}
break;
}
// 's'/'S' w/out ALT
case 's': case 'S':
{
if (keymod)
{
int stereo_render = Interactor->GetRenderWindow()->GetStereoRender();
if (!stereo_render)
{
if (stereo_anaglyph_mask_default_)
{
Interactor->GetRenderWindow()->SetAnaglyphColorMask(4, 3);
stereo_anaglyph_mask_default_ = false;
}
else
{
Interactor->GetRenderWindow()->SetAnaglyphColorMask(2, 5);
stereo_anaglyph_mask_default_ = true;
}
}
Interactor->GetRenderWindow()->SetStereoRender(!stereo_render);
Interactor->GetRenderWindow()->Render();
Interactor->Render();
}
else
Superclass::OnKeyDown();
break;
}
case 'o': case 'O':
{
vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera();
cam->SetParallelProjection(!cam->GetParallelProjection());
CurrentRenderer->SetActiveCamera(cam);
CurrentRenderer->Render();
break;
}
// Overwrite the camera reset
case 'r': case 'R':
{
if (!keymod)
{
Superclass::OnKeyDown();
break;
}
vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera();
static WidgetActorMap::iterator it = widget_actor_map_->begin();
// it might be that some actors don't have a valid transformation set -> we skip them to avoid a seg fault.
bool found_transformation = false;
for (size_t idx = 0; idx < widget_actor_map_->size(); ++idx, ++it)
{
if (it == widget_actor_map_->end())
it = widget_actor_map_->begin();
vtkProp3D * actor = vtkProp3D::SafeDownCast(it->second);
if (actor && actor->GetUserMatrix())
{
found_transformation = true;
break;
}
}
// if a valid transformation was found, use it otherwise fall back to default view point.
if (found_transformation)
{
const vtkMatrix4x4* m = vtkProp3D::SafeDownCast(it->second)->GetUserMatrix();
cam->SetFocalPoint(m->GetElement(0, 3) - m->GetElement(0, 2),
m->GetElement(1, 3) - m->GetElement(1, 2),
m->GetElement(2, 3) - m->GetElement(2, 2));
cam->SetViewUp (m->GetElement(0, 1), m->GetElement(1, 1), m->GetElement(2, 1));
cam->SetPosition(m->GetElement(0, 3), m->GetElement(1, 3), m->GetElement(2, 3));
}
else
{
cam->SetPosition(0, 0, 0);
cam->SetFocalPoint(0, 0, 1);
cam->SetViewUp(0, -1, 0);
}
// go to the next actor for the next key-press event.
if (it != widget_actor_map_->end())
++it;
else
it = widget_actor_map_->begin();
CurrentRenderer->SetActiveCamera(cam);
CurrentRenderer->ResetCameraClippingRange();
CurrentRenderer->Render();
break;
}
case 'q': case 'Q':
{
Interactor->ExitCallback();
return;
}
default:
{
Superclass::OnKeyDown();
break;
}
}
KeyboardEvent event(true, Interactor->GetKeySym(), Interactor->GetKeyCode(), getAltKey(), getControlKey(), getShiftKey());
// Check if there is a keyboard callback registered
if (keyboardCallback_)
keyboardCallback_(event, keyboard_callback_cookie_);
renderer_->Render();
Interactor->Render();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnKeyUp()
{
KeyboardEvent event(false, Interactor->GetKeySym(), Interactor->GetKeyCode(), getAltKey(), getControlKey(), getShiftKey());
// Check if there is a keyboard callback registered
if (keyboardCallback_)
keyboardCallback_(event, keyboard_callback_cookie_);
Superclass::OnKeyUp();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnMouseMove()
{
Vec2i p(Interactor->GetEventPosition());
MouseEvent event(MouseEvent::MouseMove, MouseEvent::NoButton, p, getAltKey(), getControlKey(), getShiftKey());
if (mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
Superclass::OnMouseMove();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnLeftButtonDown()
{
Vec2i p(Interactor->GetEventPosition());
MouseEvent::Type type = (Interactor->GetRepeatCount() == 0) ? MouseEvent::MouseButtonPress : MouseEvent::MouseDblClick;
MouseEvent event(type, MouseEvent::LeftButton, p, getAltKey(), getControlKey(), getShiftKey());
if (mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
Superclass::OnLeftButtonDown();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnLeftButtonUp()
{
Vec2i p(Interactor->GetEventPosition());
MouseEvent event(MouseEvent::MouseButtonRelease, MouseEvent::LeftButton, p, getAltKey(), getControlKey(), getShiftKey());
if (mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
Superclass::OnLeftButtonUp();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnMiddleButtonDown()
{
Vec2i p(Interactor->GetEventPosition());
MouseEvent::Type type = (Interactor->GetRepeatCount() == 0) ? MouseEvent::MouseButtonPress : MouseEvent::MouseDblClick;
MouseEvent event(type, MouseEvent::MiddleButton, p, getAltKey(), getControlKey(), getShiftKey());
if (mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
Superclass::OnMiddleButtonDown();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnMiddleButtonUp()
{
Vec2i p(Interactor->GetEventPosition());
MouseEvent event(MouseEvent::MouseButtonRelease, MouseEvent::MiddleButton, p, getAltKey(), getControlKey(), getShiftKey());
if (mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
Superclass::OnMiddleButtonUp();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnRightButtonDown()
{
Vec2i p(Interactor->GetEventPosition());
MouseEvent::Type type = (Interactor->GetRepeatCount() == 0) ? MouseEvent::MouseButtonPress : MouseEvent::MouseDblClick;
MouseEvent event(type, MouseEvent::RightButton, p, getAltKey(), getControlKey(), getShiftKey());
if (mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
Superclass::OnRightButtonDown();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnRightButtonUp()
{
Vec2i p(Interactor->GetEventPosition());
MouseEvent event(MouseEvent::MouseButtonRelease, MouseEvent::RightButton, p, getAltKey(), getControlKey(), getShiftKey());
if (mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
Superclass::OnRightButtonUp();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnMouseWheelForward()
{
Vec2i p(Interactor->GetEventPosition());
MouseEvent event(MouseEvent::MouseScrollUp, MouseEvent::VScroll, p, getAltKey(), getControlKey(), getShiftKey());
// If a mouse callback registered, call it!
if (mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
if (Interactor->GetRepeatCount() && mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
if (Interactor->GetAltKey())
{
// zoom
vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera();
double opening_angle = cam->GetViewAngle();
if (opening_angle > 15.0)
opening_angle -= 1.0;
cam->SetViewAngle(opening_angle);
cam->Modified();
CurrentRenderer->SetActiveCamera(cam);
CurrentRenderer->ResetCameraClippingRange();
CurrentRenderer->Modified();
CurrentRenderer->Render();
renderer_->Render();
Interactor->Render();
}
else
Superclass::OnMouseWheelForward();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnMouseWheelBackward()
{
Vec2i p(Interactor->GetEventPosition());
MouseEvent event(MouseEvent::MouseScrollDown, MouseEvent::VScroll, p, getAltKey(), getControlKey(), getShiftKey());
// If a mouse callback registered, call it!
if (mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
if (Interactor->GetRepeatCount() && mouseCallback_)
mouseCallback_(event, mouse_callback_cookie_);
if (Interactor->GetAltKey())
{
// zoom
vtkSmartPointer<vtkCamera> cam = CurrentRenderer->GetActiveCamera();
double opening_angle = cam->GetViewAngle();
if (opening_angle < 170.0)
opening_angle += 1.0;
cam->SetViewAngle(opening_angle);
cam->Modified();
CurrentRenderer->SetActiveCamera(cam);
CurrentRenderer->ResetCameraClippingRange();
CurrentRenderer->Modified();
CurrentRenderer->Render();
renderer_->Render();
Interactor->Render();
}
else
Superclass::OnMouseWheelBackward();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void cv::viz::InteractorStyle::OnTimer()
{
CV_Assert("Interactor style not initialized." && init_);
CV_Assert("Renderer has not been set." && renderer_);
renderer_->Render();
Interactor->Render();
}
namespace cv { namespace viz
{
//Standard VTK macro for *New()
vtkStandardNewMacro(InteractorStyle)
}}
| 37.806638 | 141 | 0.560038 | [
"render"
] |
ccf2b21b0e7181ecc76cb1805bdcddf7bbf23056 | 1,181 | cc | C++ | leet_code/Hand_of_Straights/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | 1 | 2020-04-11T22:04:23.000Z | 2020-04-11T22:04:23.000Z | leet_code/Hand_of_Straights/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | leet_code/Hand_of_Straights/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | class Solution {
private :
const int invalid = -1;
public:
bool isNStraightHand(vector<int>& hand, int W) {
unordered_map<int, int> hash;
vector<int> unique;
sort(hand.begin(), hand.end());
for (int i = 0; i < hand.size(); ++i) {
if (hash.find(hand[i]) == hash.end()) {
hash[hand[i]] = 0;
}
++hash[hand[i]];
if (unique.empty() || unique[unique.size() - 1] != hand[i]) {
unique.push_back(hand[i]);
}
}
for (int i = 0; i < unique.size(); ++i) {
int num = hash[unique[i]];
if (num < 0) {
return false;
} else if (num == 0) {
continue;
}
for (int j = 0; j < W; ++j) {
int k = unique[i] + j;
if (hash.find(k) == hash.end()) {
return false;
}
hash[k] -= num;
}
}
for (int i = 0; i < unique.size(); ++i) {
if (hash[unique[i]] != 0) {
return false;
}
}
return true;
}
};
| 25.12766 | 73 | 0.370025 | [
"vector"
] |
ccf4a42af3445d5e7758435d511bd5a7cc07ef59 | 14,630 | hpp | C++ | include/UnityEngine/RenderTextureDescriptor.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/RenderTextureDescriptor.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/RenderTextureDescriptor.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // 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: UnityEngine.Experimental.Rendering.GraphicsFormat
#include "UnityEngine/Experimental/Rendering/GraphicsFormat.hpp"
// Including type: UnityEngine.Rendering.TextureDimension
#include "UnityEngine/Rendering/TextureDimension.hpp"
// Including type: UnityEngine.Rendering.ShadowSamplingMode
#include "UnityEngine/Rendering/ShadowSamplingMode.hpp"
// Including type: UnityEngine.VRTextureUsage
#include "UnityEngine/VRTextureUsage.hpp"
// Including type: UnityEngine.RenderTextureCreationFlags
#include "UnityEngine/RenderTextureCreationFlags.hpp"
// Including type: UnityEngine.RenderTextureMemoryless
#include "UnityEngine/RenderTextureMemoryless.hpp"
// Including type: UnityEngine.RenderTextureFormat
#include "UnityEngine/RenderTextureFormat.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
// Type namespace: UnityEngine
namespace UnityEngine {
// Size: 0x34
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: UnityEngine.RenderTextureDescriptor
struct RenderTextureDescriptor/*, public System::ValueType*/ {
public:
// [CompilerGeneratedAttribute] Offset: 0xD9344C
// [DebuggerBrowsableAttribute] Offset: 0xD9344C
// private System.Int32 <width>k__BackingField
// Size: 0x4
// Offset: 0x0
int width;
// Field size check
static_assert(sizeof(int) == 0x4);
// [CompilerGeneratedAttribute] Offset: 0xD93488
// [DebuggerBrowsableAttribute] Offset: 0xD93488
// private System.Int32 <height>k__BackingField
// Size: 0x4
// Offset: 0x4
int height;
// Field size check
static_assert(sizeof(int) == 0x4);
// [DebuggerBrowsableAttribute] Offset: 0xD934C4
// [CompilerGeneratedAttribute] Offset: 0xD934C4
// private System.Int32 <msaaSamples>k__BackingField
// Size: 0x4
// Offset: 0x8
int msaaSamples;
// Field size check
static_assert(sizeof(int) == 0x4);
// [DebuggerBrowsableAttribute] Offset: 0xD93500
// [CompilerGeneratedAttribute] Offset: 0xD93500
// private System.Int32 <volumeDepth>k__BackingField
// Size: 0x4
// Offset: 0xC
int volumeDepth;
// Field size check
static_assert(sizeof(int) == 0x4);
// [CompilerGeneratedAttribute] Offset: 0xD9353C
// [DebuggerBrowsableAttribute] Offset: 0xD9353C
// private System.Int32 <mipCount>k__BackingField
// Size: 0x4
// Offset: 0x10
int mipCount;
// Field size check
static_assert(sizeof(int) == 0x4);
// private UnityEngine.Experimental.Rendering.GraphicsFormat _graphicsFormat
// Size: 0x4
// Offset: 0x14
UnityEngine::Experimental::Rendering::GraphicsFormat graphicsFormat;
// Field size check
static_assert(sizeof(UnityEngine::Experimental::Rendering::GraphicsFormat) == 0x4);
// [DebuggerBrowsableAttribute] Offset: 0xD93578
// [CompilerGeneratedAttribute] Offset: 0xD93578
// private UnityEngine.Experimental.Rendering.GraphicsFormat <stencilFormat>k__BackingField
// Size: 0x4
// Offset: 0x18
UnityEngine::Experimental::Rendering::GraphicsFormat stencilFormat;
// Field size check
static_assert(sizeof(UnityEngine::Experimental::Rendering::GraphicsFormat) == 0x4);
// private System.Int32 _depthBufferBits
// Size: 0x4
// Offset: 0x1C
int depthBufferBits;
// Field size check
static_assert(sizeof(int) == 0x4);
// [CompilerGeneratedAttribute] Offset: 0xD935B4
// [DebuggerBrowsableAttribute] Offset: 0xD935B4
// private UnityEngine.Rendering.TextureDimension <dimension>k__BackingField
// Size: 0x4
// Offset: 0x20
UnityEngine::Rendering::TextureDimension dimension;
// Field size check
static_assert(sizeof(UnityEngine::Rendering::TextureDimension) == 0x4);
// [CompilerGeneratedAttribute] Offset: 0xD935F0
// [DebuggerBrowsableAttribute] Offset: 0xD935F0
// private UnityEngine.Rendering.ShadowSamplingMode <shadowSamplingMode>k__BackingField
// Size: 0x4
// Offset: 0x24
UnityEngine::Rendering::ShadowSamplingMode shadowSamplingMode;
// Field size check
static_assert(sizeof(UnityEngine::Rendering::ShadowSamplingMode) == 0x4);
// [CompilerGeneratedAttribute] Offset: 0xD9362C
// [DebuggerBrowsableAttribute] Offset: 0xD9362C
// private UnityEngine.VRTextureUsage <vrUsage>k__BackingField
// Size: 0x4
// Offset: 0x28
UnityEngine::VRTextureUsage vrUsage;
// Field size check
static_assert(sizeof(UnityEngine::VRTextureUsage) == 0x4);
// private UnityEngine.RenderTextureCreationFlags _flags
// Size: 0x4
// Offset: 0x2C
UnityEngine::RenderTextureCreationFlags flags;
// Field size check
static_assert(sizeof(UnityEngine::RenderTextureCreationFlags) == 0x4);
// [DebuggerBrowsableAttribute] Offset: 0xD93668
// [CompilerGeneratedAttribute] Offset: 0xD93668
// private UnityEngine.RenderTextureMemoryless <memoryless>k__BackingField
// Size: 0x4
// Offset: 0x30
UnityEngine::RenderTextureMemoryless memoryless;
// Field size check
static_assert(sizeof(UnityEngine::RenderTextureMemoryless) == 0x4);
// Creating value type constructor for type: RenderTextureDescriptor
constexpr RenderTextureDescriptor(int width_ = {}, int height_ = {}, int msaaSamples_ = {}, int volumeDepth_ = {}, int mipCount_ = {}, UnityEngine::Experimental::Rendering::GraphicsFormat graphicsFormat_ = {}, UnityEngine::Experimental::Rendering::GraphicsFormat stencilFormat_ = {}, int depthBufferBits_ = {}, UnityEngine::Rendering::TextureDimension dimension_ = {}, UnityEngine::Rendering::ShadowSamplingMode shadowSamplingMode_ = {}, UnityEngine::VRTextureUsage vrUsage_ = {}, UnityEngine::RenderTextureCreationFlags flags_ = {}, UnityEngine::RenderTextureMemoryless memoryless_ = {}) noexcept : width{width_}, height{height_}, msaaSamples{msaaSamples_}, volumeDepth{volumeDepth_}, mipCount{mipCount_}, graphicsFormat{graphicsFormat_}, stencilFormat{stencilFormat_}, depthBufferBits{depthBufferBits_}, dimension{dimension_}, shadowSamplingMode{shadowSamplingMode_}, vrUsage{vrUsage_}, flags{flags_}, memoryless{memoryless_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Get static field: static private System.Int32[] depthFormatBits
static ::Array<int>* _get_depthFormatBits();
// Set static field: static private System.Int32[] depthFormatBits
static void _set_depthFormatBits(::Array<int>* value);
// public System.Int32 get_width()
// Offset: 0xF05444
int get_width();
// public System.Void set_width(System.Int32 value)
// Offset: 0xF0544C
void set_width(int value);
// public System.Int32 get_height()
// Offset: 0xF05454
int get_height();
// public System.Void set_height(System.Int32 value)
// Offset: 0xF0545C
void set_height(int value);
// public System.Int32 get_msaaSamples()
// Offset: 0xF05464
int get_msaaSamples();
// public System.Void set_msaaSamples(System.Int32 value)
// Offset: 0xF0546C
void set_msaaSamples(int value);
// public System.Int32 get_volumeDepth()
// Offset: 0xF05474
int get_volumeDepth();
// public System.Void set_volumeDepth(System.Int32 value)
// Offset: 0xF0547C
void set_volumeDepth(int value);
// public System.Void set_mipCount(System.Int32 value)
// Offset: 0xF05484
void set_mipCount(int value);
// public UnityEngine.Experimental.Rendering.GraphicsFormat get_graphicsFormat()
// Offset: 0xF0548C
UnityEngine::Experimental::Rendering::GraphicsFormat get_graphicsFormat();
// public System.Void set_graphicsFormat(UnityEngine.Experimental.Rendering.GraphicsFormat value)
// Offset: 0xF05494
void set_graphicsFormat(UnityEngine::Experimental::Rendering::GraphicsFormat value);
// public UnityEngine.RenderTextureFormat get_colorFormat()
// Offset: 0xF054D8
UnityEngine::RenderTextureFormat get_colorFormat();
// public System.Void set_colorFormat(UnityEngine.RenderTextureFormat value)
// Offset: 0xF054E4
void set_colorFormat(UnityEngine::RenderTextureFormat value);
// public System.Boolean get_sRGB()
// Offset: 0xF054EC
bool get_sRGB();
// public System.Void set_sRGB(System.Boolean value)
// Offset: 0xF054F8
void set_sRGB(bool value);
// public System.Int32 get_depthBufferBits()
// Offset: 0xF05504
int get_depthBufferBits();
// public System.Void set_depthBufferBits(System.Int32 value)
// Offset: 0xF0550C
void set_depthBufferBits(int value);
// public System.Void set_dimension(UnityEngine.Rendering.TextureDimension value)
// Offset: 0xF05538
void set_dimension(UnityEngine::Rendering::TextureDimension value);
// public System.Void set_shadowSamplingMode(UnityEngine.Rendering.ShadowSamplingMode value)
// Offset: 0xF05540
void set_shadowSamplingMode(UnityEngine::Rendering::ShadowSamplingMode value);
// public System.Void set_vrUsage(UnityEngine.VRTextureUsage value)
// Offset: 0xF05548
void set_vrUsage(UnityEngine::VRTextureUsage value);
// public System.Void set_memoryless(UnityEngine.RenderTextureMemoryless value)
// Offset: 0xF05550
void set_memoryless(UnityEngine::RenderTextureMemoryless value);
// public System.Void .ctor(System.Int32 width, System.Int32 height, UnityEngine.RenderTextureFormat colorFormat, System.Int32 depthBufferBits)
// Offset: 0xF05558
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
RenderTextureDescriptor(int width, int height, UnityEngine::RenderTextureFormat colorFormat, int depthBufferBits) {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RenderTextureDescriptor::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(width), ::il2cpp_utils::ExtractType(height), ::il2cpp_utils::ExtractType(colorFormat), ::il2cpp_utils::ExtractType(depthBufferBits)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, width, height, colorFormat, depthBufferBits);
}
// public System.Void .ctor(System.Int32 width, System.Int32 height, UnityEngine.Experimental.Rendering.GraphicsFormat colorFormat, System.Int32 depthBufferBits)
// Offset: 0xF05560
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
RenderTextureDescriptor(int width, int height, UnityEngine::Experimental::Rendering::GraphicsFormat colorFormat, int depthBufferBits) {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RenderTextureDescriptor::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(width), ::il2cpp_utils::ExtractType(height), ::il2cpp_utils::ExtractType(colorFormat), ::il2cpp_utils::ExtractType(depthBufferBits)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, width, height, colorFormat, depthBufferBits);
}
// public System.Void .ctor(System.Int32 width, System.Int32 height, UnityEngine.Experimental.Rendering.GraphicsFormat colorFormat, System.Int32 depthBufferBits, System.Int32 mipCount)
// Offset: 0xF05568
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
RenderTextureDescriptor(int width, int height, UnityEngine::Experimental::Rendering::GraphicsFormat colorFormat, int depthBufferBits, int mipCount) {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::RenderTextureDescriptor::.ctor");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(width), ::il2cpp_utils::ExtractType(height), ::il2cpp_utils::ExtractType(colorFormat), ::il2cpp_utils::ExtractType(depthBufferBits), ::il2cpp_utils::ExtractType(mipCount)})));
::il2cpp_utils::RunMethodThrow<void, false>(*this, ___internal__method, width, height, colorFormat, depthBufferBits, mipCount);
}
// private System.Void SetOrClearRenderTextureCreationFlag(System.Boolean value, UnityEngine.RenderTextureCreationFlags flag)
// Offset: 0xF05570
void SetOrClearRenderTextureCreationFlag(bool value, UnityEngine::RenderTextureCreationFlags flag);
// public System.Void set_useMipMap(System.Boolean value)
// Offset: 0xF0558C
void set_useMipMap(bool value);
// public System.Void set_autoGenerateMips(System.Boolean value)
// Offset: 0xF055A8
void set_autoGenerateMips(bool value);
// public System.Void set_enableRandomWrite(System.Boolean value)
// Offset: 0xF055C4
void set_enableRandomWrite(bool value);
// System.Void set_createdFromScript(System.Boolean value)
// Offset: 0xF055E0
void set_createdFromScript(bool value);
// public System.Void set_useDynamicScale(System.Boolean value)
// Offset: 0xF055FC
void set_useDynamicScale(bool value);
// static private System.Void .cctor()
// Offset: 0x1B0ED14
static void _cctor();
}; // UnityEngine.RenderTextureDescriptor
#pragma pack(pop)
static check_size<sizeof(RenderTextureDescriptor), 48 + sizeof(UnityEngine::RenderTextureMemoryless)> __UnityEngine_RenderTextureDescriptorSizeCheck;
static_assert(sizeof(RenderTextureDescriptor) == 0x34);
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::RenderTextureDescriptor, "UnityEngine", "RenderTextureDescriptor");
| 56.705426 | 935 | 0.73609 | [
"vector"
] |
ccfbd03f36173f05039a657bd47031cef6e19d52 | 513 | cpp | C++ | vnoj/hsgso20_permswap.cpp | tiozo/Training | 02cc8c4fcf68e07c16520fd05fcbfa524c171b6b | [
"MIT"
] | 1 | 2021-08-28T04:16:34.000Z | 2021-08-28T04:16:34.000Z | vnoj/hsgso20_permswap.cpp | tiozo/Training | 02cc8c4fcf68e07c16520fd05fcbfa524c171b6b | [
"MIT"
] | null | null | null | vnoj/hsgso20_permswap.cpp | tiozo/Training | 02cc8c4fcf68e07c16520fd05fcbfa524c171b6b | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main() {
int N,C; cin >> N >> C;
map<int,int> diff;
vector<int> p(N+1,0);
for (int i=1;i<=N;++i) {
cin >> p[i];
if (p[i]!=i) {
diff[i] = p[i];
}
}
for (int i=1;i<=C;++i) {
int x,y; cin >> x >> y;
swap(p[x],p[y]);
if (p[x]!=x) diff[x] = p[x]; else diff.erase(x);
if (p[y]!=y) diff[y] = p[y]; else diff.erase(y);
cout << diff.size()-1 << '\n';
}
return 0;
} | 23.318182 | 56 | 0.401559 | [
"vector"
] |
690e40b062f77674be9188b512f6d54b7501ccc5 | 1,628 | cpp | C++ | Code(2021)/20210328_Algospot_std-freejia.cpp | std-freejia/hymni.study | 6c1f5f5f64f931c8da0580a09efa37929b3b502f | [
"MIT"
] | 1 | 2020-06-06T04:01:57.000Z | 2020-06-06T04:01:57.000Z | Code(2021)/20210328_Algospot_std-freejia.cpp | std-freejia/hymni.study | 6c1f5f5f64f931c8da0580a09efa37929b3b502f | [
"MIT"
] | null | null | null | Code(2021)/20210328_Algospot_std-freejia.cpp | std-freejia/hymni.study | 6c1f5f5f64f931c8da0580a09efa37929b3b502f | [
"MIT"
] | 1 | 2020-07-30T13:15:30.000Z | 2020-07-30T13:15:30.000Z | #include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
#include <utility>
#define MAX 101
using namespace std;
// 알고스팟 BOJ 13549
int N, M, answer;
int map[MAX][MAX]; // 지도 (0은 빈 방, 1은 벽)
int broken_cnt[MAX][MAX] = {-1, }; // // 현재 지점에서 벽을 부순 횟수
// 4방향 이동
int xx[5] = {0, 0, -1, 1};
int yy[5] = {-1, 1, 0, 0};
deque<pair<int, int> > de; // 벽을 뚫는 경우 에는 뒤에, 안뚫는 경우에는 앞에 추가한다.
bool check_boundary(int x, int y){
return (x <= N && x >= 1 && y <= M && y >= 1 );
}
void BFS(){ // (1,1)에서 시작해서 (N,M)에 도착해야 한다.
de.push_back( {1, 1});
broken_cnt[1][1] = 0;
while(!de.empty()){
int now_x = de.front().first ;
int now_y = de.front().second;
de.pop_front();
int now_cnt = broken_cnt[now_x][now_y]; // 현재 지점에서 벽을 부순 횟수
for(int i=0; i < 4; i++){
int next_x = now_x + xx[i];
int next_y = now_y + yy[i];
if(check_boundary(next_x, next_y) == false) continue; // 좌표 범위 체크
if(broken_cnt[next_x][next_y] != -1) continue; // 이미 방문했다면 지나간다.
if(map[next_x][next_y] == 1){ // 벽이면 뚫는다.
broken_cnt[next_x][next_y] = now_cnt+1;
de.push_back({next_x, next_y});
}else if(map[next_x][next_y] == 0){ // 빈방이면 안뚫어도 된다
broken_cnt[next_x][next_y] = broken_cnt[now_x][now_y];
de.push_front({next_x, next_y});
}
}
}
}
void Solve(){
BFS();
cout << broken_cnt[N][M];
}
void Input(){
cin >> M >> N ; // 가로M, 세로 N
char ch = 0;
for(int i = 1; i <= N; i++){ //map 입력받기
for(int j = 1; j <= M; j++){
scanf("%1d", &map[i][j]);
broken_cnt[i][j] = -1;
}
}
}
int main(void){
Input();
Solve();
return 0;
}
| 18.712644 | 70 | 0.542998 | [
"vector"
] |
690efa70a42205c358dbaab6e86c916e6c6eb441 | 2,522 | cpp | C++ | L298N_Jetson.cpp | JKI757/L298N_Jetson | 23109d95656b9e361d26a3ee998e66f3aff6409e | [
"MIT"
] | null | null | null | L298N_Jetson.cpp | JKI757/L298N_Jetson | 23109d95656b9e361d26a3ee998e66f3aff6409e | [
"MIT"
] | 1 | 2020-05-24T04:20:07.000Z | 2020-05-24T04:20:07.000Z | L298N_Jetson.cpp | JKI757/L298N_Jetson | 23109d95656b9e361d26a3ee998e66f3aff6409e | [
"MIT"
] | null | null | null | /*
* MIT License
*/
/*
* File: L298N_Jetson.cpp
* Author: josh
*
* Created on May 23, 2020, 12:58 AM
*/
#include "L298N_Jetson.hpp"
L298N_Jetson::L298N_Jetson() = default;
L298N_Jetson::~L298N_Jetson() {
this->Drive_PWM->stop();
if (this->setup){
GPIO::cleanup();
}
};
L298N_Jetson::L298N_Jetson(int EnablePin,
int IN1, int IN2) {
this->Enable = EnablePin;
this->IN1 = IN1;
this->IN2 = IN2;
this->pwmVal = 0;
GPIO::setmode(GPIO::BOARD);
GPIO::setup(this->IN1, GPIO::OUT,GPIO::LOW);
GPIO::setup(this->IN2, GPIO::OUT,GPIO::LOW);
GPIO::setup(this->Enable, GPIO::OUT, GPIO::HIGH);
this->Drive_PWM = std::make_shared<GPIO::PWM>(this->Enable, 50);
this->setup = true;
// approximately 50hz is the correct frequency for the L298N board
}
L298N_Jetson::L298N_Jetson(int pinIN1, int pinIN2) {
this->IN1 = IN1;
this->IN2 = IN2;
this->pwmVal = 0;
GPIO::setmode(GPIO::BOARD);
GPIO::setup(this->IN1, GPIO::OUT,GPIO::LOW);
GPIO::setup(this->IN2, GPIO::OUT,GPIO::LOW);
this->setup = true;
}
L298N_Jetson::L298N_Jetson(std::shared_ptr<GPIO::PWM> drive, int IN1, int IN2, bool setup){
this->Drive_PWM = drive;
this->IN1 = IN1;
this->IN2 = IN2;
this->pwmVal = 0;
GPIO::setup(this->IN1, GPIO::OUT,GPIO::LOW);
GPIO::setup(this->IN2, GPIO::OUT,GPIO::LOW);
this->setup = false; // this tells the object we didn't create the PWM object and thus can't destroy it or stop PWM
// The argument doesn't matter, we have to have another argument so the override doesn't collide with
// the other constructor
}
void L298N_Jetson::setSpeed(const unsigned char pwmVal){
this->pwmVal = pwmVal;
}
const unsigned char L298N_Jetson::getSpeed(){
return pwmVal;
}
void L298N_Jetson::forward(){
GPIO::output(this->IN1, GPIO::HIGH);
GPIO::output(this->IN2, GPIO::LOW);
run();
}
void L298N_Jetson::backward(){
GPIO::output(this->IN1, GPIO::LOW);
GPIO::output(this->IN2, GPIO::HIGH);
run();
}
void L298N_Jetson::run(){
//this->Drive_PWM->ChangeDutyCycle( (this->pwmVal) / 255.0 );
this->Drive_PWM->start((this->pwmVal) );
//important -- you need to send in values from [0, 100]. These are a percentage
//a percentage for the GPIO library
}
void L298N_Jetson::stop(){
GPIO::output(this->IN1, GPIO::LOW);
GPIO::output(this->IN2, GPIO::LOW);
this->Drive_PWM->stop();
}
| 28.337079 | 125 | 0.616971 | [
"object"
] |
69100e2bcd564f566c893fbd85cbc162189d90ad | 38,449 | cpp | C++ | implementation codes/quartic oscillator/simulation_quart.cpp | Z-T-WANG/DeepReinforcementLearningControlOfQuantumCartpoles | 3b243f235b4945a4817b738d8dbc412937de9f28 | [
"MIT"
] | 6 | 2020-08-01T09:30:17.000Z | 2021-10-31T19:40:51.000Z | implementation codes/inverted quartic oscillator/simulation_quart.cpp | Z-T-WANG/DeepReinforcementLearningControlOfQuantumCartpoles | 3b243f235b4945a4817b738d8dbc412937de9f28 | [
"MIT"
] | null | null | null | implementation codes/inverted quartic oscillator/simulation_quart.cpp | Z-T-WANG/DeepReinforcementLearningControlOfQuantumCartpoles | 3b243f235b4945a4817b738d8dbc412937de9f28 | [
"MIT"
] | 1 | 2020-07-28T06:10:08.000Z | 2020-07-28T06:10:08.000Z | #define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <cmath>
#include <iostream>
#include <string>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#include <cstdio>
#include <mkl.h>
// used to initialize numpy, otherwise it fails.
int init_(){
mkl_set_dynamic(0);
mkl_set_num_threads(1);
import_array(); // PyError if not successful
return 0;
}
const static double x_max = X_MAX, grid_size = GRID_SIZE;
const static MKL_INT x_n = int(x_max/grid_size+0.5)*2+1;
const static double lambda = LAMBDA, mass = MASS;
const static int derivative_estimation_points = 4; // this parameter should influence the dimension and contents of matrix ab and p_hat, Hamiltonian etc.
const static struct matrix_descr descr = {SPARSE_MATRIX_TYPE_SYMMETRIC, SPARSE_FILL_MODE_UPPER, SPARSE_DIAG_NON_UNIT}; // notice that first order derivative and p_hat do not satisfy
static MKL_Complex16 ab[2*derivative_estimation_points+1][x_n]={{{0.,0.}}}, ab_LU[3*derivative_estimation_points+1][x_n]={{{0.,0.}}}; MKL_INT LU_ipiv[x_n];
class Set_World{
public:
double x[x_n], x_2[x_n], quartic_V[x_n]; sparse_matrix_t identity;
sparse_matrix_t delta_x, delta_2_x;
sparse_matrix_t x_hat, p_hat, p_hat_2, xp_px_hat;
sparse_matrix_t quartic_Hamil; // these two involve complex numbers
// the following are substituted into imaginary parts of matrix ab
double ab_upper[derivative_estimation_points][x_n]={{0.}}, ab_lower[derivative_estimation_points][x_n]={{0.}},\
ab_center[x_n]={0.};
int init_status = 0;
sparse_matrix_t empty_matrix; // the "empty_matrix" is for simpler calculation writing
MKL_INT* empty_rowindex_start, *empty_rowindex_end, *empty_column; // *** Somehow MKL does not allow copying and automatically allocating such a matrix,
MKL_Complex16* empty_value; // and we have to manage its memory manually.
///////////////////////////// *** initializer *** ///////////////////////////////////////////
Set_World(){
// compute the basic x, x^2, V=\lambda*x^4 arrays
for(int i=0;i < x_n;i++){x[i]=grid_size*((double)(i-int(x_max/grid_size+0.5)));}
for(int i=0;i < x_n;i++){x_2[i]=x[i]*x[i];}
for(int i=0;i < x_n;i++){quartic_V[i]=x_2[i]*x_2[i]*lambda;}
// Fortran defaults to one-based indexing with column major format. zero-based indexing implies C format? it seems so.
// If we simply use ```MKL_Complex16 delta_x_dense[x_n][x_n], delta_2_x_dense[x_n][x_n];```, it will result in a stack overflow when x_n is too large
using arr2d = MKL_Complex16(*)[x_n];
arr2d delta_x_dense = new MKL_Complex16[x_n][x_n]; arr2d delta_2_x_dense = new MKL_Complex16[x_n][x_n];
//MKL_Complex16 delta_x_dense[x_n][x_n], delta_2_x_dense[x_n][x_n];
for(int i=0;i<x_n;i++){for(int j=0;j<x_n;j++){delta_x_dense[i][j]={0.,0.};delta_2_x_dense[i][j]={0.,0.};}}
for(int i=1;i < x_n-1;i++){
delta_x_dense[i][i-1].real=-672./840. / grid_size;
delta_x_dense[i-1][i].real=672./840. / grid_size;}
for(int i=2;i < x_n-2;i++){
delta_x_dense[i][i-2].real=168./840. / grid_size;
delta_x_dense[i-2][i].real=-168./840. / grid_size;}
for(int i=3;i < x_n-3;i++){
delta_x_dense[i][i-3].real=-32./840. / grid_size;
delta_x_dense[i-3][i].real=32./840. / grid_size;}
for(int i=4;i < x_n-4;i++){
delta_x_dense[i][i-4].real=3./840. / grid_size;
delta_x_dense[i-4][i].real=-3./840. / grid_size;}//
for(int i=0;i < x_n;i++){
delta_2_x_dense[i][i].real=-14350./5040. / (grid_size*grid_size);
ab_center[i]=(delta_2_x_dense[i][i].real*(-1.)/(2.*mass)+quartic_V[i])*0.5;}
for(int i=1;i < x_n;i++){
delta_2_x_dense[i][i-1].real=8064./5040. / (grid_size*grid_size);
delta_2_x_dense[i-1][i].real=8064./5040. / (grid_size*grid_size);
ab_upper[3][i]=0.5*delta_2_x_dense[i][i-1].real*(-1.)/(2.*mass);
ab_lower[0][i-1]=0.5*delta_2_x_dense[i][i-1].real*(-1.)/(2.*mass);}
for(int i=2;i < x_n;i++){
delta_2_x_dense[i][i-2].real=-1008./5040. / (grid_size*grid_size);
delta_2_x_dense[i-2][i].real=-1008./5040. / (grid_size*grid_size);
ab_upper[2][i]=0.5*delta_2_x_dense[i][i-2].real*(-1.)/(2.*mass);
ab_lower[1][i-2]=0.5*delta_2_x_dense[i][i-2].real*(-1.)/(2.*mass);}
for(int i=3;i < x_n;i++){
delta_2_x_dense[i][i-3].real=128./5040. / (grid_size*grid_size);
delta_2_x_dense[i-3][i].real=128./5040. / (grid_size*grid_size);
ab_upper[1][i]=0.5*delta_2_x_dense[i][i-3].real*(-1.)/(2.*mass);
ab_lower[2][i-3]=0.5*delta_2_x_dense[i][i-3].real*(-1.)/(2.*mass);}
for(int i=4;i < x_n;i++){
delta_2_x_dense[i][i-4].real=-9./5040. / (grid_size*grid_size);
delta_2_x_dense[i-4][i].real=-9./5040. / (grid_size*grid_size);
ab_upper[0][i]=0.5*delta_2_x_dense[i][i-4].real*(-1.)/(2.*mass);
ab_lower[3][i-4]=0.5*delta_2_x_dense[i][i-4].real*(-1.)/(2.*mass);}
/* if we add lower order derivative estimations around the borders,
it will become not hermitian */
for(int i=0;i < x_n;i++){ab[derivative_estimation_points][i].real=1.;}
// create an empty sparse matrix for convenience
empty_rowindex_start = (MKL_INT*)mkl_malloc(sizeof(MKL_INT)*x_n, 64);
empty_rowindex_end = (MKL_INT*)mkl_malloc(sizeof(MKL_INT)*x_n, 64);
empty_column = (MKL_INT*)mkl_malloc(sizeof(MKL_INT)*1 , 64);
empty_value = (MKL_Complex16*)mkl_malloc(sizeof(MKL_Complex16)*1, 64);
for(int i=0;i<x_n;i++){
empty_rowindex_start[i]=1; empty_rowindex_end[i]=1;
}
empty_rowindex_start[0]=0; empty_column[0]=0; empty_value[0]={0.,0.};
if (SPARSE_STATUS_SUCCESS!= mkl_sparse_z_create_csr (&empty_matrix, SPARSE_INDEX_BASE_ZERO, x_n, x_n, empty_rowindex_start, empty_rowindex_end, empty_column, empty_value)&& \
init_status==0){init_status = -1;}
// prepare for mkl_?dnscsr(...), which transforms a dense matrix to a sparse
MKL_INT job[6]={0,0,0,2,(2*derivative_estimation_points+1)*x_n,3}; MKL_INT info;
MKL_Complex16 acsr_1[(2*derivative_estimation_points+1)*x_n]={{0.,0.}};
MKL_INT ja_1[(2*derivative_estimation_points+1)*x_n]={0}, ia_1[x_n+1]={0};
/* dense -> CSR, zero-based indexing in CSR, and dense,
adns is a whole matrix, max non-zero values, require all outputs */
mkl_zdnscsr (job, &x_n, &x_n, &(delta_x_dense[0][0]) , &x_n , acsr_1 , ja_1 , ia_1 , &info );
if(info!=0)printf("CSR conversion-1 error info %d",(int)info);
// create delta_x operator
sparse_matrix_t temp;
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_create_csr (&temp, SPARSE_INDEX_BASE_ZERO, x_n, x_n, ia_1, ia_1+1, ja_1, acsr_1) && init_status==0){init_status = -2;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_copy (temp, {SPARSE_MATRIX_TYPE_GENERAL,SPARSE_FILL_MODE_UPPER,SPARSE_DIAG_NON_UNIT}, &delta_x) && init_status==0){
init_status = -2;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_destroy (temp) && init_status==0){init_status = -2;}
delete[] delta_x_dense;
// store the CSR format of delta_2_x_dense
MKL_Complex16 acsr_2[(2*derivative_estimation_points+1)*x_n]={{0.,0.}};
MKL_INT ja_2[(2*derivative_estimation_points+1)*x_n]={0}, ia_2[x_n+1]={0};
mkl_zdnscsr (job , &x_n , &x_n , delta_2_x_dense[0] , &x_n , acsr_2 , ja_2 , ia_2 , &info );
if(info!=0)printf("CSR conversion-2 error info %d",(int)info);
// create delta_2_x
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_create_csr (&temp, SPARSE_INDEX_BASE_ZERO, x_n, x_n, ia_2, ia_2+1, ja_2, acsr_2) && init_status==0){init_status = -3;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_copy (temp, {SPARSE_MATRIX_TYPE_SYMMETRIC,SPARSE_FILL_MODE_UPPER,SPARSE_DIAG_NON_UNIT}, &delta_2_x) && init_status==0){
init_status = -3;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_destroy (temp) && init_status==0){init_status = -3;}
delete[] delta_2_x_dense;
// create x_hat CSR matrix
// prepare for mkl_?csrdia(...)
job[0]=1, job[3]=0, job[4]=0, job[5]=0;
/* diagonal -> CSR, zero-based indexing in CSR, and diagonal,
N/A, N/A, check zeroes and leave out them */
// vairables for the CSR matrix, the "_rem"s are not used. There should be exactly x_n values in total.
MKL_Complex16 *acsr_rem=nullptr; MKL_INT *ja_rem=nullptr, *ia_rem=nullptr;
MKL_Complex16 x_C[x_n]={{0.,0.}};
for(int i=0;i<x_n;i++){x_C[i].real=x[i];}
// variables for the diagonal format matrix.
MKL_INT distance[1]={0}, idiag=1;
MKL_Complex16 acsr_3[x_n]={{0.,0.}};
MKL_INT ja_3[x_n]={0}, ia_3[x_n+1]={0};
// change the format to CSR:
mkl_zcsrdia (job, &x_n , acsr_3 , ja_3 , ia_3 , x_C , &x_n , distance , &idiag , acsr_rem , ja_rem , ia_rem , &info );
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_create_csr (&temp, SPARSE_INDEX_BASE_ZERO, x_n, x_n, ia_3, ia_3+1, ja_3, acsr_3) && init_status==0){init_status = -4;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_copy (temp, {SPARSE_MATRIX_TYPE_DIAGONAL,SPARSE_FILL_MODE_UPPER,SPARSE_DIAG_NON_UNIT}, &x_hat) && init_status==0){
init_status = -4;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_destroy (temp) && init_status==0){init_status = -4;}
// create quartic_V CSR matrix
sparse_matrix_t V_hat;
MKL_Complex16 quartic_V_C[x_n]={{0.,0.}};
for(int i=0;i<x_n;i++){quartic_V_C[i].real=quartic_V[i];}
MKL_Complex16 acsr_4[x_n]={{0.,0.}};
MKL_INT ja_4[x_n]={0}, ia_4[x_n+1]={0};
mkl_zcsrdia (job, &x_n , acsr_4 , ja_4 , ia_4 , quartic_V_C , &x_n , distance , &idiag , acsr_rem , ja_rem , ia_rem , &info );
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_create_csr (&temp, SPARSE_INDEX_BASE_ZERO, x_n, x_n, ia_4, ia_4+1, ja_4, acsr_4) && init_status==0){init_status = -5;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_copy (temp, {SPARSE_MATRIX_TYPE_DIAGONAL,SPARSE_FILL_MODE_UPPER,SPARSE_DIAG_NON_UNIT}, &V_hat) && init_status==0){
init_status = -5;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_destroy (temp) && init_status==0){init_status = -5;}
// create identity CSR matrix
MKL_Complex16 identity_C[x_n]; for(int i=0;i<x_n;i++){identity_C[i]={1.,0.};} /* it does not initialize in the form of ={{1.,0.}}. */
MKL_Complex16 acsr_5[x_n]={{0.,0.}};
MKL_INT ja_5[x_n]={0}, ia_5[x_n+1]={0};
mkl_zcsrdia (job, &x_n , acsr_5 , ja_5 , ia_5 , identity_C , &x_n , distance , &idiag , acsr_rem , ja_rem , ia_rem , &info );
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_create_csr (&temp, SPARSE_INDEX_BASE_ZERO, x_n, x_n, ia_5, ia_5+1, ja_5, acsr_5) && init_status==0){init_status = -6;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_copy (temp, {SPARSE_MATRIX_TYPE_HERMITIAN,SPARSE_FILL_MODE_UPPER,SPARSE_DIAG_UNIT}, &identity) && init_status==0){
init_status = -6;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_destroy (temp) && init_status==0){init_status = -6;}
// create p_hat, p_hat_2
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_add (SPARSE_OPERATION_NON_TRANSPOSE, delta_x, {0.,-1.}, empty_matrix, &p_hat) && init_status==0){init_status = -7;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_add (SPARSE_OPERATION_NON_TRANSPOSE, delta_2_x, {-1.,0.}, empty_matrix, &p_hat_2) && init_status==0){init_status = -7;}
// create xp_px_hat
sparse_matrix_t temp2;
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_spmm (SPARSE_OPERATION_NON_TRANSPOSE, x_hat, p_hat, &temp) && init_status==0){init_status = -8;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_copy (temp, {SPARSE_MATRIX_TYPE_GENERAL,SPARSE_FILL_MODE_UPPER,SPARSE_DIAG_NON_UNIT}, &temp2) && init_status==0){init_status = -8;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_add (SPARSE_OPERATION_CONJUGATE_TRANSPOSE, temp, {1.,0.}, temp2, &xp_px_hat) && init_status==0){init_status = -8;}
if ((SPARSE_STATUS_SUCCESS!=mkl_sparse_destroy (temp)||SPARSE_STATUS_SUCCESS!=mkl_sparse_destroy (temp2)) && init_status==0){init_status = -9;}
// create quartic_Hamiltonian
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_add (SPARSE_OPERATION_NON_TRANSPOSE, p_hat_2, {1./(2.*mass),0.}, V_hat, &quartic_Hamil) && init_status==0){init_status = -10;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_order (quartic_Hamil) && init_status==0){init_status = -11;}
if ((SPARSE_STATUS_SUCCESS!=mkl_sparse_order (x_hat)||SPARSE_STATUS_SUCCESS!=mkl_sparse_order (p_hat)) && init_status==0){init_status = -12;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_set_mv_hint (quartic_Hamil, SPARSE_OPERATION_NON_TRANSPOSE, descr, 10000000) && init_status==0){init_status = -13;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_optimize (quartic_Hamil) && init_status==0){init_status = -14;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_set_mv_hint (p_hat, SPARSE_OPERATION_NON_TRANSPOSE, {SPARSE_MATRIX_TYPE_HERMITIAN, SPARSE_FILL_MODE_UPPER, SPARSE_DIAG_NON_UNIT}, 1000000) && init_status==0){init_status = -14;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_optimize (p_hat) && init_status==0){init_status = -15;}
}
// use of mkl sparse handler involves memory leak problems. Because mkl is based on C, not C++
~Set_World(){
mkl_sparse_destroy (empty_matrix);
mkl_sparse_destroy (delta_x); mkl_sparse_destroy (delta_2_x);
mkl_sparse_destroy (x_hat); mkl_sparse_destroy (p_hat); mkl_sparse_destroy (p_hat_2); mkl_sparse_destroy (xp_px_hat);
mkl_sparse_destroy (quartic_Hamil);
}
};
const static Set_World world;
static int check_type(PyArrayObject* state);
static void compute_x_hat_state(const double &alpha, const MKL_Complex16* psi, const double &beta, MKL_Complex16* result){
const double* psi_pointer;
double* result_pointer;
psi_pointer = &(psi[0].real), result_pointer = &(result[0].real);
if(beta==0.){
for(int i=0; i<x_n; i++){
result_pointer[2*i] = alpha * psi_pointer[2*i]*world.x[i];
result_pointer[2*i+1] = alpha * psi_pointer[2*i+1]*world.x[i];}
}else{
for(int i=0; i<x_n; i++){
result_pointer[2*i] *= beta;
result_pointer[2*i] += alpha * psi_pointer[2*i]*world.x[i];
result_pointer[2*i+1] *= beta;
result_pointer[2*i+1] += alpha * psi_pointer[2*i+1]*world.x[i];}
}
}
static double x_expct(const MKL_Complex16* psi){
MKL_Complex16 x_hat_state[x_n]={{0.,0.}};
compute_x_hat_state(1., psi, 0., x_hat_state);
MKL_Complex16 temp;
cblas_zdotc_sub (x_n, psi, 1, x_hat_state, 1, &temp);
return temp.real*grid_size;
}
static double p_expct(const MKL_Complex16* psi){
MKL_Complex16 p_hat_state[x_n]={{0.,0.}};
mkl_sparse_z_mv(SPARSE_OPERATION_NON_TRANSPOSE, {1.,0.}, world.p_hat, {SPARSE_MATRIX_TYPE_HERMITIAN, SPARSE_FILL_MODE_UPPER, SPARSE_DIAG_NON_UNIT}, psi, {0.,0.}, p_hat_state);
MKL_Complex16 temp;
cblas_zdotc_sub (x_n, psi, 1, p_hat_state, 1, &temp);
return temp.real*grid_size;
}
static PyObject* x_expectation(PyObject *self, PyObject *args){
PyObject* temp;
PyArrayObject* state;
if (!PyArg_ParseTuple(args, "O", &temp)){
PyErr_SetString(PyExc_TypeError, "The input state is not a Numpy array");
return NULL;
}
PyArray_OutputConverter(temp, &state);
if (!state) {PyErr_SetString(PyExc_TypeError, "The input state cannot be identified as a Numpy array"); return NULL;}
if (check_type(state)!=0) return NULL;
// get the c array from numpy (complex128 is stored as successive float64 two by two)
MKL_Complex16* psi;
psi = (MKL_Complex16*) PyArray_GETPTR1(state, 0);
return Py_BuildValue("d", x_expct(psi));
}
static void normalize(MKL_Complex16* psi){
double norm;
norm = cblas_dznrm2 (x_n, psi, 1);
cblas_zdscal (x_n, 1./norm / std::sqrt(grid_size), psi, 1);
}
static double x_relative[x_n];
// the following two functions assume that "x_relative" is already prepared in advance
// the use of "x_relative" is only involved in the following functions that compute distribuion moments
static void compute_x_relative_state(const MKL_Complex16* psi, MKL_Complex16* result){
const double* psi_pointer;
double* result_pointer; psi_pointer = &(psi[0].real), result_pointer = &(result[0].real);
for(int i=0; i<x_n; i++){
result_pointer[2*i] = psi_pointer[2*i]*x_relative[i];
result_pointer[2*i+1] = psi_pointer[2*i+1]*x_relative[i];}
}
static void compute_x_relative_inplace(MKL_Complex16* state){
double* state_pointer;
state_pointer = &(state[0].real);
for(int i=0; i<x_n; i++){
state_pointer[2*i] *= x_relative[i];
state_pointer[2*i+1] *= x_relative[i];}
}
static sparse_matrix_t p_hat_relative;
static inline void compute_x_or_p_relative_state(const MKL_Complex16* psi, char x_or_p, MKL_Complex16* result){
if(x_or_p=='x'){compute_x_relative_state(psi,result);}
if(x_or_p=='p'){mkl_sparse_z_mv(SPARSE_OPERATION_NON_TRANSPOSE, {1.,0.}, p_hat_relative, {SPARSE_MATRIX_TYPE_HERMITIAN, SPARSE_FILL_MODE_UPPER, SPARSE_DIAG_NON_UNIT}, psi, {0.,0.}, result);}
}
static int check_type(PyArrayObject* state){
if(PyArray_NDIM(state)!=1){
PyErr_SetString(PyExc_ValueError, "The state array is not one-dimensional");
return -1;
}else{
if(PyArray_SHAPE(state)[0]!=x_n){
PyErr_SetString(PyExc_ValueError, ("The state array does not match the required size "+std::to_string(x_n)).c_str());
return -1;
}else{
PyArray_Descr* descr = PyArray_DESCR(state);
if(descr->type_num!=NPY_COMPLEX128){
PyErr_SetString(PyExc_ValueError, "The state array does not match the required datatype: Complex128");
return -1;
}
return 0;
}
}
}
static int check_moment_data_array(PyArrayObject* data, int dimension){
if(PyArray_NDIM(data)!=1){
PyErr_SetString(PyExc_ValueError, "The moment data array is not one-dimensional");
return -1;
}else{
if(PyArray_SHAPE(data)[0]!=dimension){
PyErr_SetString(PyExc_ValueError, ("The moment data array does not match the required size "+std::to_string(dimension)).c_str());
return -1;
}else{
PyArray_Descr* descr = PyArray_DESCR(data);
if(descr->type_num!=NPY_FLOAT64){
PyErr_SetString(PyExc_ValueError, "The moment data array does not match the required datatype: Float64");
return -1;
}
return 0;
}
}
}
static int moment_order = MOMENT;
static int compute_statistics(const MKL_Complex16* psi, double* data){
// data are arranged in the order of:
// <x>, <p>
// centered moments -- <xx>, Re<xp>, <pp>, <xxx>, Re<xxp>, Re<xpp>, <ppp>, <xxxx>, Re<xxxp>, Re<xxpp>, Re<xppp>, <pppp>,
// <xxxxx>, Re<xxxxp>, Re<xxxpp>, Re<xxppp>, Re<xpppp>, Re<ppppp>
// calculate <x>, <p> and prepare (x_hat-<x>) and (p_hat-<p>)
data[0] = x_expct(psi), data[1] = p_expct(psi);
for(int i=0;i<x_n;i++){x_relative[i]=world.x[i]-data[0];}
sparse_status_t status=mkl_sparse_destroy (p_hat_relative);
if(SPARSE_STATUS_SUCCESS!=status && SPARSE_STATUS_NOT_INITIALIZED!=status){return -1;}
mkl_sparse_z_add (SPARSE_OPERATION_NON_TRANSPOSE, world.identity, {-data[1],0.}, world.p_hat, &p_hat_relative);
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_set_mv_hint (p_hat_relative, SPARSE_OPERATION_NON_TRANSPOSE, {SPARSE_MATRIX_TYPE_HERMITIAN, SPARSE_FILL_MODE_UPPER, SPARSE_DIAG_NON_UNIT}, 5)){return -2;}
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_optimize (p_hat_relative)){return -2;}
// arrange a temp array in the form of x|psi>, p|psi>, pp|psi>, ppp|psi>, pppp|psi>, ppppp|psi>, ...
MKL_Complex16 temp[moment_order+1][x_n];
compute_x_or_p_relative_state(psi, 'x', temp[0]);
compute_x_or_p_relative_state(psi, 'p', temp[1]);
for(int i=2;i<moment_order+1;i++){compute_x_or_p_relative_state(temp[i-1], 'p', temp[i]);}
// prepare the moments
MKL_Complex16 temp_scalar;
int data_i = 2;
for(int j=2;j<=moment_order;j++){
for(int i=0;i<j;i++){
// e.g. for moment 3, we change the temp array to the form of xxx|psi>, xxp|psi>, xpp|psi>, ppp|psi>, pppp|psi>, ppppp|psi>, ...,
// and we collect the first four values
compute_x_relative_inplace(temp[i]);}
for(int i=0;i<j+1;i++){
cblas_zdotc_sub (x_n, psi, 1, temp[i], 1, &temp_scalar);
data[data_i] = temp_scalar.real*grid_size;
data_i+=1;
}
}
return 0;
}
static PyObject* get_moments(PyObject *self, PyObject *args){
PyObject* temp1, *temp2;
PyArrayObject* state, *data_np;
if (!PyArg_ParseTuple(args, "OO", &temp1, &temp2)){
PyErr_SetString(PyExc_TypeError, "The input does not match the required signature (state array (complex), moment data array (float))");
return NULL;
}
PyArray_OutputConverter(temp1, &state);
if (!state) {
PyErr_SetString(PyExc_TypeError, "The input state (argument 1) cannot be identified as a Numpy array");
return NULL;
}
PyArray_OutputConverter(temp2, &data_np);
if (!state) {
PyErr_SetString(PyExc_TypeError, "The input moment data array (argument 2) cannot be identified as a Numpy array");
return NULL;
}
if (check_type(state)!=0) return NULL;
if (check_moment_data_array(data_np, (2+moment_order+1)*moment_order/2)!=0) return NULL;
MKL_Complex16* psi;
psi = (MKL_Complex16*) PyArray_GETPTR1(state, 0);
double* data;
data = (double*) PyArray_GETPTR1(data_np, 0);
if (compute_statistics(psi, data)!=0) return NULL;
Py_RETURN_NONE;
}
static double _dt_cache=0., _force_cache=-1000000.;
static sparse_matrix_t Hamiltonian_addup_factor;
static sparse_matrix_t Hamil_temp[8];
// reset matrix ab
static int reset_ab(bool change_t){
// compute the central diagonal
cblas_dcopy (x_n, world.ab_center, 1, &(ab[derivative_estimation_points][0].imag), 2);
cblas_dscal (x_n, _dt_cache, &(ab[derivative_estimation_points][0].imag), 2);
cblas_daxpy (x_n, -_dt_cache*_force_cache*0.5*M_PI, world.x, 1, &(ab[derivative_estimation_points][0].imag), 2);
if(change_t){
// compute the upper and lower diagonals
cblas_dcopy (derivative_estimation_points*x_n, world.ab_upper[0], 1, &(ab[0][0].imag), 2);
cblas_dscal (derivative_estimation_points*x_n, _dt_cache, &(ab[0][0].imag), 2);
cblas_dcopy (derivative_estimation_points*x_n, world.ab_lower[0], 1, &(ab[derivative_estimation_points+1][0].imag), 2);
cblas_dscal (derivative_estimation_points*x_n, _dt_cache, &(ab[derivative_estimation_points+1][0].imag), 2);
}
sparse_status_t status=mkl_sparse_destroy (Hamiltonian_addup_factor);
if(SPARSE_STATUS_SUCCESS!=status && SPARSE_STATUS_NOT_INITIALIZED!=status){return -1;}
cblas_zcopy ((2*derivative_estimation_points+1)*x_n, &(ab[0][0]), 1, &(ab_LU[derivative_estimation_points][0]), 1);
LAPACKE_zgbtrf (LAPACK_ROW_MAJOR, x_n , x_n , derivative_estimation_points , derivative_estimation_points , &(ab_LU[0][0]) , x_n , LU_ipiv );
// compute the high order correction factors of the Hamiltonian evolution
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_add (SPARSE_OPERATION_NON_TRANSPOSE, world.x_hat, {-M_PI*_force_cache, 0.}, world.quartic_Hamil, &Hamil_temp[0])) return -1;
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_spmm (SPARSE_OPERATION_NON_TRANSPOSE, Hamil_temp[0], Hamil_temp[0], &Hamil_temp[1])) return -1; // H^2
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_spmm (SPARSE_OPERATION_NON_TRANSPOSE, Hamil_temp[1], Hamil_temp[0], &Hamil_temp[2])) return -1; // H^3
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_spmm (SPARSE_OPERATION_NON_TRANSPOSE, Hamil_temp[1], Hamil_temp[1], &Hamil_temp[3])) return -1; // H^4
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_spmm (SPARSE_OPERATION_NON_TRANSPOSE, Hamil_temp[1], Hamil_temp[2], &Hamil_temp[4])) return -1; // H^5
// the following is the correction factor 3-4-5-6 for an implicit method
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_add (SPARSE_OPERATION_NON_TRANSPOSE, Hamil_temp[1], {_dt_cache*_dt_cache*_dt_cache / 12., 0.}, world.empty_matrix, &Hamil_temp[5])) return -1;
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_add (SPARSE_OPERATION_NON_TRANSPOSE, Hamil_temp[2], {0., - _dt_cache*_dt_cache*_dt_cache*_dt_cache / 24.}, Hamil_temp[5], &Hamil_temp[6])) return -1;
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_add (SPARSE_OPERATION_NON_TRANSPOSE, Hamil_temp[3], {- _dt_cache*_dt_cache*_dt_cache*_dt_cache*_dt_cache / 80.,0.} \
, Hamil_temp[6], &Hamil_temp[7])) return -1;
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_z_add (SPARSE_OPERATION_NON_TRANSPOSE, Hamil_temp[4], {0., _dt_cache*_dt_cache*_dt_cache*_dt_cache*_dt_cache*_dt_cache / 360.} \
, Hamil_temp[7], &Hamiltonian_addup_factor)) return -1;
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_set_mv_hint (Hamiltonian_addup_factor, SPARSE_OPERATION_NON_TRANSPOSE, descr, 80)) return -1;
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_order(Hamiltonian_addup_factor)) return -1;
if (SPARSE_STATUS_SUCCESS!=mkl_sparse_optimize (Hamiltonian_addup_factor)) return -1;
// avoid memory leak
for(int i=0;i<8;i++){if(SPARSE_STATUS_SUCCESS!=mkl_sparse_destroy (Hamil_temp[i])){return -1;}}
return 0;
}
// carry out one step calculation
static void __attribute__((hot)) D1(MKL_Complex16* state, const double &force, const double &gamma, MKL_Complex16* result, MKL_Complex16* relative_state, double x_avg){
MKL_Complex16 x_hat_state[x_n];
compute_x_hat_state(1., state, 0., x_hat_state);
// compute the relative_state
cblas_zcopy (x_n, x_hat_state, 1, relative_state, 1); // x_hat_state = relative_state = x|psi>
cblas_daxpy (2*x_n, -x_avg, (double*)state, 1, (double*)relative_state, 1); // relative_state = (x-<x>)|psi>
// compute the deterministic Hamiltonian term, stored in x_hat_state
mkl_sparse_z_mv(SPARSE_OPERATION_NON_TRANSPOSE, {0.,-1.}, world.quartic_Hamil, descr, state, {0.,+1.*M_PI*force}, x_hat_state);
cblas_zcopy (x_n, x_hat_state, 1, result, 1); // store the result: x_hat_state = result = -1.j(H|psi>-oemga*F*x|psi>)
// compute the deterministic squeezing term , stored in x_hat_state
cblas_zcopy (x_n, relative_state, 1, x_hat_state, 1); // x_hat_state = (x-<x>)|psi>
compute_x_hat_state(1., relative_state, -x_avg, x_hat_state); // x_hat_state = (x(x-<x>)|psi>-<x>(x-<x>)|psi>) = (x-<x>)^2 |psi>
// compute the result. The coefficient of the first term (currently in result) is already handled.
cblas_daxpy (2*x_n, -gamma/4., (double*)x_hat_state, 1, (double*)result, 1); // result = -1.j(H-oemga*F*x)|psi> -gamma/4.(x-<x>)^2 |psi>
}
// The "ImRe" is a mistaken notation. The "Im" part refers to the Hamiltonian part that can be evaluated with implicit methods
static void __attribute__((hot)) D1ImRe(MKL_Complex16* state, const double &force, const double &gamma, MKL_Complex16* resultIm, MKL_Complex16* resultRe, MKL_Complex16* relative_state){
// resultIm can replace the role of x_hat_state
compute_x_hat_state(1., state, 0., resultIm);
// compute x_avg
double x_avg;
MKL_Complex16 temp;
cblas_zdotc_sub (x_n, state, 1, resultIm, 1, &temp);
x_avg = temp.real*grid_size;
// compute the relative_state
cblas_zcopy (x_n, resultIm, 1, relative_state, 1);
cblas_daxpy (2*x_n, -x_avg, (double*)state, 1, (double*)relative_state, 1);
// compute the deterministic Hamiltonian term, stored in resultIm
mkl_sparse_z_mv(SPARSE_OPERATION_NON_TRANSPOSE, {0.,-1,}, world.quartic_Hamil, descr, state,{0.,+1.*M_PI*force}, resultIm);
// compute the deterministic squeezing term , stored in resultRe
cblas_zcopy (x_n, relative_state, 1, resultRe, 1);
compute_x_hat_state(-gamma/4., relative_state, x_avg*gamma/4., resultRe);
// compute the result with a required coefficient gamma/-4
}
static void __attribute__((hot)) D2(MKL_Complex16* state, const double &gamma, MKL_Complex16* relative_state_and_result, bool precomputed_relative_state){
if (! precomputed_relative_state){
// compute the relative_state
// compute x|psi>
compute_x_hat_state(1., state, 0., relative_state_and_result);
// compute <x>
double x_avg;
MKL_Complex16 temp;
cblas_zdotc_sub (x_n, state, 1, relative_state_and_result, 1, &temp);
x_avg = temp.real*grid_size;
// compute (x-<x>)|psi>
cblas_daxpy (2*x_n, -x_avg, (double*)state, 1, (double*)relative_state_and_result, 1);}
cblas_zdscal (x_n, sqrt(gamma/2.), relative_state_and_result, 1);
}
static VSLStreamStatePtr stream;
static void go_one_step(MKL_Complex16* psi, double dt, double force, double _gamma, double* q_output, double* x_mean_output);
static void check_boundary_error(MKL_Complex16* psi, int* Fail);
static PyObject* step(PyObject *self, PyObject *args){
double dt, force, _gamma;
PyObject* temp;
PyArrayObject* state;
if (!PyArg_ParseTuple(args, "Oddd", &temp, &dt, &force, &_gamma)){
PyErr_SetString(PyExc_TypeError, "The input does not match the required input signature (state (numpy array), dt (double), F (double), \\gamma (double))");
return NULL;
}
PyArray_OutputConverter(temp, &state);
if (!state) {
PyErr_SetString(PyExc_TypeError, "The input object cannot be identified as a Numpy array");
return NULL;
}
// check the shape and datatype of the array, so that an error will be raised if the shape is not consistent with this c module, avoiding a segmentation fault
if (check_type(state)==-1) return NULL;
// get the c array from numpy (complex128 is stored as successive float64 two by two)
MKL_Complex16* psi;
psi = (MKL_Complex16*) PyArray_GETPTR1(state, 0);
// update the cache of dt and force
bool change_t;
change_t=(dt != _dt_cache);
if (change_t||(force != _force_cache)){
_dt_cache=dt;_force_cache=force;
if(0!=reset_ab(change_t)){PyErr_SetString(PyExc_RuntimeError, "Failed to manage the sparse matrices when setting the implicit solver"); return NULL;}
}
double q=0., x_mean=0.;
go_one_step(psi, dt, force, _gamma, &q, &x_mean);
int Fail=0; // compute the norm of a single value in psi
check_boundary_error(psi, &Fail);
return Py_BuildValue("ddi", q, x_mean, Fail);
}
static PyObject* simulate_10_steps(PyObject *self, PyObject *args){
double dt, force, _gamma;
PyObject* temp;
PyArrayObject* state;
if (!PyArg_ParseTuple(args, "Oddd", &temp, &dt, &force, &_gamma)){
PyErr_SetString(PyExc_TypeError, "The input does not match the required input signature (state (numpy array), dt (double), F (double), \\gamma (double))");
return NULL;
}
PyArray_OutputConverter(temp, &state);
if (!state) {
PyErr_SetString(PyExc_TypeError, "The input object cannot be identified as a Numpy array");
return NULL;
}
// check the shape and datatype of the array, so that an error will be raised if the shape is not consistent with this c module, avoiding a segmentation fault
if (check_type(state)==-1) return NULL;
// get the c array from numpy (complex128 is stored as successive float64 two by two)
MKL_Complex16* psi;
psi = (MKL_Complex16*) PyArray_GETPTR1(state, 0);
// update the cache of dt and force
bool change_t;
change_t=(dt != _dt_cache);
if (change_t||(force != _force_cache)){
_dt_cache=dt;_force_cache=force;
if(0!=reset_ab(change_t)){PyErr_SetString(PyExc_RuntimeError, "Failed to manage the sparse matrices when setting the implicit solver"); return NULL;}
}
double q=0., x_mean=0.;
for(int i=0; i<10; i++){go_one_step(psi, dt, force, _gamma, &q, &x_mean);}
int Fail=0; // compute the norm of a single value in psi
check_boundary_error(psi, &Fail);
return Py_BuildValue("ddi", q, x_mean, Fail);
}
static void check_boundary_error(MKL_Complex16* psi, int* Fail){
int boundary_length = 6;
double threshold = 5.e-3;
if ( cblas_dznrm2(boundary_length, &(psi[x_n-boundary_length]), 1)>threshold || cblas_dznrm2(boundary_length, &(psi[0]), 1)>threshold){
*Fail = 1;
}
}
static void simple_sum_up(double* state, double dt, double dW, double dZ, double* D2_state, double* D1_Y_plusIm_substract_D1_Y_minusIm, double* D1_Y_plusRe, \
double* D1_Y_minusRe, double* D1_state, double* D2_Y_plus, double* D2_Y_minus, double* D2_Phi_plus, double* D2_Phi_minus);
static void __attribute__((hot)) go_one_step(MKL_Complex16* psi, double dt, double force, double _gamma, double* q_output, double* x_mean_output){
// sample random variables
double r[2], dW, dZ;
vdRngGaussian( VSL_RNG_METHOD_GAUSSIAN_BOXMULLER, stream, 2, r, 0., 1. );
dW = r[0]*sqrt(dt), dZ = sqrt(dt)*dt*0.5*(r[0]+r[1]/sqrt(3.));
double x_mean, q;
x_mean = x_expct(psi);
q = x_mean + dW/sqrt(2.*_gamma)/dt;
*q_output=q; *x_mean_output=x_mean;
// start calculation
MKL_Complex16 D1_state[x_n], D2_state[x_n];
MKL_Complex16 D2_state_drt[x_n]={{0.,0.}};
D1(psi, force, _gamma, D1_state, D2_state, x_mean);
D2(psi, _gamma, D2_state, true);
cblas_daxpy (2*x_n, sqrt(dt), (double*)D2_state, 1, (double*)D2_state_drt, 1);
// initialize Y as a 1st order step forward from psi
MKL_Complex16 Y_plus[x_n], Y_minus[x_n];
cblas_zcopy (x_n, psi, 1, Y_plus, 1);
cblas_daxpy (2*x_n, dt, (double*)D1_state, 1, (double*)Y_plus , 1); cblas_zcopy (x_n, Y_plus, 1, Y_minus, 1);
cblas_daxpy (2*x_n, 1., (double*)D2_state_drt, 1, (double*)Y_plus , 1);
cblas_daxpy (2*x_n,-1., (double*)D2_state_drt, 1, (double*)Y_minus, 1);
MKL_Complex16 D1_Y_plusIm[x_n], D1_Y_plusRe[x_n], D2_Y_plus[x_n];
MKL_Complex16 D1_Y_minusIm[x_n], D1_Y_minusRe[x_n], D2_Y_minus[x_n];
D1ImRe(Y_plus, force, _gamma, D1_Y_plusIm, D1_Y_plusRe, D2_Y_plus);
D1ImRe(Y_minus, force, _gamma, D1_Y_minusIm, D1_Y_minusRe, D2_Y_minus);
D2(Y_plus,_gamma, D2_Y_plus, true); D2(Y_minus,_gamma, D2_Y_minus, true);
// use the storage of D1_Y_plusIm as another variable name:
MKL_Complex16* D1_Y_plusIm_substract_D1_Y_minusIm; D1_Y_plusIm_substract_D1_Y_minusIm=D1_Y_plusIm;
cblas_daxpy (2*x_n, -1., (double*)D1_Y_minusIm, 1, (double*)D1_Y_plusIm_substract_D1_Y_minusIm, 1);
// use the storage of Y_minus as another variable name: Phi_minus
MKL_Complex16* Phi_minus; Phi_minus=Y_minus;
cblas_zcopy (x_n, Y_plus, 1, Phi_minus, 1);
// Phi_minus = Y_plus - sqrt(dt) D2(Y_plus)
cblas_daxpy (2*x_n, - sqrt(dt), (double*)D2_Y_plus, 1, (double*)Phi_minus, 1);
// use the storage of Y_plus as Phi_plus
// Phi_plus = Y_plus + sqrt(dt) D2(Y_plus)
MKL_Complex16* Phi_plus; Phi_plus=Y_plus;
cblas_daxpy (2*x_n, sqrt(dt), (double*)D2_Y_plus, 1, (double*)Phi_plus, 1);
MKL_Complex16 D2_Phi_plus[x_n], D2_Phi_minus[x_n];
D2(Phi_plus, _gamma, D2_Phi_plus, false); D2(Phi_minus, _gamma, D2_Phi_minus, false);
// sum them all
simple_sum_up((double*)psi, dt, dW, dZ, (double*)D2_state, (double*)D1_Y_plusIm_substract_D1_Y_minusIm, (double*)D1_Y_plusRe, (double*)D1_Y_minusRe, \
(double*)D1_state, (double*)D2_Y_plus, (double*)D2_Y_minus, (double*)D2_Phi_plus, (double*)D2_Phi_minus);
// implicitly solve
LAPACKE_zgbtrs (LAPACK_ROW_MAJOR, 'N' , x_n , derivative_estimation_points , derivative_estimation_points , 1 , &(ab_LU[0][0]) , x_n , LU_ipiv , psi , 1 );
normalize(psi);
}
static void __attribute__((hot)) simple_sum_up(double* state, double dt, double dW, double dZ, double* D2_state, double* D1_Y_plusIm_substract_D1_Y_minusIm, double* D1_Y_plusRe, \
double* D1_Y_minusRe, double* D1_state, double* D2_Y_plus, double* D2_Y_minus, double* D2_Phi_plus, double* D2_Phi_minus){
MKL_Complex16 term7[x_n]={{0.,0.}};
// note that D1_state has included a factor of -1.j ***
mkl_sparse_z_mv (SPARSE_OPERATION_NON_TRANSPOSE, {1., 0.}, Hamiltonian_addup_factor, descr, (MKL_Complex16*)D1_state, {0.,0.}, term7);
double* dterm7;
dterm7=(double*)term7;
// summation for the implicit method
for(int i=0;i<2*x_n;i++){
state[i]+=D2_state[i]*dW+0.5/sqrt(dt)*dZ*(D1_Y_plusIm_substract_D1_Y_minusIm[i]+D1_Y_plusRe[i]-D1_Y_minusRe[i])+\
0.25*dt*(D1_Y_plusRe[i]+2*D1_state[i]+D1_Y_minusRe[i]) + \
0.25/sqrt(dt)*(dW*dW-dt)*(D2_Y_plus[i] - D2_Y_minus[i]) + \
0.5/dt*(dW*dt-dZ)*(D2_Y_plus[i] + D2_Y_minus[i] - 2*D2_state[i]) + \
0.25/dt*(dW*dW/3-dt)*dW*(D2_Phi_plus[i] - D2_Phi_minus[i] - D2_Y_plus[i] + D2_Y_minus[i]) \
- 0.25*sqrt(dt)*dW*(D1_Y_plusIm_substract_D1_Y_minusIm[i]) \
+ dterm7[i];
}
}
static PyObject* set_seed(PyObject* self, PyObject *args){
int seed;
if (!PyArg_ParseTuple(args, "i", &seed)){printf("Parse fail.\n"); return NULL;}
vslNewStream( &stream, VSL_BRNG_MT19937, seed );
Py_RETURN_NONE;
}
static PyObject* check_settings(PyObject* self, PyObject *args){
return Py_BuildValue("(idddi)", x_n, grid_size, lambda, mass, moment_order);
}
static PyMethodDef methods[] = {
{"step", (PyCFunction)step, METH_VARARGS,
"Do one simulation step."},
{"simulate_10_steps", (PyCFunction)simulate_10_steps, METH_VARARGS,
"Do 10 simulation steps."},
{"set_seed", (PyCFunction)set_seed, METH_VARARGS,
"Initialize the random number generator with a seed."},
{"check_settings", (PyCFunction)check_settings, METH_VARARGS,
"test whether the imported C module responds and return (x_n,grid_size,\\lambda,mass)."},
{"x_expectation", (PyCFunction)x_expectation,METH_VARARGS,""},
{"get_moments", (PyCFunction)get_moments,METH_VARARGS,("get distribution moments up to the "+std::to_string(MOMENT)+"th").c_str()},
{NULL, NULL, 0, NULL} /* sentinel */
};
static struct PyModuleDef simulationmodule = {
PyModuleDef_HEAD_INIT,
"simulation",
NULL,
-1,
methods
};
const int init = init_();
extern "C"{
PyMODINIT_FUNC
__attribute__((externally_visible)) PyInit_simulation(void)
{
//mkl_set_memory_limit (MKL_MEM_MCDRAM, 256); // mbytes
if(world.init_status!=0){
printf("initialization status: %d\n",world.init_status);
PyErr_SetString(PyExc_RuntimeError, "Initialization Failure");
}
//init_();
return PyModule_Create(&simulationmodule);
}
}
| 55.322302 | 219 | 0.686338 | [
"object",
"shape"
] |
6910eb6c47400b9d1994ba853b8217846020b271 | 1,792 | cpp | C++ | test/api/pack/simple_binning_test.cpp | Felix-Droop/chopper-1 | 2dc9ff8f26509164cf28a504690793deb76fb5fc | [
"BSD-3-Clause"
] | null | null | null | test/api/pack/simple_binning_test.cpp | Felix-Droop/chopper-1 | 2dc9ff8f26509164cf28a504690793deb76fb5fc | [
"BSD-3-Clause"
] | null | null | null | test/api/pack/simple_binning_test.cpp | Felix-Droop/chopper-1 | 2dc9ff8f26509164cf28a504690793deb76fb5fc | [
"BSD-3-Clause"
] | null | null | null | #include <gtest/gtest.h>
#include <sstream>
#include <vector>
#include <chopper/pack/simple_binning.hpp>
TEST(simple_binning_test, small_example)
{
std::stringstream output_buffer;
pack_data data;
data.output_buffer = &output_buffer;
data.header_buffer = &output_buffer;
data.kmer_counts = {100, 40, 20, 20};
data.filenames = {"seq1", "seq2", "seq3", "seq4"};
data.fp_correction = std::vector<double>(65, 1.0);
simple_binning algo{data, 9};
size_t max_bin = algo.execute();
std::string expected
{
"seq4\t;0\t;1\n"
"seq3\t;1\t;1\n"
"seq2\t;2\t;2\n"
"seq1\t;4\t;5\n"
};
EXPECT_EQ(output_buffer.str(), expected);
EXPECT_EQ(max_bin, 0);
}
TEST(simple_binning_test, uniform_distribution)
{
std::stringstream output_buffer;
pack_data data;
data.output_buffer = &output_buffer;
data.header_buffer = &output_buffer;
data.kmer_counts = {20, 20, 20, 20};
data.filenames = {"seq1", "seq2", "seq3", "seq4"};
data.fp_correction = std::vector<double>(65, 1.0);
simple_binning algo{data, 4};
size_t max_bin = algo.execute();
std::string expected
{
"seq4\t;0\t;1\n"
"seq3\t;1\t;1\n"
"seq2\t;2\t;1\n"
"seq1\t;3\t;1\n"
};
EXPECT_EQ(output_buffer.str(), expected);
EXPECT_EQ(max_bin, 0);
}
TEST(simple_binning_test, user_bins_must_be_smaller_than_technical_bins)
{
std::stringstream output_buffer;
pack_data data;
data.output_buffer = &output_buffer;
data.header_buffer = &output_buffer;
data.kmer_counts = {100, 40, 20, 20};
data.filenames = {"seq1", "seq2", "seq3", "seq4"};
data.fp_correction = std::vector<double>(65, 1.0);
EXPECT_THROW((simple_binning{data, 2}), std::runtime_error);
}
| 25.6 | 72 | 0.637835 | [
"vector"
] |
6911c90001c3cd51a0fe1b94f3d2c7d91d9ce5bd | 80,008 | cpp | C++ | cpp/search/search.cpp | 030helios/Kata2Connect5 | e8ace620284b46f4a50fc0582924cbadf32653e7 | [
"MIT"
] | null | null | null | cpp/search/search.cpp | 030helios/Kata2Connect5 | e8ace620284b46f4a50fc0582924cbadf32653e7 | [
"MIT"
] | 1 | 2021-06-03T14:30:04.000Z | 2021-06-03T14:40:32.000Z | cpp/search/search.cpp | 030helios/Kata2Surakarta | e8ace620284b46f4a50fc0582924cbadf32653e7 | [
"MIT"
] | null | null | null |
//-------------------------------------------------------------------------------------
// This file contains the main core logic of the search.
//-------------------------------------------------------------------------------------
#include "../search/search.h"
#include <algorithm>
#include <numeric>
#include "../core/fancymath.h"
#include "../core/timer.h"
#include "../search/distributiontable.h"
using namespace std;
ReportedSearchValues::ReportedSearchValues() {}
ReportedSearchValues::~ReportedSearchValues() {}
NodeStats::NodeStats()
: visits(0),
winValueSum(0.0),
noResultValueSum(0.0),
scoreMeanSum(0.0),
scoreMeanSqSum(0.0),
leadSum(0.0),
utilitySum(0.0),
utilitySqSum(0.0),
weightSum(0.0),
weightSqSum(0.0) {}
NodeStats::~NodeStats() {}
double NodeStats::getResultUtilitySum(const SearchParams &searchParams) const
{
return (
(2.0 * winValueSum - weightSum + noResultValueSum) * searchParams.winLossUtilityFactor +
noResultValueSum * searchParams.noResultUtilityForWhite);
}
double Search::getResultUtility(double winValue, double noResultValue) const
{
return (
(2.0 * winValue - 1.0 + noResultValue) * searchParams.winLossUtilityFactor +
noResultValue * searchParams.noResultUtilityForWhite);
}
double Search::getResultUtilityFromNN(const NNOutput &nnOutput) const
{
return (
(nnOutput.whiteWinProb - nnOutput.whiteLossProb) * searchParams.winLossUtilityFactor +
nnOutput.whiteNoResultProb * searchParams.noResultUtilityForWhite);
}
double Search::getScoreStdev(double scoreMean, double scoreMeanSq)
{
double variance = scoreMeanSq - scoreMean * scoreMean;
if (variance <= 0.0)
return 0.0;
return sqrt(variance);
}
//-----------------------------------------------------------------------------------------
SearchNode::SearchNode(
Search &search,
Player prevPla,
Rand &rand,
Loc prevMoveFromLoc,
Loc prevMoveToLoc,
SearchNode *p)
: lockIdx(),
nextPla(getOpp(prevPla)),
prevFromLoc(prevMoveFromLoc),
prevToLoc(prevMoveToLoc),
nnOutput(),
nnOutputAge(0),
parent(p),
children(NULL),
numChildren(0),
childrenCapacity(0),
stats(),
virtualLosses(0),
lastSubtreeValueBiasDeltaSum(0.0),
lastSubtreeValueBiasWeight(0.0),
subtreeValueBiasTableEntry()
{
lockIdx = rand.nextUInt(search.mutexPool->getNumMutexes());
}
SearchNode::~SearchNode()
{
if (children != NULL)
{
for (int i = 0; i < numChildren; i++)
delete children[i];
}
delete[] children;
}
//-----------------------------------------------------------------------------------------
static string makeSeed(const Search &search, int threadIdx)
{
stringstream ss;
ss << search.randSeed;
ss << "$searchThread$";
ss << threadIdx;
ss << "$";
ss << search.rootBoard.pos_hash;
ss << "$";
ss << search.rootHistory.moveHistory.size();
ss << "$";
ss << search.numSearchesBegun;
return ss.str();
}
SearchThread::SearchThread(int tIdx, const Search &search, Logger *lg)
: threadIdx(tIdx),
pla(search.rootPla),
board(search.rootBoard),
history(search.rootHistory),
rand(makeSeed(search, tIdx)),
nnResultBuf(),
logStream(NULL),
logger(lg),
weightFactorBuf(),
weightBuf(),
weightSqBuf(),
winValuesBuf(),
noResultValuesBuf(),
scoreMeansBuf(),
scoreMeanSqsBuf(),
leadsBuf(),
utilityBuf(),
utilitySqBuf(),
selfUtilityBuf(),
visitsBuf(),
upperBoundVisitsLeft(1e30)
{
if (logger != NULL)
logStream = logger->createOStream();
weightFactorBuf.reserve(NNPos::MAX_NN_POLICY_SIZE);
weightBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
weightSqBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
winValuesBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
noResultValuesBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
scoreMeansBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
scoreMeanSqsBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
leadsBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
utilityBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
utilitySqBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
selfUtilityBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
visitsBuf.resize(NNPos::MAX_NN_POLICY_SIZE);
}
SearchThread::~SearchThread()
{
if (logStream != NULL)
delete logStream;
logStream = NULL;
logger = NULL;
}
//-----------------------------------------------------------------------------------------
static const double VALUE_WEIGHT_DEGREES_OF_FREEDOM = 3.0;
Search::Search(SearchParams params, NNEvaluator *nnEval, const string &rSeed)
: rootPla(P_BLACK),
rootBoard(),
rootHistory(),
rootHintLoc(Move(0,0,0)),
avoidMoveUntilByLocBlack(),
avoidMoveUntilByLocWhite(),
rootSafeArea(NULL),
recentScoreCenter(0.0),
searchParams(params),
numSearchesBegun(0),
searchNodeAge(0),
plaThatSearchIsFor(C_EMPTY),
plaThatSearchIsForLastSearch(C_EMPTY),
lastSearchNumPlayouts(0),
effectiveSearchTimeCarriedOver(0.0),
randSeed(rSeed),
normToTApproxZ(0.0),
nnEvaluator(nnEval),
nonSearchRand(rSeed + string("$nonSearchRand")),
subtreeValueBiasTable(NULL)
{
nnXLen = nnEval->getNNXLen();
nnYLen = nnEval->getNNYLen();
assert(nnXLen > 0 && nnXLen <= NNPos::MAX_BOARD_LEN);
assert(nnYLen > 0 && nnYLen <= NNPos::MAX_BOARD_LEN);
policySize = NNPos::getPolicySize(nnXLen, nnYLen);
rootKoHashTable = new KoHashTable();
rootSafeArea = new Color[Board::MAX_ARR_SIZE];
valueWeightDistribution = new DistributionTable(
[](double z)
{ return FancyMath::tdistpdf(z, VALUE_WEIGHT_DEGREES_OF_FREEDOM); },
[](double z)
{ return FancyMath::tdistcdf(z, VALUE_WEIGHT_DEGREES_OF_FREEDOM); },
-50.0,
50.0,
2000);
rootNode = NULL;
mutexPool = new MutexPool(params.mutexPoolSize);
rootHistory.clear(rootBoard, rootPla, Rules());
rootKoHashTable->recompute(rootHistory);
}
Search::~Search()
{
delete[] rootSafeArea;
delete rootKoHashTable;
delete valueWeightDistribution;
delete rootNode;
delete mutexPool;
delete subtreeValueBiasTable;
}
const Board &Search::getRootBoard() const
{
return rootBoard;
}
const BoardHistory &Search::getRootHist() const
{
return rootHistory;
}
Player Search::getRootPla() const
{
return rootPla;
}
Player Search::getPlayoutDoublingAdvantagePla() const
{
return searchParams.playoutDoublingAdvantagePla == C_EMPTY ? plaThatSearchIsFor
: searchParams.playoutDoublingAdvantagePla;
}
void Search::setPosition(Player pla, const Board &board, const BoardHistory &history)
{
clearSearch();
rootPla = pla;
plaThatSearchIsFor = C_EMPTY;
rootBoard = board;
rootHistory = history;
rootKoHashTable->recompute(rootHistory);
avoidMoveUntilByLocBlack.clear();
avoidMoveUntilByLocWhite.clear();
}
void Search::setPlayerAndClearHistory(Player pla)
{
clearSearch();
rootPla = pla;
plaThatSearchIsFor = C_EMPTY;
Rules rules = rootHistory.rules;
rootHistory.clear(rootBoard, rootPla, rules);
rootKoHashTable->recompute(rootHistory);
avoidMoveUntilByLocBlack.clear();
avoidMoveUntilByLocWhite.clear();
}
void Search::setAvoidMoveUntilByLoc(const std::vector<int> &bVec, const std::vector<int> &wVec)
{
if (avoidMoveUntilByLocBlack == bVec && avoidMoveUntilByLocWhite == wVec)
return;
clearSearch();
avoidMoveUntilByLocBlack = bVec;
avoidMoveUntilByLocWhite = wVec;
}
void Search::setRootHintLoc(Move loc)
{
// When we positively change the hint loc, we clear the search to make absolutely sure
// that the hintloc takes effect, and that all nnevals (including the root noise that adds the hintloc) has a chance
// to happen
if (loc.fromLoc != Board::NULL_LOC &&loc.toLoc != Board::NULL_LOC && rootHintLoc.fromLoc != loc.fromLoc&& rootHintLoc.toLoc != loc.toLoc)
clearSearch();
rootHintLoc = loc;
}
void Search::setAlwaysIncludeOwnerMap(bool b)
{
if (!alwaysIncludeOwnerMap && b)
clearSearch();
alwaysIncludeOwnerMap = b;
}
void Search::setParams(SearchParams params)
{
clearSearch();
searchParams = params;
}
void Search::setParamsNoClearing(SearchParams params)
{
searchParams = params;
}
void Search::setNNEval(NNEvaluator *nnEval)
{
clearSearch();
nnEvaluator = nnEval;
nnXLen = nnEval->getNNXLen();
nnYLen = nnEval->getNNYLen();
assert(nnXLen > 0 && nnXLen <= NNPos::MAX_BOARD_LEN);
assert(nnYLen > 0 && nnYLen <= NNPos::MAX_BOARD_LEN);
policySize = NNPos::getPolicySize(nnXLen, nnYLen);
}
void Search::clearSearch()
{
effectiveSearchTimeCarriedOver = 0.0;
delete rootNode;
rootNode = NULL;
}
bool Search::makeMove(Loc fromLoc, Loc toLoc, Player movePla)
{
if (!rootBoard.isLegal(fromLoc, toLoc, movePla))
return false;
if (movePla != rootPla)
setPlayerAndClearHistory(movePla);
if (rootNode != NULL)
{
bool foundChild = false;
int foundChildIdx = -1;
for (int i = 0; i < rootNode->numChildren; i++)
{
SearchNode *child = rootNode->children[i];
if (!foundChild && child->prevFromLoc == fromLoc && child->prevToLoc == toLoc)
{
foundChild = true;
foundChildIdx = i;
break;
}
}
// Just in case, make sure the child has an nnOutput, otherwise no point keeping it.
// This is a safeguard against any oddity involving node preservation into states that
// were considered terminal.
if (foundChild)
{
SearchNode *child = rootNode->children[foundChildIdx];
std::mutex &mutex = mutexPool->getMutex(child->lockIdx);
lock_guard<std::mutex> lock(mutex);
if (child->nnOutput == nullptr)
foundChild = false;
}
if (foundChild)
{
// Grab out the node to prevent its deletion along with the root
// Delete the root and replace it with the child
SearchNode *child = rootNode->children[foundChildIdx];
{
while (rootNode->statsLock.test_and_set(std::memory_order_acquire))
;
int64_t rootVisits = rootNode->stats.visits;
rootNode->statsLock.clear(std::memory_order_release);
while (child->statsLock.test_and_set(std::memory_order_acquire))
;
int64_t childVisits = child->stats.visits;
child->statsLock.clear(std::memory_order_release);
effectiveSearchTimeCarriedOver = effectiveSearchTimeCarriedOver * (double)childVisits / (double)rootVisits *
searchParams.treeReuseCarryOverTimeFactor;
}
child->parent = NULL;
rootNode->children[foundChildIdx] = NULL;
recursivelyRemoveSubtreeValueBiasBeforeDeleteSynchronous(rootNode);
delete rootNode;
rootNode = child;
}
else
{
clearSearch();
}
}
rootHistory.makeBoardMoveAssumeLegal(rootBoard, fromLoc, toLoc, rootPla, rootKoHashTable);
rootPla = getOpp(rootPla);
rootKoHashTable->recompute(rootHistory);
avoidMoveUntilByLocBlack.clear();
avoidMoveUntilByLocWhite.clear();
return true;
}
double Search::getScoreUtility(double scoreMeanSum, double scoreMeanSqSum, double weightSum) const
{
double scoreMean = scoreMeanSum / weightSum;
double scoreMeanSq = scoreMeanSqSum / weightSum;
double scoreStdev = getScoreStdev(scoreMean, scoreMeanSq);
double staticScoreValue = ScoreValue::expectedWhiteScoreValue(scoreMean, scoreStdev, 0.0, 2.0, rootBoard);
double dynamicScoreValue = ScoreValue::expectedWhiteScoreValue(
scoreMean, scoreStdev, recentScoreCenter, searchParams.dynamicScoreCenterScale, rootBoard);
return staticScoreValue * searchParams.staticScoreUtilityFactor +
dynamicScoreValue * searchParams.dynamicScoreUtilityFactor;
}
double Search::getUtilityFromNN(const NNOutput &nnOutput) const
{
double resultUtility = getResultUtilityFromNN(nnOutput);
return resultUtility + getScoreUtility(nnOutput.whiteScoreMean, nnOutput.whiteScoreMeanSq, 1.0);
}
uint32_t
Search::chooseIndexWithTemperature(Rand &rand, const double *relativeProbs, int numRelativeProbs, double temperature)
{
assert(numRelativeProbs > 0);
assert(numRelativeProbs <= Board::MAX_ARR_SIZE); // We're just doing this on the stack
double processedRelProbs[Board::MAX_ARR_SIZE];
double maxValue = 0.0;
for (int i = 0; i < numRelativeProbs; i++)
{
if (relativeProbs[i] > maxValue)
maxValue = relativeProbs[i];
}
assert(maxValue > 0.0);
// Temperature so close to 0 that we just calculate the max directly
if (temperature <= 1.0e-4)
{
double bestProb = relativeProbs[0];
int bestIdx = 0;
for (int i = 1; i < numRelativeProbs; i++)
{
if (relativeProbs[i] > bestProb)
{
bestProb = relativeProbs[i];
bestIdx = i;
}
}
return bestIdx;
}
// Actual temperature
else
{
double logMaxValue = log(maxValue);
double sum = 0.0;
for (int i = 0; i < numRelativeProbs; i++)
{
// Numerically stable way to raise to power and normalize
processedRelProbs[i] = relativeProbs[i] <= 0.0 ? 0.0 : exp((log(relativeProbs[i]) - logMaxValue) / temperature);
sum += processedRelProbs[i];
}
assert(sum > 0.0);
uint32_t idxChosen = rand.nextUInt(processedRelProbs, numRelativeProbs);
return idxChosen;
}
}
double Search::interpolateEarly(double halflife, double earlyValue, double value) const
{
double rawHalflives = (rootHistory.initialTurnNumber + rootHistory.moveHistory.size()) / halflife;
double halflives = rawHalflives * 6.0 / sqrt(rootBoard.x_size * rootBoard.y_size);
return value + (earlyValue - value) * pow(0.5, halflives);
}
Move Search::runWholeSearchAndGetMove(Player movePla, Logger &logger)
{
return runWholeSearchAndGetMove(movePla, logger, false);
}
Move Search::runWholeSearchAndGetMove(Player movePla, Logger &logger, bool pondering)
{
runWholeSearch(movePla, logger, pondering);
return getChosenMoveLoc();
}
void Search::runWholeSearch(Player movePla, Logger &logger)
{
runWholeSearch(movePla, logger, false);
}
void Search::runWholeSearch(Player movePla, Logger &logger, bool pondering)
{
if (movePla != rootPla)
setPlayerAndClearHistory(movePla);
std::atomic<bool> shouldStopNow(false);
runWholeSearch(logger, shouldStopNow, pondering);
}
void Search::runWholeSearch(Logger &logger, std::atomic<bool> &shouldStopNow)
{
runWholeSearch(logger, shouldStopNow, false);
}
void Search::runWholeSearch(Logger &logger, std::atomic<bool> &shouldStopNow, bool pondering)
{
std::function<void()> *searchBegun = NULL;
runWholeSearch(logger, shouldStopNow, searchBegun, pondering, TimeControls(), 1.0);
}
double Search::numVisitsNeededToBeNonFutile(double maxVisitsMoveVisits)
{
double requiredVisits = searchParams.futileVisitsThreshold * maxVisitsMoveVisits;
// In the case where we're playing high temperature, also require that we can't get to more than a 1:100 odds of
// playing the move.
double chosenMoveTemperature = interpolateEarly(
searchParams.chosenMoveTemperatureHalflife,
searchParams.chosenMoveTemperatureEarly,
searchParams.chosenMoveTemperature);
if (chosenMoveTemperature < 1e-3)
return requiredVisits;
double requiredVisitsDueToTemp = maxVisitsMoveVisits * pow(0.01, chosenMoveTemperature);
return std::min(requiredVisits, requiredVisitsDueToTemp);
}
double Search::computeUpperBoundVisitsLeftDueToTime(int64_t rootVisits, double timeUsed, double plannedTimeLimit)
{
if (rootVisits <= 1)
return 1e30;
double timeThoughtSoFar = effectiveSearchTimeCarriedOver + timeUsed;
double timeLeftPlanned = plannedTimeLimit - timeUsed;
// Require at least a tenth of a second of search to begin to trust an estimate of visits/time.
if (timeThoughtSoFar < 0.1)
return 1e30;
double proportionOfTimeThoughtLeft = timeLeftPlanned / timeThoughtSoFar;
return ceil(proportionOfTimeThoughtLeft * rootVisits + searchParams.numThreads - 1);
}
double
Search::recomputeSearchTimeLimit(const TimeControls &tc, double timeUsed, double searchFactor, int64_t rootVisits)
{
double tcMin;
double tcRec;
double tcMax;
tc.getTime(rootBoard, rootHistory, searchParams.lagBuffer, tcMin, tcRec, tcMax);
tcRec *= searchParams.overallocateTimeFactor;
if (searchParams.midgameTimeFactor != 1.0)
{
double boardAreaScale = rootBoard.x_size * rootBoard.y_size / 361.0;
int64_t presumedTurnNumber = rootHistory.initialTurnNumber + rootHistory.moveHistory.size();
if (presumedTurnNumber < 0)
presumedTurnNumber = 0;
double midGameWeight;
if (presumedTurnNumber < searchParams.midgameTurnPeakTime * boardAreaScale)
midGameWeight = (double)presumedTurnNumber / (searchParams.midgameTurnPeakTime * boardAreaScale);
else
midGameWeight = exp(
-(presumedTurnNumber - searchParams.midgameTurnPeakTime * boardAreaScale) /
(searchParams.endgameTurnTimeDecay * boardAreaScale));
if (midGameWeight < 0)
midGameWeight = 0;
if (midGameWeight > 1)
midGameWeight = 1;
tcRec *= 1.0 + midGameWeight * (searchParams.midgameTimeFactor - 1.0);
}
if (searchParams.obviousMovesTimeFactor < 1.0)
{
double surprise = 0.0;
double searchEntropy = 0.0;
double policyEntropy = 0.0;
bool suc = getPolicySurpriseAndEntropy(surprise, searchEntropy, policyEntropy);
if (suc)
{
// If the original policy was confident and the surprise is low, then this is probably an "obvious" move.
double obviousnessByEntropy = exp(-policyEntropy / searchParams.obviousMovesPolicyEntropyTolerance);
double obviousnessBySurprise = exp(-surprise / searchParams.obviousMovesPolicySurpriseTolerance);
double obviousnessWeight = std::min(obviousnessByEntropy, obviousnessBySurprise);
tcRec *= 1.0 + obviousnessWeight * (searchParams.obviousMovesTimeFactor - 1.0);
}
}
if (tcRec > 1e-20)
{
double remainingTimeNeeded = tcRec - effectiveSearchTimeCarriedOver;
double remainingTimeNeededFactor = remainingTimeNeeded / tcRec;
// TODO this is a bit conservative relative to old behavior, it might be of slightly detrimental value, needs
// testing. Apply softplus so that we still do a tiny bit of search even in the presence of variable search time
// instead of instamoving, there are some benefits from root-level search due to broader root exploration and the
// cost is small, also we may be over counting the ponder benefit if search is faster on this node than on the
// previous turn.
tcRec = tcRec * std::min(1.0, log(1.0 + exp(remainingTimeNeededFactor * 6.0)) / 6.0);
}
// Make sure we're not wasting time
tcRec = tc.roundUpTimeLimitIfNeeded(searchParams.lagBuffer, timeUsed, tcRec);
if (tcRec > tcMax)
tcRec = tcMax;
// After rounding up time, check if with our planned rounded time, anything is futile to search
if (searchParams.futileVisitsThreshold > 0)
{
double upperBoundVisitsLeftDueToTime = computeUpperBoundVisitsLeftDueToTime(rootVisits, timeUsed, tcRec);
if (upperBoundVisitsLeftDueToTime < searchParams.futileVisitsThreshold * rootVisits)
{
std::vector<Loc> fromLocs;
std::vector<Loc> toLocs;
std::vector<double> playSelectionValues;
std::vector<double> visitCounts;
bool suc = getPlaySelectionValues(fromLocs,toLocs, playSelectionValues, &visitCounts, 1.0);
if (suc && playSelectionValues.size() > 0)
{
// This may fail to hold if we have no actual visits and play selections are being pulled from stuff like raw
// policy
if (playSelectionValues.size() == visitCounts.size())
{
int numMoves = (int)playSelectionValues.size();
int maxVisitsIdx = 0;
int bestMoveIdx = 0;
for (int i = 1; i < numMoves; i++)
{
if (playSelectionValues[i] > playSelectionValues[bestMoveIdx])
bestMoveIdx = i;
if (visitCounts[i] > visitCounts[maxVisitsIdx])
maxVisitsIdx = i;
}
if (maxVisitsIdx == bestMoveIdx)
{
double requiredVisits = numVisitsNeededToBeNonFutile(visitCounts[maxVisitsIdx]);
bool foundPossibleAlternativeMove = false;
for (int i = 0; i < numMoves; i++)
{
if (i == bestMoveIdx)
continue;
if (visitCounts[i] + upperBoundVisitsLeftDueToTime >= requiredVisits)
{
foundPossibleAlternativeMove = true;
break;
}
}
if (!foundPossibleAlternativeMove)
{
// We should stop search now - set our desired thinking to very slightly smaller than what we used.
tcRec = timeUsed * (1.0 - (1e-10));
}
}
}
}
}
}
// Make sure we're not wasting time, even after considering that we might want to stop early
tcRec = tc.roundUpTimeLimitIfNeeded(searchParams.lagBuffer, timeUsed, tcRec);
if (tcRec > tcMax)
tcRec = tcMax;
// Apply caps and search factor
// Since searchFactor is mainly used for friendliness (like, play faster after many passes)
// we allow it to violate the min time.
if (tcRec < tcMin)
tcRec = tcMin;
tcRec *= searchFactor;
if (tcRec > tcMax)
tcRec = tcMax;
return tcRec;
}
void Search::runWholeSearch(
Logger &logger,
std::atomic<bool> &shouldStopNow,
std::function<void()> *searchBegun,
bool pondering,
const TimeControls &tc,
double searchFactor)
{
ClockTimer timer;
atomic<int64_t> numPlayoutsShared(0);
if (!std::atomic_is_lock_free(&numPlayoutsShared))
logger.write("Warning: int64_t atomic numPlayoutsShared is not lock free");
if (!std::atomic_is_lock_free(&shouldStopNow))
logger.write("Warning: bool atomic shouldStopNow is not lock free");
// Do this first, just in case this causes us to clear things and have 0 effective time carried over
beginSearch(pondering);
if (searchBegun != NULL)
(*searchBegun)();
const int64_t numNonPlayoutVisits = getRootVisits();
// Compute caps on search
int64_t maxVisits = pondering ? searchParams.maxVisitsPondering : searchParams.maxVisits;
int64_t maxPlayouts = pondering ? searchParams.maxPlayoutsPondering : searchParams.maxPlayouts;
double_t maxTime = pondering ? searchParams.maxTimePondering : searchParams.maxTime;
{
if (searchFactor != 1.0)
{
double cap = (double)((int64_t)1L << 62);
maxVisits = (int64_t)ceil(std::min(cap, maxVisits * searchFactor));
maxPlayouts = (int64_t)ceil(std::min(cap, maxPlayouts * searchFactor));
maxTime = maxTime * searchFactor;
}
}
// Apply time controls. These two don't particularly need to be synchronized with each other so its fine to have two
// separate atomics.
std::atomic<double> tcMaxTime(1e30);
std::atomic<double> upperBoundVisitsLeftDueToTime(1e30);
const bool hasMaxTime = maxTime < 1.0e12;
const bool hasTc = !pondering && !tc.isEffectivelyUnlimitedTime();
if (!pondering && (hasTc || hasMaxTime))
{
int64_t rootVisits = numPlayoutsShared.load(std::memory_order_relaxed) + numNonPlayoutVisits;
double timeUsed = timer.getSeconds();
double tcLimit = 1e30;
if (hasTc)
{
tcLimit = recomputeSearchTimeLimit(tc, timeUsed, searchFactor, rootVisits);
tcMaxTime.store(tcLimit, std::memory_order_release);
}
double upperBoundVisits = computeUpperBoundVisitsLeftDueToTime(rootVisits, timeUsed, std::min(tcLimit, maxTime));
upperBoundVisitsLeftDueToTime.store(upperBoundVisits, std::memory_order_release);
}
auto searchLoop = [this,
&timer,
&numPlayoutsShared,
numNonPlayoutVisits,
&tcMaxTime,
&upperBoundVisitsLeftDueToTime,
&tc,
&hasMaxTime,
&hasTc,
&logger,
&shouldStopNow,
maxVisits,
maxPlayouts,
maxTime,
pondering,
searchFactor](int threadIdx)
{
SearchThread *stbuf = new SearchThread(threadIdx, *this, &logger);
int64_t numPlayouts = numPlayoutsShared.load(std::memory_order_relaxed);
try
{
double lastTimeUsedRecomputingTcLimit = 0.0;
while (true)
{
double timeUsed = 0.0;
if (hasTc || hasMaxTime)
timeUsed = timer.getSeconds();
double tcMaxTimeLimit = 0.0;
if (hasTc)
tcMaxTimeLimit = tcMaxTime.load(std::memory_order_acquire);
bool shouldStop = (numPlayouts >= maxPlayouts) || (numPlayouts + numNonPlayoutVisits >= maxVisits);
if (hasMaxTime && numPlayouts >= 2 && timeUsed >= maxTime)
shouldStop = true;
if (hasTc && numPlayouts >= 2 && timeUsed >= tcMaxTimeLimit)
shouldStop = true;
if (shouldStop || shouldStopNow.load(std::memory_order_relaxed))
{
shouldStopNow.store(true, std::memory_order_relaxed);
break;
}
// Thread 0 alone is responsible for recomputing time limits every once in a while
// Cap of 10 times per second.
if (!pondering && (hasTc || hasMaxTime) && threadIdx == 0 && timeUsed >= lastTimeUsedRecomputingTcLimit + 0.1)
{
int64_t rootVisits = numPlayouts + numNonPlayoutVisits;
double tcLimit = 1e30;
if (hasTc)
{
tcLimit = recomputeSearchTimeLimit(tc, timeUsed, searchFactor, rootVisits);
tcMaxTime.store(tcLimit, std::memory_order_release);
}
double upperBoundVisits =
computeUpperBoundVisitsLeftDueToTime(rootVisits, timeUsed, std::min(tcLimit, maxTime));
upperBoundVisitsLeftDueToTime.store(upperBoundVisits, std::memory_order_release);
}
double upperBoundVisitsLeft = 1e30;
if (hasTc)
upperBoundVisitsLeft = upperBoundVisitsLeftDueToTime.load(std::memory_order_acquire);
upperBoundVisitsLeft = std::min(upperBoundVisitsLeft, (double)maxPlayouts - numPlayouts);
upperBoundVisitsLeft = std::min(upperBoundVisitsLeft, (double)maxVisits - numPlayouts - numNonPlayoutVisits);
runSinglePlayout(*stbuf, upperBoundVisitsLeft);
numPlayouts = numPlayoutsShared.fetch_add((int64_t)1, std::memory_order_relaxed);
numPlayouts += 1;
}
}
catch (const exception &e)
{
logger.write(string("ERROR: Search thread failed: ") + e.what());
delete stbuf;
throw;
}
catch (const string &e)
{
logger.write("ERROR: Search thread failed: " + e);
delete stbuf;
throw;
}
catch (...)
{
logger.write("ERROR: Search thread failed with unexpected throw");
delete stbuf;
throw;
}
delete stbuf;
};
double actualSearchStartTime = timer.getSeconds();
if (searchParams.numThreads <= 1)
searchLoop(0);
else
{
std::thread *threads = new std::thread[searchParams.numThreads - 1];
for (int i = 0; i < searchParams.numThreads - 1; i++)
threads[i] = std::thread(searchLoop, i + 1);
searchLoop(0);
for (int i = 0; i < searchParams.numThreads - 1; i++)
threads[i].join();
delete[] threads;
}
// Relaxed load is fine since numPlayoutsShared should be synchronized already due to the joins
lastSearchNumPlayouts = numPlayoutsShared.load(std::memory_order_relaxed);
effectiveSearchTimeCarriedOver += timer.getSeconds() - actualSearchStartTime;
}
// If we're being asked to search from a position where the game is over, this is fine. Just keep going, the
// boardhistory should reasonably tolerate just continuing. We do NOT want to clear history because we could
// inadvertently make a move that an external ruleset COULD think violated superko.
void Search::beginSearch(bool pondering)
{
if (rootBoard.x_size > nnXLen || rootBoard.y_size > nnYLen)
throw StringError(
"Search got from NNEval nnXLen = " + Global::intToString(nnXLen) + " nnYLen = " + Global::intToString(nnYLen) +
" but was asked to search board with larger x or y size");
rootBoard.checkConsistency();
numSearchesBegun++;
searchNodeAge++;
if (searchNodeAge == 0) // Just in case, as we roll over
clearSearch();
if (!pondering)
plaThatSearchIsFor = rootPla;
// If we begin the game with a ponder, then assume that "we" are the opposing side until we see otherwise.
if (plaThatSearchIsFor == C_EMPTY)
plaThatSearchIsFor = getOpp(rootPla);
// In the case we are doing playoutDoublingAdvantage without a specific player (so, doing the root player)
// and the player that the search is for changes, we need to clear the tree since we need new evals for the new way
// around
if (
plaThatSearchIsForLastSearch != plaThatSearchIsFor && searchParams.playoutDoublingAdvantage != 0 &&
searchParams.playoutDoublingAdvantagePla == C_EMPTY)
clearSearch();
plaThatSearchIsForLastSearch = plaThatSearchIsFor;
// cout << "BEGINSEARCH " << PlayerIO::playerToString(rootPla) << " " << PlayerIO::playerToString(plaThatSearchIsFor)
// << endl;
computeRootValues();
maybeRecomputeNormToTApproxTable();
// Prepare value bias table if we need it
if (searchParams.subtreeValueBiasFactor != 0 && subtreeValueBiasTable == NULL)
subtreeValueBiasTable = new SubtreeValueBiasTable(searchParams.subtreeValueBiasTableNumShards);
SearchThread dummyThread(-1, *this, NULL);
if (rootNode == NULL)
{
Loc fromLoc = rootHistory.moveHistory.size() <= 0
? Board::NULL_LOC
: rootHistory.moveHistory[rootHistory.moveHistory.size() - 1].fromLoc;
Loc toloc = rootHistory.moveHistory.size() <= 0 ? Board::NULL_LOC
: rootHistory.moveHistory[rootHistory.moveHistory.size() - 1].toLoc;
rootNode = new SearchNode(*this, getOpp(rootPla), dummyThread.rand, fromLoc, toloc, NULL);
}
else
{
// If the root node has any existing children, then prune things down if there are moves that should not be allowed
// at the root.
SearchNode &node = *rootNode;
int numChildren = node.numChildren;
if (node.children != NULL && numChildren > 0)
{
assert(node.nnOutput != NULL);
// Perform the filtering
int numGoodChildren = 0;
for (int i = 0; i < numChildren; i++)
{
SearchNode *child = node.children[i];
node.children[i] = NULL;
node.children[numGoodChildren++] = child;
}
bool anyFiltered = numChildren != numGoodChildren;
node.numChildren = numGoodChildren;
numChildren = numGoodChildren;
if (anyFiltered)
{
// Fix up the number of visits of the root node after doing this filtering
int64_t newNumVisits = 0;
for (int i = 0; i < numChildren; i++)
{
const SearchNode *child = node.children[i];
while (child->statsLock.test_and_set(std::memory_order_acquire))
;
int64_t childVisits = child->stats.visits;
child->statsLock.clear(std::memory_order_release);
newNumVisits += childVisits;
}
// For the node's own visit itself
newNumVisits += 1;
// Set the visits in place
while (node.statsLock.test_and_set(std::memory_order_acquire))
;
node.stats.visits = newNumVisits;
node.statsLock.clear(std::memory_order_release);
// Update all other stats
recomputeNodeStats(node, dummyThread, 0, 0, true);
}
}
// Recursively update all stats in the tree if we have dynamic score values
// And also to clear out lastResponseBiasDeltaSum and lastResponseBiasWeight
if (searchParams.dynamicScoreUtilityFactor != 0 || searchParams.subtreeValueBiasFactor != 0)
{
recursivelyRecomputeStats(node, dummyThread, true);
}
}
// Clear unused stuff in value bias table since we may have pruned rootNode stuff
if (searchParams.subtreeValueBiasFactor != 0 && subtreeValueBiasTable != NULL)
subtreeValueBiasTable->clearUnusedSynchronous();
}
// Recursively walk over part of the tree that we are about to delete and remove its contribution to the value bias in
// the table Assumes we aren't doing any multithreadingy stuff, so doesn't bother with locks.
void Search::recursivelyRemoveSubtreeValueBiasBeforeDeleteSynchronous(SearchNode *node)
{
if (node == NULL || searchParams.subtreeValueBiasFactor == 0)
return;
int numChildren = node->numChildren;
for (int i = 0; i < numChildren; i++)
{
recursivelyRemoveSubtreeValueBiasBeforeDeleteSynchronous(node->children[i]);
}
if (node->subtreeValueBiasTableEntry != nullptr)
{
node->subtreeValueBiasTableEntry->deltaUtilitySum -=
node->lastSubtreeValueBiasDeltaSum * searchParams.subtreeValueBiasFreeProp;
node->subtreeValueBiasTableEntry->weightSum -=
node->lastSubtreeValueBiasWeight * searchParams.subtreeValueBiasFreeProp;
}
}
void Search::recursivelyRecomputeStats(SearchNode &node, SearchThread &thread, bool isRoot)
{
// First, recompute all children.
std::vector<SearchNode *> children;
children.reserve(rootBoard.x_size * rootBoard.y_size + 1);
int numChildren;
bool noNNOutput;
{
std::mutex &mutex = mutexPool->getMutex(node.lockIdx);
lock_guard<std::mutex> lock(mutex);
numChildren = node.numChildren;
for (int i = 0; i < numChildren; i++)
children.push_back(node.children[i]);
noNNOutput = node.nnOutput == nullptr;
}
for (int i = 0; i < numChildren; i++)
{
recursivelyRecomputeStats(*(children[i]), thread, false);
}
// If this node has no nnOutput, then it must also have no children, because it's
// a terminal node
assert(!(noNNOutput && numChildren > 0));
(void)noNNOutput; // avoid warning when we have no asserts
// If the node has no children, then just update its utility directly
if (numChildren <= 0)
{
while (node.statsLock.test_and_set(std::memory_order_acquire))
;
double resultUtilitySum = node.stats.getResultUtilitySum(searchParams);
double scoreMeanSum = node.stats.scoreMeanSum;
double scoreMeanSqSum = node.stats.scoreMeanSqSum;
double weightSum = node.stats.weightSum;
int64_t numVisits = node.stats.visits;
node.statsLock.clear(std::memory_order_release);
// It's possible that this node has 0 weight in the case where it's the root node
// and has 0 visits because we began a search and then stopped it before any playouts happened.
// In that case, there's not much to recompute.
if (weightSum <= 0.0)
{
assert(numVisits == 0);
assert(isRoot);
}
else
{
double scoreUtility = getScoreUtility(scoreMeanSum, scoreMeanSqSum, weightSum);
double newUtility = resultUtilitySum / weightSum + scoreUtility;
double newUtilitySum = newUtility * weightSum;
double newUtilitySqSum = newUtility * newUtility * weightSum;
while (node.statsLock.test_and_set(std::memory_order_acquire))
;
node.stats.utilitySum = newUtilitySum;
node.stats.utilitySqSum = newUtilitySqSum;
node.statsLock.clear(std::memory_order_release);
}
}
else
{
// Otherwise recompute it using the usual method
recomputeNodeStats(node, thread, 0, 0, isRoot);
}
}
void Search::computeRootNNEvaluation(NNResultBuf &nnResultBuf, bool includeOwnerMap)
{
Board board = rootBoard;
const BoardHistory &hist = rootHistory;
Player pla = rootPla;
bool skipCache = false;
// bool isRoot = true;
MiscNNInputParams nnInputParams;
nnInputParams.drawEquivalentWinsForWhite = searchParams.drawEquivalentWinsForWhite;
nnInputParams.nnPolicyTemperature = searchParams.nnPolicyTemperature;
if (searchParams.playoutDoublingAdvantage != 0)
{
Player playoutDoublingAdvantagePla = getPlayoutDoublingAdvantagePla();
}
nnEvaluator->evaluate(board, hist, pla, nnInputParams, nnResultBuf, skipCache, includeOwnerMap);
}
void Search::computeRootValues()
{
// rootSafeArea is strictly pass-alive groups and strictly safe territory.
bool nonPassAliveStones = false;
bool safeBigTerritories = false;
bool unsafeBigTerritories = false;
// Figure out how to set recentScoreCenter
{
bool foundExpectedScoreFromTree = false;
double expectedScore = 0.0;
if (rootNode != NULL)
{
const SearchNode &node = *rootNode;
while (node.statsLock.test_and_set(std::memory_order_acquire))
;
double scoreMeanSum = node.stats.scoreMeanSum;
double weightSum = node.stats.weightSum;
int64_t numVisits = node.stats.visits;
node.statsLock.clear(std::memory_order_release);
if (numVisits > 0 && weightSum > 0)
{
foundExpectedScoreFromTree = true;
expectedScore = scoreMeanSum / weightSum;
}
}
// Grab a neural net evaluation for the current position and use that as the center
if (!foundExpectedScoreFromTree)
{
NNResultBuf nnResultBuf;
bool includeOwnerMap = true;
computeRootNNEvaluation(nnResultBuf, includeOwnerMap);
expectedScore = nnResultBuf.result->whiteScoreMean;
}
recentScoreCenter = expectedScore * (1.0 - searchParams.dynamicScoreCenterZeroWeight);
double cap = sqrt(rootBoard.x_size * rootBoard.y_size) * searchParams.dynamicScoreCenterScale;
if (recentScoreCenter > expectedScore + cap)
recentScoreCenter = expectedScore + cap;
if (recentScoreCenter < expectedScore - cap)
recentScoreCenter = expectedScore - cap;
}
}
int64_t Search::getRootVisits() const
{
if (rootNode == NULL)
return 0;
while (rootNode->statsLock.test_and_set(std::memory_order_acquire))
;
int64_t n = rootNode->stats.visits;
rootNode->statsLock.clear(std::memory_order_release);
return n;
}
void Search::computeDirichletAlphaDistribution(int policySize, const float *policyProbs, double *alphaDistr)
{
int legalCount = 0;
for (int i = 0; i < policySize; i++)
{
if (policyProbs[i] >= 0)
legalCount += 1;
}
if (legalCount <= 0)
throw StringError("computeDirichletAlphaDistribution: No move with nonnegative policy value - can't even pass?");
// We're going to generate a gamma draw on each move with alphas that sum up to
// searchParams.rootDirichletNoiseTotalConcentration. Half of the alpha weight are uniform. The other half are shaped
// based on the log of the existing policy.
double logPolicySum = 0.0;
for (int i = 0; i < policySize; i++)
{
if (policyProbs[i] >= 0)
{
alphaDistr[i] = log(std::min(0.01, (double)policyProbs[i]) + 1e-20);
logPolicySum += alphaDistr[i];
}
}
double logPolicyMean = logPolicySum / legalCount;
double alphaPropSum = 0.0;
for (int i = 0; i < policySize; i++)
{
if (policyProbs[i] >= 0)
{
alphaDistr[i] = std::max(0.0, alphaDistr[i] - logPolicyMean);
alphaPropSum += alphaDistr[i];
}
}
double uniformProb = 1.0 / legalCount;
if (alphaPropSum <= 0.0)
{
for (int i = 0; i < policySize; i++)
{
if (policyProbs[i] >= 0)
alphaDistr[i] = uniformProb;
}
}
else
{
for (int i = 0; i < policySize; i++)
{
if (policyProbs[i] >= 0)
alphaDistr[i] = 0.5 * (alphaDistr[i] / alphaPropSum + uniformProb);
}
}
}
void Search::addDirichletNoise(const SearchParams &searchParams, Rand &rand, int policySize, float *policyProbs)
{
double r[NNPos::MAX_NN_POLICY_SIZE];
Search::computeDirichletAlphaDistribution(policySize, policyProbs, r);
// r now contains the proportions with which we would like to split the alpha
// The total of the alphas is searchParams.rootDirichletNoiseTotalConcentration
// Generate gamma draw on each move
double rSum = 0.0;
for (int i = 0; i < policySize; i++)
{
if (policyProbs[i] >= 0)
{
r[i] = rand.nextGamma(r[i] * searchParams.rootDirichletNoiseTotalConcentration);
rSum += r[i];
}
else
r[i] = 0.0;
}
// Normalized gamma draws -> dirichlet noise
for (int i = 0; i < policySize; i++)
r[i] /= rSum;
// At this point, r[i] contains a dirichlet distribution draw, so add it into the nnOutput.
for (int i = 0; i < policySize; i++)
{
if (policyProbs[i] >= 0)
{
double weight = searchParams.rootDirichletNoiseWeight;
policyProbs[i] = (float)(r[i] * weight + policyProbs[i] * (1.0 - weight));
}
}
}
// Assumes node is locked
void Search::maybeAddPolicyNoiseAndTempAlreadyLocked(SearchThread &thread, SearchNode &node, bool isRoot) const
{
if (!isRoot)
return;
if (
!searchParams.rootNoiseEnabled && searchParams.rootPolicyTemperature == 1.0 &&
searchParams.rootPolicyTemperatureEarly == 1.0 && rootHintLoc.fromLoc != Board::NULL_LOC &&rootHintLoc.toLoc != Board::NULL_LOC)
return;
if (node.nnOutput->noisedPolicyProbs != NULL)
return;
// Copy nnOutput as we're about to modify its policy to add noise or temperature
{
shared_ptr<NNOutput> newNNOutput = std::make_shared<NNOutput>(*(node.nnOutput));
// Replace the old pointer
node.nnOutput = newNNOutput;
}
float *noisedPolicyProbs = new float[NNPos::MAX_NN_POLICY_SIZE];
node.nnOutput->noisedPolicyProbs = noisedPolicyProbs;
std::copy(node.nnOutput->policyProbs, node.nnOutput->policyProbs + NNPos::MAX_NN_POLICY_SIZE, noisedPolicyProbs);
if (searchParams.rootPolicyTemperature != 1.0 || searchParams.rootPolicyTemperatureEarly != 1.0)
{
double rootPolicyTemperature = interpolateEarly(
searchParams.chosenMoveTemperatureHalflife,
searchParams.rootPolicyTemperatureEarly,
searchParams.rootPolicyTemperature);
double maxValue = 0.0;
for (int i = 0; i < policySize; i++)
{
double prob = noisedPolicyProbs[i];
if (prob > maxValue)
maxValue = prob;
}
assert(maxValue > 0.0);
double logMaxValue = log(maxValue);
double invTemp = 1.0 / rootPolicyTemperature;
double sum = 0.0;
for (int i = 0; i < policySize; i++)
{
if (noisedPolicyProbs[i] > 0)
{
// Numerically stable way to raise to power and normalize
float p = (float)exp((log((double)noisedPolicyProbs[i]) - logMaxValue) * invTemp);
noisedPolicyProbs[i] = p;
sum += p;
}
}
assert(sum > 0.0);
for (int i = 0; i < policySize; i++)
{
if (noisedPolicyProbs[i] >= 0)
{
noisedPolicyProbs[i] = (float)(noisedPolicyProbs[i] / sum);
}
}
}
if (searchParams.rootNoiseEnabled)
{
addDirichletNoise(searchParams, thread.rand, policySize, noisedPolicyProbs);
}
}
void Search::getValueChildWeights(
int numChildren,
// Unlike everywhere else where values are from white's perspective, values here are from one's own perspective
const std::vector<double> &childSelfValuesBuf,
const std::vector<int64_t> &childVisitsBuf,
std::vector<double> &resultBuf) const
{
resultBuf.clear();
if (numChildren <= 0)
return;
if (numChildren == 1)
{
resultBuf.push_back(1.0);
return;
}
assert(numChildren <= NNPos::MAX_NN_POLICY_SIZE);
double stdevs[NNPos::MAX_NN_POLICY_SIZE];
for (int i = 0; i < numChildren; i++)
{
int64_t numVisits = childVisitsBuf[i];
assert(numVisits >= 0);
if (numVisits == 0)
{
stdevs[i] = 0.0; // Unused
continue;
}
double precision = 1.5 * sqrt((double)numVisits);
// Ensure some minimum variance for stability regardless of how we change the above formula
static const double minVariance = 0.00000001;
stdevs[i] = sqrt(minVariance + 1.0 / precision);
}
double simpleValueSum = 0.0;
int64_t numChildVisits = 0;
for (int i = 0; i < numChildren; i++)
{
simpleValueSum += childSelfValuesBuf[i] * childVisitsBuf[i];
numChildVisits += childVisitsBuf[i];
}
double simpleValue = simpleValueSum / numChildVisits;
double weight[NNPos::MAX_NN_POLICY_SIZE];
for (int i = 0; i < numChildren; i++)
{
if (childVisitsBuf[i] == 0)
{
weight[i] = 0.0;
continue;
}
else
{
double z = (childSelfValuesBuf[i] - simpleValue) / stdevs[i];
// Also just for numeric sanity, make sure everything has some tiny minimum value.
weight[i] = valueWeightDistribution->getCdf(z) + 0.0001;
}
}
// Post-process and normalize, to make sure we exactly have a probability distribution and sum exactly to 1.
double totalWeight = 0.0;
for (int i = 0; i < numChildren; i++)
{
double p = weight[i];
totalWeight += p;
resultBuf.push_back(p);
}
assert(totalWeight >= 0.0);
if (totalWeight > 0)
{
for (int i = 0; i < numChildren; i++)
{
resultBuf[i] /= totalWeight;
}
}
}
static double cpuctExploration(int64_t totalChildVisits, const SearchParams &searchParams)
{
return searchParams.cpuctExploration +
searchParams.cpuctExplorationLog *
log((totalChildVisits + searchParams.cpuctExplorationBase) / searchParams.cpuctExplorationBase);
}
double Search::getExploreSelectionValue(
double nnPolicyProb,
int64_t totalChildVisits,
int64_t childVisits,
double childUtility,
Player pla) const
{
if (nnPolicyProb < 0)
return POLICY_ILLEGAL_SELECTION_VALUE;
double exploreComponent =
cpuctExploration(totalChildVisits, searchParams) * nnPolicyProb *
sqrt((double)totalChildVisits + 0.01) // TODO this is weird when totalChildVisits == 0, first exploration
/ (1.0 + childVisits);
// At the last moment, adjust value to be from the player's perspective, so that players prefer values in their favor
// rather than in white's favor
double valueComponent = pla == P_WHITE ? childUtility : -childUtility;
return exploreComponent + valueComponent;
}
// Return the childVisits that would make Search::getExploreSelectionValue return the given explore selection value.
// Or return 0, if it would be less than 0.
double Search::getExploreSelectionValueInverse(
double exploreSelectionValue,
double nnPolicyProb,
int64_t totalChildVisits,
double childUtility,
Player pla) const
{
if (nnPolicyProb < 0)
return 0;
double valueComponent = pla == P_WHITE ? childUtility : -childUtility;
double exploreComponent = exploreSelectionValue - valueComponent;
double exploreComponentScaling =
cpuctExploration(totalChildVisits, searchParams) * nnPolicyProb *
sqrt((double)totalChildVisits + 0.01); // TODO this is weird when totalChildVisits == 0, first exploration
// Guard against float weirdness
if (exploreComponent <= 0)
return 1e100;
double childVisits = exploreComponentScaling / exploreComponent - 1;
if (childVisits < 0)
childVisits = 0;
return childVisits;
}
int Search::getDouplePos(Loc fromLoc, Loc toLoc) const
{
return NNPos::locToDoublePos(fromLoc, toLoc, rootBoard.x_size, nnXLen, nnYLen);
}
static void maybeApplyWideRootNoise(
double &childUtility,
float &nnPolicyProb,
const SearchParams &searchParams,
SearchThread *thread,
const SearchNode &parent)
{
// For very large wideRootNoise, go ahead and also smooth out the policy
nnPolicyProb = (float)pow(nnPolicyProb, 1.0 / (4.0 * searchParams.wideRootNoise + 1.0));
if (thread->rand.nextBool(0.5))
{
double bonus = searchParams.wideRootNoise * abs(thread->rand.nextGaussian());
if (parent.nextPla == P_WHITE)
childUtility += bonus;
else
childUtility -= bonus;
}
}
static double square(double x)
{
return x * x;
}
// Parent must be locked
double Search::getExploreSelectionValue(
const SearchNode &parent,
const float *parentPolicyProbs,
const SearchNode *child,
int64_t totalChildVisits,
double fpuValue,
double parentUtility,
bool isDuringSearch,
int64_t maxChildVisits,
SearchThread *thread) const
{
(void)parentUtility;
Loc fromLoc = child->prevFromLoc;
Loc toLoc = child->prevToLoc;
int movePos = getDouplePos(fromLoc, toLoc);
float nnPolicyProb = parentPolicyProbs[movePos];
while (child->statsLock.test_and_set(std::memory_order_acquire))
;
int64_t childVisits = child->stats.visits;
double utilitySum = child->stats.utilitySum;
double scoreMeanSum = child->stats.scoreMeanSum;
double scoreMeanSqSum = child->stats.scoreMeanSqSum;
double weightSum = child->stats.weightSum;
int32_t childVirtualLosses = child->virtualLosses;
child->statsLock.clear(std::memory_order_release);
// It's possible that childVisits is actually 0 here with multithreading because we're visiting this node while a
// child has been expanded but its thread not yet finished its first visit
double childUtility;
if (childVisits <= 0)
childUtility = fpuValue;
else
{
assert(weightSum > 0.0);
childUtility = utilitySum / weightSum;
}
// When multithreading, totalChildVisits could be out of sync with childVisits, so if they provably are, then fix that
// up
if (totalChildVisits < childVisits)
totalChildVisits = childVisits;
// Virtual losses to direct threads down different paths
if (childVirtualLosses > 0)
{
// totalChildVisits += childVirtualLosses; //Should get better thread dispersal without this
childVisits += childVirtualLosses;
double utilityRadius = searchParams.winLossUtilityFactor + searchParams.staticScoreUtilityFactor +
searchParams.dynamicScoreUtilityFactor;
double virtualLossUtility = (parent.nextPla == P_WHITE ? -utilityRadius : utilityRadius);
double virtualLossVisitFrac = (double)childVirtualLosses / childVisits;
childUtility = childUtility + (virtualLossUtility - childUtility) * virtualLossVisitFrac;
}
if (isDuringSearch && (&parent == rootNode))
{
// Futile visits pruning - skip this move if the amount of time we have left to search is too small
if (searchParams.futileVisitsThreshold > 0)
{
double requiredVisits = searchParams.futileVisitsThreshold * maxChildVisits;
if (childVisits + thread->upperBoundVisitsLeft < requiredVisits)
return FUTILE_VISITS_PRUNE_VALUE;
}
// Hack to get the root to funnel more visits down child branches
if (searchParams.rootDesiredPerChildVisitsCoeff > 0.0)
{
if (childVisits < sqrt(nnPolicyProb * totalChildVisits * searchParams.rootDesiredPerChildVisitsCoeff))
{
return 1e20;
}
}
if (searchParams.wideRootNoise > 0.0)
{
maybeApplyWideRootNoise(childUtility, nnPolicyProb, searchParams, thread, parent);
}
}
return getExploreSelectionValue(nnPolicyProb, totalChildVisits, childVisits, childUtility, parent.nextPla);
}
double Search::getNewExploreSelectionValue(
const SearchNode &parent,
float nnPolicyProb,
int64_t totalChildVisits,
double fpuValue,
int64_t maxChildVisits,
SearchThread *thread) const
{
int64_t childVisits = 0;
double childUtility = fpuValue;
if (&parent == rootNode)
{
// Futile visits pruning - skip this move if the amount of time we have left to search is too small
if (searchParams.futileVisitsThreshold > 0)
{
double requiredVisits = searchParams.futileVisitsThreshold * maxChildVisits;
if (thread->upperBoundVisitsLeft < requiredVisits)
return FUTILE_VISITS_PRUNE_VALUE;
}
if (searchParams.wideRootNoise > 0.0)
{
maybeApplyWideRootNoise(childUtility, nnPolicyProb, searchParams, thread, parent);
}
}
return getExploreSelectionValue(nnPolicyProb, totalChildVisits, childVisits, childUtility, parent.nextPla);
}
// Parent must be locked
int64_t Search::getReducedPlaySelectionVisits(
const SearchNode &parent,
const float *parentPolicyProbs,
const SearchNode *child,
int64_t totalChildVisits,
double bestChildExploreSelectionValue) const
{
assert(&parent == rootNode);
Loc fromLoc = child->prevFromLoc;
Loc toLoc = child->prevToLoc;
int movePos = getDouplePos(fromLoc, toLoc);
float nnPolicyProb = parentPolicyProbs[movePos];
while (child->statsLock.test_and_set(std::memory_order_acquire))
;
int64_t childVisits = child->stats.visits;
double utilitySum = child->stats.utilitySum;
double scoreMeanSum = child->stats.scoreMeanSum;
double scoreMeanSqSum = child->stats.scoreMeanSqSum;
double weightSum = child->stats.weightSum;
child->statsLock.clear(std::memory_order_release);
// Child visits may be 0 if this function is called in a multithreaded context, such as during live analysis
if (childVisits <= 0)
return 0;
assert(weightSum > 0.0);
double childUtility = utilitySum / weightSum;
double childVisitsWeRetrospectivelyWanted = getExploreSelectionValueInverse(
bestChildExploreSelectionValue, nnPolicyProb, totalChildVisits, childUtility, parent.nextPla);
if (childVisits > childVisitsWeRetrospectivelyWanted)
childVisits = (int64_t)ceil(childVisitsWeRetrospectivelyWanted);
return childVisits;
}
double Search::getFpuValueForChildrenAssumeVisited(
const SearchNode &node,
Player pla,
bool isRoot,
double policyProbMassVisited,
double &parentUtility) const
{
if (searchParams.fpuParentWeight < 1.0)
{
while (node.statsLock.test_and_set(std::memory_order_acquire))
;
double utilitySum = node.stats.utilitySum;
double weightSum = node.stats.weightSum;
node.statsLock.clear(std::memory_order_release);
assert(weightSum > 0.0);
parentUtility = utilitySum / weightSum;
if (searchParams.fpuParentWeight > 0.0)
{
parentUtility = searchParams.fpuParentWeight * getUtilityFromNN(*node.nnOutput) +
(1.0 - searchParams.fpuParentWeight) * parentUtility;
}
}
else
{
parentUtility = getUtilityFromNN(*node.nnOutput);
}
double fpuValue;
{
double fpuReductionMax = isRoot ? searchParams.rootFpuReductionMax : searchParams.fpuReductionMax;
double fpuLossProp = isRoot ? searchParams.rootFpuLossProp : searchParams.fpuLossProp;
double utilityRadius = searchParams.winLossUtilityFactor + searchParams.staticScoreUtilityFactor +
searchParams.dynamicScoreUtilityFactor;
double reduction = fpuReductionMax * sqrt(policyProbMassVisited);
fpuValue = pla == P_WHITE ? parentUtility - reduction : parentUtility + reduction;
double lossValue = pla == P_WHITE ? -utilityRadius : utilityRadius;
fpuValue = fpuValue + (lossValue - fpuValue) * fpuLossProp;
}
return fpuValue;
}
// Assumes node is locked
void Search::selectBestChildToDescend(
SearchThread &thread,
const SearchNode &node,
int &bestChildIdx,
Loc &bestChildFromLoc,
Loc &bestChildToLoc,
bool posesWithChildBuf[NNPos::MAX_NN_POLICY_SIZE],
bool isRoot) const
{
assert(thread.pla == node.nextPla);
double maxSelectionValue = POLICY_ILLEGAL_SELECTION_VALUE;
bestChildIdx = -1;
bestChildFromLoc = Board::NULL_LOC;
bestChildToLoc = Board::NULL_LOC;
int numChildren = node.numChildren;
double policyProbMassVisited = 0.0;
int64_t maxChildVisits = 0;
int64_t totalChildVisits = 0;
float *policyProbs = node.nnOutput->getPolicyProbsMaybeNoised();
for (int i = 0; i < numChildren; i++)
{
const SearchNode *child = node.children[i];
Loc fromLoc = child->prevFromLoc;
Loc toLoc = child->prevToLoc;
int movePos = getDouplePos(fromLoc, toLoc);
float nnPolicyProb = policyProbs[movePos];
policyProbMassVisited += nnPolicyProb;
while (child->statsLock.test_and_set(std::memory_order_acquire))
;
int64_t childVisits = child->stats.visits;
child->statsLock.clear(std::memory_order_release);
totalChildVisits += childVisits;
if (childVisits > maxChildVisits)
maxChildVisits = childVisits;
}
// Probability mass should not sum to more than 1, giving a generous allowance
// for floating point error.
assert(policyProbMassVisited <= 1.0001);
// First play urgency
double parentUtility;
double fpuValue = getFpuValueForChildrenAssumeVisited(node, thread.pla, isRoot, policyProbMassVisited, parentUtility);
std::fill(posesWithChildBuf, posesWithChildBuf + NNPos::MAX_NN_POLICY_SIZE, false);
// Try all existing children
for (int i = 0; i < numChildren; i++)
{
const SearchNode *child = node.children[i];
Loc fromLoc = child->prevFromLoc;
Loc toLoc = child->prevToLoc;
bool isDuringSearch = true;
double selectionValue = getExploreSelectionValue(
node, policyProbs, child, totalChildVisits, fpuValue, parentUtility, isDuringSearch, maxChildVisits, &thread);
if (selectionValue > maxSelectionValue)
{
maxSelectionValue = selectionValue;
bestChildIdx = i;
bestChildFromLoc = fromLoc;
bestChildToLoc = toLoc;
}
posesWithChildBuf[getDouplePos(fromLoc, toLoc)] = true;
}
const std::vector<int> &avoidMoveUntilByLoc =
thread.pla == P_BLACK ? avoidMoveUntilByLocBlack : avoidMoveUntilByLocWhite;
// Try the new child with the best policy value
Loc bestNewFromLoc = Board::NULL_LOC;
Loc bestNewToLoc = Board::NULL_LOC;
float bestNewNNPolicyProb = -1.0f;
for (int movePos = 0; movePos < policySize; movePos++)
{
if (posesWithChildBuf[movePos])
continue;
Loc fromLoc = NNPos::posToFromLoc(movePos, thread.board.x_size, thread.board.y_size, nnXLen, nnYLen);
Loc toLoc = NNPos::posToToLoc(movePos, thread.board.x_size, thread.board.y_size, nnXLen, nnYLen);
if (fromLoc == Board::NULL_LOC || toLoc == Board::NULL_LOC)
continue;
float nnPolicyProb = policyProbs[movePos];
if (nnPolicyProb > bestNewNNPolicyProb)
{
bestNewNNPolicyProb = nnPolicyProb;
bestNewFromLoc = fromLoc;
bestNewToLoc = toLoc;
}
}
if (bestNewFromLoc != Board::NULL_LOC)
{
double selectionValue =
getNewExploreSelectionValue(node, bestNewNNPolicyProb, totalChildVisits, fpuValue, maxChildVisits, &thread);
if (selectionValue > maxSelectionValue)
{
maxSelectionValue = selectionValue;
bestChildIdx = numChildren;
bestChildFromLoc = bestNewFromLoc;
bestChildToLoc = bestNewToLoc;
}
}
}
void Search::updateStatsAfterPlayout(
SearchNode &node,
SearchThread &thread,
int32_t virtualLossesToSubtract,
bool isRoot)
{
recomputeNodeStats(node, thread, 1, virtualLossesToSubtract, isRoot);
}
// Recompute all the stats of this node based on its children, except its visits and virtual losses, which are not
// child-dependent and are updated in the manner specified. Assumes this node has an nnOutput
void Search::recomputeNodeStats(
SearchNode &node,
SearchThread &thread,
int numVisitsToAdd,
int32_t virtualLossesToSubtract,
bool isRoot)
{
// Find all children and compute weighting of the children based on their values
std::vector<double> &weightFactors = thread.weightFactorBuf;
std::vector<double> &winValues = thread.winValuesBuf;
std::vector<double> &noResultValues = thread.noResultValuesBuf;
std::vector<double> &scoreMeans = thread.scoreMeansBuf;
std::vector<double> &scoreMeanSqs = thread.scoreMeanSqsBuf;
std::vector<double> &leads = thread.leadsBuf;
std::vector<double> &utilitySums = thread.utilityBuf;
std::vector<double> &utilitySqSums = thread.utilitySqBuf;
std::vector<double> &selfUtilities = thread.selfUtilityBuf;
std::vector<double> &weightSums = thread.weightBuf;
std::vector<double> &weightSqSums = thread.weightSqBuf;
std::vector<int64_t> &visits = thread.visitsBuf;
int64_t totalChildVisits = 0;
int64_t maxChildVisits = 0;
std::mutex &mutex = mutexPool->getMutex(node.lockIdx);
unique_lock<std::mutex> lock(mutex);
int numChildren = node.numChildren;
int numGoodChildren = 0;
for (int i = 0; i < numChildren; i++)
{
const SearchNode *child = node.children[i];
while (child->statsLock.test_and_set(std::memory_order_acquire))
;
int64_t childVisits = child->stats.visits;
double winValueSum = child->stats.winValueSum;
double noResultValueSum = child->stats.noResultValueSum;
double scoreMeanSum = child->stats.scoreMeanSum;
double scoreMeanSqSum = child->stats.scoreMeanSqSum;
double leadSum = child->stats.leadSum;
double weightSum = child->stats.weightSum;
double weightSqSum = child->stats.weightSqSum;
double utilitySum = child->stats.utilitySum;
double utilitySqSum = child->stats.utilitySqSum;
child->statsLock.clear(std::memory_order_release);
if (childVisits <= 0)
continue;
assert(weightSum > 0.0);
double childUtility = utilitySum / weightSum;
winValues[numGoodChildren] = winValueSum / weightSum;
noResultValues[numGoodChildren] = noResultValueSum / weightSum;
scoreMeans[numGoodChildren] = scoreMeanSum / weightSum;
scoreMeanSqs[numGoodChildren] = scoreMeanSqSum / weightSum;
leads[numGoodChildren] = leadSum / weightSum;
utilitySums[numGoodChildren] = utilitySum;
utilitySqSums[numGoodChildren] = utilitySqSum;
selfUtilities[numGoodChildren] = node.nextPla == P_WHITE ? childUtility : -childUtility;
weightSums[numGoodChildren] = weightSum;
weightSqSums[numGoodChildren] = weightSqSum;
visits[numGoodChildren] = childVisits;
totalChildVisits += childVisits;
if (childVisits > maxChildVisits)
maxChildVisits = childVisits;
numGoodChildren++;
}
lock.unlock();
// In the case we're enabling noise at the root node, also apply the slight subtraction
// of visits from the root node's children so as to downweight the effect of the few dozen visits
// we send towards children that are so bad that we never try them even once again.
// One slightly surprising behavior is that this slight subtraction won't happen in the case where
// we have just promoted a child to the root due to preservation of the tree across moves
// but we haven't sent any playouts through the root yet. But having rootNoiseEnabled without
// clearing the tree every search is a bit weird anyways.
double amountToSubtract = 0.0;
double amountToPrune = 0.0;
if (isRoot && searchParams.rootNoiseEnabled)
{
amountToSubtract = std::min(searchParams.chosenMoveSubtract, maxChildVisits / 64.0);
amountToPrune = std::min(searchParams.chosenMovePrune, maxChildVisits / 64.0);
}
double winValueSum = 0.0;
double noResultValueSum = 0.0;
double scoreMeanSum = 0.0;
double scoreMeanSqSum = 0.0;
double leadSum = 0.0;
double utilitySum = 0.0;
double utilitySqSum = 0.0;
double weightSum = 0.0;
double weightSqSum = 0.0;
for (int i = 0; i < numGoodChildren; i++)
{
if (visits[i] < amountToPrune)
continue;
double desiredWeight = (double)visits[i] - amountToSubtract;
if (desiredWeight < 0.0)
continue;
if (searchParams.valueWeightExponent > 0)
desiredWeight *= pow(weightFactors[i], searchParams.valueWeightExponent);
double weightScaling = desiredWeight / weightSums[i];
winValueSum += desiredWeight * winValues[i];
noResultValueSum += desiredWeight * noResultValues[i];
scoreMeanSum += desiredWeight * scoreMeans[i];
scoreMeanSqSum += desiredWeight * scoreMeanSqs[i];
leadSum += desiredWeight * leads[i];
utilitySum += weightScaling * utilitySums[i];
utilitySqSum += weightScaling * utilitySqSums[i];
weightSum += desiredWeight;
weightSqSum += weightScaling * weightScaling * weightSqSums[i];
}
// Also add in the direct evaluation of this node.
{
// Since we've scaled all the child weights in some arbitrary way, adjust and make sure
// that the direct evaluation of the node still has precisely 1/N weight.
// Do some things to carefully avoid divide by 0.
double desiredWeight = (totalChildVisits > 0) ? weightSum / totalChildVisits : weightSum;
if (desiredWeight < 0.0001) // Just in case
desiredWeight = 0.0001;
desiredWeight *= searchParams.parentValueWeightFactor;
double winProb = (double)node.nnOutput->whiteWinProb;
double noResultProb = (double)node.nnOutput->whiteNoResultProb;
double scoreMean = (double)node.nnOutput->whiteScoreMean;
double scoreMeanSq = (double)node.nnOutput->whiteScoreMeanSq;
double lead = (double)node.nnOutput->whiteLead;
double utility = getResultUtility(winProb, noResultProb) + getScoreUtility(scoreMean, scoreMeanSq, 1.0);
if (searchParams.subtreeValueBiasFactor != 0 && node.subtreeValueBiasTableEntry != nullptr)
{
SubtreeValueBiasEntry &entry = *(node.subtreeValueBiasTableEntry);
double newEntryDeltaUtilitySum;
double newEntryWeightSum;
if (totalChildVisits >= 1 && weightSum > 1e-10)
{
double utilityChildren = utilitySum / weightSum;
double subtreeValueBiasWeight = pow(totalChildVisits, searchParams.subtreeValueBiasWeightExponent);
double subtreeValueBiasDeltaSum = (utilityChildren - utility) * subtreeValueBiasWeight;
while (entry.entryLock.test_and_set(std::memory_order_acquire))
;
entry.deltaUtilitySum += subtreeValueBiasDeltaSum - node.lastSubtreeValueBiasDeltaSum;
entry.weightSum += subtreeValueBiasWeight - node.lastSubtreeValueBiasWeight;
newEntryDeltaUtilitySum = entry.deltaUtilitySum;
newEntryWeightSum = entry.weightSum;
node.lastSubtreeValueBiasDeltaSum = subtreeValueBiasDeltaSum;
node.lastSubtreeValueBiasWeight = subtreeValueBiasWeight;
entry.entryLock.clear(std::memory_order_release);
}
else
{
while (entry.entryLock.test_and_set(std::memory_order_acquire))
;
newEntryDeltaUtilitySum = entry.deltaUtilitySum;
newEntryWeightSum = entry.weightSum;
entry.entryLock.clear(std::memory_order_release);
}
// This is the amount of the direct evaluation of this node that we are going to bias towards the table entry
const double biasFactor = searchParams.subtreeValueBiasFactor;
if (newEntryWeightSum > 0.001)
utility += biasFactor * newEntryDeltaUtilitySum / newEntryWeightSum;
// This is the amount by which we need to scale desiredWeight such that if the table entry were actually equal to
// the current difference between the direct eval and the children, we would perform a no-op... unless a noop is
// actually impossible Then we just take what we can get. desiredWeight *= weightSum / (1.0-biasFactor) /
// std::max(0.001, (weightSum + desiredWeight - desiredWeight / (1.0-biasFactor)));
}
winValueSum += winProb * desiredWeight;
noResultValueSum += noResultProb * desiredWeight;
scoreMeanSum += scoreMean * desiredWeight;
scoreMeanSqSum += scoreMeanSq * desiredWeight;
leadSum += lead * desiredWeight;
utilitySum += utility * desiredWeight;
utilitySqSum += utility * utility * desiredWeight;
weightSum += desiredWeight;
weightSqSum += desiredWeight * desiredWeight;
}
while (node.statsLock.test_and_set(std::memory_order_acquire))
;
node.stats.visits += numVisitsToAdd;
// It's possible that these values are a bit wrong if there's a race and two threads each try to update this
// each of them only having some of the latest updates for all the children. We just accept this and let the
// error persist, it will get fixed the next time a visit comes through here and the values will at least
// be consistent with each other within this node, since statsLock at least ensures these three are set atomically.
node.stats.winValueSum = winValueSum;
node.stats.noResultValueSum = noResultValueSum;
node.stats.scoreMeanSum = scoreMeanSum;
node.stats.scoreMeanSqSum = scoreMeanSqSum;
node.stats.leadSum = leadSum;
node.stats.utilitySum = utilitySum;
node.stats.utilitySqSum = utilitySqSum;
node.stats.weightSum = weightSum;
node.stats.weightSqSum = weightSqSum;
node.virtualLosses -= virtualLossesToSubtract;
node.statsLock.clear(std::memory_order_release);
}
void Search::runSinglePlayout(SearchThread &thread, double upperBoundVisitsLeft)
{
// Store this value, used for futile-visit pruning this thread's root children selections.
thread.upperBoundVisitsLeft = upperBoundVisitsLeft;
bool posesWithChildBuf[NNPos::MAX_NN_POLICY_SIZE];
playoutDescend(thread, *rootNode, posesWithChildBuf, true, 0);
// Restore thread state back to the root state
thread.pla = rootPla;
thread.board = rootBoard;
thread.history = rootHistory;
}
void Search::addLeafValue(
SearchNode &node,
double winValue,
double noResultValue,
double scoreMean,
double scoreMeanSq,
double lead,
int32_t virtualLossesToSubtract,
bool isTerminal)
{
double utility = getResultUtility(winValue, noResultValue) + getScoreUtility(scoreMean, scoreMeanSq, 1.0);
if (searchParams.subtreeValueBiasFactor != 0 && !isTerminal && node.subtreeValueBiasTableEntry != nullptr)
{
SubtreeValueBiasEntry &entry = *(node.subtreeValueBiasTableEntry);
while (entry.entryLock.test_and_set(std::memory_order_acquire))
;
double newEntryDeltaUtilitySum = entry.deltaUtilitySum;
double newEntryWeightSum = entry.weightSum;
entry.entryLock.clear(std::memory_order_release);
// This is the amount of the direct evaluation of this node that we are going to bias towards the table entry
const double biasFactor = searchParams.subtreeValueBiasFactor;
if (newEntryWeightSum > 0.001)
utility += biasFactor * newEntryDeltaUtilitySum / newEntryWeightSum;
}
while (node.statsLock.test_and_set(std::memory_order_acquire))
;
node.stats.visits += 1;
node.stats.winValueSum += winValue;
node.stats.noResultValueSum += noResultValue;
node.stats.scoreMeanSum += scoreMean;
node.stats.scoreMeanSqSum += scoreMeanSq;
node.stats.leadSum += lead;
node.stats.utilitySum += utility;
node.stats.utilitySqSum += utility * utility;
node.stats.weightSum += 1.0;
node.stats.weightSqSum += 1.0;
node.virtualLosses -= virtualLossesToSubtract;
node.statsLock.clear(std::memory_order_release);
}
// Assumes node is locked
// Assumes node already has an nnOutput
void Search::maybeRecomputeExistingNNOutput(SearchThread &thread, SearchNode &node, bool isRoot)
{
// Right now only the root node currently ever needs to recompute, and only if it's old
if (isRoot && node.nnOutputAge != searchNodeAge)
{
node.nnOutputAge = searchNodeAge;
// Recompute if we have no ownership map, since we need it for getEndingWhiteScoreBonus
// If conservative passing, then we may also need to recompute the root policy ignoring the history if a pass ends
// the game If averaging a bunch of symmetries, then we need to recompute it too
if (node.nnOutput->whiteOwnerMap == NULL)
{
initNodeNNOutput(thread, node, isRoot, false, 0, true);
assert(node.nnOutput->whiteOwnerMap != NULL);
}
// We also need to recompute the root nn if we have root noise or temperature and that's missing.
else
{
// We don't need to go all the way to the nnEvaluator, we just need to maybe add those transforms
// to the existing policy.
maybeAddPolicyNoiseAndTempAlreadyLocked(thread, node, isRoot);
}
}
}
// Assumes node is locked
void Search::initNodeNNOutput(
SearchThread &thread,
SearchNode &node,
bool isRoot,
bool skipCache,
int32_t virtualLossesToSubtract,
bool isReInit)
{
bool includeOwnerMap = isRoot || alwaysIncludeOwnerMap;
MiscNNInputParams nnInputParams;
nnInputParams.drawEquivalentWinsForWhite = searchParams.drawEquivalentWinsForWhite;
nnInputParams.nnPolicyTemperature = searchParams.nnPolicyTemperature;
if (isRoot && searchParams.rootNumSymmetriesToSample > 1)
{
std::vector<shared_ptr<NNOutput>> ptrs;
std::array<int, NNInputs::NUM_SYMMETRY_COMBINATIONS> symmetryIndexes;
std::iota(symmetryIndexes.begin(), symmetryIndexes.end(), 0);
for (int i = 0; i < searchParams.rootNumSymmetriesToSample; i++)
{
std::swap(symmetryIndexes[i], symmetryIndexes[thread.rand.nextInt(i, NNInputs::NUM_SYMMETRY_COMBINATIONS - 1)]);
nnInputParams.symmetry = symmetryIndexes[i];
bool skipCacheThisIteration = true; // Skip cache since there's no guarantee which symmetry is in the cache
nnEvaluator->evaluate(
thread.board,
thread.history,
thread.pla,
nnInputParams,
thread.nnResultBuf,
skipCacheThisIteration,
includeOwnerMap);
ptrs.push_back(std::move(thread.nnResultBuf.result));
}
node.nnOutput = std::shared_ptr<NNOutput>(new NNOutput(ptrs));
}
else
{
nnEvaluator->evaluate(
thread.board, thread.history, thread.pla, nnInputParams, thread.nnResultBuf, skipCache, includeOwnerMap);
node.nnOutput = std::move(thread.nnResultBuf.result);
}
assert(node.nnOutput->noisedPolicyProbs == NULL);
maybeAddPolicyNoiseAndTempAlreadyLocked(thread, node, isRoot);
node.nnOutputAge = searchNodeAge;
// If this is a re-initialization of the nnOutput, we don't want to add any visits or anything.
// Also don't bother updating any of the stats. Technically we should do so because winValueSum
// and such will have changed potentially due to a new orientation of the neural net eval
// slightly affecting the evals, but this is annoying to recompute from scratch, and on the next
// visit updateStatsAfterPlayout should fix it all up anyways.
if (isReInit)
return;
addCurentNNOutputAsLeafValue(node, virtualLossesToSubtract);
}
void Search::addCurentNNOutputAsLeafValue(SearchNode &node, int32_t virtualLossesToSubtract)
{
// Values in the search are from the perspective of white positive always
double winProb = (double)node.nnOutput->whiteWinProb;
double noResultProb = (double)node.nnOutput->whiteNoResultProb;
double scoreMean = (double)node.nnOutput->whiteScoreMean;
double scoreMeanSq = (double)node.nnOutput->whiteScoreMeanSq;
double lead = (double)node.nnOutput->whiteLead;
addLeafValue(node, winProb, noResultProb, scoreMean, scoreMeanSq, lead, virtualLossesToSubtract, false);
}
void Search::playoutDescend(
SearchThread &thread,
SearchNode &node,
bool posesWithChildBuf[NNPos::MAX_NN_POLICY_SIZE],
bool isRoot,
int32_t virtualLossesToSubtract)
{
// Hit terminal node, finish
// In the case where we're forcing the search to make another move at the root, don't terminate, actually run search
// for a move more. In the case where we're conservativePass and the game just ended due to a root pass, actually let
// it keep going. Note that in the second case with tree reuse we can end up with a weird situation where a terminal
// node becomes nonterminal due to now being a child of the root! This is okay - subsequent visits to the node will
// fall through to initNodeNNOutput, and we will have a weird leaf node with 2 visits worth of mixed terminal and nn
// values, but further visits will even hit recomputeNodeStats which should clean it all it.
if (!isRoot && thread.history.isGameFinished)
{
if (thread.history.isNoResult)
{
double winValue = 0.0;
double noResultValue = 1.0;
double scoreMean = 0.0;
double scoreMeanSq = 0.0;
double lead = 0.0;
addLeafValue(node, winValue, noResultValue, scoreMean, scoreMeanSq, lead, virtualLossesToSubtract, true);
return;
}
else
{
double winValue = ScoreValue::whiteWinsOfWinner(thread.history.winner, searchParams.drawEquivalentWinsForWhite);
double noResultValue = 0.0;
double scoreMean = thread.history.finalWhiteMinusBlackScore;
double scoreMeanSq = ScoreValue::whiteScoreMeanSqOfScoreGridded(
thread.history.finalWhiteMinusBlackScore, searchParams.drawEquivalentWinsForWhite);
double lead = scoreMean;
addLeafValue(node, winValue, noResultValue, scoreMean, scoreMeanSq, lead, virtualLossesToSubtract, true);
return;
}
}
std::mutex &mutex = mutexPool->getMutex(node.lockIdx);
unique_lock<std::mutex> lock(mutex);
// Hit leaf node, finish
if (node.nnOutput == nullptr)
{
initNodeNNOutput(thread, node, isRoot, false, virtualLossesToSubtract, false);
return;
}
maybeRecomputeExistingNNOutput(thread, node, isRoot);
// Not leaf node, so recurse
// Find the best child to descend down
int bestChildIdx;
Loc bestChildFromLoc;
Loc bestChildToLoc;
selectBestChildToDescend(thread, node, bestChildIdx, bestChildFromLoc, bestChildToLoc, posesWithChildBuf, isRoot);
// The absurdly rare case that the move chosen is not legal
//(this should only happen either on a bug or where the nnHash doesn't have full legality information or when there's
// an actual hash collision). Regenerate the neural net call and continue
if (bestChildIdx >= 0 && !thread.history.isLegal(thread.board, bestChildFromLoc, bestChildToLoc, thread.pla))
{
bool isReInit = true;
initNodeNNOutput(thread, node, isRoot, true, 0, isReInit);
if (thread.logStream != NULL)
(*thread.logStream) << "WARNING: Chosen move not legal so regenerated nn output, nnhash=" << node.nnOutput->nnHash
<< endl;
// As isReInit is true, we don't return, just keep going, since we didn't count this as a true visit in the node
// stats
selectBestChildToDescend(thread, node, bestChildIdx, bestChildFromLoc, bestChildToLoc, posesWithChildBuf, isRoot);
if (bestChildIdx >= 0)
{
// We should absolutely be legal this time
assert(thread.history.isLegal(thread.board, bestChildFromLoc, bestChildToLoc, thread.pla));
}
}
if (bestChildIdx <= -1)
{
// This might happen if all moves have been forbidden. The node will just get stuck at 1 visit forever then
// and we won't do any search.
lock.unlock();
addCurentNNOutputAsLeafValue(node, virtualLossesToSubtract);
return;
}
// Reallocate the children array to increase capacity if necessary
if (bestChildIdx >= node.childrenCapacity)
{
int newCapacity = node.childrenCapacity + (node.childrenCapacity / 4) + 1;
assert(newCapacity < 0x3FFF);
SearchNode **newArr = new SearchNode *[newCapacity];
for (int i = 0; i < node.numChildren; i++)
{
newArr[i] = node.children[i];
node.children[i] = NULL;
}
SearchNode **oldArr = node.children;
node.children = newArr;
node.childrenCapacity = (uint16_t)newCapacity;
delete[] oldArr;
}
// Allocate a new child node if necessary
SearchNode *child;
if (bestChildIdx == node.numChildren)
{
node.numChildren++;
child = new SearchNode(*this, thread.pla, thread.rand, bestChildFromLoc, bestChildToLoc, &node);
node.children[bestChildIdx] = child;
}
else
{
child = node.children[bestChildIdx];
}
while (child->statsLock.test_and_set(std::memory_order_acquire))
;
child->virtualLosses += searchParams.numVirtualLossesPerThread;
child->statsLock.clear(std::memory_order_release);
if (searchParams.subtreeValueBiasFactor != 0)
{
/*
if(node.prevMoveLoc != Board::NULL_LOC) {
assert(subtreeValueBiasTable != NULL);
child->subtreeValueBiasTableEntry =
std::move(subtreeValueBiasTable->get(thread.pla, node.prevMoveLoc, child->prevMoveLoc, thread.board));
}
*/
}
// Unlock before making moves if the child already exists since we don't depend on it at this point
lock.unlock();
thread.history.makeBoardMoveAssumeLegal(thread.board, bestChildFromLoc, bestChildToLoc, thread.pla, rootKoHashTable);
thread.pla = getOpp(thread.pla);
// Recurse!
playoutDescend(thread, *child, posesWithChildBuf, false, searchParams.numVirtualLossesPerThread);
// Update this node stats
updateStatsAfterPlayout(node, thread, virtualLossesToSubtract, isRoot);
}
| 35.448826 | 139 | 0.698905 | [
"vector"
] |
6916eeac982064cb73a023b9561bf11a3603f650 | 22,985 | cpp | C++ | apps/vaporgui/main/vizwin.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | apps/vaporgui/main/vizwin.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | apps/vaporgui/main/vizwin.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | //************************************************************************
// *
// Copyright (C) 2004 *
// University Corporation for Atmospheric Research *
// All Rights Reserved *
// *
//************************************************************************/
// File: vizwin.cpp
//
// Author: Alan Norton
// National Center for Atmospheric Research
// PO 3000, Boulder, Colorado
//
// Date: July 2004
//
// Description: Implements the VizWin class
// This is the widget that contains the visualizers
// Supports mouse event reporting
//
#include "glutil.h" // Must be included first!!!
#include "vizwin.h"
#include <qdatetime.h>
#include <qvariant.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qaction.h>
#include <qmenubar.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qpushbutton.h>
#include <qslider.h>
#include <qmessagebox.h>
#include <qapplication.h>
#include <qnamespace.h>
#include <QHideEvent>
#include <QResizeEvent>
#include <QFocusEvent>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QCloseEvent>
#include "glwindow.h"
#include "vizwinmgr.h"
#include <qdesktopwidget.h>
#include "tabmanager.h"
#include "viztab.h"
#include "regiontab.h"
#include "viewpointparams.h"
#include "regionparams.h"
#include "messagereporter.h"
#include "viewpoint.h"
#include "manip.h"
#include "regioneventrouter.h"
#include "viewpointeventrouter.h"
#include "animationeventrouter.h"
#include "floweventrouter.h"
#include "flowrenderer.h"
#include "VolumeRenderer.h"
#include "mainform.h"
#include "assert.h"
#include "session.h"
#include <vapor/jpegapi.h>
#include "images/vapor-icon-32.xpm"
using namespace VAPoR;
/*
* Constructs a VizWindow as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*
*/
VizWin::VizWin( MainForm* parent, const QString& name, Qt::WFlags fl, VizWinMgr* myMgr, QRect* location, int winNum)
: QWidget( (QWidget*)parent, fl )
{
setFocusPolicy(Qt::StrongFocus);
setAttribute(Qt::WA_DeleteOnClose);
MessageReporter::infoMsg("VizWin::VizWin() begin");
myName = name;
myParent = parent;
myWindowNum = winNum;
spinTimer = 0;
elapsedTime = 0;
moveCount = 0;
moveCoords[0] = moveCoords[1] = 0;
moveDist = 0;
move(location->topLeft());
resize(location->size());
myWinMgr = myMgr;
mouseDownHere = false;
languageChange();
setWindowIcon(QPixmap(vapor_icon___));
// Create our OpenGL widget.
QGLFormat fmt;
fmt.setAlpha(true);
fmt.setRgba(true);
fmt.setDepth(true);
fmt.setDoubleBuffer(true);
fmt.setDirectRendering(true);
myGLWindow = new GLWindow(fmt, this ,myWindowNum);
fmt = myGLWindow->format();
// if (!(fmt.directRendering() && fmt.depth() && fmt.rgba() && fmt.alpha() && fmt.doubleBuffer())){
if (!(fmt.depth() && fmt.rgba() && fmt.alpha() && fmt.doubleBuffer())){
Params::BailOut("Unable to obtain required OpenGL rendering format",__FILE__,__LINE__);
}
#ifdef DEBUG
cerr << "accum : " << fmt.accum() << endl;
cerr << "accumBufferSize : " << fmt.accumBufferSize() << endl;
cerr << "alpha : " << fmt.alpha() << endl;
cerr << "alphaBufferSize : " << fmt.alphaBufferSize() << endl;
cerr << "depth : " << fmt.depth() << endl;
cerr << "depthBufferSize : " << fmt.depthBufferSize() << endl;
cerr << "stencil : " << fmt.stencil() << endl;
cerr << "stencilBufferSize : " << fmt.stencilBufferSize() << endl;
cerr << "directRendering : " << fmt.directRendering() << endl;
cerr << "doubleBuffer : " << fmt.doubleBuffer() << endl;
cerr << "stereo : " << fmt.stereo() << endl;
cerr << "hasOverlay : " << fmt.hasOverlay() << endl;
//cerr << "majorVersion : " << fmt.majorVersion() << endl;
//cerr << "minorVersion : " << fmt.minorVersion() << endl;
//cerr << "profile : " << fmt.profile() << endl;
cerr << "rgba : " << fmt.rgba() << endl;
cerr << "sampleBuffers : " << fmt.sampleBuffers() << endl;
cerr << "openGLVersionFlags : " << fmt.openGLVersionFlags() << endl;
#endif
for (int i = 1; i<= Params::GetNumParamsClasses(); i++)
myGLWindow->setActiveParams(Params::GetCurrentParamsInstance(i,myWindowNum),i);
myGLWindow->setPreRenderCB(preRenderSetup);
myGLWindow->setPostRenderCB(endRender);
QHBoxLayout* flayout = new QHBoxLayout(this);
flayout->setContentsMargins(2,2,2,2);
flayout->addWidget(myGLWindow);
//Get viewpoint from viewpointParams
ViewpointParams* vpparms = myWinMgr->getViewpointParams(myWindowNum);
//Attach the trackball:
localTrackball = new Trackball();
if (vpparms->isLocal()){
myTrackball = localTrackball;
globalVP = false;
} else {
myTrackball = myWinMgr->getGlobalTrackball();
globalVP = true;
}
myGLWindow->myTBall = myTrackball;
setValuesFromGui(vpparms);
MessageReporter::infoMsg("VizWin::VizWin() end");
}
/*
* Destroys the object and frees any allocated resources
*/
VizWin::~VizWin()
{
if (localTrackball) delete localTrackball;
//The renderers are deleted in the glwindow destructor:
if (spinTimer) delete spinTimer;
}
void VizWin::closeEvent(QCloseEvent* e){
delete myGLWindow;
//Tell the winmgr that we are closing:
myWinMgr->vizAboutToDisappear(myWindowNum);
QWidget::closeEvent(e);
}
/******************************************************
* React when focus is on window:
******************************************************/
void VizWin::
focusInEvent(QFocusEvent* e){
//Test for hidden here, since a vanishing window can get this event.
if (e->gotFocus() && !isHidden()){
if (myWinMgr->getActiveViz() != myWindowNum ){
myWinMgr->setActiveViz(myWindowNum);
}
}
}
// React to a user-change in window activation:
void VizWin::windowActivationChange(bool ){
//qWarning(" Activation Event %d received in window %d ", value, myWindowNum);
//We may also be going out of minimized state:
if (isReallyMaximized()) {
//qWarning( " resize due to maximization");
myWinMgr->maximize(myWindowNum);
}
else if (isMinimized()) {
myWinMgr->minimize(myWindowNum);
}
else {
//went to normal
myWinMgr->normalize(myWindowNum);
}
}
// React to a user-change in window size/position (or possibly max/min)
// Either the window is minimized, maximized, restored, or just resized.
void VizWin::resizeEvent(QResizeEvent*){
//qWarning(" Resize Event received in window %d ", myWindowNum);
if (isReallyMaximized()) {
//qWarning( " resize due to maximization");
myWinMgr->maximize(myWindowNum);
}
else if (isMinimized()) {
myWinMgr->minimize(myWindowNum);
}
else {
//User either resized or restored from min/max
myWinMgr->normalize(myWindowNum);
}
QSize sz = size();
MessageReporter::infoMsg("Window size %d x %d",sz.width(), sz.height());
}
void VizWin::hideEvent(QHideEvent* ){
myWinMgr->minimize(myWindowNum);
}
/* If the user presses the mouse on the active viz window,
* We record the position of the click.
*/
void VizWin::
mousePressEvent(QMouseEvent* e){
float screenCoords[2];
//if (numRenderers <= 0) return;// Even with no renderers, do mouse mode stuff
screenCoords[0] = (float)e->x()-3.f;
//To keep orientation correct in plane, and use
//OpenGL convention (Y 0 at bottom of window), reverse
//value of y:
screenCoords[1] = (float)(height() - e->y()) - 5.f;
int buttonNum = 0;
if ((e->buttons() & Qt::LeftButton) && (e->buttons() & Qt::RightButton))
;//do nothing
else if (e->button()== Qt::LeftButton) buttonNum = 1;
else if (e->button() == Qt::RightButton) buttonNum = 2;
else if (e->button() == Qt::MidButton) buttonNum = 3;
//If ctrl + left button is pressed, only respond in navigation mode
if((buttonNum == 1) && ((e->modifiers() & (Qt::ControlModifier|Qt::MetaModifier))))
buttonNum = 0;
//possibly navigate after other activities
bool doNavigate = true;
endSpin();
int mode = GLWindow::getCurrentMouseMode();
if (mode > 0 && buttonNum > 0) { //Not navigation mode:
int timestep = VizWinMgr::getActiveAnimationParams()->getCurrentTimestep();
int faceNum;
float boxExtents[6];
ViewpointParams* vParams = myWinMgr->getViewpointParams(myWindowNum);
ParamsBase::ParamsBaseType t = GLWindow::getModeParamType(mode);
Params* rParams = VizWinMgr::getInstance()->getParams(myWindowNum,t);
TranslateStretchManip* manip = myGLWindow->getManip(Params::GetTagFromType(t));
manip->setParams(rParams);
int manipType = GLWindow::getModeManipType(mode);
if(manipType != 3) rParams->calcStretchedBoxExtentsInCube(boxExtents, timestep); //non-rotated manip
else rParams->calcContainingStretchedBoxExtentsInCube(boxExtents,true);//rotated
int handleNum = manip->mouseIsOverHandle(screenCoords, boxExtents, &faceNum);
if (handleNum >= 0 && myGLWindow->startHandleSlide(screenCoords, handleNum,rParams)){
//With manip type 2, need to prevent right mouse slide on orthogonal handle
//With manip type 3, need to use orientation
bool OK = true;//Flag indicates whether the manip takes the mouse
switch (manipType) {
case 1 : //3d box manip
break;
case 2 : //2d box manip, ok if not right mouse on orthog direction
//Do nothing if grabbing orthog direction with right mouse:
if (buttonNum == 2 && ((handleNum == (rParams->getOrientation() +3))
|| (handleNum == (rParams->getOrientation() -2)))){
OK = false;
}
break;
case 3 : //Rotate-stretch: check if it's rotated too far
if (buttonNum <= 1) break; //OK if left mouse button
{
bool doStretch = true;
//check if the rotation angle is approx a multiple of 90 degrees:
int tolerance = 20;
int thet = (int)(fabs(rParams->getTheta())+0.5f);
int ph = (int)(fabs(rParams->getPhi())+ 0.5f);
int ps = (int)(fabs(rParams->getPsi())+ 0.5f);
//Make sure that these are within tolerance of a multiple of 90
if (abs(((thet+45)/90)*90 -thet) > tolerance) doStretch = false;
if (abs(((ps+45)/90)*90 -ps) > tolerance) doStretch = false;
if (abs(((ph+45)/90)*90 -ph) > tolerance) doStretch = false;
if (!doStretch) {
MessageReporter::warningMsg("Manipulator is not axis-aligned.\n%s %s %s",
"To stretch or shrink,\n",
"You must use the size\n",
"(sliders or text) in the tab.");
OK = false;
}
}
break;
default: assert(0); //Invalid manip type
}//end switch
if (OK) {
doNavigate = false;
float dirVec[3];
//Find the direction vector of the camera (Local coords)
myGLWindow->pixelToVector(screenCoords,
vParams->getCameraPosLocal(), dirVec);
//Remember which handle we hit, highlight it, save the intersection point.
manip->captureMouseDown(handleNum, faceNum, vParams->getCameraPosLocal(), dirVec, buttonNum);
EventRouter* rep = VizWinMgr::getInstance()->getEventRouter(t);
rep->captureMouseDown(buttonNum);
setMouseDown(true);
myGLWindow->update();
} //otherwise, fall through to navigation mode
}
//Set up for spin animation
} else if (mode == 0 && buttonNum == 1){ //Navigation mode, prepare for spin
// doNavigate is true;
//Create a timer to use to measure how long between mouse moves:
if (spinTimer) delete spinTimer;
spinTimer = new QTime();
spinTimer->start();
moveCount = 0;
olderMoveTime = latestMoveTime = 0;
}
//Otherwise, either mode > 0 or buttonNum != 1. OK to navigate
if (doNavigate){
ViewpointEventRouter* vep = VizWinMgr::getInstance()->getViewpointRouter();
vep->captureMouseDown(buttonNum);
Qt::MouseButton btn = e->button();
//Left button + ctrl = mid button:
if ((e->buttons() & Qt::LeftButton) && (e->buttons() & Qt::RightButton)) btn = Qt::MidButton;
else if(btn == Qt::LeftButton && ((e->modifiers() & (Qt::ControlModifier|Qt::MetaModifier))))
btn = Qt::MidButton;
myTrackball->MouseOnTrackball(0, btn, e->x(), e->y(), width(), height());
setMouseDown(true);
mouseDownPosition = e->pos();
}
}
/*
* If the user releases the mouse or moves it (with the left mouse down)
* then we note the displacement
*/
void VizWin::
mouseReleaseEvent(QMouseEvent*e){
//if (numRenderers <= 0) return;//used for mouse mode stuff
bool doNavigate = false;
bool navMode = false;
TranslateStretchManip* myManip;
int mode = GLWindow::getCurrentMouseMode();
if (mode > 0) {
ParamsBase::ParamsBaseType t = GLWindow::getModeParamType(mode);
myManip = myGLWindow->getManip(Params::GetTagFromType(t));
//Check if the seed bounds were moved
if (myManip->draggingHandle() >= 0){
float screenCoords[2];
screenCoords[0] = (float)e->x();
screenCoords[1] = (float)(height() - e->y());
setMouseDown(false);
//The manip must move the region, and then tells the params to
//record end of move
myManip->mouseRelease(screenCoords);
VizWinMgr::getInstance()->getEventRouter(t)->captureMouseUp();
} else {//otherwise fall through to navigate mode
doNavigate = true;
}
} else {//In true navigation mode
doNavigate = true;
navMode = true;
}
if(doNavigate){
myTrackball->MouseOnTrackball(2, e->button(), e->x(), e->y(), width(), height());
setMouseDown(false);
//If it's a right mouse being released, must update near/far distances:
if (e->button() == Qt::RightButton){
myWinMgr->resetViews(
myWinMgr->getViewpointParams(myWindowNum));
}
//Decide whether or not to start a spin animation
bool doSpin = (GLWindow::spinAnimationEnabled() && navMode && e->button() == Qt::LeftButton && spinTimer &&
!getGLWindow()->getActiveAnimationParams()->isPlaying());
//Determine if the motion is sufficient to start a spin animation.
//Require that some time has elapsed since the last move event, and,
//to allow users to stop spin by holding mouse steady, make sure that
//the time from the last move event is no more than 6 times the
//difference between the last two move times.
if (doSpin) {
int latestTime = spinTimer->elapsed();
if (moveDist > 3 && moveCount > 0 && (latestTime - latestMoveTime)< 6*(latestMoveTime-olderMoveTime)){
myGLWindow->startSpin(latestTime/moveCount);
} else {
doSpin = false;
}
}
if (!doSpin){
//terminate current mouse motion
VizWinMgr::getEventRouter(Params::_viewpointParamsTag)->captureMouseUp();
}
//Done with timer:
if(spinTimer) delete spinTimer;
spinTimer = 0;
//Force rerender, so correct resolution is shown
//setRegionNavigating(true);
myGLWindow->update();
}
}
/*
* When the mouse is moved, it can affect navigation,
* region position, light position, or probe position, depending
* on current mode. The values associated with the window are
* changed whether or not the tabbed panel is visible.
* It's important that coordinate changes eventually get recorded in the
* viewpoint params panel. This requires some work every time there is
* mouse navigation. Changes in the viewpoint params panel will notify
* the viztab if it is active and change the values there.
* Conversely, when values are changed in the viztab, the viewpoint
* values are set in the vizwin class, provided they did not originally
* come from the mouse navigation. Such a change forces a reinitialization
* of the trackball and the new values will be used at the next rendering.
*
*/
void VizWin::
mouseMoveEvent(QMouseEvent* e){
if (!mouseIsDown()) return;
bool doNavigate = true;
//Respond based on what activity we are tracking
//Need to tell the appropriate params about the change,
//And it should refresh the panel
float mouseCoords[2];
float projMouseCoords[2];
mouseCoords[0] = (float) e->x();
mouseCoords[1] = (float) height()-e->y();
int mode = GLWindow::getCurrentMouseMode();
ParamsBase::ParamsBaseType t = GLWindow::getModeParamType(mode);
if (mode > 0){
TranslateStretchManip* manip = myGLWindow->getManip(Params::GetTagFromType(t));
bool constrain = manip->getParams()->isDomainConstrained();
ViewpointParams* vParams = myWinMgr->getViewpointParams(myWindowNum);
int handleNum = manip->draggingHandle();
//check first to see if we are dragging face
if (handleNum >= 0){
if (myGLWindow->projectPointToLine(mouseCoords,projMouseCoords)) {
float dirVec[3];
myGLWindow->pixelToVector(projMouseCoords, vParams->getCameraPosLocal(), dirVec);
//qWarning("Sliding handle %d, direction %f %f %f", handleNum, dirVec[0],dirVec[1],dirVec[2]);
manip->slideHandle(handleNum, dirVec,constrain);
doNavigate = false;
}
}
} else if (spinTimer) { //Navigate mode, handle spin animation
moveCount++;
if (moveCount > 0){//find distance from last move event...
moveDist = abs(moveCoords[0]-e->x())+abs(moveCoords[1]-e->y());
}
moveCoords[0] = e->x();
moveCoords[1] = e->y();
int latestTime = spinTimer->elapsed();
olderMoveTime = latestMoveTime;
latestMoveTime = latestTime;
}
if(doNavigate){
myTrackball->MouseOnTrackball(1, e->button(), e->x(), e->y(), width(), height());
//Note that the coords have changed:
myGLWindow->setViewerCoordsChanged(true);
setDirtyBit(ProjMatrixBit, true);
}
myGLWindow->update();
return;
}
void VizWin::keyPressEvent( QKeyEvent *e) {
myTrackball->TrackballSetPosition(0,0);
switch(e->key()) {
case Qt::Key_Left:
if (e->modifiers() & Qt::ShiftModifier)
myTrackball->TrackballPan(-.05,0);
else
myTrackball->TrackballRotate(-.05,0);
myGLWindow->update();
break;
case Qt::Key_Right:
if (e->modifiers() & Qt::ShiftModifier)
myTrackball->TrackballPan(.05,0);
else
myTrackball->TrackballRotate(.05,0);
myGLWindow->update();
break;
case Qt::Key_Up:
if (e->modifiers() & Qt::ShiftModifier)
myTrackball->TrackballPan(0,.05);
else
myTrackball->TrackballRotate(0,.05);
myGLWindow->update();
break;
case Qt::Key_Down:
if (e->modifiers() & Qt::ShiftModifier)
myTrackball->TrackballPan(0,-.05);
else
myTrackball->TrackballRotate(0,-.05);
myGLWindow->update();
break;
case Qt::Key_Underscore:
myTrackball->TrackballZoom(-.05,-.05);
myGLWindow->update();
break;
case Qt::Key_Minus:
myTrackball->TrackballZoom(-.05,-.05);
myGLWindow->update();
break;
case Qt::Key_Plus:
myTrackball->TrackballZoom(.05,.05);
myGLWindow->update();
break;
case Qt::Key_Equal:
myTrackball->TrackballZoom(.05,.05);
myGLWindow->update();
break;
}
}
/*
* Sets the strings of the subwidgets using the current
* language.
*/
void VizWin::languageChange()
{
setWindowTitle(myName);
}
void VizWin::helpIndex()
{
//qWarning( "VizWin::helpIndex(): Not implemented yet" );
}
void VizWin::helpContents()
{
//qWarning( "VizWin::helpContents(): Not implemented yet" );
}
void VizWin::helpAbout()
{
//qWarning( "VizWin::helpAbout(): Not implemented yet" );
}
//Due to X11 probs need to check again. Compare this window with the available space.
bool VizWin::isReallyMaximized() {
if (isMaximized() ) return true;
QWidget* thisCentralWidget = (MainForm::getInstance())->centralWidget();
QSize mySize = frameSize();
QSize spaceSize = thisCentralWidget->size();
//qWarning(" space is %d by %d, frame is %d by %d ", spaceSize.width(), spaceSize.height(), mySize.width(), mySize.height());
if ((mySize.width() > 0.95*spaceSize.width()) && (mySize.height() > 0.95*spaceSize.height()) )return true;
return false;
}
void VizWin::setFocus(){
//qWarning("Setting Focus in win %d", myWindowNum);
//??QMainWindow::setFocus();
QWidget::setFocus();
}
/*
* Following method is called when the coords have changed in visualizer. Need to reset the params and
* update the gui
*/
void VizWin::
changeCoords(float *vpos, float* vdir, float* upvec) {
float worldPos[3];
ViewpointParams::localFromStretchedCube(vpos,worldPos);
myWinMgr->getViewpointRouter()->navigate(myWinMgr->getViewpointParams(myWindowNum),worldPos, vdir, upvec);
myGLWindow->setViewerCoordsChanged(false);
//If this window is using global VP, must tell all other global windows to update:
if (globalVP){
for (int i = 0; i< MAXVIZWINS; i++){
if (i == myWindowNum) continue;
VizWin* viz = myWinMgr->getVizWin(i);
if (viz && viz->globalVP) viz->updateGL();
}
}
}
/*
* Get viewpoint info from GUI
* Note: if the current settings are global, this should be using global params
*/
void VizWin::
setValuesFromGui(ViewpointParams* vpparams){
if (!vpparams->isLocal()){
assert(myWinMgr->getViewpointParams(myWindowNum) == vpparams);
}
Viewpoint* vp = vpparams->getCurrentViewpoint();
float transCameraPos[3];
float cubeCoords[3];
//Must transform from world coords to unit cube coords for trackball.
ViewpointParams::localToStretchedCube(vpparams->getCameraPosLocal(), transCameraPos);
ViewpointParams::localToStretchedCube(vpparams->getRotationCenterLocal(), cubeCoords);
myTrackball->setFromFrame(transCameraPos, vp->getViewDir(), vp->getUpVec(), cubeCoords, vp->hasPerspective());
//If the perspective was changed, a resize event will be triggered at next redraw:
myGLWindow->setPerspective(vp->hasPerspective());
//Set dirty bit.
setDirtyBit(ProjMatrixBit,true);
//Force a redraw
myGLWindow->update();
}
/*
* Switch Tball when change to local or global viewpoint
*/
void VizWin::
setGlobalViewpoint(bool setGlobal){
if (!setGlobal){
myTrackball = localTrackball;
globalVP = false;
} else {
myTrackball = myWinMgr->getGlobalTrackball();
globalVP = true;
}
myGLWindow->myTBall = myTrackball;
ViewpointParams* vpparms = myWinMgr->getViewpointParams(myWindowNum);
setValuesFromGui(vpparms);
}
/*
* Obtain current view frame from gl model matrix
*/
void VizWin::
changeViewerFrame(){
GLfloat m[16], minv[16];
GLdouble modelViewMtx[16];
//Get the frame from GL:
glGetFloatv(GL_MODELVIEW_MATRIX, m);
//Also, save the modelview matrix for picking purposes:
glGetDoublev(GL_MODELVIEW_MATRIX, modelViewMtx);
//save the modelViewMatrix in the viewpoint params (it may be shared!)
VizWinMgr::getInstance()->getViewpointParams(myWindowNum)->
setModelViewMatrix(modelViewMtx);
//Invert it:
int rc = minvert(m, minv);
if(!rc) assert(rc);
vscale(minv+8, -1.f);
if (!myGLWindow->getPerspective()){
//Note: This is a hack. Putting off the time when we correctly implement
//Ortho coords to actually send perspective viewer to infinity.
//get the scale out of the (1st 3 elements of) matrix:
//
float scale = vlength(m);
float trans;
if (scale < 5.f) trans = 1.-5./scale;
else trans = scale - 5.f;
minv[14] = -trans;
}
changeCoords(minv+12, minv+8, minv+4);
}
//Terminate the current spin, and complete the VizEventRouter command that
//started when the mouse was pressed...
void VizWin::endSpin(){
if (!myGLWindow) return;
if (!myGLWindow->stopSpin()) return;
VizWinMgr::getInstance()->getViewpointRouter()->endSpin();
myGLWindow->update();
}
| 33.119597 | 129 | 0.675919 | [
"object",
"vector",
"model",
"transform",
"3d"
] |
691cdabb20b744dea1a26fae07599506b6a15679 | 6,690 | cpp | C++ | native_libs/plotter/Matplotlib/Plot.cpp | Magalame/dataframes | b851983fe707f6368bda1d2f3561289d069764fc | [
"MIT"
] | 4 | 2019-05-09T17:25:29.000Z | 2019-10-30T21:22:14.000Z | native_libs/plotter/Matplotlib/Plot.cpp | Magalame/dataframes | b851983fe707f6368bda1d2f3561289d069764fc | [
"MIT"
] | 94 | 2018-07-09T19:02:56.000Z | 2019-03-29T13:30:39.000Z | native_libs/plotter/Matplotlib/Plot.cpp | Magalame/dataframes | b851983fe707f6368bda1d2f3561289d069764fc | [
"MIT"
] | 3 | 2019-05-16T21:05:39.000Z | 2020-06-19T14:36:33.000Z | #include "Plot.h"
#include <cmath>
#include <arrow/array.h>
#include <Core/ArrowUtilities.h>
#include "B64.h"
#include "ValueHolder.h"
#include "Core/Error.h"
#include "Python/IncludePython.h"
#include <matplotlibcpp.h>
#include "Python/PythonInterpreter.h"
namespace
{
thread_local ValueHolder returnedString;
}
///////////////////////////////////////////////////////////////////////////////
namespace plt = matplotlibcpp;
struct PyListBuilder
{
protected:
pybind11::list list;
size_t ind = 0;
public:
PyListBuilder(size_t length)
: list(length)
{
}
~PyListBuilder()
{}
void append(pybind11::object item)
{
setAt(list, ind++, item);
}
void append(int64_t i)
{
append(pybind11::int_(i));
}
void append(double d)
{
append(pybind11::float_(d));
}
void append(std::string_view s)
{
append(pybind11::str(s.data(), s.length()));
}
void append(Timestamp t)
{
append(PythonInterpreter::instance().toPyDateTime(t));
}
void appendNull()
{
append(pybind11::float_(std::numeric_limits<double>::quiet_NaN()));
}
auto release()
{
assert(list);
assert(ind == list.size());
return std::exchange(list, pybind11::list{});
}
};
pybind11::list toPyList(const arrow::ChunkedArray &arr)
{
try
{
PyListBuilder builder{ (size_t)arr.length() };
iterateOverGeneric(arr,
[&](auto &&elem) { builder.append(elem); },
[&]() { builder.appendNull(); });
return builder.release();
}
catch(std::exception &e)
{
throw std::runtime_error("failed to convert chunked array to python list: "s + e.what());
}
}
pybind11::list toPyList(const arrow::Column &column)
{
try
{
return toPyList(*column.data());
}
catch(std::exception &e)
{
throw std::runtime_error("column " + column.name() + ": " + e.what());
}
}
pybind11::list toPyList(const arrow::Table &table)
{
auto cols = getColumns(table);
pybind11::list result(table.num_columns());
for(int i = 0; i < table.num_columns(); i++)
{
auto columnAsPyList = toPyList(*cols[i]);
pybind11::setAt(result, i, columnAsPyList);
}
return result;
}
std::string getPNG()
{
plt::tight_layout();
return plt::getPNG();
}
void saveFigure(const std::string &fname)
{
plt::tight_layout();
return plt::save(fname);
}
extern "C"
{
void plot(const arrow::Column *xs, const arrow::Column *ys, const char* label, const char *style, const char *color, double alpha, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
auto xsarray = toPyList(*xs);
auto ysarray = toPyList(*ys);
plt::plot(xsarray, ysarray, label, style, color, alpha);
};
}
void plotDate(const arrow::Column *xs, const arrow::Column *ys, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
auto xsarray = toPyList(*xs);
auto ysarray = toPyList(*ys);
plt::plot_date(xsarray, ysarray);
};
}
void scatter(const arrow::Column *xs, const arrow::Column *ys, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
auto xsarray = toPyList(*xs);
auto ysarray = toPyList(*ys);
plt::scatter(xsarray, ysarray);
};
}
void kdeplot(const arrow::Column *xs, const char *label, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
auto xsarray = toPyList(*xs);
plt::kdeplot(xsarray, label);
};
}
void kdeplot2(const arrow::Column *xs, const arrow::Column *ys, const char *colormap, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
auto xsarray = toPyList(*xs);
auto ysarray = toPyList(*ys);
plt::kdeplot2(xsarray, ysarray, colormap);
};
}
void fillBetween(const arrow::Column *xs, const arrow::Column *ys1, const arrow::Column *ys2, const char *label, const char *color, double alpha, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
auto xsarray = toPyList(*xs);
auto ysarray1 = toPyList(*ys1);
auto ysarray2 = toPyList(*ys2);
plt::fill_between(xsarray, ysarray1, ysarray2, label, color, alpha);
};
}
void heatmap(const arrow::Table* xs, const char* cmap, const char* annot, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
auto xsarray = toPyList(*xs);
plt::heatmap(xsarray, cmap, annot);
};
}
void histogram(const arrow::Column *xs, size_t bins, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
auto xsarray = toPyList(*xs);
plt::hist(xsarray, bins);
};
}
void show(const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
plt::show();
};
}
void init(size_t w, size_t h, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
// matplotlib doesn't verify sizes and they yield errors when
// writing files (eg. through libpng) where we cannot tell what
// went wrong. Let's check sizes here then.
if(w == 0)
THROW("figure width must be positive, requested width={}", w);
if(h == 0)
THROW("figure height must be positive, requested height={}", h);
plt::backend("Agg");
plt::detail::_interpreter::get();
plt::figure_size(w, h);
plt::rotate_ticks(45);
};
}
void subplot(long nrows, long ncols, long plot_number, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
plt::subplot(nrows, ncols, plot_number);
};
}
const char* getPngBase64(const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
auto png = ::getPNG();
auto encodedPng = base64_encode(png);
return returnedString.store(std::move(encodedPng));
};
}
void savefig(const char *fname, const char **outError) noexcept
{
return TRANSLATE_EXCEPTION(outError)
{
return saveFigure(fname);
};
}
}
| 25.930233 | 181 | 0.569058 | [
"object"
] |
6926cca2808bef84238fb3496213e6ac3ffa00d8 | 2,432 | hpp | C++ | src/libgl/draw/CGlDrawWireframeBox.hpp | schreiberx/lbm_free_surface_opencl | 1149b68dc6bc5f3d7e4f3c646c4c9a72dcf4914e | [
"Apache-2.0"
] | null | null | null | src/libgl/draw/CGlDrawWireframeBox.hpp | schreiberx/lbm_free_surface_opencl | 1149b68dc6bc5f3d7e4f3c646c4c9a72dcf4914e | [
"Apache-2.0"
] | null | null | null | src/libgl/draw/CGlDrawWireframeBox.hpp | schreiberx/lbm_free_surface_opencl | 1149b68dc6bc5f3d7e4f3c646c4c9a72dcf4914e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010 Martin Schreiber
*
* 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 CGL_WIREFRAME_BOX_HPP
#define CGL_WIREFRAME_BOX_HPP
#include "libgl/core/CGlState.hpp"
/**
* \brief render sky boxes with cube map textures
*/
class CGlWireframeBox
{
CGlBuffer vertex_buffer;
CGlBuffer index_buffer;
public:
CError error; ///< error handler
CGlUniform pvm_matrix_uniform; ///< uniform to pvm matrix
CGlProgram program; ///< program to render sky box
CGlWireframeBox() :
vertex_buffer(GL_ARRAY_BUFFER),
index_buffer(GL_ELEMENT_ARRAY_BUFFER)
{
program.initVertFragShadersFromDirectory("draw/wireframe_box");
program.link();
program.setupUniform(pvm_matrix_uniform, "pvm_matrix");
/**
* initialize buffers
*/
/*
* vertices for cube drawn counterclockwise
* use quads to draw surfaces
*/
#define P +1.0f
#define N -1.0f
static const GLfloat vertices[8][3] = {
{N,N,P}, // 0
{N,N,N}, // 1
{N,P,P}, // 2
{N,P,N}, // 3
{P,N,P}, // 4
{P,N,N}, // 5
{P,P,P}, // 6
{P,P,N}, // 7
};
#undef N
#undef P
static const GLubyte indices[16] = {
// faces for clockwise triangle strips
0,1,3,2,0, // left
4,6,2,6, // front
7,5,4, // right
5,1,3,7 // back
};
vertex_buffer.bind();
vertex_buffer.data(sizeof(vertices), vertices);
vertex_buffer.unbind();
index_buffer.bind();
index_buffer.data(sizeof(indices), indices);
index_buffer.unbind();
}
/**
* render skybox
*/
void render(GLSL::mat4 &p_pvm_matrix)
{
program.use();
pvm_matrix_uniform.set(p_pvm_matrix);
vertex_buffer.bind();
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(0);
index_buffer.bind();
glDrawElements(GL_LINE_STRIP, 16, GL_UNSIGNED_BYTE, 0);
index_buffer.unbind();
glDisableVertexAttribArray(0);
vertex_buffer.unbind();
program.disable();
}
};
#endif
| 22.311927 | 75 | 0.679276 | [
"render"
] |
69317c2d06dc0c0bd0c1adc00bd63f731b71befd | 15,545 | cc | C++ | inet/src/inet/common/packet/printer/PacketPrinter.cc | ntanetani/quisp | 003f85746266d2eb62c66883e5b965b654672c70 | [
"BSD-3-Clause"
] | null | null | null | inet/src/inet/common/packet/printer/PacketPrinter.cc | ntanetani/quisp | 003f85746266d2eb62c66883e5b965b654672c70 | [
"BSD-3-Clause"
] | null | null | null | inet/src/inet/common/packet/printer/PacketPrinter.cc | ntanetani/quisp | 003f85746266d2eb62c66883e5b965b654672c70 | [
"BSD-3-Clause"
] | 1 | 2021-07-02T13:32:40.000Z | 2021-07-02T13:32:40.000Z | //
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
#include "inet/common/ProtocolTag_m.h"
#include "inet/common/packet/printer/PacketPrinter.h"
#include "inet/common/packet/printer/ProtocolPrinterRegistry.h"
namespace inet {
Register_MessagePrinter(PacketPrinter);
const char *PacketPrinter::DirectiveResolver::resolveDirective(char directive) const
{
static std::string result;
switch (directive) {
case 's':
result = context.sourceColumn.str();
break;
case 'd':
result = context.destinationColumn.str();
break;
case 'p':
result = context.protocolColumn.str();
break;
case 'l':
result = context.lengthColumn.str();
break;
case 't':
result = context.typeColumn.str();
break;
case 'i':
result = context.infoColumn.str();
break;
case 'n':
result = std::to_string(numPacket);
break;
default:
throw cRuntimeError("Unknown directive: %c", directive);
}
return result.c_str();
}
int PacketPrinter::getScoreFor(cMessage *msg) const
{
return msg->isPacket() ? 100 : 0;
}
bool PacketPrinter::isEnabledOption(const Options *options, const char *name) const
{
return options->enabledTags.find(name) != options->enabledTags.end();
}
bool PacketPrinter::isEnabledInfo(const Options *options, const Protocol *protocol) const
{
if (isEnabledOption(options, "Show all info"))
return true;
if (protocol) {
switch (protocol->getLayer()) {
case Protocol::PhysicalLayer: return isEnabledOption(options, "Show physical layer info");
case Protocol::LinkLayer: return isEnabledOption(options, "Show link layer info");
case Protocol::NetworkLayer: return isEnabledOption(options, "Show network layer info");
case Protocol::TransportLayer: return isEnabledOption(options, "Show transport layer info");
default: break;
}
}
return false;
}
const ProtocolPrinter& PacketPrinter::getProtocolPrinter(const Protocol *protocol) const
{
auto protocolPrinter = ProtocolPrinterRegistry::globalRegistry.findProtocolPrinter(protocol);
if (protocolPrinter == nullptr)
protocolPrinter = ProtocolPrinterRegistry::globalRegistry.findProtocolPrinter(nullptr);
return *protocolPrinter;
}
std::set<std::string> PacketPrinter::getSupportedTags() const
{
return {"Print inside out", "Print left to right",
"Show 'Source' column", "Show 'Destination' column", "Show 'Protocol' column", "Show 'Type' column", "Show 'Length' column", "Show 'Info' column",
"Show all PDU source fields", "Show all PDU destination fields", "Show all PDU protocols", "Show all PDU lengths",
"Show physical layer info", "Show link layer info", "Show network layer info", "Show transport layer info", "Show all info", "Show innermost info",
"Show auto source fields", "Show auto destination fields", "Show auto info"};
}
std::set<std::string> PacketPrinter::getDefaultEnabledTags() const
{
return {"Print inside out",
"Show 'Source' column", "Show 'Destination' column", "Show 'Protocol' column", "Show 'Type' column", "Show 'Length' column", "Show 'Info' column",
"Show auto source fields", "Show auto destination fields", "Show auto info"};
}
std::vector<std::string> PacketPrinter::getColumnNames(const Options *options) const
{
std::vector<std::string> columnNames;
if (isEnabledOption(options, "Show 'Source' column"))
columnNames.push_back("Source");
if (isEnabledOption(options, "Show 'Destination' column"))
columnNames.push_back("Destination");
if (isEnabledOption(options, "Show 'Protocol' column"))
columnNames.push_back("Protocol");
if (isEnabledOption(options, "Show 'Type' column"))
columnNames.push_back("Type");
if (isEnabledOption(options, "Show 'Length' column"))
columnNames.push_back("Length");
if (isEnabledOption(options, "Show 'Info' column"))
columnNames.push_back("Info");
return columnNames;
}
void PacketPrinter::printContext(std::ostream& stream, const Options *options, Context& context) const
{
if (!context.isCorrect)
stream << "\x1b[103m";
stream << "\x1b[30m";
if (isEnabledOption(options, "Show 'Source' column"))
stream << context.sourceColumn.str() << "\t";
if (isEnabledOption(options, "Show 'Destination' column"))
stream << context.destinationColumn.str() << "\t";
if (isEnabledOption(options, "Show 'Protocol' column"))
stream << "\x1b[34m" << context.protocolColumn.str() << "\x1b[30m\t";
if (isEnabledOption(options, "Show 'Type' column"))
stream << "\x1b[34m" << context.typeColumn.str() << "\x1b[30m\t";
if (isEnabledOption(options, "Show 'Length' column"))
stream << context.lengthColumn.str() << "\t";
if (isEnabledOption(options, "Show 'Info' column"))
stream << context.infoColumn.str();
stream << std::endl;
}
void PacketPrinter::printMessage(std::ostream& stream, cMessage *message) const
{
Options options;
options.enabledTags = getDefaultEnabledTags();
printMessage(stream, message, &options);
}
void PacketPrinter::printMessage(std::ostream& stream, cMessage *message, const Options *options) const
{
Context context;
for (auto cpacket = dynamic_cast<cPacket *>(message); cpacket != nullptr; cpacket = cpacket->getEncapsulatedPacket()) {
if (false) {}
#ifdef WITH_RADIO
else if (auto signal = dynamic_cast<inet::physicallayer::Signal *>(cpacket))
printSignal(signal, options, context);
#endif // WITH_RADIO
else if (auto packet = dynamic_cast<Packet *>(cpacket))
printPacket(packet, options, context);
else
context.infoColumn << cpacket->str();
}
printContext(stream, options, context);
}
#ifdef WITH_RADIO
void PacketPrinter::printSignal(std::ostream& stream, inet::physicallayer::Signal *signal) const
{
Options options;
options.enabledTags = getDefaultEnabledTags();
printSignal(stream, signal, &options);
}
void PacketPrinter::printSignal(std::ostream& stream, inet::physicallayer::Signal *signal, const Options *options) const
{
Context context;
printSignal(signal, options, context);
printContext(stream, options, context);
}
void PacketPrinter::printSignal(inet::physicallayer::Signal *signal, const Options *options, Context& context) const
{
context.infoColumn << signal->str();
}
#endif // WITH_RADIO
void PacketPrinter::printPacket(std::ostream& stream, Packet *packet, const char *format) const
{
Options options;
options.enabledTags = getDefaultEnabledTags();
printPacket(stream, packet, &options, format);
}
void PacketPrinter::printPacket(std::ostream& stream, Packet *packet, const Options *options, const char *format) const
{
Context context;
printPacket(packet, options, context);
if (format == nullptr)
printContext(stream, options, context);
else {
DirectiveResolver directiveResolver(context, numPacket++);
StringFormat stringFormat;
stringFormat.parseFormat(format);
stream << stringFormat.formatString(&directiveResolver);
}
}
void PacketPrinter::printPacket(Packet *packet, const Options *options, Context& context) const
{
PacketDissector::PduTreeBuilder pduTreeBuilder;
auto packetProtocolTag = packet->findTag<PacketProtocolTag>();
auto protocol = packetProtocolTag != nullptr ? packetProtocolTag->getProtocol() : nullptr;
PacketDissector packetDissector(ProtocolDissectorRegistry::globalRegistry, pduTreeBuilder);
packetDissector.dissectPacket(packet, protocol);
auto& protocolDataUnit = pduTreeBuilder.getTopLevelPdu();
if (pduTreeBuilder.isSimplyEncapsulatedPacket() && isEnabledOption(options, "Print inside out"))
const_cast<PacketPrinter *>(this)->printPacketInsideOut(protocolDataUnit, options, context);
else
const_cast<PacketPrinter *>(this)->printPacketLeftToRight(protocolDataUnit, options, context);
}
std::string PacketPrinter::printPacketToString(Packet *packet, const char *format) const
{
std::stringstream stream;
printPacket(stream, packet, format);
return stream.str();
}
std::string PacketPrinter::printPacketToString(Packet *packet, const Options *options, const char *format) const
{
std::stringstream stream;
printPacket(stream, packet, options, format);
return stream.str();
}
void PacketPrinter::printPacketInsideOut(const Ptr<const PacketDissector::ProtocolDataUnit>& protocolDataUnit, const Options *options, Context& context) const
{
auto protocol = protocolDataUnit->getProtocol();
context.isCorrect &= protocolDataUnit->isCorrect();
printLengthColumn(protocolDataUnit, options, context);
for (const auto& chunk : protocolDataUnit->getChunks()) {
if (auto childLevel = dynamicPtrCast<const PacketDissector::ProtocolDataUnit>(chunk))
printPacketInsideOut(childLevel, options, context);
else {
auto& protocolPrinter = getProtocolPrinter(protocol);
ProtocolPrinter::Context protocolContext;
protocolPrinter.print(chunk, protocol, options, protocolContext);
if (protocolDataUnit->getLevel() > context.infoLevel) {
context.infoLevel = protocolDataUnit->getLevel();
printSourceColumn(protocolContext.sourceColumn.str(), protocol, options, context);
printDestinationColumn(protocolContext.destinationColumn.str(), protocol, options, context);
printProtocolColumn(protocol, options, context);
// prepend info column
bool showAutoInfo = isEnabledOption(options, "Show auto info");
bool showInnermostInfo = isEnabledOption(options, "Show innermost info");
if (showAutoInfo || showInnermostInfo || isEnabledInfo(options, protocol)) {
if (showInnermostInfo && !(showAutoInfo && protocol == nullptr)) {
context.typeColumn.str("");
context.infoColumn.str("");
}
if (protocolContext.typeColumn.str().length() != 0) {
if (context.typeColumn.str().length() != 0)
protocolContext.typeColumn << " | ";
context.typeColumn.str(protocolContext.typeColumn.str() + context.typeColumn.str());
}
if (protocolContext.infoColumn.str().length() != 0) {
if (context.infoColumn.str().length() != 0)
protocolContext.infoColumn << " | ";
context.infoColumn.str(protocolContext.infoColumn.str() + context.infoColumn.str());
}
}
}
}
}
}
void PacketPrinter::printPacketLeftToRight(const Ptr<const PacketDissector::ProtocolDataUnit>& protocolDataUnit, const Options *options, Context& context) const
{
auto protocol = protocolDataUnit->getProtocol();
context.isCorrect &= protocolDataUnit->isCorrect();
printLengthColumn(protocolDataUnit, options, context);
for (const auto& chunk : protocolDataUnit->getChunks()) {
if (auto childLevel = dynamicPtrCast<const PacketDissector::ProtocolDataUnit>(chunk))
printPacketLeftToRight(childLevel, options, context);
else {
auto& protocolPrinter = getProtocolPrinter(protocol);
ProtocolPrinter::Context protocolContext;
protocolPrinter.print(chunk, protocol, options, protocolContext);
if (protocolDataUnit->getLevel() > context.infoLevel) {
context.infoLevel = protocolDataUnit->getLevel();
printSourceColumn(protocolContext.sourceColumn.str(), protocol, options, context);
printDestinationColumn(protocolContext.destinationColumn.str(), protocol, options, context);
printProtocolColumn(protocol, options, context);
}
// append info column
if (isEnabledInfo(options, protocol)) {
if (context.typeColumn.str().length() != 0)
context.typeColumn << " | ";
context.typeColumn << protocolContext.typeColumn.str();
if (context.infoColumn.str().length() != 0)
context.infoColumn << " | ";
context.infoColumn << protocolContext.infoColumn.str();
}
}
}
}
void PacketPrinter::printSourceColumn(const std::string source, const Protocol *protocol, const Options *options, Context& context) const
{
if (source.length() != 0) {
bool concatenate = isEnabledOption(options, "Show all PDU source fields") ||
(isEnabledOption(options, "Show auto source fields") && !(protocol && protocol->getLayer() == Protocol::NetworkLayer));
if (!concatenate)
context.sourceColumn.str("");
else if (context.sourceColumn.str().length() != 0)
context.sourceColumn << ":";
context.sourceColumn << source;
}
}
void PacketPrinter::printDestinationColumn(const std::string destination, const Protocol *protocol, const Options *options, Context& context) const
{
if (destination.length() != 0) {
bool concatenate = isEnabledOption(options, "Show all PDU destination fields") ||
(isEnabledOption(options, "Show auto destination fields") && !(protocol && protocol->getLayer() == Protocol::NetworkLayer));
if (!concatenate)
context.destinationColumn.str("");
else if (context.destinationColumn.str().length() != 0)
context.destinationColumn << ":";
context.destinationColumn << destination;
}
}
void PacketPrinter::printProtocolColumn(const Protocol *protocol, const Options *options, Context& context) const
{
if (protocol != nullptr) {
if (!isEnabledOption(options, "Show all PDU protocols"))
context.protocolColumn.str("");
else if (context.protocolColumn.str().length() != 0)
context.protocolColumn << ", ";
context.protocolColumn << protocol->getDescriptiveName();
}
}
void PacketPrinter::printLengthColumn(const Ptr<const PacketDissector::ProtocolDataUnit>& protocolDataUnit, const Options *options, Context& context) const
{
auto lengthColumnLength = context.lengthColumn.str().length();
if (lengthColumnLength == 0 || isEnabledOption(options, "Show all PDU lengths")) {
if (lengthColumnLength != 0)
context.lengthColumn << ", ";
context.lengthColumn << protocolDataUnit->getChunkLength();
}
}
} // namespace
| 43.421788 | 160 | 0.662592 | [
"vector"
] |
6935eeffd01e13861dd6f8d409af868fcf2a769c | 4,951 | cpp | C++ | src/loop064.cpp | TannerRogalsky/Demoloops | 13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5 | [
"MIT"
] | 4 | 2016-11-07T12:50:14.000Z | 2020-04-30T19:48:05.000Z | src/loop064.cpp | TannerRogalsky/Demoloops | 13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5 | [
"MIT"
] | 1 | 2017-04-17T12:00:16.000Z | 2017-04-17T12:00:16.000Z | src/loop064.cpp | TannerRogalsky/Demoloops | 13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5 | [
"MIT"
] | null | null | null | #include "demoloop.h"
#include "graphics/shader.h"
#include "helpers.h"
#include <glm/gtx/rotate_vector.hpp>
#include <array>
#include <tuple>
using namespace std;
using namespace demoloop;
const uint32_t CYCLE_LENGTH = 10;
const static std::string shaderCode = R"===(
uniform mediump float uTime;
#ifdef VERTEX
uniform sampler2D _tex0_;
vec4 position(mat4 transform_proj, mat4 model, vec4 vertpos) {
vec4 tex = texture2D(_tex0_, VertexTexCoord.st);
return transform_proj * model * vec4(tex.rgb - vec3(.5, .5, .5), 1.);
// vec4 tex = texture2D(_tex0_, VertexTexCoord.st);
// vec4 tex2 = texture2D(_tex0_, fract(tex.rb + uTime));
// return transform_proj * model * vec4(tex2.rgb - vec3(.5, .5, .5), 1.);
// return transform_proj * model * vertpos;
}
#endif
#ifdef PIXEL
vec4 effect(vec4 color, Image texture, vec2 tc, vec2 screen_coords) {
vec4 tex = texture2D(texture, fract(tc + uTime));
float a = .13;
// a = 1.0;
// return vec4(tex.rgb * 1.5, a + (1.0 - pow(sin(uTime * 5000), 2.0) * a));
return vec4(tex.rgb * 1.5, a);
}
#endif
)===";
template<size_t slices, size_t stacks>
tuple<array<Vertex, (stacks + 1) * (slices + 1)>, array<uint32_t, stacks * slices * 6>>
parametric(std::function<Vertex(float, float, uint32_t, uint32_t)> func) {
array<Vertex, (stacks + 1) * (slices + 1)> vertices;
uint32_t index = 0;
const uint32_t sliceCount = slices + 1;
for (uint32_t i = 0; i <= stacks; ++i) {
const float v = static_cast<float>(i) / stacks;
for (uint32_t j = 0; j <= slices; ++j) {
const float u = static_cast<float>(j) / slices;
vertices[index++] = func(u, v, slices, stacks);
}
}
printf("%u\n", index);
array<uint32_t, stacks * slices * 6> indices;
index = 0;
for (uint32_t i = 0; i < stacks; ++i) {
for (uint32_t j = 0; j < slices; ++j) {
const uint32_t a = i * sliceCount + j;
const uint32_t b = i * sliceCount + j + 1;
const uint32_t c = (i + 1) * sliceCount + j;
const uint32_t d = (i + 1) * sliceCount + j + 1;
// faces one and two
indices[index++] = c;
indices[index++] = a;
indices[index++] = b;
indices[index++] = c;
indices[index++] = d;
indices[index++] = b;
}
}
printf("%u\n", index);
return {vertices, indices};
}
function<Vertex(float, float, uint32_t, uint32_t)> plane(float width, float height) {
return [width, height](float u, float v, uint32_t /*stacks*/, uint32_t /*slices*/) {
return Vertex(
(u - 0.5) * width, (1 - v - 0.5) * height, 0,
u * 1, v * 1,
255, 255, 255, 255
);
};
}
class Loop055 : public Demoloop {
public:
Loop055() : Demoloop(CYCLE_LENGTH, 720, 720, 0, 0, 0), shader({shaderCode, shaderCode}), offset(rand()) {
// glDisable(GL_DEPTH_TEST);
glm::mat4 perspective = glm::perspective(static_cast<float>(DEMOLOOP_M_PI) / 4.0f, (float)width / (float)height, 0.1f, 100.0f);
gl.getProjection() = perspective;
noiseTexture = loadTexture("loop064/rgb-perlin-seamless-512.png");
// planeMesh(plane(0.2, 0.2, 10, 10))
auto [vertices, indices] = parametric<128, 128>(plane(0.2, 0.2));
gl.bufferVertices(vertices.data(), vertices.size(), GL_STATIC_DRAW);
gl.bufferIndices(indices.data(), indices.size(), GL_STATIC_DRAW);
indicesCount = indices.size();
// gl.bufferVertices(planeMesh.mVertices.data(), planeMesh.mVertices.size(), GL_STATIC_DRAW);
// gl.bufferIndices(planeMesh.mIndices.data(), planeMesh.mIndices.size(), GL_STATIC_DRAW);
gl.useVertexAttribArrays(ATTRIBFLAG_POS | ATTRIBFLAG_TEXCOORD);
glVertexAttribPointer(ATTRIB_POS, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, x));
glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*) offsetof(Vertex, s));
}
~Loop055() {
}
void Update() {
const float cycle_ratio = getCycleRatio();
// const float eyeRot = 0;
const float eyeRot = cycle_ratio * DEMOLOOP_M_PI * 2;
const glm::vec3 eye = glm::rotate(glm::vec3(0, 0, 1), eyeRot, glm::vec3(-0.3, 1, 0));
// const glm::vec3 eye = glm::rotate(glm::vec3(0, 4, 40), eyeRot, glm::vec3(-0.3, 1, 0));
const glm::vec3 up = glm::vec3(0, 1, 0);
const glm::vec3 target = glm::vec3(0, 0, 0);
glm::mat4 camera = glm::lookAt(eye, target, up);
GL::TempTransform t1(gl);
t1.get() = camera;
shader.attach();
{
// float uTime = powf(sinf(cycle_ratio * DEMOLOOP_M_PI), 2) / 350 + offset / static_cast<float>(RAND_MAX);
shader.sendFloat("uTime", 1, &cycle_ratio, 1);
}
gl.prepareDraw();
// gl.drawElements(GL_TRIANGLES, indicesCount, GL_UNSIGNED_INT, 0);
gl.drawElements(GL_LINE_STRIP, indicesCount, GL_UNSIGNED_INT, 0);
shader.detach();
}
private:
Shader shader;
size_t indicesCount;
GLuint noiseTexture;
const int offset;
};
int main(int, char**){
srand(time(0)); rand();
Loop055 test;
test.Run();
return 0;
}
| 29.470238 | 131 | 0.635427 | [
"model"
] |
6935f7f1a73138cd9b07e763da26b29dbd29d369 | 5,381 | cpp | C++ | ImageSearchingGoogle/src/ofApp.cpp | emodz/DM-GY-9103-Advanced-Creative-Coding | b1298ed6b0f067715437e51ca5e8f99b95ace01a | [
"MIT"
] | 29 | 2018-01-26T00:34:06.000Z | 2022-02-15T18:51:49.000Z | ImageSearchingGoogle/src/ofApp.cpp | emodz/DM-GY-9103-Advanced-Creative-Coding | b1298ed6b0f067715437e51ca5e8f99b95ace01a | [
"MIT"
] | 2 | 2018-02-16T00:50:17.000Z | 2018-02-16T01:15:34.000Z | ImageSearchingGoogle/src/ofApp.cpp | emodz/DM-GY-9103-Advanced-Creative-Coding | b1298ed6b0f067715437e51ca5e8f99b95ace01a | [
"MIT"
] | 11 | 2018-01-26T00:08:46.000Z | 2019-05-30T05:15:15.000Z | #include "ofApp.h"
//Adapted from the Regular Expressions Example by @Kevin Siwoff
// we need to include the standard regex library
#include <regex>
// Some explanation on regular expressions
// http://gnosis.cx/publish/programming/regular_expressions.html
// more info
// http://www.regular-expressions.info/reference.html
//--------------------------------------------------------------
void ofApp::setup() {
ofBackground(250);
page = 0;
searchPhrase = "storage unit";
searchGoogleImages(searchPhrase);
searchPhrase.clear();//clear our search phrase so we can type a new phrase
ofSetRectMode(OF_RECTMODE_CENTER);
}
//--------------------------------------------------------------
void ofApp::searchGoogleImages( string term ) {
// clear old imges
images.clear();
urls.clear();
// create the google url string
ofStringReplace(term, " ", "%20");
ofLogNotice() << term << endl;
string googleImgURL = "http://www.google.com/search?q="+term+"&tbm=isch&oq="+term+"&tbs=isz&&start="+ofToString(page);
cout << "searching for " << googleImgURL << endl;
ofHttpResponse res = ofLoadURL(googleImgURL);
if(res.status > 0) {
ofLogNotice() << "success response" << endl;
// copy over the response date fromt the url load
rawData = res.data.getText();
//uncomment to see raw data response from google images
//ofLogNotice() << rawData << endl;
// We start our scrape by matching all content within the div#ires
// want to get the content in the div using
// a regular expression match and subgroup
string imgResultsPattern = ".*\"ires\">(.*)<div id=\"foot\">.*";
regex regEx(imgResultsPattern, std::regex::extended);
smatch m;
if( regex_match(rawData, m, regEx) ){
//we want the second element in m because it contains our subgroup
string imageResultsStr = m[1];
smatch img;
regex imgPattern("src=\"([^> | ^\"]*)\"");
//once we've matched our outer content, we can
//search for all of the image tags containg src attributes
while(regex_search(imageResultsStr, img, imgPattern)){
//push the image src onto our urls vector
urls.push_back(img[1].str());
//regex_search will return one result at a time. To iterate our regex_search
//replace the string we are searching with the unsearched content
imageResultsStr = img.suffix().str();
}
}
}
// load all the images
for (unsigned int i=0; i<urls.size(); i++) {
images.push_back(URLImage());
images.back().url = urls[i];
images.back().bDoneLoading = false;
}
// just clean up for rendering to screen
ofStringReplace(rawData, "\n", "");
ofStringReplace(rawData, " ", "");
ofStringReplace(rawData, "\t", "");
string str;
for (unsigned int i=0; i<rawData.size(); i++) {
str += rawData[i];
if(i%40==39) str+="\n";
}
rawData = str.substr(0, 2000)+"...";
}
//--------------------------------------------------------------
void ofApp::update(){
for(unsigned int i=0; i<images.size(); i++) {
if(!images[i].bDoneLoading) {
images[i].load(images[i].url);
images[i].bDoneLoading = true;
break;
}
}
}
//--------------------------------------------------------------
void ofApp::draw() {
//draw our search phrase in the top left corner
ofDrawBitmapString(searchPhrase, 20.0f, 20.0f);
//ofPushMatrix();
// draw the images
ofTranslate(ofGetWidth()*0.5f, ofGetHeight()*0.5f);
ofScale(4.0);
for(unsigned int i=0; i<images.size(); i++) {
ofSetColor(255);
//check that the image is done loading
//so we don't draw an unallocated texture
if(images[i].bDoneLoading){
images[i].draw(0,0);
}
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if(key == OF_KEY_DEL || key == OF_KEY_BACKSPACE){
searchPhrase = searchPhrase.substr(0, searchPhrase.length()-1);
}
else if(key == OF_KEY_RETURN){
page += 22;
searchGoogleImages(searchPhrase);
searchPhrase.clear();
} else {
//we append our key character to the string searchPhrase
ofUTF8Append(searchPhrase,key);
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 27.880829 | 119 | 0.524438 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.