text string | size int64 | token_count int64 |
|---|---|---|
/* Copyright 2014 Gareth Cross, 2018-2019 TomTom N.V.
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 "OgreTile.h"
#include <string>
namespace
{
/**
* Convert any QImage to a 24bit RGB QImage
*/
QImage convertImage(QImage image)
{
return image.convertToFormat(QImage::Format_RGB888).mirrored();
}
/**
* Generate a different texture name each call
*/
std::string uniqueTextureName()
{
static int count = 0;
++count;
return "satellite_texture_" + std::to_string(count);
}
/**
* Create a Ogre::Texture on the GPU using a QImage
*/
Ogre::TexturePtr textureFromImage(QImage image)
{
Ogre::DataStreamPtr data_stream;
data_stream.bind(new Ogre::MemoryDataStream((void*)image.constBits(), image.byteCount()));
Ogre::String const res_group = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;
Ogre::TextureManager& texture_manager = Ogre::TextureManager::getSingleton();
// swap byte order when going from QImage to Ogre
return texture_manager.loadRawData(uniqueTextureName(), res_group, data_stream, image.width(), image.height(),
Ogre::PF_B8G8R8, Ogre::TEX_TYPE_2D, 0);
}
} // namespace
OgreTile::OgreTile(QImage image_) : texture(textureFromImage(convertImage(std::move(image_))))
{
}
| 1,743 | 570 |
#include "comparison.h"
#include <iostream>
using namespace std;
int main(int argc, char * argv[])
{
if (argc < 6)
{
cerr << "Expected arguments: root-dir1 file1 root-dir2 file2 type [--binary]" << endl;
cerr << "Use '.' for <type> to compare all messages and enums in given files." << endl;
return 1;
}
Comparison::Options options;
if (argc > 6)
{
for (int i = 6; i < argc; ++i)
{
string arg = argv[i];
if (arg == "--binary")
{
options.binary = true;
}
else
{
cerr << "Unknown option: " << arg << endl;
return 1;
}
}
}
Comparison comparison(options);
try
{
Source source1(argv[2], argv[1]);
Source source2(argv[4], argv[3]);
string message_name = argv[5];
if (message_name == ".")
comparison.compare(source1, source2);
else
comparison.compare(source1, message_name, source2, message_name);
}
catch(std::exception & e)
{
cerr << e.what() << endl;
return 1;
}
comparison.root.trim();
comparison.root.print();
return 0;
}
| 1,258 | 399 |
#include "json.hpp"
#include <fstream>
#include <iostream>
int main()
{
std::ifstream ifs("c_cpp_properties.json"); //input filestream to read
nlohmann::json data; //json object
ifs >> data; //.json file into data object
std::cout << data["configurations"][0]["compilerPath"] << std::endl;
std::cout << data["configurations"][0]["intelliSenseMode"] << std::endl;
data["configurations"][0]["cppStandard"] = "c++11";
std::ofstream ofs("c_cpp_properties_edited.json"); //output filestream to write
ofs << std::setw(4) << data;
return 0;
}
| 630 | 210 |
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include "Thread.hpp"
#include "Object.hpp"
#include "System.hpp"
#include "Barrier.hpp"
#include "ByteArrayReader.hpp"
using namespace obotcha;
extern void testReadline();
extern void basetest();
extern void testByteArrayLittleEndian();
extern void testByteArrayBigEndian();
extern void testReaderArray();
int main() {
testReaderArray();
testByteArrayLittleEndian();
testByteArrayBigEndian();
testReadline();
//basetest();
}
| 511 | 175 |
#include <iostream>
#include <future>
#include <exception>
#include <stdexcept>
using namespace std;
int calculate()
{
throw runtime_error("Exception thrown from calculate().");
}
int main()
{
// Use the launch::async policy to force asynchronous execution.
auto myFuture = async(launch::async, calculate);
// Do some more work...
// Get the result.
try {
int result = myFuture.get();
cout << result << endl;
} catch (const exception& ex) {
cout << "Caught exception: " << ex.what() << endl;
}
return 0;
}
| 556 | 181 |
// Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net
// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.
// This notice and the license may not be removed or altered from any source distribution.
#ifdef TWO_MODULES
module;
#include <infra/Cpp20.h>
module TWO(ecs);
#else
#include <type/Indexer.h>
#include <type/Proto.h>
#include <ecs/Complex.h>
#endif
namespace two
{
Complex::Complex(uint32_t id, Type& type)
: m_id(index(type, id, Ref(this, type)))
, m_type(type)
, m_prototype(proto(type))
, m_parts(m_prototype.m_parts.size())
{}
Complex::Complex(uint32_t id, Type& type, span<Ref> parts)
: Complex(id, type)
{
this->setup(parts);
}
Complex::~Complex()
{
unindex(m_type, m_id);
}
void Complex::setup(span<Ref> parts)
{
for(Ref ref : parts)
this->add_part(ref);
}
}
| 848 | 368 |
#include <iostream>
#include <string>
// For External Library
#include <torch/torch.h>
// For Original Header
#include "loss.hpp"
#include "losses.hpp"
// -----------------------------------
// class{Loss} -> constructor
// -----------------------------------
Loss::Loss(const std::string loss){
if (loss == "l1"){
this->judge = 0;
}
else if (loss == "l2"){
this->judge = 1;
}
else{
std::cerr << "Error : The loss fuction isn't defined right." << std::endl;
std::exit(1);
}
}
// -----------------------------------
// class{Loss} -> operator
// -----------------------------------
torch::Tensor Loss::operator()(torch::Tensor &input, torch::Tensor &target){
if (this->judge == 0){
static auto criterion = torch::nn::L1Loss(torch::nn::L1LossOptions().reduction(torch::kMean));
return criterion(input, target);
}
static auto criterion = torch::nn::MSELoss(torch::nn::MSELossOptions().reduction(torch::kMean));
return criterion(input, target);
}
| 1,035 | 343 |
#include "Ideas.h"
#include "IdeaGroup.h"
#include "IdeaUpdaters.h"
#include "Log.h"
#include "ParserHelpers.h"
#include <fstream>
HoI4::Ideas::Ideas() noexcept
{
importIdeologicalIdeas();
importGeneralIdeas();
}
void HoI4::Ideas::importIdeologicalIdeas()
{
registerRegex(commonItems::catchallRegex, [this](const std::string& ideology, std::istream& theStream) {
ideologicalIdeas.insert(make_pair(ideology, IdeaGroup(ideology, theStream)));
});
parseFile("ideologicalIdeas.txt");
clearRegisteredKeywords();
}
void HoI4::Ideas::importGeneralIdeas()
{
registerRegex(commonItems::catchallRegex, [this](const std::string& ideaGroupName, std::istream& theStream) {
generalIdeas.emplace_back(IdeaGroup{ideaGroupName, theStream});
});
parseFile("converterIdeas.txt");
clearRegisteredKeywords();
}
void HoI4::Ideas::updateIdeas(const std::set<std::string>& majorIdeologies)
{
Log(LogLevel::Info) << "\tUpdating ideas";
auto foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) {
return (theGroup.getName() == "mobilization_laws");
});
updateMobilizationLaws(*foundGroup, majorIdeologies);
foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) {
return (theGroup.getName() == "economy");
});
updateEconomyIdeas(*foundGroup, majorIdeologies);
foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) {
return (theGroup.getName() == "trade_laws");
});
updateTradeLaws(*foundGroup, majorIdeologies);
foundGroup = std::find_if(generalIdeas.begin(), generalIdeas.end(), [](auto& theGroup) {
return (theGroup.getName() == "country");
});
updateGeneralIdeas(*foundGroup, majorIdeologies);
} | 1,721 | 652 |
//
// Created by Felix Klauke on 29.03.18.
//
#include <RootNode.h>
#include <ClassNode.h>
#include <iostream>
#include <StatementNode.h>
#include <VarDeclarationNode.h>
#include <VarAssignNode.h>
#include <IntegerNode.h>
#include <FunctionCallNode.h>
#include <VarDeclarationAndInitializationNode.h>
#include "Parser.h"
Parser::Parser(const Lexer &lexer) : lexer(lexer) {
}
Node *Parser::parse() {
currentToken = lexer.ReadNextToken();
std::vector<Node *> classNodes = std::vector<Node *>();
while (currentToken->GetTokenType() == TokenType::CLASS) {
ClassNode *classNode = ParseClass();
classNodes.push_back(classNode);
}
auto *rootNode = new RootNode(&classNodes);
std::cout << "Found root with " << classNodes.size() << " classes.";
return rootNode;
}
ClassNode *Parser::ParseClass() {
std::vector<FunctionNode *> functionNodes = std::vector<FunctionNode *>();
EatToken(TokenType::CLASS);
std::string className = currentToken->GetValue();
EatToken(TokenType::LABEL);
EatToken(TokenType::LEFT_CURLY_BRACE);
while (currentToken->GetTokenType() == TokenType::FUNCTION) {
FunctionNode *functionNode = ParseFunction();
functionNodes.push_back(functionNode);
}
EatToken(TokenType::RIGHT_CURLY_BRACE);
auto *classNode = new ClassNode(className, &functionNodes);
std::cout << "Found class " << className << " with " << functionNodes.size() << " functions." << std::endl;
return classNode;
}
void Parser::EatToken(TokenType type) {
if (currentToken->GetTokenType() == type) {
Token *token = lexer.ReadNextToken();
currentToken = token;
return;
}
throw std::invalid_argument("Unexpected token " + currentToken->GetValue());
}
FunctionNode *Parser::ParseFunction() {
EatToken(TokenType::FUNCTION);
std::string functionName = currentToken->GetValue();
EatToken(TokenType::FUNCTION_CALL);
EatToken(TokenType::LEFT_BRACE);
std::vector<Node *> parameters = std::vector<Node *>();
while (currentToken->GetTokenType() != TokenType::RIGHT_BRACE) {
parameters.push_back(ParseValue());
if (currentToken->GetTokenType() == TokenType::COMMA) {
EatToken(TokenType::COMMA);
}
}
EatToken(TokenType::RIGHT_BRACE);
EatToken(TokenType::LEFT_CURLY_BRACE);
std::vector<Node *> statements = std::vector<Node *>();
while (currentToken->GetTokenType() != TokenType::RIGHT_CURLY_BRACE) {
Node *statementNode = ParseStatement();
statements.push_back(statementNode);
}
EatToken(TokenType::RIGHT_CURLY_BRACE);
auto *functionNode = new FunctionNode(&functionName, &statements, ¶meters);
std::cout << "Found function " << functionName << " with " << statements.size() << " statements and "
<< parameters.size() << " parameters." << std::endl;
return functionNode;
}
Node *Parser::ParseStatement() {
if (currentToken->GetTokenType() == TokenType::INTEGER || currentToken->GetTokenType() == TokenType::STRING) {
return ParseVariableStatement();
} else if (currentToken->GetTokenType() == TokenType::FUNCTION_CALL) {
return ParseFunctionCall();
} else if (currentToken->GetTokenType() == TokenType::LABEL) {
return ParseVariableAssignStatement();
}
}
StatementNode *Parser::ParseVariableStatement() {
TokenType variableType = currentToken->GetTokenType();
EatToken(variableType);
std::string variableName = currentToken->GetValue();
EatToken(TokenType::LABEL);
if (currentToken->GetTokenType() == TokenType::ASSIGN) {
EatToken(TokenType::ASSIGN);
auto *variableStatement = new VarDeclarationAndInitializationNode(&variableName, variableType, ParseValue());
std::cout << "Found declared and assigned variable: " << variableName << "." << std::endl;
return variableStatement;
}
auto *variableStatement = new VarDeclarationNode(&variableName, variableType);
std::cout << "Found declared variable: " << variableName << "." << std::endl;
return variableStatement;
}
Node *Parser::ParseValue() {
if (currentToken->GetTokenType() == TokenType::INTEGER) {
IntegerNode *integerNode = new IntegerNode(std::stoi(currentToken->GetValue()));
EatToken(TokenType::INTEGER);
return integerNode;
}
}
Node *Parser::ParseFunctionCall() {
std::string functionName = currentToken->GetValue();
EatToken(TokenType::FUNCTION_CALL);
EatToken(TokenType::LEFT_BRACE);
std::vector<Node *> parameters = std::vector<Node *>();
while (currentToken->GetTokenType() != TokenType::RIGHT_BRACE) {
parameters.push_back(ParseValue());
if (currentToken->GetTokenType() == TokenType::COMMA) {
EatToken(TokenType::COMMA);
}
}
EatToken(TokenType::RIGHT_BRACE);
auto *functionCallNode = new FunctionCallNode(nullptr, ¶meters);
std::cout << "Found function call: " << functionName << " with " << parameters.size() << " parameters."
<< std::endl;
return functionCallNode;
}
Node *Parser::ParseVariableAssignStatement() {
std::string variableName = currentToken->GetValue();
EatToken(TokenType::LABEL);
EatToken(TokenType::ASSIGN);
auto *varAssignNode = new VarAssignNode(&variableName, ParseValue());
std::cout << "Found variable assign node: " << variableName << std::endl;
return varAssignNode;
}
| 5,495 | 1,659 |
#include <algorithm>
#include <cstdio>
using namespace std;
int H, M;
double a, b; // angles for the two hands
int main()
{
while (true) {
scanf("%d:%d", &H, &M);
if (H == 0 && M == 0) break;
a = H*30 + 1.0*M/2.0;
b = M*6;
double x = a - b;
double y = b - a;
if (x < 0) x += 360;
if (y < 0) y += 360;
printf("%.3lf\n", min(x, y));
}
return 0;
}
| 436 | 194 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/browser/cast_content_window.h"
namespace chromecast {
CastContentWindow::CastContentWindow(const CreateParams& params)
: delegate_(params.delegate) {}
CastContentWindow::~CastContentWindow() = default;
CastContentWindow::CreateParams::CreateParams() = default;
CastContentWindow::CreateParams::CreateParams(const CreateParams& other) =
default;
CastContentWindow::CreateParams::~CreateParams() = default;
void CastContentWindow::AddObserver(Observer* observer) {
observer_list_.AddObserver(observer);
}
void CastContentWindow::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
mojom::MediaControlUi* CastContentWindow::media_controls() {
return nullptr;
}
} // namespace chromecast
| 922 | 265 |
/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2022 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/gpu/texture_cache.h"
#include <algorithm>
#include <cstdint>
#include <utility>
#include "xenia/base/assert.h"
#include "xenia/base/clock.h"
#include "xenia/base/cvar.h"
#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/base/profiling.h"
#include "xenia/gpu/gpu_flags.h"
#include "xenia/gpu/register_file.h"
#include "xenia/gpu/texture_info.h"
#include "xenia/gpu/texture_util.h"
#include "xenia/gpu/xenos.h"
DEFINE_int32(
draw_resolution_scale_x, 1,
"Integer pixel width scale used for scaling the rendering resolution "
"opaquely to the game.\n"
"1, 2 and 3 may be supported, but support of anything above 1 depends on "
"the device properties, such as whether it supports sparse binding / tiled "
"resources, the number of virtual address bits per resource, and other "
"factors.\n"
"Various effects and parts of game rendering pipelines may work "
"incorrectly as pixels become ambiguous from the game's perspective and "
"because half-pixel offset (which normally doesn't affect coverage when "
"MSAA isn't used) becomes full-pixel.",
"GPU");
DEFINE_int32(
draw_resolution_scale_y, 1,
"Integer pixel width scale used for scaling the rendering resolution "
"opaquely to the game.\n"
"See draw_resolution_scale_x for more information.",
"GPU");
DEFINE_uint32(
texture_cache_memory_limit_soft, 384,
"Maximum host texture memory usage (in megabytes) above which old textures "
"will be destroyed.",
"GPU");
DEFINE_uint32(
texture_cache_memory_limit_soft_lifetime, 30,
"Seconds a texture should be unused to be considered old enough to be "
"deleted if texture memory usage exceeds texture_cache_memory_limit_soft.",
"GPU");
DEFINE_uint32(
texture_cache_memory_limit_hard, 768,
"Maximum host texture memory usage (in megabytes) above which textures "
"will be destroyed as soon as possible.",
"GPU");
DEFINE_uint32(
texture_cache_memory_limit_render_to_texture, 24,
"Part of the host texture memory budget (in megabytes) that will be scaled "
"by the current drawing resolution scale.\n"
"If texture_cache_memory_limit_soft, for instance, is 384, and this is 24, "
"it will be assumed that the game will be using roughly 24 MB of "
"render-to-texture (resolve) targets and 384 - 24 = 360 MB of regular "
"textures - so with 2x2 resolution scaling, the soft limit will be 360 + "
"96 MB, and with 3x3, it will be 360 + 216 MB.",
"GPU");
namespace xe {
namespace gpu {
TextureCache::TextureCache(const RegisterFile& register_file,
SharedMemory& shared_memory,
uint32_t draw_resolution_scale_x,
uint32_t draw_resolution_scale_y)
: register_file_(register_file),
shared_memory_(shared_memory),
draw_resolution_scale_x_(draw_resolution_scale_x),
draw_resolution_scale_y_(draw_resolution_scale_y) {
assert_true(draw_resolution_scale_x >= 1);
assert_true(draw_resolution_scale_x <= kMaxDrawResolutionScaleAlongAxis);
assert_true(draw_resolution_scale_y >= 1);
assert_true(draw_resolution_scale_y <= kMaxDrawResolutionScaleAlongAxis);
if (draw_resolution_scale_x > 1 || draw_resolution_scale_y > 1) {
constexpr uint32_t kScaledResolvePageDwordCount =
SharedMemory::kBufferSize / 4096 / 32;
scaled_resolve_pages_ =
std::unique_ptr<uint32_t[]>(new uint32_t[kScaledResolvePageDwordCount]);
std::memset(scaled_resolve_pages_.get(), 0,
kScaledResolvePageDwordCount * sizeof(uint32_t));
std::memset(scaled_resolve_pages_l2_, 0, sizeof(scaled_resolve_pages_l2_));
scaled_resolve_global_watch_handle_ = shared_memory.RegisterGlobalWatch(
ScaledResolveGlobalWatchCallbackThunk, this);
}
}
TextureCache::~TextureCache() {
DestroyAllTextures(true);
if (scaled_resolve_global_watch_handle_) {
shared_memory().UnregisterGlobalWatch(scaled_resolve_global_watch_handle_);
}
}
bool TextureCache::GetConfigDrawResolutionScale(uint32_t& x_out,
uint32_t& y_out) {
uint32_t config_x =
uint32_t(std::max(INT32_C(1), cvars::draw_resolution_scale_x));
uint32_t config_y =
uint32_t(std::max(INT32_C(1), cvars::draw_resolution_scale_y));
uint32_t clamped_x = std::min(kMaxDrawResolutionScaleAlongAxis, config_x);
uint32_t clamped_y = std::min(kMaxDrawResolutionScaleAlongAxis, config_y);
x_out = clamped_x;
y_out = clamped_y;
return clamped_x == config_x && clamped_y == config_y;
}
void TextureCache::ClearCache() { DestroyAllTextures(); }
void TextureCache::CompletedSubmissionUpdated(
uint64_t completed_submission_index) {
// If memory usage is too high, destroy unused textures.
uint64_t current_time = xe::Clock::QueryHostUptimeMillis();
// texture_cache_memory_limit_render_to_texture is assumed to be included in
// texture_cache_memory_limit_soft and texture_cache_memory_limit_hard, at 1x,
// so subtracting 1 from the scale.
uint32_t limit_scaled_resolve_add_mb =
cvars::texture_cache_memory_limit_render_to_texture *
(draw_resolution_scale_x() * draw_resolution_scale_y() - 1);
uint32_t limit_soft_mb =
cvars::texture_cache_memory_limit_soft + limit_scaled_resolve_add_mb;
uint32_t limit_hard_mb =
cvars::texture_cache_memory_limit_hard + limit_scaled_resolve_add_mb;
uint32_t limit_soft_lifetime =
cvars::texture_cache_memory_limit_soft_lifetime * 1000;
bool destroyed_any = false;
while (texture_used_first_ != nullptr) {
uint64_t total_host_memory_usage_mb =
(textures_total_host_memory_usage_ + ((UINT32_C(1) << 20) - 1)) >> 20;
bool limit_hard_exceeded = total_host_memory_usage_mb > limit_hard_mb;
if (total_host_memory_usage_mb <= limit_soft_mb && !limit_hard_exceeded) {
break;
}
Texture* texture = texture_used_first_;
if (texture->last_usage_submission_index() > completed_submission_index) {
break;
}
if (!limit_hard_exceeded &&
(texture->last_usage_time() + limit_soft_lifetime) > current_time) {
break;
}
if (!destroyed_any) {
destroyed_any = true;
// The texture being destroyed might have been bound in the previous
// submissions, and nothing has overwritten the binding yet, so completion
// of the submission where the texture was last actually used on the GPU
// doesn't imply that it's not bound currently. Reset bindings if
// any texture has been destroyed.
ResetTextureBindings();
}
// Remove the texture from the map and destroy it via its unique_ptr.
auto found_texture_it = textures_.find(texture->key());
assert_true(found_texture_it != textures_.end());
if (found_texture_it != textures_.end()) {
assert_true(found_texture_it->second.get() == texture);
textures_.erase(found_texture_it);
// `texture` is invalid now.
}
}
if (destroyed_any) {
COUNT_profile_set("gpu/texture_cache/textures", textures_.size());
}
}
void TextureCache::BeginSubmission(uint64_t new_submission_index) {
assert_true(new_submission_index > current_submission_index_);
current_submission_index_ = new_submission_index;
current_submission_time_ = xe::Clock::QueryHostUptimeMillis();
}
void TextureCache::BeginFrame() {
// In case there was a failure to create something in the previous frame, make
// sure bindings are reset so a new attempt will surely be made if the texture
// is requested again.
ResetTextureBindings();
}
void TextureCache::MarkRangeAsResolved(uint32_t start_unscaled,
uint32_t length_unscaled) {
if (length_unscaled == 0) {
return;
}
start_unscaled &= 0x1FFFFFFF;
length_unscaled = std::min(length_unscaled, 0x20000000 - start_unscaled);
if (IsDrawResolutionScaled()) {
uint32_t page_first = start_unscaled >> 12;
uint32_t page_last = (start_unscaled + length_unscaled - 1) >> 12;
uint32_t block_first = page_first >> 5;
uint32_t block_last = page_last >> 5;
auto global_lock = global_critical_region_.Acquire();
for (uint32_t i = block_first; i <= block_last; ++i) {
uint32_t add_bits = UINT32_MAX;
if (i == block_first) {
add_bits &= ~((UINT32_C(1) << (page_first & 31)) - 1);
}
if (i == block_last && (page_last & 31) != 31) {
add_bits &= (UINT32_C(1) << ((page_last & 31) + 1)) - 1;
}
scaled_resolve_pages_[i] |= add_bits;
scaled_resolve_pages_l2_[i >> 6] |= UINT64_C(1) << (i & 63);
}
}
// Invalidate textures. Toggling individual textures between scaled and
// unscaled also relies on invalidation through shared memory.
shared_memory().RangeWrittenByGpu(start_unscaled, length_unscaled, true);
}
uint32_t TextureCache::GuestToHostSwizzle(uint32_t guest_swizzle,
uint32_t host_format_swizzle) {
uint32_t host_swizzle = 0;
for (uint32_t i = 0; i < 4; ++i) {
uint32_t guest_swizzle_component = (guest_swizzle >> (3 * i)) & 0b111;
uint32_t host_swizzle_component;
if (guest_swizzle_component >= xenos::XE_GPU_TEXTURE_SWIZZLE_0) {
// Get rid of 6 and 7 values (to prevent host GPU errors if the game has
// something broken) the simple way - by changing them to 4 (0) and 5 (1).
host_swizzle_component = guest_swizzle_component & 0b101;
} else {
host_swizzle_component =
(host_format_swizzle >> (3 * guest_swizzle_component)) & 0b111;
}
host_swizzle |= host_swizzle_component << (3 * i);
}
return host_swizzle;
}
void TextureCache::RequestTextures(uint32_t used_texture_mask) {
const auto& regs = register_file();
if (texture_became_outdated_.exchange(false, std::memory_order_acquire)) {
// A texture has become outdated - make sure whether textures are outdated
// is rechecked in this draw and in subsequent ones to reload the new data
// if needed.
ResetTextureBindings();
}
// Update the texture keys and the textures.
uint32_t bindings_changed = 0;
uint32_t textures_remaining = used_texture_mask & ~texture_bindings_in_sync_;
uint32_t index = 0;
while (xe::bit_scan_forward(textures_remaining, &index)) {
uint32_t index_bit = UINT32_C(1) << index;
textures_remaining &= ~index_bit;
TextureBinding& binding = texture_bindings_[index];
const auto& fetch = regs.Get<xenos::xe_gpu_texture_fetch_t>(
XE_GPU_REG_SHADER_CONSTANT_FETCH_00_0 + index * 6);
TextureKey old_key = binding.key;
uint8_t old_swizzled_signs = binding.swizzled_signs;
BindingInfoFromFetchConstant(fetch, binding.key, &binding.swizzled_signs);
texture_bindings_in_sync_ |= index_bit;
if (!binding.key.is_valid) {
if (old_key.is_valid) {
bindings_changed |= index_bit;
}
binding.Reset();
continue;
}
uint32_t old_host_swizzle = binding.host_swizzle;
binding.host_swizzle =
GuestToHostSwizzle(fetch.swizzle, GetHostFormatSwizzle(binding.key));
// Check if need to load the unsigned and the signed versions of the texture
// (if the format is emulated with different host bit representations for
// signed and unsigned - otherwise only the unsigned one is loaded).
bool key_changed = binding.key != old_key;
bool any_sign_was_not_signed =
texture_util::IsAnySignNotSigned(old_swizzled_signs);
bool any_sign_was_signed =
texture_util::IsAnySignSigned(old_swizzled_signs);
bool any_sign_is_not_signed =
texture_util::IsAnySignNotSigned(binding.swizzled_signs);
bool any_sign_is_signed =
texture_util::IsAnySignSigned(binding.swizzled_signs);
if (key_changed || binding.host_swizzle != old_host_swizzle ||
any_sign_is_not_signed != any_sign_was_not_signed ||
any_sign_is_signed != any_sign_was_signed) {
bindings_changed |= index_bit;
}
bool load_unsigned_data = false, load_signed_data = false;
if (IsSignedVersionSeparateForFormat(binding.key)) {
// Can reuse previously loaded unsigned/signed versions if the key is the
// same and the texture was previously bound as unsigned/signed
// respectively (checking the previous values of signedness rather than
// binding.texture != nullptr and binding.texture_signed != nullptr also
// prevents repeated attempts to load the texture if it has failed to
// load).
if (any_sign_is_not_signed) {
if (key_changed || !any_sign_was_not_signed) {
binding.texture = FindOrCreateTexture(binding.key);
load_unsigned_data = true;
}
} else {
binding.texture = nullptr;
}
if (any_sign_is_signed) {
if (key_changed || !any_sign_was_signed) {
TextureKey signed_key = binding.key;
signed_key.signed_separate = 1;
binding.texture_signed = FindOrCreateTexture(signed_key);
load_signed_data = true;
}
} else {
binding.texture_signed = nullptr;
}
} else {
// Same resource for both unsigned and signed, but descriptor formats may
// be different.
if (key_changed) {
binding.texture = FindOrCreateTexture(binding.key);
load_unsigned_data = true;
}
binding.texture_signed = nullptr;
}
if (load_unsigned_data && binding.texture != nullptr) {
LoadTextureData(*binding.texture);
}
if (load_signed_data && binding.texture_signed != nullptr) {
LoadTextureData(*binding.texture_signed);
}
}
if (bindings_changed) {
UpdateTextureBindingsImpl(bindings_changed);
}
}
const char* TextureCache::TextureKey::GetLogDimensionName(
xenos::DataDimension dimension) {
switch (dimension) {
case xenos::DataDimension::k1D:
return "1D";
case xenos::DataDimension::k2DOrStacked:
return "2D";
case xenos::DataDimension::k3D:
return "3D";
case xenos::DataDimension::kCube:
return "cube";
default:
assert_unhandled_case(dimension);
return "unknown";
}
}
void TextureCache::TextureKey::LogAction(const char* action) const {
XELOGGPU(
"{} {} {}{}x{}x{} {} {} texture with {} {}packed mip level{}, "
"base at 0x{:08X} (pitch {}), mips at 0x{:08X}",
action, tiled ? "tiled" : "linear", scaled_resolve ? "scaled " : "",
GetWidth(), GetHeight(), GetDepthOrArraySize(), GetLogDimensionName(),
FormatInfo::Get(format)->name, mip_max_level + 1, packed_mips ? "" : "un",
mip_max_level != 0 ? "s" : "", base_page << 12, pitch << 5,
mip_page << 12);
}
void TextureCache::Texture::LogAction(const char* action) const {
XELOGGPU(
"{} {} {}{}x{}x{} {} {} texture with {} {}packed mip level{}, "
"base at 0x{:08X} (pitch {}, size 0x{:08X}), mips at 0x{:08X} (size "
"0x{:08X})",
action, key_.tiled ? "tiled" : "linear",
key_.scaled_resolve ? "scaled " : "", key_.GetWidth(), key_.GetHeight(),
key_.GetDepthOrArraySize(), key_.GetLogDimensionName(),
FormatInfo::Get(key_.format)->name, key_.mip_max_level + 1,
key_.packed_mips ? "" : "un", key_.mip_max_level != 0 ? "s" : "",
key_.base_page << 12, key_.pitch << 5, GetGuestBaseSize(),
key_.mip_page << 12, GetGuestMipsSize());
}
// The texture must be in the recent usage list. Place it in front now because
// after creation, the texture will likely be used immediately, and it should
// not be destroyed immediately after creation if dropping of old textures is
// performed somehow. The list is maintained by the Texture, not the
// TextureCache itself (unlike the `textures_` container).
TextureCache::Texture::Texture(TextureCache& texture_cache,
const TextureKey& key)
: texture_cache_(texture_cache),
key_(key),
guest_layout_(key.GetGuestLayout()),
base_resolved_(key.scaled_resolve),
mips_resolved_(key.scaled_resolve),
last_usage_submission_index_(texture_cache.current_submission_index_),
last_usage_time_(texture_cache.current_submission_time_),
used_previous_(texture_cache.texture_used_last_),
used_next_(nullptr) {
if (texture_cache.texture_used_last_) {
texture_cache.texture_used_last_->used_next_ = this;
} else {
texture_cache.texture_used_first_ = this;
}
texture_cache.texture_used_last_ = this;
// Never try to upload data that doesn't exist.
base_outdated_ = guest_layout().base.level_data_extent_bytes != 0;
mips_outdated_ = guest_layout().mips_total_extent_bytes != 0;
}
TextureCache::Texture::~Texture() {
if (mips_watch_handle_) {
texture_cache().shared_memory().UnwatchMemoryRange(mips_watch_handle_);
}
if (base_watch_handle_) {
texture_cache().shared_memory().UnwatchMemoryRange(base_watch_handle_);
}
if (used_previous_) {
used_previous_->used_next_ = used_next_;
} else {
texture_cache_.texture_used_first_ = used_next_;
}
if (used_next_) {
used_next_->used_previous_ = used_previous_;
} else {
texture_cache_.texture_used_last_ = used_previous_;
}
texture_cache_.UpdateTexturesTotalHostMemoryUsage(0, host_memory_usage_);
}
void TextureCache::Texture::MakeUpToDateAndWatch(
const std::unique_lock<std::recursive_mutex>& global_lock) {
SharedMemory& shared_memory = texture_cache().shared_memory();
if (base_outdated_) {
assert_not_zero(GetGuestBaseSize());
base_outdated_ = false;
base_watch_handle_ = shared_memory.WatchMemoryRange(
key().base_page << 12, GetGuestBaseSize(), TextureCache::WatchCallback,
this, nullptr, 0);
}
if (mips_outdated_) {
assert_not_zero(GetGuestMipsSize());
mips_outdated_ = false;
mips_watch_handle_ = shared_memory.WatchMemoryRange(
key().mip_page << 12, GetGuestMipsSize(), TextureCache::WatchCallback,
this, nullptr, 1);
}
}
void TextureCache::Texture::MarkAsUsed() {
// This is called very frequently, don't relink unless needed for caching.
if (last_usage_submission_index_ ==
texture_cache_.current_submission_index_) {
return;
}
last_usage_submission_index_ = texture_cache_.current_submission_index_;
last_usage_time_ = texture_cache_.current_submission_time_;
if (used_next_ == nullptr) {
// Already the most recently used.
return;
}
if (used_previous_ != nullptr) {
used_previous_->used_next_ = used_next_;
} else {
texture_cache_.texture_used_first_ = used_next_;
}
used_next_->used_previous_ = used_previous_;
used_previous_ = texture_cache_.texture_used_last_;
used_next_ = nullptr;
if (texture_cache_.texture_used_last_ != nullptr) {
texture_cache_.texture_used_last_->used_next_ = this;
}
texture_cache_.texture_used_last_ = this;
}
void TextureCache::Texture::WatchCallback(
[[maybe_unused]] const std::unique_lock<std::recursive_mutex>& global_lock,
bool is_mip) {
if (is_mip) {
assert_not_zero(GetGuestMipsSize());
mips_outdated_ = true;
mips_watch_handle_ = nullptr;
} else {
assert_not_zero(GetGuestBaseSize());
base_outdated_ = true;
base_watch_handle_ = nullptr;
}
}
void TextureCache::WatchCallback(
const std::unique_lock<std::recursive_mutex>& global_lock, void* context,
void* data, uint64_t argument, bool invalidated_by_gpu) {
Texture& texture = *static_cast<Texture*>(context);
texture.WatchCallback(global_lock, argument != 0);
texture.texture_cache().texture_became_outdated_.store(
true, std::memory_order_release);
}
void TextureCache::DestroyAllTextures(bool from_destructor) {
ResetTextureBindings(from_destructor);
textures_.clear();
COUNT_profile_set("gpu/texture_cache/textures", 0);
}
TextureCache::Texture* TextureCache::FindOrCreateTexture(TextureKey key) {
// Check if the texture is a scaled resolve texture.
if (IsDrawResolutionScaled() && key.tiled &&
IsScaledResolveSupportedForFormat(key)) {
texture_util::TextureGuestLayout scaled_resolve_guest_layout =
key.GetGuestLayout();
if ((scaled_resolve_guest_layout.base.level_data_extent_bytes &&
IsRangeScaledResolved(
key.base_page << 12,
scaled_resolve_guest_layout.base.level_data_extent_bytes)) ||
(scaled_resolve_guest_layout.mips_total_extent_bytes &&
IsRangeScaledResolved(
key.mip_page << 12,
scaled_resolve_guest_layout.mips_total_extent_bytes))) {
key.scaled_resolve = 1;
}
}
uint32_t host_width = key.GetWidth();
uint32_t host_height = key.GetHeight();
if (key.scaled_resolve) {
host_width *= draw_resolution_scale_x();
host_height *= draw_resolution_scale_y();
}
// With 3x resolution scaling, a 2D texture may become bigger than the
// Direct3D 11 limit, and with 2x, a 3D one as well.
// TODO(Triang3l): Skip mips on Vulkan in this case - the minimum requirement
// there is 4096, which is below the Xenos maximum texture size of 8192.
uint32_t max_host_width_height = GetMaxHostTextureWidthHeight(key.dimension);
uint32_t max_host_depth_or_array_size =
GetMaxHostTextureDepthOrArraySize(key.dimension);
if (host_width > max_host_width_height ||
host_height > max_host_width_height ||
key.GetDepthOrArraySize() > max_host_depth_or_array_size) {
return nullptr;
}
// Try to find an existing texture.
// TODO(Triang3l): Reuse a texture with mip_page unchanged, but base_page
// previously 0, now not 0, to save memory - common case in streaming.
auto found_texture_it = textures_.find(key);
if (found_texture_it != textures_.end()) {
return found_texture_it->second.get();
}
// Create the texture and add it to the map.
Texture* texture;
{
std::unique_ptr<Texture> new_texture = CreateTexture(key);
if (!new_texture) {
key.LogAction("Failed to create");
return nullptr;
}
assert_true(new_texture->key() == key);
texture =
textures_.emplace(key, std::move(new_texture)).first->second.get();
}
COUNT_profile_set("gpu/texture_cache/textures", textures_.size());
texture->LogAction("Created");
return texture;
}
bool TextureCache::LoadTextureData(Texture& texture) {
// Check what needs to be uploaded.
bool base_outdated, mips_outdated;
{
auto global_lock = global_critical_region_.Acquire();
base_outdated = texture.base_outdated(global_lock);
mips_outdated = texture.mips_outdated(global_lock);
}
if (!base_outdated && !mips_outdated) {
return true;
}
TextureKey texture_key = texture.key();
// Request uploading of the texture data to the shared memory.
// This is also necessary when resolution scaling is used - the texture cache
// relies on shared memory for invalidation of both unscaled and scaled
// textures. Plus a texture may be unscaled partially, when only a portion of
// its pages is invalidated, in this case we'll need the texture from the
// shared memory to load the unscaled parts.
// TODO(Triang3l): Load unscaled parts.
bool base_resolved = texture.GetBaseResolved();
if (base_outdated) {
if (!shared_memory().RequestRange(
texture_key.base_page << 12, texture.GetGuestBaseSize(),
texture_key.scaled_resolve ? nullptr : &base_resolved)) {
return false;
}
}
bool mips_resolved = texture.GetMipsResolved();
if (mips_outdated) {
if (!shared_memory().RequestRange(
texture_key.mip_page << 12, texture.GetGuestMipsSize(),
texture_key.scaled_resolve ? nullptr : &mips_resolved)) {
return false;
}
}
if (texture_key.scaled_resolve) {
// Make sure all the scaled resolve memory is resident and accessible from
// the shader, including any possible padding that hasn't yet been touched
// by an actual resolve, but is still included in the texture size, so the
// GPU won't be trying to access unmapped memory.
if (!EnsureScaledResolveMemoryCommitted(texture_key.base_page << 12,
texture.GetGuestBaseSize())) {
return false;
}
if (!EnsureScaledResolveMemoryCommitted(texture_key.mip_page << 12,
texture.GetGuestMipsSize())) {
return false;
}
}
// Actually load the texture data.
if (!LoadTextureDataFromResidentMemoryImpl(texture, base_outdated,
mips_outdated)) {
return false;
}
// Update the source of the texture (resolve vs. CPU or memexport) for
// purposes of handling piecewise gamma emulation via sRGB and for resolution
// scale in sampling offsets.
if (!texture_key.scaled_resolve) {
texture.SetBaseResolved(base_resolved);
texture.SetMipsResolved(mips_resolved);
}
// Mark the ranges as uploaded and watch them. This is needed for scaled
// resolves as well to detect when the CPU wants to reuse the memory for a
// regular texture or a vertex buffer, and thus the scaled resolve version is
// not up to date anymore.
texture.MakeUpToDateAndWatch(global_critical_region_.Acquire());
texture.LogAction("Loaded");
return true;
}
void TextureCache::BindingInfoFromFetchConstant(
const xenos::xe_gpu_texture_fetch_t& fetch, TextureKey& key_out,
uint8_t* swizzled_signs_out) {
// Reset the key and the signedness.
key_out.MakeInvalid();
if (swizzled_signs_out != nullptr) {
*swizzled_signs_out =
uint8_t(xenos::TextureSign::kUnsigned) * uint8_t(0b01010101);
}
switch (fetch.type) {
case xenos::FetchConstantType::kTexture:
break;
case xenos::FetchConstantType::kInvalidTexture:
if (cvars::gpu_allow_invalid_fetch_constants) {
break;
}
XELOGW(
"Texture fetch constant ({:08X} {:08X} {:08X} {:08X} {:08X} {:08X}) "
"has \"invalid\" type! This is incorrect behavior, but you can try "
"bypassing this by launching Xenia with "
"--gpu_allow_invalid_fetch_constants=true.",
fetch.dword_0, fetch.dword_1, fetch.dword_2, fetch.dword_3,
fetch.dword_4, fetch.dword_5);
return;
default:
XELOGW(
"Texture fetch constant ({:08X} {:08X} {:08X} {:08X} {:08X} {:08X}) "
"is completely invalid!",
fetch.dword_0, fetch.dword_1, fetch.dword_2, fetch.dword_3,
fetch.dword_4, fetch.dword_5);
return;
}
uint32_t width_minus_1, height_minus_1, depth_or_array_size_minus_1;
uint32_t base_page, mip_page, mip_max_level;
texture_util::GetSubresourcesFromFetchConstant(
fetch, &width_minus_1, &height_minus_1, &depth_or_array_size_minus_1,
&base_page, &mip_page, nullptr, &mip_max_level);
if (base_page == 0 && mip_page == 0) {
// No texture data at all.
return;
}
if (fetch.dimension == xenos::DataDimension::k1D) {
bool is_invalid_1d = false;
// TODO(Triang3l): Support long 1D textures.
if (width_minus_1 >= xenos::kTexture2DCubeMaxWidthHeight) {
XELOGE(
"1D texture is too wide ({}) - ignoring! Report the game to Xenia "
"developers",
width_minus_1 + 1);
is_invalid_1d = true;
}
assert_false(fetch.tiled);
if (fetch.tiled) {
XELOGE(
"1D texture has tiling enabled in the fetch constant, but this "
"appears to be completely wrong - ignoring! Report the game to Xenia "
"developers");
is_invalid_1d = true;
}
assert_false(fetch.packed_mips);
if (fetch.packed_mips) {
XELOGE(
"1D texture has packed mips enabled in the fetch constant, but this "
"appears to be completely wrong - ignoring! Report the game to Xenia "
"developers");
is_invalid_1d = true;
}
if (is_invalid_1d) {
return;
}
}
xenos::TextureFormat format = GetBaseFormat(fetch.format);
key_out.base_page = base_page;
key_out.mip_page = mip_page;
key_out.dimension = fetch.dimension;
key_out.width_minus_1 = width_minus_1;
key_out.height_minus_1 = height_minus_1;
key_out.depth_or_array_size_minus_1 = depth_or_array_size_minus_1;
key_out.pitch = fetch.pitch;
key_out.mip_max_level = mip_max_level;
key_out.tiled = fetch.tiled;
key_out.packed_mips = fetch.packed_mips;
key_out.format = format;
key_out.endianness = fetch.endianness;
key_out.is_valid = 1;
if (swizzled_signs_out != nullptr) {
*swizzled_signs_out = texture_util::SwizzleSigns(fetch);
}
}
void TextureCache::ResetTextureBindings(bool from_destructor) {
uint32_t bindings_reset = 0;
for (size_t i = 0; i < texture_bindings_.size(); ++i) {
TextureBinding& binding = texture_bindings_[i];
if (!binding.key.is_valid) {
continue;
}
binding.Reset();
bindings_reset |= UINT32_C(1) << i;
}
texture_bindings_in_sync_ &= ~bindings_reset;
if (!from_destructor && bindings_reset) {
UpdateTextureBindingsImpl(bindings_reset);
}
}
void TextureCache::UpdateTexturesTotalHostMemoryUsage(uint64_t add,
uint64_t subtract) {
textures_total_host_memory_usage_ =
textures_total_host_memory_usage_ - subtract + add;
COUNT_profile_set("gpu/texture_cache/total_host_memory_usage_mb",
uint32_t((textures_total_host_memory_usage_ +
((UINT32_C(1) << 20) - 1)) >>
20));
}
bool TextureCache::IsRangeScaledResolved(uint32_t start_unscaled,
uint32_t length_unscaled) {
if (!IsDrawResolutionScaled()) {
return false;
}
start_unscaled = std::min(start_unscaled, SharedMemory::kBufferSize);
length_unscaled =
std::min(length_unscaled, SharedMemory::kBufferSize - start_unscaled);
if (!length_unscaled) {
return false;
}
// Two-level check for faster rejection since resolve targets are usually
// placed in relatively small and localized memory portions (confirmed by
// testing - pretty much all times the deeper level was entered, the texture
// was a resolve target).
uint32_t page_first = start_unscaled >> 12;
uint32_t page_last = (start_unscaled + length_unscaled - 1) >> 12;
uint32_t block_first = page_first >> 5;
uint32_t block_last = page_last >> 5;
uint32_t l2_block_first = block_first >> 6;
uint32_t l2_block_last = block_last >> 6;
auto global_lock = global_critical_region_.Acquire();
for (uint32_t i = l2_block_first; i <= l2_block_last; ++i) {
uint64_t l2_block = scaled_resolve_pages_l2_[i];
if (i == l2_block_first) {
l2_block &= ~((UINT64_C(1) << (block_first & 63)) - 1);
}
if (i == l2_block_last && (block_last & 63) != 63) {
l2_block &= (UINT64_C(1) << ((block_last & 63) + 1)) - 1;
}
uint32_t block_relative_index;
while (xe::bit_scan_forward(l2_block, &block_relative_index)) {
l2_block &= ~(UINT64_C(1) << block_relative_index);
uint32_t block_index = (i << 6) + block_relative_index;
uint32_t check_bits = UINT32_MAX;
if (block_index == block_first) {
check_bits &= ~((UINT32_C(1) << (page_first & 31)) - 1);
}
if (block_index == block_last && (page_last & 31) != 31) {
check_bits &= (UINT32_C(1) << ((page_last & 31) + 1)) - 1;
}
if (scaled_resolve_pages_[block_index] & check_bits) {
return true;
}
}
}
return false;
}
void TextureCache::ScaledResolveGlobalWatchCallbackThunk(
const std::unique_lock<std::recursive_mutex>& global_lock, void* context,
uint32_t address_first, uint32_t address_last, bool invalidated_by_gpu) {
TextureCache* texture_cache = reinterpret_cast<TextureCache*>(context);
texture_cache->ScaledResolveGlobalWatchCallback(
global_lock, address_first, address_last, invalidated_by_gpu);
}
void TextureCache::ScaledResolveGlobalWatchCallback(
const std::unique_lock<std::recursive_mutex>& global_lock,
uint32_t address_first, uint32_t address_last, bool invalidated_by_gpu) {
assert_true(IsDrawResolutionScaled());
if (invalidated_by_gpu) {
// Resolves themselves do exactly the opposite of what this should do.
return;
}
// Mark scaled resolve ranges as non-scaled. Textures themselves will be
// invalidated by their shared memory watches.
uint32_t resolve_page_first = address_first >> 12;
uint32_t resolve_page_last = address_last >> 12;
uint32_t resolve_block_first = resolve_page_first >> 5;
uint32_t resolve_block_last = resolve_page_last >> 5;
uint32_t resolve_l2_block_first = resolve_block_first >> 6;
uint32_t resolve_l2_block_last = resolve_block_last >> 6;
for (uint32_t i = resolve_l2_block_first; i <= resolve_l2_block_last; ++i) {
uint64_t resolve_l2_block = scaled_resolve_pages_l2_[i];
uint32_t resolve_block_relative_index;
while (
xe::bit_scan_forward(resolve_l2_block, &resolve_block_relative_index)) {
resolve_l2_block &= ~(UINT64_C(1) << resolve_block_relative_index);
uint32_t resolve_block_index = (i << 6) + resolve_block_relative_index;
uint32_t resolve_keep_bits = 0;
if (resolve_block_index == resolve_block_first) {
resolve_keep_bits |= (UINT32_C(1) << (resolve_page_first & 31)) - 1;
}
if (resolve_block_index == resolve_block_last &&
(resolve_page_last & 31) != 31) {
resolve_keep_bits |=
~((UINT32_C(1) << ((resolve_page_last & 31) + 1)) - 1);
}
scaled_resolve_pages_[resolve_block_index] &= resolve_keep_bits;
if (scaled_resolve_pages_[resolve_block_index] == 0) {
scaled_resolve_pages_l2_[i] &=
~(UINT64_C(1) << resolve_block_relative_index);
}
}
}
}
} // namespace gpu
} // namespace xe
| 34,293 | 11,844 |
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "PCSTree.h"
#include "PCSNode.h"
// constructor
PCSTree::PCSTree()
{
info.maxLevelCount = 0;
info.maxNodeCount = 0;
info.numLevels = 0;
info.numNodes = 0;
root = NULL;
};
// destructor
PCSTree::~PCSTree()
{
// printf("PCSTree: destructor()\n");
};
// get Root
PCSNode *PCSTree::getRoot( void ) const
{
return (PCSNode *)root;
}
// insert
void PCSTree::insert(PCSNode *inNode, PCSNode *parent)
{
if (this->getRoot() != 0) // if tree has a root already
{
inNode->setParent(parent); // set node's parent to specified parent.
inNode->setLevel((inNode->getParent()->getLevel()) + 1);
if (parent->getChild() != 0) // if parent node has children, add it as first sibling on list.
{ // store first sibling as tmp, add node as parent's child, adjust sibling list
PCSNode *tmp = parent->getChild();
parent->setChild(inNode);
inNode->setSibling(tmp);
}
else // if that parent node has no children, make it a child.
{
parent->setChild(inNode); // set parents node child to inNode
}
}
else // tree has no root. it is now the root. forget your parent specifier.
{
root = inNode; // make root the first node
inNode->setParent(NULL); // set the node's parent to null. its now the root.
inNode->setLevel(1);
}
checkLevels(inNode);
info.maxNodeCount++;
info.numNodes++;
}
// Remove
// super easy process. just remove its link from the parent and make sure siblings to left link to the right
void PCSTree::remove(PCSNode * const inNode)
{
// make sure inNode is NOT the root. if it is the root, just zero out all its stats.
if (inNode != root)
{
// check to see if inNode is NOT the only child.
if (inNode->getParent()->getChild() != inNode || inNode->getSibling())
{
// first case, its a "first child". set the parent's first child to the next child in line.
if (inNode->getParent()->getChild() == inNode)
{
inNode->getParent()->setChild( inNode->getSibling() );
}
// second case, its the "middle" or "youngest". find previous sibling point.
else
{
PCSNode *tmp = inNode->getParent()->getChild(); // create temp node to find previous child
while (tmp->getSibling() != inNode)
tmp = tmp->getSibling(); // move temp node to position right before child
// youngest
if (inNode->getSibling() == NULL)
tmp->setSibling(NULL); // set final sibling to null
// middle
else
tmp->setSibling(inNode->getSibling()); // link inNode's previous sibling to its next sibling.
}
}
// inNode is only child. just tell parent that it has no children.
else
inNode->getParent()->setChild(NULL);
}
else
root = NULL;
// set everything derived from inNode (children and their siblings, etc) to 0
if (inNode->getChild())
removeDown(inNode->getChild());
// clean up inNode links to 0
inNode->setChild(NULL);
inNode->setParent(NULL);
inNode->setSibling(NULL);
// update info
info.numNodes--;
}
// get tree info
void PCSTree::getInfo( PCSTreeInfo &infoContainer )
{
info.numLevels = 0;
PCSNode *travelTree = root;
if (travelTree != NULL) // if it isn't a null pointer, check the depth of the tree.
{
goDown(travelTree);
}
infoContainer.maxLevelCount = info.maxLevelCount;
infoContainer.maxNodeCount = info.maxNodeCount;
infoContainer.numLevels = info.numLevels;
infoContainer.numNodes = info.numNodes;
}
void PCSTree::dumpTree( ) const
{
if (root)
{
printf("\ndumpTree() ----------------");
root->printDown(root);
}
}
// this function is called just once to check the levels with getInfo().
void PCSTree::goDown( const PCSNode* const _root )
{
if (_root->getChild() != NULL) // if root has a child, go down again.
{
goDown(_root->getChild());
}
checkLevels(_root); // check levels for that tree
if (_root->getSibling() != NULL) // now traverse siblings.
{
goDown(_root->getSibling());
}
}
// this deletes all children below a specified original root. basically the same as goDown, but calls remove function.
// at its final iteration, it is always at the final sibling, so it zeroes everything out.
void PCSTree::removeDown( PCSNode * const _root )
{
if (_root->getChild() != NULL) // if root has a child, go down again.
{
removeDown(_root->getChild());
}
if (_root->getSibling() != NULL) // now traverse siblings.
{
removeDown(_root->getSibling());
}
// zero out current node
_root->setChild(NULL);
_root->setParent(NULL);
_root->setSibling(NULL);
// update info
info.numNodes--;
}
// this is a function that just checks the number of levels away from the root any given node is.
void PCSTree::checkLevels( const PCSNode * const inNode )
{
if (inNode->getLevel() > info.maxLevelCount) // if current level is greater than max, increase max
info.maxLevelCount = inNode->getLevel();
if (inNode->getLevel() > info.numLevels) // if current level is greater than recorded levels, increase recorded levels
info.numLevels = inNode->getLevel();
} | 5,050 | 1,865 |
#include <stdio.h>
#include <iostream>
#include "./Civilization.hpp"
#ifndef BUBBLE
#define BUBBLE
namespace Emperor2
{
class Bubble
{
public:
Civilization *BubbleSort(Civilization *civilizations, int numberOfCivilizations);
};
} // namespace Emperor2
#endif | 282 | 95 |
// Copyright (c) 2015 Gregor Klinke
// All rights reserved.
#pragma once
#include "fo.hpp"
#include <iterator>
#include <memory>
#include <string>
#include <vector>
namespace eyestep {
class SosofoIterator;
class Sosofo
{
public:
/*! Creates an empty sosofo */
Sosofo();
Sosofo(const Sosofo& one, const Sosofo& two);
Sosofo(const std::vector<Sosofo>& sosofos);
/*! Creates a sosofo with exactly one formatting object */
Sosofo(std::shared_ptr<IFormattingObject> fo);
Sosofo(const std::string& label, std::shared_ptr<IFormattingObject> fo);
/*! Returns a new sosofo with all FOs from @p other appended */
Sosofo concat(const Sosofo& other) const;
void set_label(const std::string& lbl) {
_label = lbl;
}
const std::string& label() const {
return _label;
}
bool empty() const {
return _fos.empty();
}
int length() const {
return int(_fos.size());
}
const IFormattingObject* operator[](size_t idx) const {
return _fos[idx].get();
}
SosofoIterator begin() const;
SosofoIterator end() const;
private:
std::string _label;
std::vector<std::shared_ptr<IFormattingObject>> _fos;
};
class SosofoIterator
{
const Sosofo* _sosofo = nullptr;
int _idx = 0;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = const IFormattingObject;
using difference_type = std::ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
/*! the end iterator */
SosofoIterator() = default;
SosofoIterator(const Sosofo* sosofo, int idx)
: _sosofo(sosofo)
, _idx(idx) {
if (_idx < 0 || _idx >= _sosofo->length()) {
*this = {};
}
}
SosofoIterator& operator++() {
++_idx;
if (_idx >= _sosofo->length()) {
*this = {};
}
return *this;
}
SosofoIterator operator++(int) {
SosofoIterator retval = *this;
++(*this);
return retval;
}
bool operator==(SosofoIterator other) const {
return _sosofo == other._sosofo && _idx == other._idx;
}
bool operator!=(SosofoIterator other) const {
return !(*this == other);
}
reference operator*() const {
return *(*_sosofo)[_idx];
}
pointer operator->() const {
return (*_sosofo)[_idx];
}
};
} // ns eyestep
| 2,255 | 837 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <jni.h>
#include <filament/IndirectLight.h>
#include <filament/Texture.h>
#include <common/NioUtils.h>
#include <common/CallbackUtils.h>
#include <math/mat4.h>
using namespace filament;
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_IndirectLight_nCreateBuilder(JNIEnv*, jclass) {
return (jlong) new IndirectLight::Builder();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nDestroyBuilder(JNIEnv*, jclass,
jlong nativeBuilder) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
delete builder;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_IndirectLight_nBuilderBuild(JNIEnv*, jclass,
jlong nativeBuilder, jlong nativeEngine) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
Engine *engine = (Engine *) nativeEngine;
return (jlong) builder->build(*engine);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nBuilderReflections(JNIEnv*, jclass,
jlong nativeBuilder, jlong nativeTexture) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
const Texture *texture = (const Texture *) nativeTexture;
builder->reflections(texture);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nIrradiance(JNIEnv* env, jclass,
jlong nativeBuilder, jint bands, jfloatArray sh_) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
builder->irradiance((uint8_t) bands, (const filament::math::float3*) sh);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nRadiance(JNIEnv* env, jclass,
jlong nativeBuilder, jint bands, jfloatArray sh_) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
builder->radiance((uint8_t) bands, (const filament::math::float3*) sh);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nIrradianceAsTexture(JNIEnv*, jclass,
jlong nativeBuilder, jlong nativeTexture) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
const Texture* texture = (const Texture*) nativeTexture;
builder->irradiance(texture);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nIntensity(JNIEnv*, jclass,
jlong nativeBuilder, jfloat envIntensity) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
builder->intensity(envIntensity);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nRotation(JNIEnv *, jclass, jlong nativeBuilder,
jfloat v0, jfloat v1, jfloat v2, jfloat v3, jfloat v4, jfloat v5, jfloat v6, jfloat v7,
jfloat v8) {
IndirectLight::Builder *builder = (IndirectLight::Builder *) nativeBuilder;
builder->rotation(filament::math::mat3f{v0, v1, v2, v3, v4, v5, v6, v7, v8});
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nSetIntensity(JNIEnv*, jclass,
jlong nativeIndirectLight, jfloat intensity) {
IndirectLight* indirectLight = (IndirectLight*) nativeIndirectLight;
indirectLight->setIntensity(intensity);
}
extern "C" JNIEXPORT jfloat JNICALL
Java_com_google_android_filament_IndirectLight_nGetIntensity(JNIEnv*, jclass,
jlong nativeIndirectLight) {
IndirectLight* indirectLight = (IndirectLight*) nativeIndirectLight;
return indirectLight->getIntensity();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nSetRotation(JNIEnv*, jclass,
jlong nativeIndirectLight, jfloat v0, jfloat v1, jfloat v2,
jfloat v3, jfloat v4, jfloat v5, jfloat v6, jfloat v7, jfloat v8) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
indirectLight->setRotation(filament::math::mat3f{v0, v1, v2, v3, v4, v5, v6, v7, v8});
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetRotation(JNIEnv* env, jclass,
jlong nativeIndirectLight, jfloatArray outRotation_) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
jfloat *outRotation = env->GetFloatArrayElements(outRotation_, NULL);
*reinterpret_cast<filament::math::mat3f*>(outRotation) = indirectLight->getRotation();
env->ReleaseFloatArrayElements(outRotation_, outRotation, 0);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetDirectionEstimate(JNIEnv* env, jclass,
jlong nativeIndirectLight, jfloatArray outDirection_) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
jfloat *outDirection = env->GetFloatArrayElements(outDirection_, NULL);
*reinterpret_cast<filament::math::float3*>(outDirection) = indirectLight->getDirectionEstimate();
env->ReleaseFloatArrayElements(outDirection_, outDirection, 0);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetColorEstimate(JNIEnv* env, jclass,
jlong nativeIndirectLight, jfloatArray outColor_, jfloat x, jfloat y, jfloat z) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
jfloat *outColor = env->GetFloatArrayElements(outColor_, NULL);
*reinterpret_cast<filament::math::float4*>(outColor) =
indirectLight->getColorEstimate(math::float3{x, y, z});
env->ReleaseFloatArrayElements(outColor_, outColor, 0);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetDirectionEstimateStatic(JNIEnv *env, jclass,
jfloatArray sh_, jfloatArray outDirection_) {
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
jfloat *outDirection = env->GetFloatArrayElements(outDirection_, NULL);
*reinterpret_cast<filament::math::float3*>(outDirection) = IndirectLight::getDirectionEstimate((filament::math::float3*)sh);
env->ReleaseFloatArrayElements(outDirection_, outDirection, 0);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetColorEstimateStatic(JNIEnv *env, jclass,
jfloatArray outColor_, jfloatArray sh_, jfloat x, jfloat y, jfloat z) {
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
jfloat *outColor = env->GetFloatArrayElements(outColor_, NULL);
*reinterpret_cast<filament::math::float4*>(outColor) =
IndirectLight::getColorEstimate((filament::math::float3*)sh, math::float3{x, y, z});
env->ReleaseFloatArrayElements(outColor_, outColor, 0);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
} | 7,542 | 2,491 |
//-------------------------------------------------------------------------
/*
Copyright (C) 1997, 2005 - 3D Realms Entertainment
This file is part of Shadow Warrior version 1.2
Shadow Warrior is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Original Source: 1997 - Frank Maddin and Jim Norwood
Prepared for public release: 03/28/2005 - Charlie Wiederhold, 3D Realms
*/
//-------------------------------------------------------------------------
#include "ns.h"
#include "build.h"
#include "mytypes.h"
#include "names2.h"
#include "panel.h"
#include "game.h"
#include "tags.h"
#include "player.h"
#include "mclip.h"
BEGIN_SW_NS
int MultiClipMove(PLAYERp pp, int z, int floor_dist)
{
int i;
vec3_t opos[MAX_CLIPBOX], pos[MAX_CLIPBOX];
SECTOR_OBJECTp sop = pp->sop;
short ang;
short min_ndx = 0;
int min_dist = 999999;
int dist;
int ret_start;
int ret;
int min_ret=0;
int xvect,yvect;
for (i = 0; i < sop->clipbox_num; i++)
{
// move the box to position instead of using offset- this prevents small rounding errors
// allowing you to move through wall
ang = NORM_ANGLE(pp->angle.ang.asbuild() + sop->clipbox_ang[i]);
vec3_t spos = { pp->posx, pp->posy, z };
xvect = sop->clipbox_vdist[i] * bcos(ang);
yvect = sop->clipbox_vdist[i] * bsin(ang);
ret_start = clipmove(&spos, &pp->cursectnum, xvect, yvect, (int)sop->clipbox_dist[i], Z(4), floor_dist, CLIPMASK_PLAYER, 1);
if (ret_start)
{
// hit something moving into start position
min_dist = 0;
min_ndx = i;
// ox is where it should be
opos[i].x = pos[i].x = pp->posx + MulScale(sop->clipbox_vdist[i], bcos(ang), 14);
opos[i].y = pos[i].y = pp->posy + MulScale(sop->clipbox_vdist[i], bsin(ang), 14);
// spos.x is where it hit
pos[i].x = spos.x;
pos[i].y = spos.y;
// see the dist moved
dist = ksqrt(SQ(pos[i].x - opos[i].x) + SQ(pos[i].y - opos[i].y));
// save it off
if (dist < min_dist)
{
min_dist = dist;
min_ndx = i;
min_ret = ret_start;
}
}
else
{
// save off the start position
opos[i] = pos[i] = spos;
pos[i].z = z;
// move the box
ret = clipmove(&pos[i], &pp->cursectnum, pp->xvect, pp->yvect, (int)sop->clipbox_dist[i], Z(4), floor_dist, CLIPMASK_PLAYER);
// save the dist moved
dist = ksqrt(SQ(pos[i].x - opos[i].x) + SQ(pos[i].y - opos[i].y));
if (ret)
{
}
if (dist < min_dist)
{
min_dist = dist;
min_ndx = i;
min_ret = ret;
}
}
}
// put posx and y off from offset
pp->posx += pos[min_ndx].x - opos[min_ndx].x;
pp->posy += pos[min_ndx].y - opos[min_ndx].y;
return min_ret;
}
short MultiClipTurn(PLAYERp pp, short new_ang, int z, int floor_dist)
{
int i;
SECTOR_OBJECTp sop = pp->sop;
int ret;
int x,y;
short ang;
int xvect, yvect;
int cursectnum = pp->cursectnum;
for (i = 0; i < sop->clipbox_num; i++)
{
ang = NORM_ANGLE(new_ang + sop->clipbox_ang[i]);
vec3_t pos = { pp->posx, pp->posy, z };
xvect = sop->clipbox_vdist[i] * bcos(ang);
yvect = sop->clipbox_vdist[i] * bsin(ang);
// move the box
ret = clipmove(&pos, &cursectnum, xvect, yvect, (int)sop->clipbox_dist[i], Z(4), floor_dist, CLIPMASK_PLAYER);
ASSERT(cursectnum >= 0);
if (ret)
{
// attempt to move a bit when turning against a wall
//ang = NORM_ANGLE(ang + 1024);
//pp->xvect += 20 * bcos(ang);
//pp->yvect += 20 * bsin(ang);
return false;
}
}
return true;
}
int testquadinsect(int *point_num, vec2_t const * q, short sectnum)
{
int i,next_i;
*point_num = -1;
for (i=0; i < 4; i++)
{
if (!inside(q[i].x, q[i].y, sectnum))
{
*point_num = i;
return false;
}
}
for (i=0; i<4; i++)
{
next_i = (i+1) & 3;
if (!cansee(q[i].x, q[i].y,0x3fffffff, sectnum,
q[next_i].x, q[next_i].y,0x3fffffff, sectnum))
{
return false;
}
}
return true;
}
//Ken gives the tank clippin' a try...
int RectClipMove(PLAYERp pp, int *qx, int *qy)
{
int i;
vec2_t xy[4];
int point_num;
for (i = 0; i < 4; i++)
{
xy[i].x = qx[i] + (pp->xvect>>14);
xy[i].y = qy[i] + (pp->yvect>>14);
}
//Given the 4 points: x[4], y[4]
if (testquadinsect(&point_num, xy, pp->cursectnum))
{
pp->posx += (pp->xvect>>14);
pp->posy += (pp->yvect>>14);
return true;
}
if (point_num < 0)
return false;
if ((point_num == 0) || (point_num == 3)) //Left side bad - strafe right
{
for (i = 0; i < 4; i++)
{
xy[i].x = qx[i] - (pp->yvect>>15);
xy[i].y = qy[i] + (pp->xvect>>15);
}
if (testquadinsect(&point_num, xy, pp->cursectnum))
{
pp->posx -= (pp->yvect>>15);
pp->posy += (pp->xvect>>15);
}
return false;
}
if ((point_num == 1) || (point_num == 2)) //Right side bad - strafe left
{
for (i = 0; i < 4; i++)
{
xy[i].x = qx[i] + (pp->yvect>>15);
xy[i].y = qy[i] - (pp->xvect>>15);
}
if (testquadinsect(&point_num, xy, pp->cursectnum))
{
pp->posx += (pp->yvect>>15);
pp->posy -= (pp->xvect>>15);
}
return false;
}
return false;
}
int testpointinquad(int x, int y, int *qx, int *qy)
{
int i, cnt, x1, y1, x2, y2;
cnt = 0;
for (i=0; i<4; i++)
{
y1 = qy[i]-y;
y2 = qy[(i+1)&3]-y;
if ((y1^y2) >= 0) continue;
x1 = qx[i]-x;
x2 = qx[(i+1)&3]-x;
if ((x1^x2) >= 0)
cnt ^= x1;
else
cnt ^= (x1*y2-x2*y1)^y2;
}
return cnt>>31;
}
short RectClipTurn(PLAYERp pp, short new_ang, int *qx, int *qy, int *ox, int *oy)
{
int i;
vec2_t xy[4];
SECTOR_OBJECTp sop = pp->sop;
short rot_ang;
int point_num;
rot_ang = NORM_ANGLE(new_ang + sop->spin_ang - sop->ang_orig);
for (i = 0; i < 4; i++)
{
vec2_t const p = { ox[i], oy[i] };
rotatepoint(pp->pos.vec2, p, rot_ang, &xy[i]);
// cannot use sop->xmid and ymid because the SO is off the map at this point
//rotatepoint(&sop->xmid, p, rot_ang, &xy[i]);
}
//Given the 4 points: x[4], y[4]
if (testquadinsect(&point_num, xy, pp->cursectnum))
{
// move to new pos
for (i = 0; i < 4; i++)
{
qx[i] = xy[i].x;
qy[i] = xy[i].y;
}
return true;
}
if (point_num < 0)
return false;
return false;
}
END_SW_NS
| 7,796 | 3,078 |
#include "ShakeFadeOut.h"
#include "../../Utils.h"
namespace oreore
{
using namespace cocos2d;
ShakeFadeOut *ShakeFadeOut::create(const float duration, const float strength)
{
return create(duration, strength, strength);
}
ShakeFadeOut *ShakeFadeOut::create(const float duration, const float level_x, const float level_y)
{
ShakeFadeOut *action = new ShakeFadeOut();
if(action && action->initWithDuration(duration, level_x, level_y))
{
action->autorelease();
return action;
}
delete action;
return nullptr;
}
void ShakeFadeOut::update(float time)
{
const float x = (random<float>(strength_x * 2) - strength_x) * (1.0f - time);
const float y = (random<float>(strength_y * 2) - strength_y) * (1.0f - time);
getOriginalTarget()->setPosition(dpos + Point(x, y));
}
ShakeFadeOut *ShakeFadeOut::reverse() const
{
return clone();
}
ShakeFadeOut *ShakeFadeOut::clone() const
{
return ShakeFadeOut::create(getDuration(), strength_x, strength_y);
}
}
| 1,133 | 372 |
//===--------------------- Scheduler.cpp ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// A scheduler for processor resource units and processor resource groups.
//
//===----------------------------------------------------------------------===//
#include "Scheduler.h"
#include "Backend.h"
#include "HWEventListener.h"
#include "Support.h"
#include "llvm/Support/raw_ostream.h"
namespace mca {
using namespace llvm;
uint64_t ResourceState::selectNextInSequence() {
assert(isReady());
uint64_t Next = getNextInSequence();
while (!isSubResourceReady(Next)) {
updateNextInSequence();
Next = getNextInSequence();
}
return Next;
}
#ifndef NDEBUG
void ResourceState::dump() const {
dbgs() << "MASK: " << ResourceMask << ", SIZE_MASK: " << ResourceSizeMask
<< ", NEXT: " << NextInSequenceMask << ", RDYMASK: " << ReadyMask
<< ", BufferSize=" << BufferSize
<< ", AvailableSlots=" << AvailableSlots
<< ", Reserved=" << Unavailable << '\n';
}
#endif
void ResourceManager::initialize(const llvm::MCSchedModel &SM) {
computeProcResourceMasks(SM, ProcResID2Mask);
for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I)
addResource(*SM.getProcResource(I), I, ProcResID2Mask[I]);
}
// Adds a new resource state in Resources, as well as a new descriptor in
// ResourceDescriptor. Map 'Resources' allows to quickly obtain ResourceState
// objects from resource mask identifiers.
void ResourceManager::addResource(const MCProcResourceDesc &Desc,
unsigned Index, uint64_t Mask) {
assert(Resources.find(Mask) == Resources.end() && "Resource already added!");
Resources[Mask] = llvm::make_unique<ResourceState>(Desc, Index, Mask);
}
// Returns the actual resource consumed by this Use.
// First, is the primary resource ID.
// Second, is the specific sub-resource ID.
std::pair<uint64_t, uint64_t> ResourceManager::selectPipe(uint64_t ResourceID) {
ResourceState &RS = *Resources[ResourceID];
uint64_t SubResourceID = RS.selectNextInSequence();
if (RS.isAResourceGroup())
return selectPipe(SubResourceID);
return std::pair<uint64_t, uint64_t>(ResourceID, SubResourceID);
}
void ResourceState::removeFromNextInSequence(uint64_t ID) {
assert(NextInSequenceMask);
assert(countPopulation(ID) == 1);
if (ID > getNextInSequence())
RemovedFromNextInSequence |= ID;
NextInSequenceMask = NextInSequenceMask & (~ID);
if (!NextInSequenceMask) {
NextInSequenceMask = ResourceSizeMask;
assert(NextInSequenceMask != RemovedFromNextInSequence);
NextInSequenceMask ^= RemovedFromNextInSequence;
RemovedFromNextInSequence = 0;
}
}
void ResourceManager::use(ResourceRef RR) {
// Mark the sub-resource referenced by RR as used.
ResourceState &RS = *Resources[RR.first];
RS.markSubResourceAsUsed(RR.second);
// If there are still available units in RR.first,
// then we are done.
if (RS.isReady())
return;
// Notify to other resources that RR.first is no longer available.
for (const std::pair<uint64_t, UniqueResourceState> &Res : Resources) {
ResourceState &Current = *Res.second.get();
if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first)
continue;
if (Current.containsResource(RR.first)) {
Current.markSubResourceAsUsed(RR.first);
Current.removeFromNextInSequence(RR.first);
}
}
}
void ResourceManager::release(ResourceRef RR) {
ResourceState &RS = *Resources[RR.first];
bool WasFullyUsed = !RS.isReady();
RS.releaseSubResource(RR.second);
if (!WasFullyUsed)
return;
for (const std::pair<uint64_t, UniqueResourceState> &Res : Resources) {
ResourceState &Current = *Res.second.get();
if (!Current.isAResourceGroup() || Current.getResourceMask() == RR.first)
continue;
if (Current.containsResource(RR.first))
Current.releaseSubResource(RR.first);
}
}
ResourceStateEvent
ResourceManager::canBeDispatched(ArrayRef<uint64_t> Buffers) const {
ResourceStateEvent Result = ResourceStateEvent::RS_BUFFER_AVAILABLE;
for (uint64_t Buffer : Buffers) {
Result = isBufferAvailable(Buffer);
if (Result != ResourceStateEvent::RS_BUFFER_AVAILABLE)
break;
}
return Result;
}
void ResourceManager::reserveBuffers(ArrayRef<uint64_t> Buffers) {
for (const uint64_t R : Buffers) {
reserveBuffer(R);
ResourceState &Resource = *Resources[R];
if (Resource.isADispatchHazard()) {
assert(!Resource.isReserved());
Resource.setReserved();
}
}
}
void ResourceManager::releaseBuffers(ArrayRef<uint64_t> Buffers) {
for (const uint64_t R : Buffers)
releaseBuffer(R);
}
bool ResourceManager::canBeIssued(const InstrDesc &Desc) const {
return std::all_of(Desc.Resources.begin(), Desc.Resources.end(),
[&](const std::pair<uint64_t, const ResourceUsage> &E) {
unsigned NumUnits =
E.second.isReserved() ? 0U : E.second.NumUnits;
return isReady(E.first, NumUnits);
});
}
// Returns true if all resources are in-order, and there is at least one
// resource which is a dispatch hazard (BufferSize = 0).
bool ResourceManager::mustIssueImmediately(const InstrDesc &Desc) {
if (!canBeIssued(Desc))
return false;
bool AllInOrderResources = all_of(Desc.Buffers, [&](uint64_t BufferMask) {
const ResourceState &Resource = *Resources[BufferMask];
return Resource.isInOrder() || Resource.isADispatchHazard();
});
if (!AllInOrderResources)
return false;
return any_of(Desc.Buffers, [&](uint64_t BufferMask) {
return Resources[BufferMask]->isADispatchHazard();
});
}
void ResourceManager::issueInstruction(
const InstrDesc &Desc,
SmallVectorImpl<std::pair<ResourceRef, double>> &Pipes) {
for (const std::pair<uint64_t, ResourceUsage> &R : Desc.Resources) {
const CycleSegment &CS = R.second.CS;
if (!CS.size()) {
releaseResource(R.first);
continue;
}
assert(CS.begin() == 0 && "Invalid {Start, End} cycles!");
if (!R.second.isReserved()) {
ResourceRef Pipe = selectPipe(R.first);
use(Pipe);
BusyResources[Pipe] += CS.size();
// Replace the resource mask with a valid processor resource index.
const ResourceState &RS = *Resources[Pipe.first];
Pipe.first = RS.getProcResourceID();
Pipes.emplace_back(
std::pair<ResourceRef, double>(Pipe, static_cast<double>(CS.size())));
} else {
assert((countPopulation(R.first) > 1) && "Expected a group!");
// Mark this group as reserved.
assert(R.second.isReserved());
reserveResource(R.first);
BusyResources[ResourceRef(R.first, R.first)] += CS.size();
}
}
}
void ResourceManager::cycleEvent(SmallVectorImpl<ResourceRef> &ResourcesFreed) {
for (std::pair<ResourceRef, unsigned> &BR : BusyResources) {
if (BR.second)
BR.second--;
if (!BR.second) {
// Release this resource.
const ResourceRef &RR = BR.first;
if (countPopulation(RR.first) == 1)
release(RR);
releaseResource(RR.first);
ResourcesFreed.push_back(RR);
}
}
for (const ResourceRef &RF : ResourcesFreed)
BusyResources.erase(RF);
}
#ifndef NDEBUG
void Scheduler::dump() const {
dbgs() << "[SCHEDULER]: WaitQueue size is: " << WaitQueue.size() << '\n';
dbgs() << "[SCHEDULER]: ReadyQueue size is: " << ReadyQueue.size() << '\n';
dbgs() << "[SCHEDULER]: IssuedQueue size is: " << IssuedQueue.size() << '\n';
Resources->dump();
}
#endif
bool Scheduler::canBeDispatched(const InstRef &IR,
HWStallEvent::GenericEventType &Event) const {
Event = HWStallEvent::Invalid;
const InstrDesc &Desc = IR.getInstruction()->getDesc();
if (Desc.MayLoad && LSU->isLQFull())
Event = HWStallEvent::LoadQueueFull;
else if (Desc.MayStore && LSU->isSQFull())
Event = HWStallEvent::StoreQueueFull;
else {
switch (Resources->canBeDispatched(Desc.Buffers)) {
default:
return true;
case ResourceStateEvent::RS_BUFFER_UNAVAILABLE:
Event = HWStallEvent::SchedulerQueueFull;
break;
case ResourceStateEvent::RS_RESERVED:
Event = HWStallEvent::DispatchGroupStall;
}
}
return false;
}
void Scheduler::issueInstructionImpl(
InstRef &IR,
SmallVectorImpl<std::pair<ResourceRef, double>> &UsedResources) {
Instruction *IS = IR.getInstruction();
const InstrDesc &D = IS->getDesc();
// Issue the instruction and collect all the consumed resources
// into a vector. That vector is then used to notify the listener.
Resources->issueInstruction(D, UsedResources);
// Notify the instruction that it started executing.
// This updates the internal state of each write.
IS->execute();
if (IS->isExecuting())
IssuedQueue[IR.getSourceIndex()] = IS;
}
// Release the buffered resources and issue the instruction.
void Scheduler::issueInstruction(
InstRef &IR,
SmallVectorImpl<std::pair<ResourceRef, double>> &UsedResources) {
const InstrDesc &Desc = IR.getInstruction()->getDesc();
releaseBuffers(Desc.Buffers);
issueInstructionImpl(IR, UsedResources);
}
void Scheduler::promoteToReadyQueue(SmallVectorImpl<InstRef> &Ready) {
// Scan the set of waiting instructions and promote them to the
// ready queue if operands are all ready.
for (auto I = WaitQueue.begin(), E = WaitQueue.end(); I != E;) {
const unsigned IID = I->first;
Instruction *IS = I->second;
// Check if this instruction is now ready. In case, force
// a transition in state using method 'update()'.
IS->update();
const InstrDesc &Desc = IS->getDesc();
bool IsMemOp = Desc.MayLoad || Desc.MayStore;
if (!IS->isReady() || (IsMemOp && !LSU->isReady({IID, IS}))) {
++I;
continue;
}
Ready.emplace_back(IID, IS);
ReadyQueue[IID] = IS;
auto ToRemove = I;
++I;
WaitQueue.erase(ToRemove);
}
}
InstRef Scheduler::select() {
// Give priority to older instructions in the ReadyQueue. Since the ready
// queue is ordered by key, this will always prioritize older instructions.
const auto It = std::find_if(ReadyQueue.begin(), ReadyQueue.end(),
[&](const QueueEntryTy &Entry) {
const InstrDesc &D = Entry.second->getDesc();
return Resources->canBeIssued(D);
});
if (It == ReadyQueue.end())
return {0, nullptr};
// We found an instruction to issue.
InstRef IR(It->first, It->second);
ReadyQueue.erase(It);
return IR;
}
void Scheduler::updatePendingQueue(SmallVectorImpl<InstRef> &Ready) {
// Notify to instructions in the pending queue that a new cycle just
// started.
for (QueueEntryTy Entry : WaitQueue)
Entry.second->cycleEvent();
promoteToReadyQueue(Ready);
}
void Scheduler::updateIssuedQueue(SmallVectorImpl<InstRef> &Executed) {
for (auto I = IssuedQueue.begin(), E = IssuedQueue.end(); I != E;) {
const QueueEntryTy Entry = *I;
Instruction *IS = Entry.second;
IS->cycleEvent();
if (IS->isExecuted()) {
Executed.push_back({Entry.first, Entry.second});
auto ToRemove = I;
++I;
IssuedQueue.erase(ToRemove);
} else {
LLVM_DEBUG(dbgs() << "[SCHEDULER]: Instruction " << Entry.first
<< " is still executing.\n");
++I;
}
}
}
void Scheduler::onInstructionExecuted(const InstRef &IR) {
LSU->onInstructionExecuted(IR);
}
void Scheduler::reclaimSimulatedResources(SmallVectorImpl<ResourceRef> &Freed) {
Resources->cycleEvent(Freed);
}
bool Scheduler::reserveResources(InstRef &IR) {
// If necessary, reserve queue entries in the load-store unit (LSU).
const bool Reserved = LSU->reserve(IR);
if (!IR.getInstruction()->isReady() || (Reserved && !LSU->isReady(IR))) {
LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding " << IR << " to the Wait Queue\n");
WaitQueue[IR.getSourceIndex()] = IR.getInstruction();
return false;
}
return true;
}
bool Scheduler::issueImmediately(InstRef &IR) {
const InstrDesc &Desc = IR.getInstruction()->getDesc();
if (!Desc.isZeroLatency() && !Resources->mustIssueImmediately(Desc)) {
LLVM_DEBUG(dbgs() << "[SCHEDULER] Adding " << IR
<< " to the Ready Queue\n");
ReadyQueue[IR.getSourceIndex()] = IR.getInstruction();
return false;
}
return true;
}
} // namespace mca
| 12,727 | 4,080 |
// ********************************************************
// This C++ code was automatically generated by ml2cpp (development version).
// Copyright 2020
// https://github.com/antoinecarme/ml2cpp
// Model : BaggingClassifier
// Dataset : FourClass_100
// This CPP code can be compiled using any C++-17 compiler.
// g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_BaggingClassifier_FourClass_100.exe ml2cpp-demo_BaggingClassifier_FourClass_100.cpp
// Model deployment code
// ********************************************************
#include "../../Generic.i"
namespace {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
namespace SubModel_0 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 7 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 11 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 17 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 18 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 20 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 21 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 23 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 25 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 26 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_62 <= 1.503589004278183) ? ( 2 ) : ( 3 ) ) : ( (Feature_19 <= -0.5789696276187897) ? ( (Feature_78 <= -0.6031690239906311) ? ( (Feature_56 <= -8.097998857498169) ? ( 7 ) : ( 8 ) ) : ( (Feature_42 <= -0.2146744355559349) ? ( (Feature_90 <= 1.5686895251274109) ? ( 11 ) : ( 12 ) ) : ( 13 ) ) ) : ( (Feature_99 <= 0.00624384731054306) ? ( (Feature_44 <= -0.7715538442134857) ? ( (Feature_53 <= -1.3674404621124268) ? ( 17 ) : ( 18 ) ) : ( (Feature_89 <= -1.1485321521759033) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_11 <= 0.45316772162914276) ? ( 23 ) : ( (Feature_50 <= -0.7742524668574333) ? ( 25 ) : ( 26 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_0
namespace SubModel_1 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 6 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 7 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 9 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 10 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 14 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 15 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 19 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 20 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 21 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 23 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 24 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( 1 ) : ( (Feature_33 <= -0.08118173107504845) ? ( (Feature_41 <= 0.6967471539974213) ? ( (Feature_16 <= -0.818017452955246) ? ( (Feature_41 <= -0.07286195456981659) ? ( 6 ) : ( 7 ) ) : ( (Feature_41 <= -2.0635533332824707) ? ( 9 ) : ( 10 ) ) ) : ( (Feature_78 <= 1.29881152510643) ? ( 12 ) : ( (Feature_14 <= -0.16014254093170166) ? ( 14 ) : ( 15 ) ) ) ) : ( (Feature_46 <= 0.3926301449537277) ? ( (Feature_48 <= -0.17612321954220533) ? ( (Feature_30 <= -0.8991427272558212) ? ( 19 ) : ( 20 ) ) : ( 21 ) ) : ( (Feature_11 <= -1.096106618642807) ? ( 23 ) : ( 24 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_1
namespace SubModel_2 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 4 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 5 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 8 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 9 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 10 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 11 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 16 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 17 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 21 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 22 , {0.5, 0.0, 0.0, 0.5 }} ,
{ 23 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 24 , {1.0, 0.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_99 <= -0.09796052239835262) ? ( (Feature_78 <= 1.7039188742637634) ? ( (Feature_89 <= -0.5055654942989349) ? ( (Feature_54 <= 0.032076217234134674) ? ( 4 ) : ( 5 ) ) : ( (Feature_59 <= -0.3915305733680725) ? ( (Feature_94 <= -0.7241016756743193) ? ( 8 ) : ( 9 ) ) : ( 10 ) ) ) : ( 11 ) ) : ( (Feature_24 <= 0.5892128348350525) ? ( (Feature_45 <= 0.11031141877174377) ? ( (Feature_38 <= -0.8665039539337158) ? ( (Feature_60 <= -0.029639005661010742) ? ( 16 ) : ( 17 ) ) : ( 18 ) ) : ( (Feature_24 <= -0.6491396576166153) ? ( (Feature_69 <= -0.3395440876483917) ? ( 21 ) : ( 22 ) ) : ( 23 ) ) ) : ( 24 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_2
namespace SubModel_3 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 1 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 6 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 7 , {0.08, 0.44, 0.32, 0.16 }} ,
{ 9 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 14 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 15 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 17 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {1.0, 0.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.2519255876541138) ? ( 1 ) : ( (Feature_92 <= 0.8728378117084503) ? ( (Feature_78 <= 0.8840557038784027) ? ( (Feature_41 <= 0.37245966494083405) ? ( (Feature_70 <= -0.36322344839572906) ? ( 6 ) : ( 7 ) ) : ( (Feature_7 <= 1.2444062232971191) ? ( 9 ) : ( 10 ) ) ) : ( (Feature_14 <= -0.3580637127161026) ? ( (Feature_40 <= 1.0264981649816036) ? ( 13 ) : ( 14 ) ) : ( 15 ) ) ) : ( (Feature_79 <= 1.8128423690795898) ? ( 17 ) : ( 18 ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_3
namespace SubModel_4 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 4 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 6 , {0.0, 0.5, 0.5, 0.0 }} ,
{ 7 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 11 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 12 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 14 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 19 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 20 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 22 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 23 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 25 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 26 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_78 <= -0.6542530655860901) ? ( (Feature_44 <= 0.2128865383565426) ? ( (Feature_99 <= -1.187854915857315) ? ( (Feature_6 <= 0.2931538235861808) ? ( 4 ) : ( (Feature_50 <= -0.677160769701004) ? ( 6 ) : ( 7 ) ) ) : ( 8 ) ) : ( (Feature_9 <= 0.727972537279129) ? ( (Feature_74 <= 1.5878617763519287) ? ( 11 ) : ( 12 ) ) : ( (Feature_7 <= -0.2916768416762352) ? ( 14 ) : ( 15 ) ) ) ) : ( (Feature_19 <= -0.08902734890580177) ? ( (Feature_32 <= 0.42078158259391785) ? ( (Feature_49 <= -2.1161219477653503) ? ( 19 ) : ( 20 ) ) : ( (Feature_43 <= 0.031263142824172974) ? ( 22 ) : ( 23 ) ) ) : ( (Feature_28 <= 1.1810160875320435) ? ( 25 ) : ( 26 ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_4
namespace SubModel_5 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 4 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 6 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 7 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 11 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 12 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.6666666666666666, 0.0, 0.3333333333333333, 0.0 }} ,
{ 16 , {0.0, 0.05263157894736842, 0.0, 0.9473684210526315 }} ,
{ 17 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 21 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 22 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 23 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 25 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 26 , {0.0, 0.0, 1.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -1.309776484966278) ? ( (Feature_99 <= -2.194583535194397) ? ( 2 ) : ( (Feature_45 <= 0.1697009578347206) ? ( 4 ) : ( (Feature_76 <= -0.5688562635332346) ? ( 6 ) : ( 7 ) ) ) ) : ( (Feature_94 <= -0.33069832623004913) ? ( (Feature_38 <= -0.7251038551330566) ? ( (Feature_53 <= -3.49560284614563) ? ( 11 ) : ( 12 ) ) : ( (Feature_5 <= 0.5689798295497894) ? ( (Feature_73 <= -0.648361474275589) ? ( 15 ) : ( 16 ) ) : ( 17 ) ) ) : ( (Feature_24 <= 0.4838130474090576) ? ( (Feature_16 <= -0.5087056756019592) ? ( (Feature_76 <= -0.5111970640718937) ? ( 21 ) : ( 22 ) ) : ( 23 ) ) : ( (Feature_91 <= -0.035808783024549484) ? ( 25 ) : ( 26 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_5
namespace SubModel_6 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 4 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 8 , {0.9130434782608695, 0.043478260869565216, 0.043478260869565216, 0.0 }} ,
{ 9 , {0.0, 0.16666666666666666, 0.16666666666666666, 0.6666666666666666 }} ,
{ 11 , {0.1111111111111111, 0.8333333333333334, 0.0, 0.05555555555555555 }} ,
{ 12 , {0.3333333333333333, 0.0, 0.0, 0.6666666666666666 }} ,
{ 15 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 16 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 18 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 19 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 20 , {0.0, 1.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_73 <= 1.6641205549240112) ? ( (Feature_44 <= -2.1092634201049805) ? ( (Feature_63 <= -1.0751223862171173) ? ( 3 ) : ( 4 ) ) : ( (Feature_14 <= 1.0025184750556946) ? ( (Feature_45 <= 0.25321291387081146) ? ( (Feature_20 <= 0.688479095697403) ? ( 8 ) : ( 9 ) ) : ( (Feature_32 <= 0.28152644634246826) ? ( 11 ) : ( 12 ) ) ) : ( (Feature_99 <= -0.3237369656562805) ? ( (Feature_27 <= 0.9087257087230682) ? ( 15 ) : ( 16 ) ) : ( (Feature_38 <= -0.6264585703611374) ? ( 18 ) : ( 19 ) ) ) ) ) : ( 20 );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_6
namespace SubModel_7 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 7 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 8 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 12 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 16 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 18 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 19 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 22 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 23 , {0.0, 0.5, 0.0, 0.5 }} ,
{ 25 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 26 , {0.07692307692307693, 0.3076923076923077, 0.5384615384615384, 0.07692307692307693 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_66 <= 1.6641189455986023) ? ( 2 ) : ( 3 ) ) : ( (Feature_44 <= -0.49318933486938477) ? ( (Feature_68 <= -0.910584956407547) ? ( (Feature_39 <= 0.012014441192150116) ? ( 7 ) : ( 8 ) ) : ( (Feature_32 <= -1.8123965859413147) ? ( 10 ) : ( (Feature_11 <= 1.5604674816131592) ? ( 12 ) : ( 13 ) ) ) ) : ( (Feature_99 <= -0.3237369656562805) ? ( (Feature_47 <= 0.7225238382816315) ? ( 16 ) : ( (Feature_93 <= -1.1102982759475708) ? ( 18 ) : ( 19 ) ) ) : ( (Feature_29 <= -1.114558756351471) ? ( (Feature_0 <= 0.44958434998989105) ? ( 22 ) : ( 23 ) ) : ( (Feature_30 <= -0.5763616859912872) ? ( 25 ) : ( 26 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_7
namespace SubModel_8 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 6 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 8 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 11 , {0.5, 0.0, 0.0, 0.5 }} ,
{ 14 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 19 , {0.9285714285714286, 0.03571428571428571, 0.03571428571428571, 0.0 }} ,
{ 21 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 22 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_30 <= 0.7127983272075653) ? ( 2 ) : ( 3 ) ) : ( (Feature_78 <= -0.8434274196624756) ? ( (Feature_99 <= -0.5882234573364258) ? ( 6 ) : ( (Feature_19 <= -0.8192912638187408) ? ( 8 ) : ( (Feature_1 <= 0.6547807157039642) ? ( 10 ) : ( 11 ) ) ) ) : ( (Feature_43 <= -0.7006235718727112) ? ( (Feature_91 <= -0.12150455266237259) ? ( 14 ) : ( 15 ) ) : ( (Feature_27 <= 3.23024845123291) ? ( (Feature_81 <= -1.4423141479492188) ? ( 18 ) : ( 19 ) ) : ( (Feature_20 <= 0.9908088445663452) ? ( 21 ) : ( 22 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_8
namespace SubModel_9 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 9 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 11 , {0.0, 0.0, 0.3333333333333333, 0.6666666666666666 }} ,
{ 12 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 13 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 0.037037037037037035, 0.07407407407407407, 0.8888888888888888 }} ,
{ 19 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 21 , {0.5, 0.5, 0.0, 0.0 }} ,
{ 22 , {0.0, 0.0, 1.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_48 <= 1.2093676924705505) ? ( 2 ) : ( 3 ) ) : ( (Feature_29 <= -0.10024451464414597) ? ( (Feature_24 <= 0.3782288730144501) ? ( (Feature_49 <= 0.33082690834999084) ? ( (Feature_85 <= 1.473156750202179) ? ( 8 ) : ( 9 ) ) : ( (Feature_72 <= 0.03332477807998657) ? ( 11 ) : ( 12 ) ) ) : ( 13 ) ) : ( (Feature_28 <= -1.3160618543624878) ? ( 15 ) : ( (Feature_71 <= 0.7019776701927185) ? ( (Feature_93 <= 1.258106768131256) ? ( 18 ) : ( 19 ) ) : ( (Feature_77 <= -0.0934767834842205) ? ( 21 ) : ( 22 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_9
namespace SubModel_10 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 5 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 6 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 8 , {0.5, 0.5, 0.0, 0.0 }} ,
{ 9 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 12 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 14 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 17 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 21 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 22 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 24 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 25 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 27 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 28 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= 2.0125714540481567) ? ( (Feature_56 <= 0.6710653007030487) ? ( (Feature_10 <= 0.4213555306196213) ? ( (Feature_91 <= -0.9002590477466583) ? ( (Feature_61 <= 2.485666036605835) ? ( 5 ) : ( 6 ) ) : ( (Feature_40 <= -1.0761661529541016) ? ( 8 ) : ( 9 ) ) ) : ( (Feature_4 <= 0.049746282398700714) ? ( (Feature_36 <= 0.48682308197021484) ? ( 12 ) : ( 13 ) ) : ( 14 ) ) ) : ( (Feature_12 <= -0.7289259433746338) ? ( (Feature_36 <= 0.3711119145154953) ? ( 17 ) : ( 18 ) ) : ( (Feature_29 <= 0.9479873329401016) ? ( (Feature_78 <= 4.133114576339722) ? ( 21 ) : ( 22 ) ) : ( (Feature_91 <= 0.15714242216199636) ? ( 24 ) : ( 25 ) ) ) ) ) : ( (Feature_1 <= -0.5874605476856232) ? ( 27 ) : ( 28 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_10
namespace SubModel_11 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 8 , {0.7142857142857143, 0.14285714285714285, 0.0, 0.14285714285714285 }} ,
{ 9 , {0.0, 0.7741935483870968, 0.0967741935483871, 0.12903225806451613 }} ,
{ 11 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 14 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 16 , {0.0, 0.0, 0.0, 1.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_48 <= 0.9457052946090698) ? ( 2 ) : ( 3 ) ) : ( (Feature_20 <= 1.2383397221565247) ? ( (Feature_24 <= 0.5572461783885956) ? ( (Feature_71 <= 0.8951122760772705) ? ( (Feature_65 <= -1.0845131874084473) ? ( 8 ) : ( 9 ) ) : ( (Feature_1 <= 0.8677243292331696) ? ( 11 ) : ( 12 ) ) ) : ( (Feature_38 <= 0.7453548833727837) ? ( 14 ) : ( 15 ) ) ) : ( 16 ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_11
namespace SubModel_12 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 4 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 6 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 7 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 9 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 14 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 15 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 18 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 20 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 21 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 24 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 25 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 28 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 29 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 31 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 32 , {0.0, 0.0, 0.6, 0.4 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_78 <= -0.6111561059951782) ? ( (Feature_44 <= 1.6692100763320923) ? ( (Feature_15 <= 0.9708277881145477) ? ( (Feature_94 <= -1.621713638305664) ? ( 4 ) : ( (Feature_27 <= -2.2659579515457153) ? ( 6 ) : ( 7 ) ) ) : ( (Feature_75 <= 0.3124377280473709) ? ( 9 ) : ( 10 ) ) ) : ( (Feature_99 <= -0.3222829457372427) ? ( 12 ) : ( (Feature_0 <= 0.4392481744289398) ? ( 14 ) : ( 15 ) ) ) ) : ( (Feature_33 <= -0.31368252635002136) ? ( (Feature_67 <= 1.2143447399139404) ? ( 18 ) : ( (Feature_45 <= 0.17234395071864128) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_38 <= -0.8088268935680389) ? ( (Feature_91 <= -0.5887814164161682) ? ( 24 ) : ( 25 ) ) : ( (Feature_88 <= 0.273276109714061) ? ( (Feature_51 <= -3.0600167512893677) ? ( 28 ) : ( 29 ) ) : ( (Feature_72 <= -0.6026551425457001) ? ( 31 ) : ( 32 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_12
namespace SubModel_13 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 3 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 7 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 11 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 12 , {0.4, 0.6, 0.0, 0.0 }} ,
{ 13 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 17 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 18 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 20 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 21 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 24 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 25 , {0.0, 0.8, 0.0, 0.2 }} ,
{ 26 , {1.0, 0.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.1092634201049805) ? ( (Feature_99 <= -2.194583535194397) ? ( 2 ) : ( 3 ) ) : ( (Feature_20 <= -0.08544048853218555) ? ( (Feature_92 <= 0.16372115537524223) ? ( (Feature_41 <= 1.1139306724071503) ? ( 7 ) : ( 8 ) ) : ( (Feature_22 <= 0.12712760269641876) ? ( (Feature_83 <= 0.04717770963907242) ? ( 11 ) : ( 12 ) ) : ( 13 ) ) ) : ( (Feature_19 <= -0.5648867189884186) ? ( (Feature_68 <= -0.43200263381004333) ? ( (Feature_23 <= 0.18997395038604736) ? ( 17 ) : ( 18 ) ) : ( (Feature_6 <= 1.6022411584854126) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_78 <= 1.8294076323509216) ? ( (Feature_94 <= 0.11547934566624463) ? ( 24 ) : ( 25 ) ) : ( 26 ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_13
namespace SubModel_14 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 4 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 5 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 8 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 9 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 13 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 14 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 18 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 20 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 21 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 23 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 26 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 27 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 29 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 30 , {0.0, 1.0, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_78 <= -0.5283965766429901) ? ( (Feature_10 <= 0.3236100971698761) ? ( (Feature_44 <= -0.010307437914889306) ? ( (Feature_51 <= -2.8441089391708374) ? ( 4 ) : ( 5 ) ) : ( (Feature_10 <= -0.5565105974674225) ? ( (Feature_90 <= 0.7287018746137619) ? ( 8 ) : ( 9 ) ) : ( 10 ) ) ) : ( (Feature_84 <= -1.0485740900039673) ? ( (Feature_85 <= 0.9519887706264853) ? ( 13 ) : ( 14 ) ) : ( 15 ) ) ) : ( (Feature_72 <= -0.9955059289932251) ? ( (Feature_50 <= -0.025953032076358795) ? ( 18 ) : ( (Feature_70 <= 1.5127062797546387) ? ( 20 ) : ( 21 ) ) ) : ( (Feature_68 <= -1.1216784715652466) ? ( 23 ) : ( (Feature_63 <= 1.0354410409927368) ? ( (Feature_24 <= -1.6794065833091736) ? ( 26 ) : ( 27 ) ) : ( (Feature_42 <= -0.2587735503911972) ? ( 29 ) : ( 30 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_14
namespace SubModel_15 {
std::vector<std::any> get_classes(){
std::vector<std::any> lClasses = { 0, 1, 2, 3 };
return lClasses;
}
typedef std::vector<double> tNodeData;
std::map<int, tNodeData> Decision_Tree_Node_data = {
{ 2 , {0.0, 0.0, 1.0, 0.0 }} ,
{ 3 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 7 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 8 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 10 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 12 , {0.0, 0.0, 0.0, 1.0 }} ,
{ 13 , {1.0, 0.0, 0.0, 0.0 }} ,
{ 15 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 18 , {0.0, 1.0, 0.0, 0.0 }} ,
{ 19 , {0.3333333333333333, 0.0, 0.5, 0.16666666666666666 }} ,
{ 21 , {0.0, 0.0, 0.038461538461538464, 0.9615384615384616 }} ,
{ 22 , {0.5, 0.5, 0.0, 0.0 }}
};
int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
int lNodeIndex = (Feature_44 <= -2.0734068751335144) ? ( (Feature_48 <= 0.9457052946090698) ? ( 2 ) : ( 3 ) ) : ( (Feature_29 <= 0.022716662992024794) ? ( (Feature_9 <= -0.41657423973083496) ? ( (Feature_96 <= 1.575301468372345) ? ( 7 ) : ( 8 ) ) : ( (Feature_50 <= -1.501459538936615) ? ( 10 ) : ( (Feature_90 <= 0.12944400310516357) ? ( 12 ) : ( 13 ) ) ) ) : ( (Feature_8 <= -1.0347691178321838) ? ( 15 ) : ( (Feature_56 <= -3.686617374420166) ? ( (Feature_18 <= -0.11845160275697708) ? ( 18 ) : ( 19 ) ) : ( (Feature_88 <= 1.3707586526870728) ? ( 21 ) : ( 22 ) ) ) ) );
return lNodeIndex;
}
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99);
std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ];
tTable lTable;
lTable["Score"] = {
std::any(),
std::any(),
std::any(),
std::any()
} ;
lTable["Proba"] = {
lNodeValue [ 0 ],
lNodeValue [ 1 ],
lNodeValue [ 2 ],
lNodeValue [ 3 ]
} ;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace SubModel_15
std::vector<std::string> get_input_names(){
std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" };
return lFeatures;
}
std::vector<std::string> get_output_names(){
std::vector<std::string> lOutputs = {
"Score_0", "Score_1", "Score_2", "Score_3",
"Proba_0", "Proba_1", "Proba_2", "Proba_3",
"LogProba_0", "LogProba_1", "LogProba_2", "LogProba_3",
"Decision", "DecisionProba" };
return lOutputs;
}
tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) {
auto lClasses = get_classes();
std::vector<tTable> lTreeScores = {
SubModel_0::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_1::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_2::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_3::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_4::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_5::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_6::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_7::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_8::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_9::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_10::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_11::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_12::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_13::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_14::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99),
SubModel_15::compute_classification_scores(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99)
};
tTable lAggregatedTable = aggregate_bag_scores(lTreeScores, {"Proba", "Score"});
tTable lTable = lAggregatedTable;
int lBestClass = get_arg_max( lTable["Proba"] );
auto lDecision = lClasses[lBestClass];
lTable["Decision"] = { lDecision } ;
lTable["DecisionProba"] = { lTable["Proba"][lBestClass] };
recompute_log_probas( lTable );
return lTable;
}
tTable compute_model_outputs_from_table( tTable const & iTable) {
tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]);
return lTable;
}
} // eof namespace
int main() {
score_csv_file("outputs/ml2cpp-demo/datasets/FourClass_100.csv");
return 0;
}
| 225,178 | 107,547 |
#include "data_transfer.h"
// Start of frame delimiter
#define SOF 0x81
#define ESC 0x7e
#define MAXDATA 10
typedef struct Message {
byte sof;
size_t len; // How many more bytes to read after this
msg_type_t type;
byte data[MAXDATA]; // Data goes here (variable length)
} msg_t;
void send_msg(msg_type_t type, byte *data, size_t len) {
msg_t m;
m.sof = SOF;
m.type = type;
byte out_buf[sizeof(msg_t) + MAXDATA];
size_t j = sizeof(msg_t) - MAXDATA; // Output buffer index
if (len > MAXDATA) {
len = MAXDATA;
}
for (size_t i = 0; i < len; i++) {
if (data[i] == ESC || data[i] == SOF) {
out_buf[j++] = ESC;
}
out_buf[j++] = data[i];
}
m.len = j - 3; // Remove SOF and len
memcpy(out_buf, &m, sizeof(msg_t));
Serial.write(out_buf, j);
}
| 802 | 347 |
// Copyright (C) 2015-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-options "-std=gnu++17" }
#include <any>
#include <testsuite_hooks.h>
struct LocationAware
{
LocationAware() { }
~LocationAware() { VERIFY(self == this); }
LocationAware(const LocationAware&) { }
LocationAware& operator=(const LocationAware&) { return *this; }
LocationAware(LocationAware&&) noexcept { }
LocationAware& operator=(LocationAware&&) noexcept { return *this; }
void* const self = this;
};
static_assert(std::is_nothrow_move_constructible<LocationAware>::value, "");
static_assert(!std::is_trivially_copyable<LocationAware>::value, "");
using std::any;
void
test01()
{
LocationAware l;
any a = l;
}
void
test02()
{
LocationAware l;
any a = l;
any b = a;
{
any tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}
}
void
test03()
{
LocationAware l;
any a = l;
any b = a;
swap(a, b);
}
int
main()
{
test01();
test02();
test03();
}
| 1,682 | 602 |
// Copyright 2016 Etix Labs
//
// 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 "server.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>
// If time overlay is enabled, add it to the pipeline
std::string time_overlay(std::shared_ptr<t_config> &config) {
if (config->time) {
return " ! timeoverlay halignment=left valignment=top "
"shaded-background=true "
"font-desc=\"Sans 10\" ! "
"clockoverlay halignment=right valignment=top "
"shaded-background=true "
"font-desc=\"Sans 10\"";
}
return "";
}
bool needs_encoding(std::shared_ptr<t_config> &config) {
return (config->framerate != "" ||
config->scale.first != "" ||
config->scale.second != "" ||
config->input_type == VIDEOTESTSRC_INPUT ||
config->input_type == FILE_INPUT||
config->input_type == DEVICE_INPUT);
}
bool needs_resize_or_rerate(std::shared_ptr<t_config> &config) {
return (config->framerate != "" ||
config->scale.first != "" ||
config->scale.second != "");
}
// Take raw, change caps according to conf and transcode in h264
std::string encode(std::shared_ptr<t_config> &config) {
std::string launchCmd = "";
if (needs_resize_or_rerate(config)) {
std::cout << "H264 encoding with:" << std::endl;
}
// Change caps & encode
if (config->scale.first != "" &&
config->scale.second != "") {
std::cout << "Resolution:\t" << config->scale.first << "x"
<< config->scale.second << std::endl
<< std::endl;
launchCmd += " ! videoscale ! video/x-raw,width=";
launchCmd += config->scale.first;
launchCmd += ",height=";
launchCmd += config->scale.second;
} else if (config->input_type == VIDEOTESTSRC_INPUT) {
std::cout << "Resolution:\t" << DEFAULT_WIDTH << "x"
<< DEFAULT_HEIGHT << std::endl
<< std::endl;
launchCmd += " ! videoscale ! video/x-raw,width=";
launchCmd += DEFAULT_WIDTH;
launchCmd += ",height=";
launchCmd += DEFAULT_HEIGHT;
}
if (config->framerate != "") {
std::cout << "Framerate:\t" << config->framerate << std::endl;
launchCmd += " ! videorate ! video/x-raw,framerate=";
launchCmd += config->framerate;
launchCmd += "/1";
}
if (needs_encoding(config)) {
//launchCmd += " ! capsfilter ! queue ! x264enc speed-preset=superfast";
launchCmd += " ! videoconvert";
}
return launchCmd;
}
// Rtsp input pipeline
std::string create_rtsp_input(std::shared_ptr<t_config> &config) {
std::string launchCmd = "";
// Receive & depay
launchCmd += "rtspsrc latency=0 auto-start=true location=";
launchCmd += config->input;
launchCmd += " ! rtph264depay";
if (needs_resize_or_rerate(config)) {
// If user request modification in framerate or scale -> encode
launchCmd += " ! h264parse ! avdec_h264"; // Decode
}
launchCmd += time_overlay(config);
launchCmd += encode(config);
return launchCmd;
}
// Videosrc input pipeline
std::string create_videotestsrc_input(std::shared_ptr<t_config> &config) {
std::string launchCmd = "";
launchCmd += "videotestsrc ";
if (config->input.compare(0, 8, "pattern:") == 0) {
launchCmd += "pattern=";
launchCmd += config->input.substr(8);
}
std::cout << "oi" << std::endl;
launchCmd += time_overlay(config);
launchCmd += encode(config);
return launchCmd;
}
// File input pipeline
std::string create_file_input(std::shared_ptr<t_config> &config) {
std::string launchCmd = "";
launchCmd += "appsrc name=mysrc";
launchCmd += time_overlay(config);
launchCmd += encode(config);
return launchCmd;
}
// Device input pipeline
std::string create_device_input(std::shared_ptr<t_config> &config) {
std::string launchCmd = "";
launchCmd += " v4l2src device=";
launchCmd += config->input;
launchCmd += time_overlay(config);
launchCmd += encode(config);
return launchCmd;
}
/* Create pipeline according to config */
std::string create_pipeline(std::shared_ptr<t_config> &config) {
std::string launchCmd = "( ";
if (config->pipeline != "") {
launchCmd += config->pipeline;
} else {
if (config->input_type == RTSP_INPUT) {
launchCmd += create_rtsp_input(config);
} else if (config->input_type == VIDEOTESTSRC_INPUT) {
launchCmd += create_videotestsrc_input(config);
} else if (config->input_type == FILE_INPUT) {
launchCmd += create_file_input(config);
} else if (config->input_type == DEVICE_INPUT) {
launchCmd += create_device_input(config);
}
launchCmd += " ! rtph264pay name=pay0 pt=96 ";
}
launchCmd += " )";
//launchCmd = "(appsrc name=mysrc ! qtdemux name=demux demux. ! queue ! faad ! audioconvert ! audioresample ! autoaudiosink demux. ! queue ! avdec_h264 ! videoconvert ! autovideosink)";
return launchCmd;
}
| 5,372 | 1,804 |
// Copyright 2020 The VGC Developers
// See the COPYRIGHT file at the top-level directory of this distribution
// and at https://github.com/vgc/vgc/blob/master/COPYRIGHT
//
// 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 <vgc/widgets/font.h>
#include <iostream>
#include <QFontDatabase>
#include <vgc/core/logging.h>
#include <vgc/core/paths.h>
#include <vgc/widgets/qtutil.h>
namespace vgc {
namespace widgets {
void addDefaultApplicationFonts()
{
const bool printFontInfo = false;
std::vector<std::pair<std::string, std::string>> fontNames {
{"SourceCodePro", "Black"},
{"SourceCodePro", "BlackIt"},
{"SourceCodePro", "Bold"},
{"SourceCodePro", "BoldIt"},
{"SourceCodePro", "ExtraLight"},
{"SourceCodePro", "ExtraLightIt"},
{"SourceCodePro", "It"},
{"SourceCodePro", "Light"},
{"SourceCodePro", "LightIt"},
{"SourceCodePro", "Medium"},
{"SourceCodePro", "MediumIt"},
{"SourceCodePro", "Regular"},
{"SourceCodePro", "Semibold"},
{"SourceCodePro", "SemiboldIt"},
{"SourceSansPro", "Black"},
{"SourceSansPro", "BlackIt"},
{"SourceSansPro", "Bold"},
{"SourceSansPro", "BoldIt"},
{"SourceSansPro", "ExtraLight"},
{"SourceSansPro", "ExtraLightIt"},
{"SourceSansPro", "It"},
{"SourceSansPro", "Light"},
{"SourceSansPro", "LightIt"},
{"SourceSansPro", "Regular"},
{"SourceSansPro", "Semibold"},
{"SourceSansPro", "SemiboldIt"},
};
for (const auto& name : fontNames) {
std::string fontExtension = ".ttf";
std::string fontSubFolder = "/TTF/";
std::string filename = name.first + "-" + name.second + fontExtension;
std::string filepath = "widgets/fonts/" + name.first + fontSubFolder + filename;
int id = widgets::addApplicationFont(filepath);
if (id == -1) {
core::warning() << "Failed to add font \"" + filepath + "\".\n";
}
else {
if (printFontInfo) {
std::cout << "Added font file: " + filepath + "\n";
}
}
}
if (printFontInfo) {
widgets::printFontFamilyInfo("Source Sans Pro");
widgets::printFontFamilyInfo("Source Code Pro");
}
}
int addApplicationFont(const std::string& name)
{
std::string fontPath = core::resourcePath(name);
int id = QFontDatabase::addApplicationFont(toQt(fontPath));
return id;
}
void printFontFamilyInfo(const std::string& family)
{
QFontDatabase fd;
std::cout << "Font Family: " << family << "\n";
std::cout << " Styles:\n";
QString f = toQt(family);
QStringList styles = fd.styles(f);
Q_FOREACH (const QString& s, styles) {
std::cout << " " << fromQt(s) << ":\n";
std::cout << " weight: " << fd.weight(f, s) << "\n";
std::cout << " bold: " << (fd.bold(f, s) ? "true" : "false") << "\n";
std::cout << " italic: " << (fd.italic(f, s) ? "true" : "false") << "\n";
std::cout << " isBitmapScalable: " << (fd.isBitmapScalable(f, s) ? "true" : "false") << "\n";
std::cout << " isFixedPitch: " << (fd.isFixedPitch(f, s) ? "true" : "false") << "\n";
std::cout << " isScalable: " << (fd.isScalable(f, s) ? "true" : "false") << "\n";
std::cout << " isSmoothlyScalable: " << (fd.isSmoothlyScalable(f, s) ? "true" : "false") << "\n";
QList<int> pointSizes = fd.pointSizes(f, s);
std::cout << " pointSizes: [";
std::string delimiter = "";
Q_FOREACH (int ps, pointSizes) {
std::cout << delimiter << ps;
delimiter = ", ";
}
std::cout << "]\n";
QList<int> smoothSizes = fd.smoothSizes(f, s);
std::cout << " smoothSizes: [";
delimiter = "";
Q_FOREACH (int ss, smoothSizes) {
std::cout << delimiter << ss;
delimiter = ", ";
}
std::cout << "]\n";
}
}
} // namespace widgets
} // namespace vgc
| 4,722 | 1,502 |
#include "stdafx.h"
#include "EoSelectCmd.h"
#include "AeSysDoc.h"
#include "AeSysView.h"
#include <DbCommandContext.h>
const OdString CommandSelect::groupName() const {
return L"AeSys";
}
const OdString CommandSelect::Name() {
return L"SELECT";
}
const OdString CommandSelect::globalName() const {
return Name();
}
void CommandSelect::execute(OdEdCommandContext* commandContext) {
OdDbCommandContextPtr CommandContext(commandContext);
OdDbDatabaseDocPtr Database {CommandContext->database()};
auto Document {Database->Document()};
auto View {Document->GetViewer()};
if (View == nullptr) {
throw OdEdCancel();
}
Document->OnEditClearSelection();
Document->UpdateAllViews(nullptr);
auto UserIo {CommandContext->dbUserIO()};
UserIo->setPickfirst(nullptr);
const auto SelectOptions {OdEd::kSelLeaveHighlighted | OdEd::kSelAllowEmpty};
try {
OdDbSelectionSetPtr SelectionSet {UserIo->select(L"", SelectOptions, View->EditorObject().GetWorkingSelectionSet())};
View->EditorObject().SetWorkingSelectionSet(SelectionSet);
} catch (const OdError&) {
throw OdEdCancel();
}
View->EditorObject().SelectionSetChanged();
Database->pageObjects();
}
| 1,166 | 390 |
/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include <dali-toolkit/public-api/controls/buttons/button.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <dali/public-api/object/property-map.h>
// INTERNAL INCLUDES
#include <dali-toolkit/internal/controls/buttons/button-impl.h>
#include <dali-toolkit/public-api/controls/image-view/image-view.h>
#include <dali-toolkit/public-api/visuals/text-visual-properties.h>
namespace Dali
{
namespace Toolkit
{
Button::Button()
{
}
Button::Button(const Button& button) = default;
Button::Button(Button&& rhs) = default;
Button& Button::operator=(const Button& button) = default;
Button& Button::operator=(Button&& rhs) = default;
Button::~Button()
{
}
Button Button::DownCast(BaseHandle handle)
{
return Control::DownCast<Button, Internal::Button>(handle);
}
Button::ButtonSignalType& Button::PressedSignal()
{
return Dali::Toolkit::GetImplementation(*this).PressedSignal();
}
Button::ButtonSignalType& Button::ReleasedSignal()
{
return Dali::Toolkit::GetImplementation(*this).ReleasedSignal();
}
Button::ButtonSignalType& Button::ClickedSignal()
{
return Dali::Toolkit::GetImplementation(*this).ClickedSignal();
}
Button::ButtonSignalType& Button::StateChangedSignal()
{
return Dali::Toolkit::GetImplementation(*this).StateChangedSignal();
}
Button::Button(Internal::Button& implementation)
: Control(implementation)
{
}
Button::Button(Dali::Internal::CustomActor* internal)
: Control(internal)
{
VerifyCustomActorPointer<Internal::Button>(internal);
}
} // namespace Toolkit
} // namespace Dali
| 2,177 | 705 |
#include <algorithm>
#include <cstdint>
#include <numeric>
#include <arpa/inet.h>
#include "spirent_pga/common/headers.h"
namespace scalar {
inline uint32_t fold64(uint64_t sum)
{
sum = (sum >> 32) + (sum & 0xffffffff);
sum += sum >> 32;
return (static_cast<uint32_t>(sum));
}
inline uint16_t fold32(uint32_t sum)
{
sum = (sum >> 16) + (sum & 0xffff);
sum += sum >> 16;
return (static_cast<uint16_t>(sum));
}
void checksum_ipv4_headers(const uint8_t* ipv4_header_ptrs[],
uint16_t count,
uint32_t checksums[])
{
std::transform(ipv4_header_ptrs,
ipv4_header_ptrs + count,
checksums,
[](const uint8_t* ptr) {
auto header =
reinterpret_cast<const pga::headers::ipv4*>(ptr);
uint64_t sum = header->data[0];
sum += header->data[1];
sum += header->data[2];
sum += header->data[3];
sum += header->data[4];
uint16_t csum = fold32(fold64(sum));
return (csum == 0xffff ? csum : (0xffff ^ csum));
});
}
void checksum_ipv4_pseudoheaders(const uint8_t* ipv4_header_ptrs[],
uint16_t count,
uint32_t checksums[])
{
std::transform(
ipv4_header_ptrs,
ipv4_header_ptrs + count,
checksums,
[](const uint8_t* ptr) {
auto ipv4 = reinterpret_cast<const pga::headers::ipv4*>(ptr);
auto pheader = pga::headers::ipv4_pseudo{
.src_address = ipv4->src_address,
.dst_address = ipv4->dst_address,
.zero = 0,
.protocol = ipv4->protocol,
.length = htons(static_cast<uint16_t>(
ntohs(ipv4->length) - sizeof(pga::headers::ipv4)))};
uint64_t sum = pheader.data[0];
sum += pheader.data[1];
sum += pheader.data[2];
return (fold32(fold64(sum)));
});
}
uint32_t checksum_data_aligned(const uint32_t data[], uint16_t length)
{
uint64_t sum = std::accumulate(
data,
data + length,
uint64_t{0},
[](const auto& left, const auto& right) { return (left + right); });
return (fold64(sum));
}
} // namespace scalar
| 2,473 | 849 |
#include "Messages/CommandMessage.h"
namespace face
{
CommandMessage::CommandMessage(Type iType, unsigned iFrameId, long long iTimestamp) :
fw::Message(iFrameId, iTimestamp),
mType(iType)
{
}
}
| 209 | 71 |
/* file: qualitymetricset_batch.cpp */
/*******************************************************************************
* Copyright 2014-2021 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#include "daal.h"
#include "com_intel_daal_algorithms_quality_metric_set_QualityMetricSetBatch.h"
/*
* Class: com_intel_daal_algorithms_QualityMetricSetBatch
* Method: cCompute
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_quality_1metric_1set_QualityMetricSetBatch_cCompute(JNIEnv * env, jobject thisObj,
jlong algAddr)
{
(*(daal::algorithms::quality_metric_set::Batch *)algAddr).compute();
if ((*(daal::algorithms::quality_metric_set::Batch *)algAddr).getErrors()->size() > 0)
{
env->ThrowNew(env->FindClass("java/lang/Exception"), (*(daal::algorithms::quality_metric_set::Batch *)algAddr).getErrors()->getDescription());
}
}
/*
* Class: com_intel_daal_algorithms_QualityMetricSetBatch
* Method: cDispose
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_quality_1metric_1set_QualityMetricSetBatch_cDispose(JNIEnv *, jobject, jlong algAddr)
{
delete (daal::algorithms::quality_metric_set::Batch *)algAddr;
}
| 1,981 | 612 |
// Copyright (c) Christopher Di Bella.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
#ifndef CJDB_TEST_FUNCTIONAL_RANGECMP_IS_EQUIVALENCE_HPP
#define CJDB_TEST_FUNCTIONAL_RANGECMP_IS_EQUIVALENCE_HPP
#include "cjdb/test/constexpr_check.hpp"
#include "cjdb/test/functional/rangecmp/is_partial_equivalence.hpp"
#include "cjdb/test/functional/rangecmp/is_reflexive.hpp"
#define CHECK_IS_EQUIVALENCE(r, a, b, c) \
{ \
CHECK_IS_PARTIAL_EQUIVALENCE(r, a, b, c); \
CHECK_IS_REFLEXIVE(r, a); \
}
#endif // CJDB_TEST_FUNCTIONAL_RANGECMP_IS_EQUIVALENCE_HPP
| 637 | 277 |
/*
* Copyright 2018-2019 Autoware Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cnn_segmentation.h"
CNNSegmentation::CNNSegmentation() : nh_()
{
}
bool CNNSegmentation::init()
{
std::string proto_file;
std::string weight_file;
ros::NodeHandle private_node_handle("~");//to receive args
if (private_node_handle.getParam("network_definition_file", proto_file))
{
ROS_INFO("[%s] network_definition_file: %s", __APP_NAME__, proto_file.c_str());
} else
{
ROS_INFO("[%s] No Network Definition File was received. Finishing execution.", __APP_NAME__);
return false;
}
if (private_node_handle.getParam("pretrained_model_file", weight_file))
{
ROS_INFO("[%s] Pretrained Model File: %s", __APP_NAME__, weight_file.c_str());
} else
{
ROS_INFO("[%s] No Pretrained Model File was received. Finishing execution.", __APP_NAME__);
return false;
}
private_node_handle.param<std::string>("points_src", topic_src_, "points_raw");
ROS_INFO("[%s] points_src: %s", __APP_NAME__, topic_src_.c_str());
private_node_handle.param<double>("range", range_, 60.);
ROS_INFO("[%s] Pretrained Model File: %.2f", __APP_NAME__, range_);
private_node_handle.param<double>("score_threshold", score_threshold_, 0.6);
ROS_INFO("[%s] score_threshold: %.2f", __APP_NAME__, score_threshold_);
private_node_handle.param<int>("width", width_, 512);
ROS_INFO("[%s] width: %d", __APP_NAME__, width_);
private_node_handle.param<int>("height", height_, 512);
ROS_INFO("[%s] height: %d", __APP_NAME__, height_);
private_node_handle.param<bool>("use_gpu", use_gpu_, false);
ROS_INFO("[%s] use_gpu: %d", __APP_NAME__, use_gpu_);
private_node_handle.param<int>("gpu_device_id", gpu_device_id_, 0);
ROS_INFO("[%s] gpu_device_id: %d", __APP_NAME__, gpu_device_id_);
/// Instantiate Caffe net
if (!use_gpu_)
{
caffe::Caffe::set_mode(caffe::Caffe::CPU);
}
else
{
caffe::Caffe::SetDevice(gpu_device_id_);
caffe::Caffe::set_mode(caffe::Caffe::GPU);
caffe::Caffe::DeviceQuery();
}
caffe_net_.reset(new caffe::Net<float>(proto_file, caffe::TEST));
caffe_net_->CopyTrainedLayersFrom(weight_file);
std::string instance_pt_blob_name = "instance_pt";
instance_pt_blob_ = caffe_net_->blob_by_name(instance_pt_blob_name);
CHECK(instance_pt_blob_ != nullptr) << "`" << instance_pt_blob_name
<< "` layer required";
std::string category_pt_blob_name = "category_score";
category_pt_blob_ = caffe_net_->blob_by_name(category_pt_blob_name);
CHECK(category_pt_blob_ != nullptr) << "`" << category_pt_blob_name
<< "` layer required";
std::string confidence_pt_blob_name = "confidence_score";
confidence_pt_blob_ = caffe_net_->blob_by_name(confidence_pt_blob_name);
CHECK(confidence_pt_blob_ != nullptr) << "`" << confidence_pt_blob_name
<< "` layer required";
std::string height_pt_blob_name = "height_pt";
height_pt_blob_ = caffe_net_->blob_by_name(height_pt_blob_name);
CHECK(height_pt_blob_ != nullptr) << "`" << height_pt_blob_name
<< "` layer required";
std::string feature_blob_name = "data";
feature_blob_ = caffe_net_->blob_by_name(feature_blob_name);
CHECK(feature_blob_ != nullptr) << "`" << feature_blob_name
<< "` layer required";
std::string class_pt_blob_name = "class_score";
class_pt_blob_ = caffe_net_->blob_by_name(class_pt_blob_name);
CHECK(class_pt_blob_ != nullptr) << "`" << class_pt_blob_name
<< "` layer required";
cluster2d_.reset(new Cluster2D());
if (!cluster2d_->init(height_, width_, range_))
{
ROS_ERROR("[%s] Fail to Initialize cluster2d for CNNSegmentation", __APP_NAME__);
return false;
}
feature_generator_.reset(new FeatureGenerator());
if (!feature_generator_->init(feature_blob_.get()))
{
ROS_ERROR("[%s] Fail to Initialize feature generator for CNNSegmentation", __APP_NAME__);
return false;
}
return true;
}
bool CNNSegmentation::segment(const pcl::PointCloud<pcl::PointXYZI>::Ptr &pc_ptr,
const pcl::PointIndices &valid_idx,
autoware_msgs::DetectedObjectArray &objects)
{
int num_pts = static_cast<int>(pc_ptr->points.size());
if (num_pts == 0)
{
ROS_INFO("[%s] Empty point cloud.", __APP_NAME__);
return true;
}
feature_generator_->generate(pc_ptr);
// network forward process
caffe_net_->Forward();
#ifndef USE_CAFFE_GPU
// caffe::Caffe::set_mode(caffe::Caffe::CPU);
#else
// int gpu_id = 0;
// caffe::Caffe::SetDevice(gpu_id);
// caffe::Caffe::set_mode(caffe::Caffe::GPU);
// caffe::Caffe::DeviceQuery();
#endif
// clutser points and construct segments/objects
float objectness_thresh = 0.5;
bool use_all_grids_for_clustering = true;
cluster2d_->cluster(*category_pt_blob_, *instance_pt_blob_, pc_ptr,
valid_idx, objectness_thresh,
use_all_grids_for_clustering);
cluster2d_->filter(*confidence_pt_blob_, *height_pt_blob_);
cluster2d_->classify(*class_pt_blob_);
float confidence_thresh = score_threshold_;
float height_thresh = 0.5;
int min_pts_num = 3;
cluster2d_->getObjects(confidence_thresh, height_thresh, min_pts_num,
objects, message_header_);
return true;
}
void CNNSegmentation::test_run()
{
std::string in_pcd_file = "uscar_12_1470770225_1470770492_1349.pcd";
pcl::PointCloud<pcl::PointXYZI>::Ptr in_pc_ptr(new pcl::PointCloud<pcl::PointXYZI>);
pcl::io::loadPCDFile(in_pcd_file, *in_pc_ptr);
pcl::PointIndices valid_idx;
auto &indices = valid_idx.indices;
indices.resize(in_pc_ptr->size());
std::iota(indices.begin(), indices.end(), 0);
autoware_msgs::DetectedObjectArray objects;
init();
segment(in_pc_ptr, valid_idx, objects);
}
void CNNSegmentation::run()
{
init();
points_sub_ = nh_.subscribe(topic_src_, 1, &CNNSegmentation::pointsCallback, this);
points_pub_ = nh_.advertise<sensor_msgs::PointCloud2>("/detection/lidar_detector/points_cluster", 1);
objects_pub_ = nh_.advertise<autoware_msgs::DetectedObjectArray>("/detection/lidar_detector/objects", 1);
ROS_INFO("[%s] Ready. Waiting for data...", __APP_NAME__);
}
void CNNSegmentation::pointsCallback(const sensor_msgs::PointCloud2 &msg)
{
std::chrono::system_clock::time_point start, end;
start = std::chrono::system_clock::now();
pcl::PointCloud<pcl::PointXYZI>::Ptr in_pc_ptr(new pcl::PointCloud<pcl::PointXYZI>);
pcl::fromROSMsg(msg, *in_pc_ptr);
pcl::PointIndices valid_idx;
auto &indices = valid_idx.indices;
indices.resize(in_pc_ptr->size());
std::iota(indices.begin(), indices.end(), 0);
message_header_ = msg.header;
autoware_msgs::DetectedObjectArray objects;
objects.header = message_header_;
segment(in_pc_ptr, valid_idx, objects);
pubColoredPoints(objects);
objects_pub_.publish(objects);
end = std::chrono::system_clock::now();
double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
}
void CNNSegmentation::pubColoredPoints(const autoware_msgs::DetectedObjectArray &objects_array)
{
pcl::PointCloud<pcl::PointXYZRGB> colored_cloud;
for (size_t object_i = 0; object_i < objects_array.objects.size(); object_i++)
{
// std::cout << "objct i" << object_i << std::endl;
pcl::PointCloud<pcl::PointXYZI> object_cloud;
pcl::fromROSMsg(objects_array.objects[object_i].pointcloud, object_cloud);
int red = (object_i) % 256;
int green = (object_i * 7) % 256;
int blue = (object_i * 13) % 256;
for (size_t i = 0; i < object_cloud.size(); i++)
{
// std::cout << "point i" << i << "/ size: "<<object_cloud.size() << std::endl;
pcl::PointXYZRGB colored_point;
colored_point.x = object_cloud[i].x;
colored_point.y = object_cloud[i].y;
colored_point.z = object_cloud[i].z;
colored_point.r = red;
colored_point.g = green;
colored_point.b = blue;
colored_cloud.push_back(colored_point);
}
}
sensor_msgs::PointCloud2 output_colored_cloud;
pcl::toROSMsg(colored_cloud, output_colored_cloud);
output_colored_cloud.header = message_header_;
points_pub_.publish(output_colored_cloud);
}
| 8,913 | 3,337 |
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QStringListModel>
class StringListModel : public QStringListModel {
Q_OBJECT
public:
Q_INVOKABLE bool removeRows(int row, int count,
const QModelIndex &parent = QModelIndex()) {
return QStringListModel::removeRows(row, count, parent);
}
};
#include "main.moc"
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QStringList l{"a", "b", "c", "d"};
StringListModel model;
model.setStringList(l);
engine.rootContext()->setContextProperty("myModel", &model);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
| 780 | 263 |
/**
* Reactive
*
* (c) 2015-2016 Axel Etcheverry
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include <string>
#include <reactive/http/request.hpp>
namespace reactive {
namespace http {
int request::on_message_begin(http_parser* parser_)
{
//request& r = *(static_cast<request*>(parser_->data));
//r.setComplete(false);
//r.setHeadersComplete(false);
return 0;
}
int request::on_message_complete(http_parser* parser_)
{
//request& r = *static_cast<request*>(parser_->data);
//r.setComplete(true);
// Force the parser to stop after the request is parsed so clients
// can process the request (or response). This is to properly
// handle HTTP/1.1 pipelined requests.
//http_parser_pause(parser_, 1);
return 0;
}
int request::on_header_field(http_parser* parser_, const char* data_, std::size_t size_)
{
request& r = *static_cast<request*>(parser_->data);
if (!r.getCurrentValue().empty()) {
process_header(r, r.getCurrentField(), r.getCurrentValue());
r.getCurrentField().clear();
r.getCurrentValue().clear();
}
r.getCurrentField().append(data_, size_);
return 0;
}
int request::on_header_value(http_parser* parser_, const char* data_, std::size_t size_)
{
request& r = *static_cast<request*>(parser_->data);
r.getCurrentValue().append(data_, size_);
return 0;
}
int request::on_headers_complete(http_parser* parser_)
{
request& r = *(static_cast<request*>(parser_->data));
if (!r.getCurrentValue().empty()) {
process_header(r, r.getCurrentField(), r.getCurrentValue());
r.getCurrentField().clear();
r.getCurrentValue().clear();
}
//r.setHeadersComplete(true);
// Force the parser to stop after the headers are parsed so clients
// can process the request (or response). This is to properly
// handle HTTP/1.1 pipelined requests.
//http_parser_pause(parser_, 1);
return 0;
}
int request::on_url(http_parser* parser_, const char* data_, std::size_t size_)
{
std::string path;
std::string query;
bool is_path = true;
for (std::size_t i = 0; i < size_; ++i) {
char chr = data_[i];
if (is_path) {
if (chr == '?') {
is_path = false;
continue;
}
path += chr;
} else {
query += chr;
}
}
request& r = *static_cast<request*>(parser_->data);
r.getUrl().setPath(path);
if (!query.empty()) {
r.getUrl().setQuery(query);
}
return 0;
}
int request::on_body(http_parser* parser_, const char* data_, std::size_t size_)
{
static_cast<request*>(parser_->data)->getContent().append(data_, size_);
return 0;
}
void request::process_header(request& request_, const std::string& field_, const std::string& value_)
{
if (field_ == "Host") {
request_.getUrl().setHost(value_);
} else if (field_ == "User-Agent") {
request_.setUserAgent(value_);
} else if (field_ == "Cookie") {
//@TODO convert this code in state machine parser
std::vector<std::string> cookies;
reactive::string::split(REACTIVE_HTTP_COOKIE_SEPARATOR, value_, cookies);
for (std::size_t i = 0; i < cookies.size(); ++i) {
std::vector<std::string> cookie_string;
reactive::string::split("=", cookies.at(i), cookie_string);
cookie_t cookie;
cookie.name = reactive::uri::decode(cookie_string[0]);
cookie.value = reactive::uri::decode(cookie_string[1]);
cookie_string.clear();
request_.getCookies().add(cookie);
}
cookies.clear();
} else if (field_ == "X-Forwarded-For") {
process_ip(request_, value_);
} else if (field_ == "X-Client") {
process_ip(request_, value_);
} else if (field_ == "Content-Type") {
request_.setContentType(value_);
}
request_.getHeaders().add(field_, value_);
}
void request::process_ip(request& request_, const std::string& ip_)
{
request_.info.by_proxy = true;
request_.info.proxy_ip_version = request_.info.ip_version;
request_.info.proxy_ip = request_.info.ip;
request_.info.proxy_port = request_.info.port;
std::size_t pos = ip_.find(",");
request_.info.ip = ip_;
if (pos != std::string::npos) {
request_.info.ip = ip_.substr(0, pos);
}
try {
boost::asio::ip::address ip_version = boost::asio::ip::address::from_string(request_.info.ip);
if (ip_version.is_v4()) {
request_.info.ip_version = reactive::net::ip::IPV4;
} else if (ip_version.is_v6()) {
request_.info.ip_version = reactive::net::ip::IPV6;
}
} catch (std::exception& e) {
request_.info.ip_version = reactive::net::ip::UNDEFINED;
//request_.info.by_proxy = false;
}
// In this process we have no port information
request_.info.port.clear();
}
request::request()
{
reset();
memset(&m_settings, 0, sizeof(m_settings));
// Setting state machine callbacks
m_settings.on_message_begin = &request::on_message_begin;
m_settings.on_message_complete = &request::on_message_complete;
m_settings.on_header_field = &request::on_header_field;
m_settings.on_header_value = &request::on_header_value;
m_settings.on_headers_complete = &request::on_headers_complete;
m_settings.on_url = &request::on_url;
m_settings.on_body = &request::on_body;
memset(&m_parser, 0, sizeof(m_parser));
http_parser_init(&m_parser, HTTP_REQUEST);
m_parser.data = this;
}
request::~request()
{
// clear headers list
getHeaders().clear();
// clear cookies list
m_cookies.clear();
}
void request::reset()
{
info.reset();
m_useragent = REACTIVE_HTTP_REQUEST_USER_AGENT;
setVersion(protocol::VERSION_11);
m_method = protocol::METHOD_GET;
// Resetting content and its type
setContent("");
m_content_type = "";
// unused undocumented variables
//m_complete = false;
//m_headers_complete = false;
m_query.clear();
m_body.clear();
}
std::size_t request::parse(const char* data_, std::size_t size_)
{
std::size_t parsed = 0;
if (size_ > 0) {
parsed = http_parser_execute(&m_parser, &m_settings, data_, size_);
//if (parsed < size_)
// LIMIT in reading is 80x1024
}
//const http_errno errno = static_cast<http_errno>(m_parser.http_errno);
// The 'on_message_complete' and 'on_headers_complete' callbacks fail
// on purpose to force the parser to stop between pipelined requests.
// This allows the clients to reliably detect the end of headers and
// the end of the message. Make sure the parser is always unpaused
// for the next call to 'feed'.
/*if (herrno == HPE_PAUSED)
{
http_parser_pause(&m_parser, 0);
}*/
/*if (used < size_)
{
if (herrno == HPE_PAUSED)
{
// Make sure the byte that triggered the pause
// after the headers is properly processed.
if (!m_complete)
{
used += http_parser_execute(&m_parser, &m_settings, data_+used, 1);
}
}
else
{
throw (error(herrno));
}
}*/
m_method = std::string(http_method_str((http_method)m_parser.method));
setVersion(std::to_string(m_parser.http_major) + "." + std::to_string(m_parser.http_minor));
if (!m_url.getQuery().empty()) {
m_query.parse(m_url.getQuery());
}
if (m_content_type == "application/x-www-form-urlencoded") {
m_body.parse(getContent());
}
return parsed;
}
bool request::hasQueryArgument(const std::string& key_) const
{
return m_query.has(key_);
}
bool request::hasBodyArgument(const std::string& key_) const
{
return m_body.has(key_);
}
bool request::shouldKeepAlive() const
{
return (http_should_keep_alive(const_cast<http_parser*>(&m_parser)) != 0);
}
const cookie_bag& request::getCookies() const
{
return m_cookies;
}
cookie_bag& request::getCookies()
{
return m_cookies;
}
void request::setMethod(const std::string& method_)
{
m_method = method_;
}
const std::string& request::getMethod() const
{
return m_method;
}
void request::setUserAgent(const std::string& useragent_)
{
m_useragent = useragent_;
}
const std::string& request::getUserAgent() const
{
return m_useragent;
}
void request::setUrl(reactive::uri::url& url_)
{
m_url = url_;
}
void request::setUrl(const std::string& url_)
{
m_url = reactive::uri::url(url_);
}
const reactive::uri::url& request::getUrl() const
{
return m_url;
}
reactive::uri::url& request::getUrl()
{
return m_url;
}
void request::setContentType(const std::string& type_)
{
std::size_t pos = type_.find(";");
if (pos != std::string::npos) {
m_content_type = type_.substr(0, pos);
} else {
m_content_type = type_;
}
getHeaders().add("Content-Type", m_content_type);
}
/**
* Get content type
*
* @return The string of content type
*/
const std::string& request::getContentType() const
{
return m_content_type;
}
bool request::isXmlHttpRequest() const
{
if (getHeaders().has("X-Requested-With") && getHeaders().get("X-Requested-With").value == "XMLHttpRequest") {
return true;
}
return false;
}
reactive::uri::query request::getData() const
{
return m_body;
}
std::string request::toString() const
{
header_bag headers = getHeaders();
headers.add("Host", m_url.toString(reactive::uri::url::HOST | reactive::uri::url::PORT));
if (!headers.has("Cache-Control")) {
headers.add("Cache-Control", "max-age=0");
}
if (!headers.has("Accept")) {
headers.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
}
if (!headers.has("User-Agent")) {
headers.add("User-Agent", m_useragent);
}
if (!headers.has("Accept-Charset")) {
headers.add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
}
std::string reqstr = m_method
+ " "
+ m_url.toString(reactive::uri::url::PATH | reactive::uri::url::QUERY)
+ " HTTP/"
+ getVersion()
+ protocol::CRLF;
// --- Constructing the cookie string
std::string full_cookies;
std::size_t count_cookie = m_cookies.size();
for (std::size_t i = 0; i < count_cookie; ++i) {
std::string cookie;
cookie.append(reactive::uri::encode(m_cookies.at(i).name));
cookie.append("=");
cookie.append(reactive::uri::encode(m_cookies.at(i).value));
if (i != (count_cookie - 1)) {
cookie.append(REACTIVE_HTTP_COOKIE_SEPARATOR);
}
full_cookies.append(cookie);
}
// --- Using the cookie string to build the header
if (!full_cookies.empty()) {
headers.add("Cookie", full_cookies);
}
// In HTTP/1.1 the default connection type is Keep-Alive
// while it is not fully supported in HTTP/1.0 it does not matter.
//
// Anyway this default header is set during connection and not here
//headers.add("Connection", "Keep-Alive");
reqstr.append(headers.toString() + protocol::CRLF);
if (!getContent().empty()) {
reqstr.append(getContent());
}
return reqstr;
}
} // end of http namespace
} // end of reactive namespace
| 13,004 | 3,976 |
//==================================================================================================
/*!
@file
@copyright 2016 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_CONSTANT_DEFINITION_THOUSAND_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_DEFINITION_THOUSAND_HPP_INCLUDED
#include <boost/simd/config.hpp>
#include <boost/simd/detail/brigand.hpp>
#include <boost/simd/detail/dispatch.hpp>
#include <boost/simd/detail/constant_traits.hpp>
#include <boost/simd/detail/dispatch/function/make_callable.hpp>
#include <boost/simd/detail/dispatch/hierarchy/functions.hpp>
#include <boost/simd/detail/dispatch/as.hpp>
namespace boost { namespace simd
{
namespace tag
{
struct thousand_ : boost::dispatch::constant_value_<thousand_>
{
BOOST_DISPATCH_MAKE_CALLABLE(ext,thousand_,boost::dispatch::constant_value_<thousand_>);
BOOST_SIMD_REGISTER_CONSTANT(1000, 0x447a0000UL, 0x408f400000000000ULL);
};
}
namespace ext
{
BOOST_DISPATCH_FUNCTION_DECLARATION(tag, thousand_)
}
namespace detail
{
BOOST_DISPATCH_CALLABLE_DEFINITION(tag::thousand_,thousand);
}
template<typename T> BOOST_FORCEINLINE auto Thousand()
BOOST_NOEXCEPT_DECLTYPE(detail::thousand( boost::dispatch::as_<T>{}))
{
return detail::thousand( boost::dispatch::as_<T>{} );
}
} }
#endif
| 1,548 | 573 |
#include "BBUtils.h"
#include <QDir>
#include <QProcess>
#include "FileSystem/BBFileListWidget.h"
#include <GL/gl.h>
QString BBConstant::BB_NAME_PROJECT = "";
QString BBConstant::BB_PATH_PROJECT = "";
// there is no / at the end
QString BBConstant::BB_PATH_PROJECT_ENGINE = "";
QString BBConstant::BB_PATH_PROJECT_USER = "";
QString BBConstant::BB_NAME_FILE_SYSTEM_USER = "contents";
QString BBConstant::BB_NAME_FILE_SYSTEM_ENGINE = "engine";
QString BBConstant::BB_NAME_OVERVIEW_MAP = "overview map.jpg";
QString BBConstant::BB_NAME_DEFAULT_SCENE = "new scene.bbscene";
QString BBConstant::BB_NAME_DEFAULT_MATERIAL = "new material.bbmtl";
QVector3D BBConstant::m_Red = QVector3D(0.937255f, 0.378431f, 0.164706f);
QVector4D BBConstant::m_RedTransparency = QVector4D(0.937255f, 0.378431f, 0.164706f, 0.7f);
QVector3D BBConstant::m_Green = QVector3D(0.498039f, 0.827451f, 0.25098f);
QVector4D BBConstant::m_GreenTransparency = QVector4D(0.498039f, 0.827451f, 0.25098f, 0.7f);
QVector3D BBConstant::m_Blue = QVector3D(0.341176f, 0.662745f, 1.0f);
QVector4D BBConstant::m_BlueTransparency = QVector4D(0.341176f, 0.662745f, 1.0f, 0.7f);
QVector3D BBConstant::m_Yellow = QVector3D(1.0f, 1.0f, 0.305882f);
QVector3D BBConstant::m_Gray = QVector3D(0.8f, 0.8f, 0.8f);
QVector4D BBConstant::m_GrayTransparency = QVector4D(0.8f, 0.8f, 0.8f, 0.7f);
//QVector3D BBConstant::m_Red = QVector3D(0.909804f, 0.337255f, 0.333333f);
//QVector4D BBConstant::m_RedTransparency = QVector4D(0.909804f, 0.337255f, 0.333333f, 0.5f);
//QVector3D BBConstant::m_Green = QVector3D(0.356863f, 0.729412f, 0.619608f);
//QVector4D BBConstant::m_GreenTransparency = QVector4D(0.356863f, 0.729412f, 0.619608f, 0.5f);
//QVector3D BBConstant::m_Blue = QVector3D(0.384314f, 0.631373f, 0.847059f);
//QVector4D BBConstant::m_BlueTransparency = QVector4D(0.384314f, 0.631373f, 0.847059f, 0.5f);
//QVector3D BBConstant::m_Yellow = QVector3D(0.847059f, 0.603922f, 0.309804f);
QVector3D BBConstant::m_OrangeRed = QVector3D(0.909804f, 0.337255f, 0.333333f);
char *BBUtils::loadFileContent(const char *filePath, int &nFileSize)
{
FILE *pFile = NULL;
char *pData = NULL;
// Read files by binary mode
// path.toLatin1().data(); will cause Chinese garbled
do{
pFile = fopen(filePath, "rb");
BB_PROCESS_ERROR(pFile);
// Seek the pointer to the end of the file
BB_PROCESS_ERROR(BB_SUCCEEDED(fseek(pFile, 0, SEEK_END)));
// Get the size of the file
size_t length = ftell(pFile);
BB_PROCESS_ERROR(length);
// Seek to the beginning of the file
BB_PROCESS_ERROR(BB_SUCCEEDED(fseek(pFile, 0, SEEK_SET)));
// +1 Terminator
pData = new char[length + 1];
BB_PROCESS_ERROR(pData);
// 1*length is the size of the file to be read
BB_PROCESS_ERROR(fread(pData, 1, length, pFile));
// Terminator
pData[length] = 0;
nFileSize = length;
}while(0);
if (pFile)
fclose(pFile);
return pData;
}
bool BBUtils::saveToFile(const char *pFilePath, void *pBuffer, int nSize)
{
FILE *pFile = fopen(pFilePath, "wb");
BB_PROCESS_ERROR_RETURN_FALSE(pFile);
fwrite(pBuffer, sizeof(char), nSize, pFile);
fclose(pFile);
return true;
}
unsigned char* BBUtils::decodeBMP(unsigned char *pBmpFileData, int &nWidth, int &nHeight)
{
// Is it a bitmap file
if (0x4D42 == *((unsigned short*)pBmpFileData))
{
int nPixelDataOffset = *((int*)(pBmpFileData + 10));
nWidth = *((int*)(pBmpFileData + 18));
nHeight = *((int*)(pBmpFileData + 22));
unsigned char *pPixelData = pBmpFileData + nPixelDataOffset;
// be saved as BGR, but opengl support RGB, exchange B with R
// bmp does not support alpha
for (int i = 0; i < nWidth * nHeight * 3; i += 3)
{
unsigned char temp = pPixelData[i];
pPixelData[i] = pPixelData[i + 2];
pPixelData[i + 2] = temp;
}
return pPixelData;
}
return nullptr;
}
QString BBUtils::getBaseName(const QString &name)
{
return name.mid(0, name.lastIndexOf('.'));
}
QString BBUtils::getPathRelativeToExecutionDirectory(const QString &absolutePath)
{
QDir dir(QDir::currentPath());
return dir.relativeFilePath(absolutePath);
}
unsigned int BBUtils::getBlendFunc(int nIndex)
{
unsigned int func = GL_ZERO;
switch (nIndex) {
case 0:
func = GL_ZERO;
break;
case 1:
func = GL_ONE;
break;
case 2:
func = GL_SRC_COLOR;
break;
case 3:
func = GL_ONE_MINUS_SRC_COLOR;
break;
case 4:
func = GL_SRC_ALPHA;
break;
case 5:
func = GL_ONE_MINUS_SRC_ALPHA;
break;
case 6:
func = GL_DST_ALPHA;
break;
case 7:
func = GL_ONE_MINUS_DST_ALPHA;
break;
default:
break;
}
return func;
}
QString BBUtils::getBlendFuncName(unsigned int func)
{
QString name;
switch (func) {
case GL_ZERO:
name = "GL_ZERO";
break;
case GL_ONE:
name = "GL_ONE";
break;
case GL_SRC_COLOR:
name = "GL_SRC_COLOR";
break;
case GL_ONE_MINUS_SRC_COLOR:
name = "GL_ONE_MINUS_SRC_COLOR";
break;
case GL_SRC_ALPHA:
name = "GL_SRC_ALPHA";
break;
case GL_ONE_MINUS_SRC_ALPHA:
name = "GL_ONE_MINUS_SRC_ALPHA";
break;
case GL_DST_ALPHA:
name = "GL_DST_ALPHA";
break;
case GL_ONE_MINUS_DST_ALPHA:
name = "GL_ONE_MINUS_DST_ALPHA";
break;
default:
break;
}
return name;
}
| 5,669 | 2,478 |
// Copyright 2019 The Fuchsia 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 <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include "src/virtualization/lib/guest_interaction/client/guest_discovery_service.h"
int main(int argc, char** argv) {
async::Loop loop(&kAsyncLoopConfigNoAttachToCurrentThread);
// Create the guest interaction service and run its gRPC processing loop on
// a separate thread.
GuestDiscoveryServiceImpl guest_discovery_service = GuestDiscoveryServiceImpl(loop.dispatcher());
return loop.Run();
}
| 648 | 212 |
/*
** ClanLib SDK
** Copyright (c) 1997-2016 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#include "Display/precomp.h"
#include "API/Display/Font/font.h"
#include "API/Display/Font/font_metrics.h"
#include "API/Display/Font/font_description.h"
#include "API/Display/TargetProviders/graphic_context_provider.h"
#include "API/Core/IOData/path_help.h"
#include "API/Core/Text/string_help.h"
#include "API/Core/Text/string_format.h"
#include "API/Core/Text/utf8_reader.h"
#include "API/Display/2D/canvas.h"
#include "API/Display/Resources/display_cache.h"
#include "font_impl.h"
namespace clan
{
Font::Font()
{
}
Font::Font(FontFamily &font_family, float height)
{
font_family.throw_if_null();
FontDescription desc;
desc.set_height(height);
*this = Font(font_family, desc);
}
Font::Font(FontFamily &font_family, const FontDescription &desc)
{
impl = std::make_shared<Font_Impl>(font_family, desc);
}
Font::Font(const std::string &typeface_name, float height)
{
FontDescription desc;
desc.set_height(height);
*this = Font(typeface_name, desc);
}
Font::Font(const std::string &typeface_name, const FontDescription &desc)
{
FontFamily font_family(typeface_name);
*this = Font(font_family, desc);
}
Font::Font(const FontDescription &desc, const std::string &ttf_filename)
{
std::string path = PathHelp::get_fullpath(ttf_filename, PathHelp::path_type_file);
std::string new_filename = PathHelp::get_filename(ttf_filename, PathHelp::path_type_file);
FileSystem vfs(path);
FontFamily font_family(new_filename);
font_family.add(desc, new_filename, vfs);
impl = std::make_shared<Font_Impl>(font_family, desc);
}
Font::Font(const FontDescription &desc, const std::string &ttf_filename, FileSystem fs)
{
std::string new_filename = PathHelp::get_filename(ttf_filename, PathHelp::path_type_file);
FontFamily font_family(new_filename);
font_family.add(desc, ttf_filename, fs);
impl = std::make_shared<Font_Impl>(font_family, desc);
}
Font::Font(Canvas &canvas, const std::string &typeface_name, Sprite &sprite, const std::string &glyph_list, float spacelen, bool monospace, const FontMetrics &metrics)
{
FontDescription desc;
desc.set_height(metrics.get_height());
FontFamily font_family(typeface_name);
font_family.add(canvas, sprite, glyph_list, spacelen, monospace, metrics);
impl = std::make_shared<Font_Impl>(font_family, desc);
}
Resource<Font> Font::resource(Canvas &canvas, const std::string &family_name, const FontDescription &desc, const ResourceManager &resources)
{
return DisplayCache::get(resources).get_font(canvas, family_name, desc);
}
void Font::throw_if_null() const
{
if (!impl)
throw Exception("Font is null");
}
void Font::set_height(float value)
{
if (impl)
impl->set_height(value);
}
void Font::set_weight(FontWeight value)
{
if (impl)
impl->set_weight(value);
}
void Font::set_line_height(float height)
{
if (impl)
impl->set_line_height(height);
}
void Font::set_style(FontStyle style)
{
if (impl)
impl->set_style(style);
}
void Font::set_scalable(float height_threshold)
{
if (impl)
impl->set_scalable(height_threshold);
}
GlyphMetrics Font::get_metrics(Canvas &canvas, unsigned int glyph) const
{
if (impl)
return impl->get_metrics(canvas, glyph);
return GlyphMetrics();
}
GlyphMetrics Font::measure_text(Canvas &canvas, const std::string &string) const
{
if (impl)
return impl->measure_text(canvas, string);
return GlyphMetrics();
}
size_t Font::clip_from_left(Canvas &canvas, const std::string &text, float width) const
{
float x = 0.0f;
UTF8_Reader reader(text.data(), text.length());
while (!reader.is_end())
{
unsigned int glyph = reader.get_char();
GlyphMetrics char_abc = get_metrics(canvas, glyph);
if (x + char_abc.advance.width > width)
return reader.get_position();
x += char_abc.advance.width;
reader.next();
}
return text.size();
}
size_t Font::clip_from_right(Canvas &canvas, const std::string &text, float width) const
{
float x = 0.0f;
UTF8_Reader reader(text.data(), text.length());
reader.set_position(text.length());
while (reader.get_position() != 0)
{
reader.prev();
unsigned int glyph = reader.get_char();
GlyphMetrics char_abc = get_metrics(canvas, glyph);
if (x + char_abc.advance.width > width)
{
reader.next();
return reader.get_position();
}
x += char_abc.advance.width;
}
return 0;
}
void Font::draw_text(Canvas &canvas, const Pointf &position, const std::string &text, const Colorf &color)
{
if (impl)
{
impl->draw_text(canvas, position, text, color);
}
}
std::string Font::get_clipped_text(Canvas &canvas, const Sizef &box_size, const std::string &text, const std::string &ellipsis_text) const
{
std::string out_string;
out_string.reserve(text.length());
if (impl)
{
Pointf pos;
FontMetrics fm = get_font_metrics(canvas);
float descent = fm.get_descent();
float line_spacing = fm.get_line_height();
std::vector<std::string> lines = StringHelp::split_text(text, "\n", false);
for (std::vector<std::string>::size_type i = 0; i < lines.size(); i++)
{
if (i == 0 || pos.y + descent < box_size.height)
{
Sizef size = measure_text(canvas, lines[i]).bbox_size;
if (pos.x + size.width <= box_size.width)
{
if (!out_string.empty())
out_string += "\n";
out_string += lines[i];
}
else
{
Sizef ellipsis = measure_text(canvas, ellipsis_text).bbox_size;
int seek_start = 0;
int seek_end = lines[i].size();
int seek_center = (seek_start + seek_end) / 2;
UTF8_Reader utf8_reader(lines[i].data(), lines[i].length());
while (true)
{
utf8_reader.set_position(seek_center);
utf8_reader.move_to_leadbyte();
if (seek_center != utf8_reader.get_position())
utf8_reader.next();
seek_center = utf8_reader.get_position();
if (seek_center == seek_end)
break;
utf8_reader.set_position(seek_start);
utf8_reader.next();
if (utf8_reader.get_position() == seek_end)
break;
Sizef text_size = measure_text(canvas, lines[i].substr(0, seek_center)).bbox_size;
if (pos.x + text_size.width + ellipsis.width >= box_size.width)
seek_end = seek_center;
else
seek_start = seek_center;
seek_center = (seek_start + seek_end) / 2;
}
if (!out_string.empty())
out_string += "\n";
out_string += lines[i].substr(0, seek_center) + ellipsis_text;
}
pos.y += line_spacing;
}
}
}
return out_string;
}
FontMetrics Font::get_font_metrics(Canvas &canvas) const
{
if (impl)
return impl->get_font_metrics(canvas);
return FontMetrics();
}
int Font::get_character_index(Canvas &canvas, const std::string &text, const Pointf &point) const
{
if (impl)
return impl->get_character_index(canvas, text, point);
return 0;
}
std::vector<Rectf> Font::get_character_indices(Canvas &canvas, const std::string &text) const
{
if (impl)
return impl->get_character_indices(canvas, text);
return std::vector<Rectf>();
}
FontHandle *Font::get_handle(Canvas &canvas)
{
if (impl)
return impl->get_handle(canvas);
return nullptr;
}
FontHandle::~FontHandle()
{
}
FontDescription Font::get_description() const
{
if (impl)
return impl->get_description();
return FontDescription();
}
}
| 8,492 | 3,336 |
// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2010 Hieu Hoang
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "ChartTrellisPath.h"
#include "ChartHypothesis.h"
#include "ChartTrellisDetour.h"
#include "ChartTrellisDetourQueue.h"
#include "ChartTrellisNode.h"
namespace Moses
{
ChartTrellisPath::ChartTrellisPath(const ChartHypothesis &hypo)
: m_finalNode(new ChartTrellisNode(hypo))
, m_deviationPoint(NULL)
, m_scoreBreakdown(hypo.GetScoreBreakdown())
, m_totalScore(hypo.GetTotalScore())
{
}
ChartTrellisPath::ChartTrellisPath(const ChartTrellisDetour &detour)
: m_finalNode(new ChartTrellisNode(detour, m_deviationPoint))
, m_scoreBreakdown(detour.GetBasePath().m_scoreBreakdown)
, m_totalScore(0)
{
CHECK(m_deviationPoint);
ScoreComponentCollection scoreChange;
scoreChange = detour.GetReplacementHypo().GetScoreBreakdown();
scoreChange.MinusEquals(detour.GetSubstitutedNode().GetHypothesis().GetScoreBreakdown());
m_scoreBreakdown.PlusEquals(scoreChange);
m_totalScore = m_scoreBreakdown.GetWeightedScore();
}
ChartTrellisPath::~ChartTrellisPath()
{
delete m_finalNode;
}
Phrase ChartTrellisPath::GetOutputPhrase() const
{
Phrase ret = GetFinalNode().GetOutputPhrase();
return ret;
}
} // namespace Moses
| 2,128 | 692 |
#pragma once
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include <mutex>
enum Direction {
Up,
Right,
Down,
Left
};
class Player : public sf::Drawable
{
public:
// Constructor
Player(const std::map<std::string, sf::Texture>&, std::mutex*);
// Destructor
~Player();
// Setters
void processKeys(sf::Keyboard::Key);
// Getters
sf::Vector2f getHeadPos();
// Processors
void movePlayer();
void addPart();
bool safeCheck(sf::RectangleShape&, sf::Text&, sf::Sound&, sf::Sound&);
private:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
private:
std::vector<sf::RectangleShape> snakeBody;
Direction m_dir;
Direction m_lastDir;
std::mutex* mu;
int playerScore;
};
| 736 | 272 |
#include <polyfem/RhsAssembler.hpp>
#include <polyfem/BoundarySampler.hpp>
#include <polyfem/LinearSolver.hpp>
// #include <polyfem/UIState.hpp>
#include <polyfem/Logger.hpp>
#include <Eigen/Sparse>
#ifdef USE_TBB
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include <tbb/enumerable_thread_specific.h>
#endif
#include <iostream>
#include <map>
#include <memory>
namespace polyfem
{
namespace
{
class LocalThreadScalarStorage
{
public:
double val;
ElementAssemblyValues vals;
LocalThreadScalarStorage()
{
val = 0;
}
};
}
RhsAssembler::RhsAssembler(const Mesh &mesh, const int n_basis, const int size, const std::vector< ElementBases > &bases, const std::vector< ElementBases > &gbases, const std::string &formulation, const Problem &problem)
: mesh_(mesh), n_basis_(n_basis), size_(size), bases_(bases), gbases_(gbases), formulation_(formulation), problem_(problem)
{ }
void RhsAssembler::assemble(Eigen::MatrixXd &rhs, const double t) const
{
rhs = Eigen::MatrixXd::Zero(n_basis_ * size_, 1);
if(!problem_.is_rhs_zero())
{
Eigen::MatrixXd rhs_fun;
const int n_elements = int(bases_.size());
ElementAssemblyValues vals;
for(int e = 0; e < n_elements; ++e)
{
vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);
const Quadrature &quadrature = vals.quadrature;
problem_.rhs(formulation_, vals.val, t, rhs_fun);
for(int d = 0; d < size_; ++d)
rhs_fun.col(d) = rhs_fun.col(d).array() * vals.det.array() * quadrature.weights.array();
const int n_loc_bases_ = int(vals.basis_values.size());
for(int i = 0; i < n_loc_bases_; ++i)
{
const AssemblyValues &v = vals.basis_values[i];
for(int d = 0; d < size_; ++d)
{
const double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum();
for(std::size_t ii = 0; ii < v.global.size(); ++ii)
rhs(v.global[ii].index*size_+d) += rhs_value * v.global[ii].val;
}
}
}
}
}
void RhsAssembler::initial_solution(Eigen::MatrixXd &sol) const
{
time_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_solution(pts, val);}, sol);
}
void RhsAssembler::initial_velocity(Eigen::MatrixXd &sol) const
{
time_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_velocity(pts, val);}, sol);
}
void RhsAssembler::initial_acceleration(Eigen::MatrixXd &sol) const
{
time_bc([&](const Eigen::MatrixXd&pts, Eigen::MatrixXd&val){ problem_.initial_acceleration(pts, val);}, sol);
}
void RhsAssembler::time_bc(const std::function<void(const Eigen::MatrixXd&, Eigen::MatrixXd&)> &fun,Eigen::MatrixXd &sol) const
{
sol = Eigen::MatrixXd::Zero(n_basis_ * size_, 1);
Eigen::MatrixXd loc_sol;
const int n_elements = int(bases_.size());
ElementAssemblyValues vals;
for(int e = 0; e < n_elements; ++e)
{
vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);
const Quadrature &quadrature = vals.quadrature;
//problem_.initial_solution(vals.val, loc_sol);
fun(vals.val, loc_sol);
for(int d = 0; d < size_; ++d)
loc_sol.col(d) = loc_sol.col(d).array() * vals.det.array() * quadrature.weights.array();
const int n_loc_bases_ = int(vals.basis_values.size());
for(int i = 0; i < n_loc_bases_; ++i)
{
const AssemblyValues &v = vals.basis_values[i];
for(int d = 0; d < size_; ++d)
{
const double sol_value = (loc_sol.col(d).array() * v.val.array()).sum();
for(std::size_t ii = 0; ii < v.global.size(); ++ii)
sol(v.global[ii].index*size_+d) += sol_value * v.global[ii].val;
}
}
}
}
void RhsAssembler::set_bc(
const std::function<void(const Eigen::MatrixXi&, const Eigen::MatrixXd&, const Eigen::MatrixXd&, Eigen::MatrixXd &)> &df,
const std::function<void(const Eigen::MatrixXi&, const Eigen::MatrixXd&, const Eigen::MatrixXd&, Eigen::MatrixXd &)> &nf,
const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs) const
{
const int n_el=int(bases_.size());
Eigen::MatrixXd uv, samples, gtmp, rhs_fun;
Eigen::VectorXi global_primitive_ids;
int index = 0;
std::vector<int> indices; indices.reserve(n_el*10);
// std::map<int, int> global_index_to_col;
long total_size = 0;
Eigen::Matrix<bool, Eigen::Dynamic, 1> is_boundary(n_basis_); is_boundary.setConstant(false);
Eigen::VectorXi global_index_to_col(n_basis_); global_index_to_col.setConstant(-1);
const int actual_dim = problem_.is_scalar() ? 1 : mesh_.dimension();
// assert((bounday_nodes.size()/actual_dim)*actual_dim == bounday_nodes.size());
for(int b : bounday_nodes)
is_boundary[b/actual_dim] = true;
for(const auto &lb : local_boundary)
{
const int e = lb.element_id();
bool has_samples = sample_boundary(lb, resolution, true, uv, samples, global_primitive_ids);
if(!has_samples)
continue;
const ElementBases &bs = bases_[e];
const int n_local_bases = int(bs.bases.size());
total_size += samples.rows();
for(int j = 0; j < n_local_bases; ++j)
{
const Basis &b=bs.bases[j];
for(std::size_t ii = 0; ii < b.global().size(); ++ii)
{
//pt found
// if(std::find(bounday_nodes.begin(), bounday_nodes.end(), size_ * b.global()[ii].index) != bounday_nodes.end())
if(is_boundary[b.global()[ii].index])
{
//if(global_index_to_col.find( b.global()[ii].index ) == global_index_to_col.end())
if(global_index_to_col(b.global()[ii].index) == -1)
{
// global_index_to_col[b.global()[ii].index] = index++;
global_index_to_col(b.global()[ii].index) = index++;
indices.push_back(b.global()[ii].index);
assert(indices.size() == size_t(index));
}
}
}
}
}
// Eigen::MatrixXd global_mat = Eigen::MatrixXd::Zero(total_size, indices.size());
Eigen::MatrixXd global_rhs = Eigen::MatrixXd::Zero(total_size, size_);
const long buffer_size = total_size * long(indices.size());
std::vector< Eigen::Triplet<double> > entries, entries_t;
// entries.reserve(buffer_size);
// entries_t.reserve(buffer_size);
index = 0;
int global_counter = 0;
Eigen::MatrixXd mapped;
std::vector<AssemblyValues> tmp_val;
for(const auto &lb : local_boundary)
{
const int e = lb.element_id();
bool has_samples = sample_boundary(lb, resolution, false, uv, samples, global_primitive_ids);
if(!has_samples)
continue;
const ElementBases &bs = bases_[e];
const ElementBases &gbs = gbases_[e];
const int n_local_bases = int(bs.bases.size());
gbs.eval_geom_mapping(samples, mapped);
bs.evaluate_bases(samples, tmp_val);
for(int j = 0; j < n_local_bases; ++j)
{
const Basis &b=bs.bases[j];
const auto &tmp = tmp_val[j].val;
for(std::size_t ii = 0; ii < b.global().size(); ++ii)
{
// auto item = global_index_to_col.find(b.global()[ii].index);
// if(item != global_index_to_col.end()){
auto item = global_index_to_col(b.global()[ii].index);
if(item != -1){
for(int k = 0; k < int(tmp.size()); ++k)
{
// entries.push_back(Eigen::Triplet<double>(global_counter+k, item->second, tmp(k, j) * b.global()[ii].val));
// entries_t.push_back(Eigen::Triplet<double>(item->second, global_counter+k, tmp(k, j) * b.global()[ii].val));
entries.push_back(Eigen::Triplet<double>(global_counter+k, item, tmp(k) * b.global()[ii].val));
entries_t.push_back(Eigen::Triplet<double>(item, global_counter+k, tmp(k) * b.global()[ii].val));
}
// global_mat.block(global_counter, item->second, tmp.size(), 1) = tmp;
}
}
}
// problem_.bc(mesh_, global_primitive_ids, mapped, t, rhs_fun);
df(global_primitive_ids, uv, mapped, rhs_fun);
global_rhs.block(global_counter, 0, rhs_fun.rows(), rhs_fun.cols()) = rhs_fun;
global_counter += rhs_fun.rows();
//UIState::ui_state().debug_data().add_points(mapped, Eigen::MatrixXd::Constant(1, 3, 0));
//Eigen::MatrixXd asd(mapped.rows(), 3);
//asd.col(0)=mapped.col(0);
//asd.col(1)=mapped.col(1);
//asd.col(2)=rhs_fun;
//UIState::ui_state().debug_data().add_points(asd, Eigen::MatrixXd::Constant(1, 3, 0));
}
assert(global_counter == total_size);
if(total_size > 0)
{
const double mmin = global_rhs.minCoeff();
const double mmax = global_rhs.maxCoeff();
if(fabs(mmin) < 1e-8 && fabs(mmax) < 1e-8)
{
// std::cout<<"is all zero, skipping"<<std::endl;
for(size_t i = 0; i < indices.size(); ++i){
for(int d = 0; d < size_; ++d){
if(problem_.all_dimentions_dirichelt() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i]*size_+d) != bounday_nodes.end())
rhs(indices[i]*size_+d) = 0;
}
}
}
else
{
StiffnessMatrix mat(int(total_size), int(indices.size()));
mat.setFromTriplets(entries.begin(), entries.end());
StiffnessMatrix mat_t(int(indices.size()), int(total_size));
mat_t.setFromTriplets(entries_t.begin(), entries_t.end());
StiffnessMatrix A = mat_t * mat;
Eigen::MatrixXd b = mat_t * global_rhs;
Eigen::MatrixXd coeffs(b.rows(), b.cols());
json params = {
{"mtype", -2}, // matrix type for Pardiso (2 = SPD)
// {"max_iter", 0}, // for iterative solvers
// {"tolerance", 1e-9}, // for iterative solvers
};
// auto solver = LinearSolver::create("", "");
auto solver = LinearSolver::create(LinearSolver::defaultSolver(), LinearSolver::defaultPrecond());
solver->setParameters(params);
solver->analyzePattern(A);
solver->factorize(A);
for(long i = 0; i < b.cols(); ++i){
solver->solve(b.col(i), coeffs.col(i));
}
logger().trace("RHS solve error {}", (A*coeffs-b).norm());
for(long i = 0; i < coeffs.rows(); ++i){
for(int d = 0; d < size_; ++d){
if(problem_.all_dimentions_dirichelt() || std::find(bounday_nodes.begin(), bounday_nodes.end(), indices[i]*size_+d) != bounday_nodes.end())
rhs(indices[i]*size_+d) = coeffs(i, d);
}
}
}
}
//Neumann
Eigen::MatrixXd points;
Eigen::VectorXd weights;
ElementAssemblyValues vals;
for(const auto &lb : local_neumann_boundary)
{
const int e = lb.element_id();
bool has_samples = boundary_quadrature(lb, resolution, false, uv, points, weights, global_primitive_ids);
if(!has_samples)
continue;
const ElementBases &gbs = gbases_[e];
const ElementBases &bs = bases_[e];
vals.compute(e, mesh_.is_volume(), points, bs, gbs);
// problem_.neumann_bc(mesh_, global_primitive_ids, vals.val, t, rhs_fun);
nf(global_primitive_ids, uv, vals.val, rhs_fun);
// UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(0,1,0));
for(int d = 0; d < size_; ++d)
rhs_fun.col(d) = rhs_fun.col(d).array() * weights.array();
for(int i = 0; i < lb.size(); ++i)
{
const int primitive_global_id = lb.global_primitive_id(i);
const auto nodes = bs.local_nodes_for_primitive(primitive_global_id, mesh_);
for(long n = 0; n < nodes.size(); ++n)
{
// const auto &b = bs.bases[nodes(n)];
const AssemblyValues &v = vals.basis_values[nodes(n)];
for(int d = 0; d < size_; ++d)
{
const double rhs_value = (rhs_fun.col(d).array() * v.val.array()).sum();
for(size_t g = 0; g < v.global.size(); ++g)
{
const int g_index = v.global[g].index*size_+d;
const bool is_neumann = std::find(bounday_nodes.begin(), bounday_nodes.end(), g_index ) == bounday_nodes.end();
if(is_neumann){
rhs(g_index) += rhs_value * v.global[g].val;
// UIState::ui_state().debug_data().add_points(v.global[g].node, Eigen::RowVector3d(1,0,0));
}
// else
// std::cout<<"skipping "<<g_index<<" "<<rhs_value * v.global[g].val<<std::endl;
}
}
}
}
}
}
void RhsAssembler::set_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const
{
set_bc(
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.bc(mesh_, global_ids, uv, pts, t, val);},
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_bc(mesh_, global_ids, uv, pts, t, val);},
local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);
}
void RhsAssembler::set_velocity_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const
{
set_bc(
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.velocity_bc(mesh_, global_ids, uv, pts, t, val);},
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_velocity_bc(mesh_, global_ids, uv, pts, t, val);},
local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);
}
void RhsAssembler::set_acceleration_bc(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, Eigen::MatrixXd &rhs, const double t) const
{
set_bc(
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.acceleration_bc(mesh_, global_ids, uv, pts, t, val);},
[&](const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, Eigen::MatrixXd &val){ problem_.neumann_acceleration_bc(mesh_, global_ids, uv, pts, t, val);},
local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs);
}
void RhsAssembler::compute_energy_grad(const std::vector< LocalBoundary > &local_boundary, const std::vector<int> &bounday_nodes, const int resolution, const std::vector< LocalBoundary > &local_neumann_boundary, const Eigen::MatrixXd &final_rhs, const double t, Eigen::MatrixXd &rhs) const
{
if(problem_.is_linear_in_time()){
if(problem_.is_time_dependent())
rhs = final_rhs;
else
rhs = final_rhs * t;
}
else
{
assemble(rhs, t);
rhs *= -1;
set_bc(local_boundary, bounday_nodes, resolution, local_neumann_boundary, rhs, t);
}
}
double RhsAssembler::compute_energy(const Eigen::MatrixXd &displacement, const std::vector< LocalBoundary > &local_neumann_boundary, const int resolution, const double t) const
{
Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> local_displacement(size_);
double res = 0;
Eigen::MatrixXd forces;
if(!problem_.is_rhs_zero())
{
#ifdef USE_TBB
typedef tbb::enumerable_thread_specific< LocalThreadScalarStorage > LocalStorage;
LocalStorage storages((LocalThreadScalarStorage()));
#else
LocalThreadScalarStorage loc_storage;
#endif
const int n_bases = int(bases_.size());
#ifdef USE_TBB
tbb::parallel_for( tbb::blocked_range<int>(0, n_bases), [&](const tbb::blocked_range<int> &r) {
LocalStorage::reference loc_storage = storages.local();
for (int e = r.begin(); e != r.end(); ++e) {
#else
for(int e=0; e < n_bases; ++e) {
#endif
ElementAssemblyValues &vals = loc_storage.vals;
vals.compute(e, mesh_.is_volume(), bases_[e], gbases_[e]);
const Quadrature &quadrature = vals.quadrature;
const Eigen::VectorXd da = vals.det.array() * quadrature.weights.array();
problem_.rhs(formulation_, vals.val, t, forces);
assert(forces.rows() == da.size());
assert(forces.cols() == size_);
for(long p = 0; p < da.size(); ++p)
{
local_displacement.setZero();
for(size_t i = 0; i < vals.basis_values.size(); ++i)
{
const auto &bs = vals.basis_values[i];
assert(bs.val.size() == da.size());
const double b_val = bs.val(p);
for(int d = 0; d < size_; ++d)
{
for(std::size_t ii = 0; ii < bs.global.size(); ++ii)
{
local_displacement(d) += (bs.global[ii].val * b_val) * displacement(bs.global[ii].index*size_ + d);
}
}
}
for(int d = 0; d < size_; ++d)
loc_storage.val += forces(p, d) * local_displacement(d) * da(p);
// res += forces(p, d) * local_displacement(d) * da(p);
}
#ifdef USE_TBB
}});
#else
}
#endif
#ifdef USE_TBB
for (LocalStorage::iterator i = storages.begin(); i != storages.end(); ++i)
{
res += i->val;
}
#else
res = loc_storage.val;
#endif
}
ElementAssemblyValues vals;
//Neumann
Eigen::MatrixXd points, uv;
Eigen::VectorXd weights;
Eigen::VectorXi global_primitive_ids;
for(const auto &lb : local_neumann_boundary)
{
const int e = lb.element_id();
bool has_samples = boundary_quadrature(lb, resolution, false, uv, points, weights, global_primitive_ids);
if(!has_samples)
continue;
const ElementBases &gbs = gbases_[e];
const ElementBases &bs = bases_[e];
vals.compute(e, mesh_.is_volume(), points, bs, gbs);
problem_.neumann_bc(mesh_, global_primitive_ids, uv, vals.val, t, forces);
// UIState::ui_state().debug_data().add_points(vals.val, Eigen::RowVector3d(1,0,0));
for(long p = 0; p < weights.size(); ++p)
{
local_displacement.setZero();
for(size_t i = 0; i < vals.basis_values.size(); ++i)
{
const auto &vv = vals.basis_values[i];
assert(vv.val.size() == weights.size());
const double b_val = vv.val(p);
for(int d = 0; d < size_; ++d)
{
for(std::size_t ii = 0; ii < vv.global.size(); ++ii)
{
local_displacement(d) += (vv.global[ii].val * b_val) * displacement(vv.global[ii].index*size_ + d);
}
}
}
for(int d = 0; d < size_; ++d)
res -= forces(p, d) * local_displacement(d) * weights(p);
}
}
return res;
}
bool RhsAssembler::boundary_quadrature(const LocalBoundary &local_boundary, const int order, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &points, Eigen::VectorXd &weights, Eigen::VectorXi &global_primitive_ids) const
{
uv.resize(0, 0);
points.resize(0, 0);
weights.resize(0);
global_primitive_ids.resize(0);
for(int i = 0; i < local_boundary.size(); ++i)
{
const int gid = local_boundary.global_primitive_id(i);
Eigen::MatrixXd tmp_p, tmp_uv;
Eigen::VectorXd tmp_w;
switch(local_boundary.type())
{
case BoundaryType::TriLine: BoundarySampler::quadrature_for_tri_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;
case BoundaryType::QuadLine: BoundarySampler::quadrature_for_quad_edge(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;
case BoundaryType::Quad: BoundarySampler::quadrature_for_quad_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;
case BoundaryType::Tri: BoundarySampler::quadrature_for_tri_face(local_boundary[i], order, gid, mesh_, tmp_uv, tmp_p, tmp_w); break;
case BoundaryType::Invalid: assert(false); break;
default: assert(false);
}
uv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols());
uv.bottomRows(tmp_uv.rows()) = tmp_uv;
points.conservativeResize(points.rows() + tmp_p.rows(), tmp_p.cols());
points.bottomRows(tmp_p.rows()) = tmp_p;
weights.conservativeResize(weights.rows() + tmp_w.rows(), tmp_w.cols());
weights.bottomRows(tmp_w.rows()) = tmp_w;
global_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp_p.rows());
global_primitive_ids.bottomRows(tmp_p.rows()).setConstant(gid);
}
assert(uv.rows() == global_primitive_ids.size());
assert(points.rows() == global_primitive_ids.size());
assert(weights.size() == global_primitive_ids.size());
return true;
}
bool RhsAssembler::sample_boundary(const LocalBoundary &local_boundary, const int n_samples, const bool skip_computation, Eigen::MatrixXd &uv, Eigen::MatrixXd &samples, Eigen::VectorXi &global_primitive_ids) const
{
uv.resize(0, 0);
samples.resize(0, 0);
global_primitive_ids.resize(0);
for(int i = 0; i < local_boundary.size(); ++i)
{
Eigen::MatrixXd tmp, tmp_uv;
switch(local_boundary.type())
{
case BoundaryType::TriLine: BoundarySampler::sample_parametric_tri_edge(local_boundary[i], n_samples, tmp_uv, tmp); break;
case BoundaryType::QuadLine: BoundarySampler::sample_parametric_quad_edge(local_boundary[i], n_samples, tmp_uv, tmp); break;
case BoundaryType::Quad: BoundarySampler::sample_parametric_quad_face(local_boundary[i], n_samples, tmp_uv, tmp); break;
case BoundaryType::Tri: BoundarySampler::sample_parametric_tri_face(local_boundary[i], n_samples, tmp_uv, tmp); break;
case BoundaryType::Invalid: assert(false); break;
default: assert(false);
}
uv.conservativeResize(uv.rows() + tmp_uv.rows(), tmp_uv.cols());
uv.bottomRows(tmp_uv.rows()) = tmp_uv;
samples.conservativeResize(samples.rows() + tmp.rows(), tmp.cols());
samples.bottomRows(tmp.rows()) = tmp;
global_primitive_ids.conservativeResize(global_primitive_ids.rows() + tmp.rows());
global_primitive_ids.bottomRows(tmp.rows()).setConstant(local_boundary.global_primitive_id(i));
}
assert(uv.rows() == global_primitive_ids.size());
assert(samples.rows() == global_primitive_ids.size());
return true;
}
}
| 21,503 | 9,445 |
/*
Copyright 2020 Marc SIBERT
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 <avr/sleep.h>
#include <Arduino.h>
#include "matrix.h"
#if 1
#include "zxpix_font.h"
#define FONT_WIDTH 6
#else
#include "homespun_font.h"
#define FONT_WIDTH 7
#endif
#include "ws2812b.h"
float Matrix::alim() const {
setTimer1(false); // unset
setADC2BG();
delay(2); // wait for Vref to settle
ADCSRA |= _BV(ADSC); // start conv.
while ( ADCSRA & _BV(ADSC) ) yield(); // wait until end conv.
const unsigned adc = ADCL + ( ADCH * 256U );
setComparator(0x06); // comp. BG vs. A6
setTimer1();
return (1023UL * BANDGAP_VOLTAGE) / adc / 1000.0f;
}
void Matrix::begin() {
for (uint8_t i = 0; i < 8; ++i) {
pinMode(cols[i], INPUT);
digitalWrite(cols[i], LOW);
pinMode(rows[i], OUTPUT);
digitalWrite(rows[i], LOW);
}
ws.setup();
ws.setRGB(0, 0, 5, 0);
ws.flush();
pinMode(A6, INPUT);
setComparator(0x06);
cCol = 0;
setTimer1();
}
Matrix::button_t Matrix::button() const {
return Matrix::buttons;
}
void Matrix::clear(const bool invert) {
for (byte i = 0; i < 8; ++i) {
leds[i] = invert ? 0xFF : 0x00;
}
}
inline
void Matrix::comparatorInt() {
// Unset all rows
PORTC &= ~B00010100;
PORTD &= ~B11111100;
// Read comparator bit (Analog Comparator Output) in ACSR
const auto b = static_cast<button_t>( 1 << cCol );
buttons = ACSR & _BV(ACO) ? static_cast<button_t>(buttons | b) : static_cast<button_t>(buttons & ~b);
// Switch col. off
pinMode(cols[cCol], INPUT);
// Next col
Matrix::cCol = (Matrix::cCol + 1) % 8;
// Count bits (Brian Kernighan’s Algorithm)
const uint8_t l = leds[cCol];
byte count = 0;
for (auto n = l; n > 0; n &= (n - 1)) ++count;
// Set timing on
OCR1A = 10 + (count << 4);
}
void Matrix::deepSleep() const {
ADCSRA = 0; // Unused ADC (mandatory)
ADCSRB = 0; // Unused Comparator
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_mode();
}
inline
void Matrix::overflowInt() {
const uint8_t l = leds[cCol];
// Set right rows
PORTC = (PORTC & ~B00010100) | (l & 0x10) | (l & 0x40) >> 4;
PORTD = (PORTD & ~B11111100) | (l & 0x03) << 5 | (l & 0x04) << 2 | (l & 0x08) << 4 | (l & 0x20) >> 2 | (l & 0x80) >> 5;
// Switch col. ON
pinMode(cols[cCol], OUTPUT);
}
bool Matrix::pressA(const String& s) {
for (unsigned i = 0 ; i < s.length() ; ++i) {
print( s.charAt(i) );
if ( button() & Matrix::A ) {
clear(true);
delay(75);
clear();
return true;
}
}
return false;
}
Matrix::button_t Matrix::pressButton(const String& s) {
for (unsigned i = 0 ; i < s.length() ; ++i) {
print( s.charAt(i) );
const auto b = button();
if ( b ) {
clear(true);
delay(75);
clear();
return b;
}
}
return NONE;
}
inline
void Matrix::print(const char c) {
println(String(c));
}
inline
void Matrix::println(const char c) {
println(String(c));
}
void Matrix::println(const String& str) {
for (unsigned l = 0; l < str.length(); ++l) {
const char c = str.charAt(l);
byte m = FONT_WIDTH;
for (byte i = FONT_WIDTH - 1; i > 1; --i) { // minimum 2 dots
if (!pgm_read_byte(&(font[c - 0x20][i]))) {
m = i;
}
}
for (byte i = 0; i < m; ++i) {
const byte b = pgm_read_byte(&(font[c - 0x20][i]));
noInterrupts();
for (byte j = 0; j < 8; ++j) {
if ( b & (0x80 >> j) )
leds[j] = ( leds[j] >> 1 ) | 0x80;
else
leds[j] >>= 1;
}
interrupts();
delay(100);
}
// 1 separator
noInterrupts();
// for (byte j = 0; j < 8; ++j) leds[j] >>= 1;
for (auto p = leds; p < leds + 8; ++p)
*p >>= 1;
interrupts();
delay(100);
}
yield();
}
void Matrix::set(const byte x, const byte y) {
leds[y] |= 1 << x;
}
void Matrix::setADC2A6() const {
noInterrupts();
ADMUX = _BV(REFS0) | _BV(ADLAR) | 0x06; // ref = AVcc & 8 bits & MUX = ADC6
ADCSRA = _BV(ADEN) | _BV(ADPS1); // ADC Prescaler div. 4
ADCSRB = 0;
interrupts();
}
void Matrix::setADC2BG() const {
noInterrupts();
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); // ref = AVcc & 10 bits & MUX = V1.1
ADCSRA = _BV(ADEN) | _BV(ADPS2); // ADC Prescaler div. 16
ADCSRB = 0;
interrupts();
}
void Matrix::setComparator(const byte mux) const {
noInterrupts();
ADMUX = mux & ( _BV(MUX2) | _BV(MUX1) | _BV(MUX0) );
ADCSRA = 0; // Unused ADC (mandatory)
ADCSRB = _BV(ACME); // Analog Comparator Multiplexer Enable
ACSR = _BV(ACBG); // Analog Comparator BandGap
interrupts();
}
void Matrix::setTimer1(const bool state) const {
noInterrupts();
OCR1A = 0;
TCCR1A = _BV(WGM10);
TCCR1B = _BV(WGM12) | _BV(CS11) | _BV(CS10); // clk/64
TIMSK1 = state ? _BV(OCIE1A) | _BV(TOIE1) : 0;
interrupts();
}
void Matrix::showBatteryAndVoltage() {
const auto a = alim();
showBattery(a);
const auto t = millis();
while (millis() - t < 2000) {
delay(100);
if (button() & Matrix::B) {
Matrix::println( String(F("Bat: ")) + String(a) + String(F("v ")) );
}
}
clear();
}
bool Matrix::test(const byte x, const byte y) const {
return ( leds[y] & (1 << x) );
}
void Matrix::unSet(const byte x, const byte y) {
leds[y] &= ~(1 << x);
}
void Matrix::showBattery(const float& v) {
if (v > 4.5) {
noInterrupts();
leds[7] = 0b00000100;
leds[6] = 0b00011100;
leds[5] = 0b01100111;
leds[4] = 0b11000100;
leds[3] = 0b01100111;
leds[2] = 0b00011100;
leds[1] = 0b00000100;
leds[0] = 0b00000000;
interrupts();
} else {
const byte i = (v >= 4.1) ? 0b00111100 :
(v >= 3.9) ? 0b00011100 :
(v >= 3.7) ? 0b00001100 :
(v >= 3.5) ? 0b00000100 :
0b00000000 ;
noInterrupts();
leds[7] = 0b01111111;
leds[6] = 0b11000001;
leds[5] = 0b10000001 | i;
leds[4] = 0b10000001 | i;
leds[3] = 0b11000001;
leds[2] = 0b01111111;
leds[1] = 0b00000000;
leds[0] = 0b00000000;
interrupts();
}
}
volatile uint8_t Matrix::leds[8];
volatile byte Matrix::cCol;
volatile Matrix::button_t Matrix::buttons;
const uint8_t Matrix::cols[] = { A0, A1, A5, 9, 8, 10, 12, A3};
const uint8_t Matrix::rows[] = { 5, 6, 4, 7, A4, 3, A2, 2};
ISR(TIMER1_OVF_vect) { // ROW ON
Matrix::overflowInt();
}
ISR(TIMER1_COMPA_vect) { // ROW OFF
Matrix::comparatorInt();
}
| 7,021 | 3,266 |
#include "FrenetOptimalTrajectory.h"
#include "FrenetPath.h"
#include "py_cpp_struct.h"
#include "CubicSpline2D.h"
#include "utils.h"
#include <stddef.h>
#include <vector>
using namespace std;
// C++ wrapper to expose the FrenetOptimalTrajectory class to python
extern "C" {
// Compute the frenet optimal trajectory given initial conditions
// in frenet space.
//
// Arguments:
// fot_ic (FrenetInitialConditions *):
// struct ptr containing relevant initial conditions to compute
// Frenet Optimal Trajectory
// fot_hp (FrenetHyperparameters *):
// struct ptr containing relevant hyperparameters to compute
// Frenet Optimal Trajectory
// x_path, y_path, speeds (double *):
// ptr to storage arrays for Frenet Optimal Trajectory
// params (double *):
// ptr to store initial conditions for debugging
//
// Returns:
// 1 if successful, 0 if failure
// Also stores the Frenet Optimal Trajectory into x_path, y_path,
// speeds if it exists
void run_fot(
FrenetInitialConditions *fot_ic, FrenetHyperparameters *fot_hp,
FrenetReturnValues *fot_rv
) {
FrenetOptimalTrajectory fot = FrenetOptimalTrajectory(fot_ic, fot_hp);
FrenetPath* best_frenet_path = fot.getBestPath();
if (best_frenet_path && !best_frenet_path->x.empty()){
fot_rv->success = 1;
fot_rv->path_length = std::min(best_frenet_path->x.size(), MAX_PATH_LENGTH);
for (size_t i = 0; i < fot_rv->path_length; i++) {
fot_rv->x_path[i] = best_frenet_path->x[i];
fot_rv->y_path[i] = best_frenet_path->y[i];
fot_rv->speeds[i] = best_frenet_path->s_d[i];
fot_rv->ix[i] = best_frenet_path->ix[i];
fot_rv->iy[i] = best_frenet_path->iy[i];
fot_rv->iyaw[i] = best_frenet_path->iyaw[i];
fot_rv->d[i] = best_frenet_path->d[i];
fot_rv->s[i] = best_frenet_path->s[i];
fot_rv->speeds_x[i] = cos(best_frenet_path->yaw[i]) *
fot_rv->speeds[i];
fot_rv->speeds_y[i] = sin(best_frenet_path->yaw[i]) *
fot_rv->speeds[i];
}
// store info for debug
fot_rv->params[0] = best_frenet_path->s[1];
fot_rv->params[1] = best_frenet_path->s_d[1];
fot_rv->params[2] = best_frenet_path->d[1];
fot_rv->params[3] = best_frenet_path->d_d[1];
fot_rv->params[4] = best_frenet_path->d_dd[1];
// store costs for logging
fot_rv->costs[0] = best_frenet_path->c_lateral_deviation;
fot_rv->costs[1] = best_frenet_path->c_lateral_velocity;
fot_rv->costs[2] = best_frenet_path->c_lateral_acceleration;
fot_rv->costs[3] = best_frenet_path->c_lateral_jerk;
fot_rv->costs[4] = best_frenet_path->c_lateral;
fot_rv->costs[5] = best_frenet_path->c_longitudinal_acceleration;
fot_rv->costs[6] = best_frenet_path->c_longitudinal_jerk;
fot_rv->costs[7] = best_frenet_path->c_time_taken;
fot_rv->costs[8] = best_frenet_path->c_end_speed_deviation;
fot_rv->costs[9] = best_frenet_path->c_longitudinal;
fot_rv->costs[10] = best_frenet_path->c_inv_dist_to_obstacles;
fot_rv->costs[11] = best_frenet_path->cf;
}
}
// Convert the initial conditions from cartesian space to frenet space
void to_frenet_initial_conditions(
double s0, double x, double y, double vx,
double vy, double forward_speed, double* xp, double* yp, int np,
double* initial_conditions
) {
vector<double> wx (xp, xp + np);
vector<double> wy (yp, yp + np);
CubicSpline2D* csp = new CubicSpline2D(wx, wy);
// get distance from car to spline and projection
double s = csp->find_s(x, y, s0);
double distance = norm(csp->calc_x(s) - x, csp->calc_y(s) - y);
tuple<double, double> bvec ((csp->calc_x(s) - x) / distance,
(csp->calc_y(s) - y) / distance);
// normal spline vector
double x0 = csp->calc_x(s0);
double y0 = csp->calc_y(s0);
double x1 = csp->calc_x(s0 + 2);
double y1 = csp->calc_y(s0 + 2);
// unit vector orthog. to spline
tuple<double, double> tvec (y1-y0, -(x1-x0));
as_unit_vector(tvec);
// compute tangent / normal car vectors
tuple<double, double> fvec (vx, vy);
as_unit_vector(fvec);
// get initial conditions in frenet frame
initial_conditions[0] = s; // current longitudinal position s
initial_conditions[1] = forward_speed; // speed [m/s]
// lateral position c_d [m]
initial_conditions[2] = copysign(distance, dot(tvec, bvec));
// lateral speed c_d_d [m/s]
initial_conditions[3] = -forward_speed * dot(tvec, fvec);
initial_conditions[4] = 0.0; // lateral acceleration c_d_dd [m/s^2]
// TODO: add lateral acceleration when CARLA 9.7 is patched (IMU)
delete csp;
}
}
| 5,274 | 1,894 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/xinclude/XIncludeDOMDocumentProcessor.hpp>
#include <xercesc/xinclude/XIncludeUtils.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/framework/XMLErrorReporter.hpp>
namespace XERCES_CPP_NAMESPACE {
DOMDocument *
XIncludeDOMDocumentProcessor::doXIncludeDOMProcess(const DOMDocument * const source, XMLErrorReporter *errorHandler, XMLEntityHandler* entityResolver /*=NULL*/){
XIncludeUtils xiu(errorHandler);
DOMImplementation* impl = source->getImplementation();
DOMDocument *xincludedDocument = impl->createDocument();
try
{
/* set up the declaration etc of the output document to match the source */
xincludedDocument->setDocumentURI( source->getDocumentURI());
xincludedDocument->setXmlStandalone( source->getXmlStandalone());
xincludedDocument->setXmlVersion( source->getXmlVersion());
/* copy entire source document into the xincluded document. Xincluded document can
then be modified in place */
DOMNode *child = source->getFirstChild();
for (; child != NULL; child = child->getNextSibling()){
if (child->getNodeType() == DOMNode::DOCUMENT_TYPE_NODE){
/* I am simply ignoring these at the moment */
continue;
}
DOMNode *newNode = xincludedDocument->importNode(child, true);
xincludedDocument->appendChild(newNode);
}
DOMNode *docNode = xincludedDocument->getDocumentElement();
/* parse and include the document node */
xiu.parseDOMNodeDoingXInclude(docNode, xincludedDocument, entityResolver);
xincludedDocument->normalizeDocument();
}
catch(const XMLErrs::Codes)
{
xincludedDocument->release();
return NULL;
}
catch(...)
{
xincludedDocument->release();
throw;
}
return xincludedDocument;
}
}
| 2,938 | 801 |
#include <bits/stdc++.h>
using namespace std;
typedef int I;
int main()
{
string s;
cin >> s;
cout << s << s << '\n';
return 0;
}
| 151 | 66 |
#include "Particle.hpp"
#include "Scenes/Scenes.hpp"
namespace acid {
static constexpr float FADE_TIME = 1.0f;
Particle::Particle(std::shared_ptr<ParticleType> particleType, const Vector3f &position, const Vector3f &velocity, float lifeLength, float stageCycles,
float rotation, float scale, float gravityEffect) :
particleType(std::move(particleType)),
position(position),
velocity(velocity),
lifeLength(lifeLength),
stageCycles(stageCycles),
rotation(rotation),
scale(scale),
gravityEffect(gravityEffect) {
}
void Particle::Update() {
auto delta = Engine::Get()->GetDelta().AsSeconds();
velocity.y += -10.0f * gravityEffect * delta;
change = velocity;
change *= delta;
position += change;
elapsedTime += delta;
if (elapsedTime > lifeLength - FADE_TIME)
transparency -= delta / FADE_TIME;
if (!IsAlive() || !Scenes::Get()->GetCamera())
return;
auto cameraToParticle = Scenes::Get()->GetCamera()->GetPosition() - position;
distanceToCamera = cameraToParticle.LengthSquared();
auto lifeFactor = stageCycles * elapsedTime / lifeLength;
if (!particleType->GetImage())
return;
auto stageCount = static_cast<int32_t>(std::pow(particleType->GetNumberOfRows(), 2));
auto atlasProgression = lifeFactor * stageCount;
auto index1 = static_cast<int32_t>(std::floor(atlasProgression));
auto index2 = index1 < stageCount - 1 ? index1 + 1 : index1;
imageBlendFactor = std::fmod(atlasProgression, 1.0f);
imageOffset1 = CalculateImageOffset(index1);
imageOffset2 = CalculateImageOffset(index2);
}
bool Particle::operator<(const Particle &rhs) const {
return distanceToCamera > rhs.distanceToCamera;
}
Vector2f Particle::CalculateImageOffset(int32_t index) const {
auto column = index % particleType->GetNumberOfRows();
auto row = index / particleType->GetNumberOfRows();
return Vector2f(static_cast<float>(column), static_cast<float>(row)) / particleType->GetNumberOfRows();
}
}
| 1,916 | 648 |
/*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Redistribution and use of this software in source and binary forms, with or
without modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of Yahoo! Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission of Yahoo! Inc.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include <iostream>
#include <sys/time.h>
#include <sys/types.h>
#include <signal.h>
#include "debug.h"
#include "logging.h"
#include "util.h"
#include "pidMap.h"
#include "processExitReason.h"
#include "manager.h"
#include "service.h"
#include "process.h"
using namespace std;
//////////////////////////////////////////////////////////////////////
// Determine how many processes should be running for a given service
// and adjust accordingly.
//
// Calibration is called for the following reasons:
//
// o) A serviceSocket has a connect request and no processes are
// running (the service is in the initial state).
//
// o) A process has sent a report via the reportingChannel
//
// o) The service has timed out waiting for a report
//
// o) A process has exited
//////////////////////////////////////////////////////////////////////
void
service::calibrateProcesses(const char* why, int listenBacklog,
bool decreaseOkFlag, bool increaseToMinimumOkFlag)
{
if (debug::calibrate()) DBGPRT << "calibrate: " << _name << ":" << why
<< " do=" << decreaseOkFlag << " io=" << increaseToMinimumOkFlag
<< endl;
//////////////////////////////////////////////////////////////////////
// If we need to ramp up to minimum, do that and return
//////////////////////////////////////////////////////////////////////
if (increaseToMinimumOkFlag && (_activeProcessCount < _config.minimumProcesses)) {
int pc = _config.minimumProcesses - _activeProcessCount;
while (pc-- > 0) createProcess("createMinimum", false);
return;
}
++_calibrateSamples;
_currListenBacklog += listenBacklog;
//////////////////////////////////////////////////////////////////////
// Only check for algorithmic changes periodically, so that activity
// times and counters aren't too granular.
//////////////////////////////////////////////////////////////////////
struct timeval now;
gettimeofday(&now, 0);
bool doneOne = false;
int samplePeriod = now.tv_sec - _prevCalibrationTime;
// First the occupancy-base tests which roll counters, etc.
if (_nextCalibrationTime <= now.tv_sec) {
_currListenBacklog /= _calibrateSamples;
_calibrateSamples = 0;
// Always do "Up" as that does calibration calcs
doneOne = calibrateOccupancyUp(why, now, samplePeriod);
// Only do "Down" if "Up" didn't create a process
if (!doneOne && decreaseOkFlag && (_activeProcessCount > _config.minimumProcesses)) {
doneOne = calibrateOccupancyDown(why, now, samplePeriod);
}
// Roll all the values from current -> previous
_prevListenBacklog = _currListenBacklog;
_currListenBacklog = 0;
if (doneOne) {
_prevOccupancyByTime = _config.occupancyPercent; // That's our guess
}
else {
_prevOccupancyByTime = _currOccupancyByTime;
}
_prevCalibrationTime = now.tv_sec;
_nextCalibrationTime = now.tv_sec + minimumSamplePeriod;
_shmService.resetAggregateCounters();
_timeInProcess = 0;
_requestsCompleted = 0;
}
// Idle timeout is done every call if nothing else happened.
if (!doneOne && decreaseOkFlag) doneOne = calibrateIdleDown(why, now, samplePeriod);
}
//////////////////////////////////////////////////////////////////////
// Ramp up processes based on occupancy. Return true if at least one
// process was started.
//////////////////////////////////////////////////////////////////////
bool
service::calibrateOccupancyUp(const char* why, const struct timeval& now, int samplePeriod)
{
if (debug::calibrate()) DBGPRT << "calibrateOccUp: " << _name << ":" << why << endl;
//////////////////////////////////////////////////////////////////////
// Get active uSeconds and request count for this sample period.
//////////////////////////////////////////////////////////////////////
long long activeuSecs = _shmService.getActiveuSecs();
long requestCount = _shmService.getRequestCount();
//////////////////////////////////////////////////////////////////////
// Sanity check shared counters and timers. They can get trashed due
// to lock-less updates or memory stomping services.
//////////////////////////////////////////////////////////////////////
long activeSecs = activeuSecs / util::MICROSECOND;
if ( (activeSecs < 0) ||
(activeSecs > (minimumSamplePeriod * 2 * _activeProcessCount))) {
if (debug::calibrate()) DBGPRT << "no calibrate: " << _name
<< " " << activeSecs << " " << _activeProcessCount << endl;
return false;
}
//////////////////////////////////////////////////////////////////////
// Average out the backlog across the sample period
//////////////////////////////////////////////////////////////////////
if (_activeProcessCount > 0) {
_currOccupancyByTime = activeuSecs;
_currOccupancyByTime /= _activeProcessCount;
_currOccupancyByTime *= 100;
_currOccupancyByTime /= static_cast<float>(samplePeriod * util::MICROSECOND);
}
else {
_currOccupancyByTime = 0;
}
//////////////////////////////////////////////////////////////////////
// Use a moving average occupancy to smooth spikes
//////////////////////////////////////////////////////////////////////
_currOccupancyByTime = _currOccupancyByTime * 0.75 + _prevOccupancyByTime * 0.25;
_currListenBacklog = _currListenBacklog * 0.75 + _prevListenBacklog * 0.25;
if (debug::calibrate()) {
DBGPRT << "calibrateUp: " << _name << ":" << why << " sample=" << samplePeriod
<< " uSecs=" << activeuSecs << "/" << _timeInProcess
<< " reqs=" << requestCount << "/" << _requestsCompleted
<< " apc=" << _activeProcessCount << "/" << _childCount
<< " occ=" << (int) _currOccupancyByTime << "/" << (int) _prevOccupancyByTime
<< " LQ=" << _currListenBacklog << "/" << _prevListenBacklog
<< " targetO=" << _config.occupancyPercent
<< endl;
}
//////////////////////////////////////////////////////////////////////
// If more are needed, calculate how many more to get to the desired
// occupancy and start them up.
//////////////////////////////////////////////////////////////////////
if (_currOccupancyByTime <= _config.occupancyPercent) return false;
int shortFall = (int) _currOccupancyByTime - _config.occupancyPercent;
shortFall *= _activeProcessCount;
shortFall += 99; // Round % up
shortFall /= 100;
if (shortFall == 0) ++shortFall; // Make sure it's at least one
if (_currListenBacklog >= 1) ++shortFall; // These may overshoot since
if ((_prevListenBacklog >= 10) && (_prevListenBacklog >= 10)) {
shortFall += 5;
}
if (shortFall > (_config.maximumProcesses - _activeProcessCount)) {
shortFall = _config.maximumProcesses - _activeProcessCount;
}
if (logging::calibrate()) {
LOGPRT << "Calibrate Up: " << _name
<< " apc=" << _activeProcessCount
<< " currO=" << (int) _currOccupancyByTime
<< " prevO=" << (int) _prevOccupancyByTime
<< " currLQ=" << (int) _currListenBacklog
<< " prevLQ=" << (int) _prevListenBacklog
<< " shortfall=" << shortFall
<< endl;
}
while (shortFall-- > 0) {
if (!createProcess("createIncrease", false)) break;
}
return true; // Say we started some
}
//////////////////////////////////////////////////////////////////////
// Ramp down processes based on occupancy. Return true if at least one
// process was told to exit.
//
// Calculate what the new occupancy would be if a process were to be
// removed. The idea is that a process will only be removed if the new
// occupancy is still below the threshold. In other words, don't
// remove a process if the result is that next time through this code
// a process is started up.
//
// n=new, o=old, C=count, O=occupancy
// nO = oO * nC / (nC-1)
//////////////////////////////////////////////////////////////////////
bool
service::calibrateOccupancyDown(const char* why, const struct timeval& now, int samplePeriod)
{
if (debug::calibrate()) DBGPRT << "calibrateOccDown: " << _name << ":" << why << endl;
float new1Occupancy = _currOccupancyByTime;
new1Occupancy *= _activeProcessCount;
new1Occupancy /= (_activeProcessCount - 1);
float new2Occupancy = _prevOccupancyByTime;
new2Occupancy *= _activeProcessCount;
new2Occupancy /= (_activeProcessCount - 1);
if (debug::calibrate()) DBGPRT << "calibrateDown: " << _name
<< " new1Occ=" << new1Occupancy
<< " new2Occ=" << new2Occupancy
<< endl;
int lowerThreshold = _config.occupancyPercent - 5; // XX Hack
if ((new1Occupancy >= lowerThreshold) && (new2Occupancy >= lowerThreshold)) return false;
if (logging::calibrate()) {
LOGPRT << "Calibrate Down: " << _name
<< " apc=" << _activeProcessCount
<< " currO=" << (int) _currOccupancyByTime
<< " prevO=" << (int) _prevOccupancyByTime
<< " propCO=" << (int) new1Occupancy
<< " propPO=" << (int) new2Occupancy
<< endl;
}
removeOldestProcess(processExit::excessProcesses);
return true;
}
//////////////////////////////////////////////////////////////////////
// Idle timeout calibration only applies when no reports have been
// seen for the idle-timeout period and there is more than the
// configured minimum processes still running.
//////////////////////////////////////////////////////////////////////
bool
service::calibrateIdleDown(const char* why, const struct timeval& now, int samplePeriod)
{
if (debug::calibrate()) DBGPRT << "calibrateIdle: " << _config.idleTimeout
<< " apc=" << _activeProcessCount
<< " lp=" << _lastPerformanceReport
<< " now=" << now.tv_sec
<< endl;
if ((_config.idleTimeout == 0) || (_activeProcessCount <= _config.minimumProcesses)) {
return false;
}
if ((_lastPerformanceReport + _config.idleTimeout) > now.tv_sec) return false;
removeOldestProcess(processExit::idleTimeout);
return true;
}
//////////////////////////////////////////////////////////////////////
// Create a new process for this service. Return true if the service
// started. The fork/exec is done here so that we *know* we have a
// pidMap entry prior to returning to the main loop and possibly
// reaping children.
//
// Return: true if a process was started.
//////////////////////////////////////////////////////////////////////
bool
service::createProcess(const char* reason, bool applyRateLimiting)
{
if (debug::service()) DBGPRT << "service::createProcess: " << _logID
<< " R=" << reason
<< " UU=" << _unusedIds.size()
<< " apc=" << _activeProcessCount
<< " nextStart " << _nextStartAttempt
<< endl;
if (!createAllowed(applyRateLimiting, false)) return false;
int id = _unusedIds.front(); // Get an unused id
_unusedIds.pop_front();
process* P = new process(this, id, _name,
_acceptSocket, _shmServiceFD, getReportingChannelWriterSocket(),
&_shmService);
_processMap[P] = P;
_M->addProcessCount(); // Add to aggregate totals
++_activeProcessCount; // It's also active until shutdown
if (!P->initialize()) {
destroyOffspring(P, "initialize failed");
return false;
}
if (debug::service()) DBGPRT << "Service: createProcess " << P->getID() << endl;
return true;
}
//////////////////////////////////////////////////////////////////////
// Find the oldest process and initiate a shutdown.
//////////////////////////////////////////////////////////////////////
bool
service::removeOldestProcess(processExit::reason why)
{
process* P = findOldestProcess();
if (!P) {
LOGPRT << "Warning: " << _logID << " Could not find oldest process" << endl;
return false;
}
P->setShutdownReason(why, true);
return true;
}
| 13,179 | 4,089 |
#include "point.h"
namespace lf::geometry {
Eigen::MatrixXd Point::Global(const Eigen::MatrixXd& local) const {
LF_ASSERT_MSG(local.rows() == 0, "local.rows() != 0");
return coord_.replicate(1, local.cols());
}
// NOLINTNEXTLINE(misc-unused-parameters)
Eigen::MatrixXd Point::Jacobian(const Eigen::MatrixXd& local) const {
return Eigen::MatrixXd::Zero(DimGlobal(), 0);
}
Eigen::MatrixXd Point::JacobianInverseGramian(
const Eigen::MatrixXd& local) const { // NOLINT(misc-unused-parameters)
LF_VERIFY_MSG(false, "JacobianInverseGramian undefined for points.");
}
Eigen::VectorXd Point::IntegrationElement(const Eigen::MatrixXd& local) const {
return Eigen::VectorXd::Ones(local.cols());
}
std::unique_ptr<Geometry> Point::SubGeometry(dim_t codim, dim_t i) const {
if (codim == 0 && i == 0) {
return std::make_unique<Point>(coord_);
}
LF_VERIFY_MSG(false, "codim or i out of bounds.");
}
std::vector<std::unique_ptr<Geometry>> Point::ChildGeometry(
const RefinementPattern& ref_pattern, lf::base::dim_t codim) const {
LF_VERIFY_MSG(codim == 0, "Only codim = 0 allowed for a point");
std::vector<std::unique_ptr<Geometry>> child_geo_uptrs{};
LF_VERIFY_MSG(ref_pattern.RefEl() == lf::base::RefEl::kPoint(),
"ref_patern.RefEl() = " << ref_pattern.RefEl().ToString());
LF_VERIFY_MSG(ref_pattern.noChildren(0) == 1,
"ref_pattern.noChildren() = " << ref_pattern.noChildren(0));
// The only way to "refine" a point is to copy it
child_geo_uptrs.push_back(std::make_unique<Point>(coord_));
return child_geo_uptrs;
}
} // namespace lf::geometry
| 1,617 | 621 |
#include "stdafx.hpp"
#include "Window/GLFWWindowWrapper.hpp"
#include "FlexEngine.hpp"
#include "Editor.hpp"
#if COMPILE_OPEN_GL
#include "Graphics/GL/GLHelpers.hpp"
#endif
#include "Graphics/Renderer.hpp"
#include "Helpers.hpp"
#include "InputManager.hpp"
#include "Platform/Platform.hpp"
#include "Window/Monitor.hpp"
namespace flex
{
std::array<bool, MAX_JOYSTICK_COUNT> g_JoysticksConnected;
GLFWWindowWrapper::GLFWWindowWrapper(const std::string& title) :
Window(title)
{
m_LastNonFullscreenWindowMode = WindowMode::WINDOWED;
}
GLFWWindowWrapper::~GLFWWindowWrapper()
{
}
void GLFWWindowWrapper::Initialize()
{
glfwSetErrorCallback(GLFWErrorCallback);
if (!glfwInit())
{
PrintError("Failed to initialize glfw! Exiting...\n");
exit(EXIT_FAILURE);
return;
}
{
i32 maj, min, rev;
glfwGetVersion(&maj, &min, &rev);
Print("GLFW v%d.%d.%d\n", maj, min, rev);
}
i32 numJoysticksConnected = 0;
for (i32 i = 0; i < MAX_JOYSTICK_COUNT; ++i)
{
g_JoysticksConnected[i] = (glfwJoystickPresent(i) == GLFW_TRUE);
if (g_JoysticksConnected[i])
{
++numJoysticksConnected;
}
}
if (numJoysticksConnected > 0)
{
Print("%i joysticks connected on bootup\n", numJoysticksConnected);
}
g_EngineInstance->mainProcessID = Platform::GetCurrentProcessID();
// TODO: Look into supporting system-DPI awareness
//SetProcessDPIAware();
}
void GLFWWindowWrapper::PostInitialize()
{
PROFILE_AUTO("GLFWWindowWrapper PostInitialize");
// TODO: Set window location/size based on previous session (load from disk)
glfwGetWindowSize(m_Window, &m_LastWindowedSize.x, &m_LastWindowedSize.y);
glfwGetWindowPos(m_Window, &m_LastWindowedPos.x, &m_LastWindowedPos.y);
}
void GLFWWindowWrapper::Destroy()
{
if (m_Window)
{
m_Window = nullptr;
}
}
void GLFWWindowWrapper::Create(const glm::vec2i& size, const glm::vec2i& pos)
{
InitFromConfig();
if (m_bMoveConsoleToOtherMonitor)
{
Platform::MoveConsole();
}
// Only use parameters if values weren't set through config file
if (m_Size.x == 0)
{
m_Size = size;
m_Position = pos;
}
m_FrameBufferSize = m_Size;
m_LastWindowedSize = m_Size;
m_StartingPosition = m_Position;
m_LastWindowedPos = m_Position;
// Don't hide window when losing focus in Windowed Fullscreen
glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_TRUE);
glfwWindowHint(GLFW_FOCUS_ON_SHOW, GLFW_TRUE);
if (g_bOpenGLEnabled)
{
#if COMPILE_OPEN_GL && DEBUG
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif // DEBUG
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_NATIVE_CONTEXT_API);
}
else if (g_bVulkanEnabled)
{
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
}
if (m_bMaximized)
{
glfwWindowHint(GLFW_MAXIMIZED, 1);
}
GLFWmonitor* monitor = NULL;
if (m_CurrentWindowMode == WindowMode::FULLSCREEN)
{
monitor = glfwGetPrimaryMonitor();
}
m_Window = glfwCreateWindow(m_Size.x, m_Size.y, m_TitleString.c_str(), monitor, NULL);
if (!m_Window)
{
PrintError("Failed to create glfw Window! Exiting...\n");
glfwTerminate();
// TODO: Try creating a window manually here
exit(EXIT_FAILURE);
}
glfwSetWindowUserPointer(m_Window, this);
SetUpCallbacks();
i32 monitorCount;
GLFWmonitor** monitors = glfwGetMonitors(&monitorCount);
// If previously the window was on an additional monitor that is no longer present,
// move the window to the primary monitor
if (monitorCount == 1)
{
const GLFWvidmode* vidMode = glfwGetVideoMode(monitors[0]);
i32 monitorWidth = vidMode->width;
i32 monitorHeight = vidMode->height;
if (m_StartingPosition.x < 0)
{
m_StartingPosition.x = 100;
}
else if (m_StartingPosition.x > monitorWidth)
{
m_StartingPosition.x = 100;
}
if (m_StartingPosition.y < 0)
{
m_StartingPosition.y = 100;
}
else if (m_StartingPosition.y > monitorHeight)
{
m_StartingPosition.y = 100;
}
}
glfwSetWindowPos(m_Window, m_StartingPosition.x, m_StartingPosition.y);
glfwFocusWindow(m_Window);
m_bHasFocus = true;
}
void GLFWWindowWrapper::RetrieveMonitorInfo()
{
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
if (!monitor)
{
i32 count;
glfwGetMonitors(&count);
PrintError("Failed to find primary monitor!\n");
PrintError("%d monitors found\n", count);
return;
}
const GLFWvidmode* vidMode = glfwGetVideoMode(monitor);
if (!vidMode)
{
PrintError("Failed to get monitor's video mode!\n");
return;
}
assert(g_Monitor); // Monitor must be created before calling RetrieveMonitorInfo!
g_Monitor->width = vidMode->width;
g_Monitor->height = vidMode->height;
g_Monitor->redBits = vidMode->redBits;
g_Monitor->greenBits = vidMode->greenBits;
g_Monitor->blueBits = vidMode->blueBits;
g_Monitor->refreshRate = vidMode->refreshRate;
// 25.4mm = 1 inch
i32 widthMM, heightMM;
glfwGetMonitorPhysicalSize(monitor, &widthMM, &heightMM);
g_Monitor->DPI = glm::vec2(vidMode->width / (widthMM / 25.4f),
vidMode->height / (heightMM / 25.4f));
glfwGetMonitorContentScale(monitor, &g_Monitor->contentScaleX, &g_Monitor->contentScaleY);
}
void GLFWWindowWrapper::SetUpCallbacks()
{
if (!m_Window)
{
PrintError("SetUpCallbacks was called before m_Window was set!\n");
return;
}
glfwSetKeyCallback(m_Window, GLFWKeyCallback);
glfwSetCharCallback(m_Window, GLFWCharCallback);
glfwSetMouseButtonCallback(m_Window, GLFWMouseButtonCallback);
glfwSetCursorPosCallback(m_Window, GLFWCursorPosCallback);
glfwSetScrollCallback(m_Window, GLFWScrollCallback);
glfwSetWindowSizeCallback(m_Window, GLFWWindowSizeCallback);
glfwSetFramebufferSizeCallback(m_Window, GLFWFramebufferSizeCallback);
glfwSetWindowFocusCallback(m_Window, GLFWWindowFocusCallback);
glfwSetWindowPosCallback(m_Window, GLFWWindowPosCallback);
// TODO: Only enable in editor builds
glfwSetDropCallback(m_Window, GLFWDropCallback);
glfwSetJoystickCallback(GLFWJoystickCallback);
glfwSetMonitorCallback(GLFWMointorCallback);
}
void GLFWWindowWrapper::SetFrameBufferSize(i32 width, i32 height)
{
m_FrameBufferSize = glm::vec2i(width, height);
m_Size = m_FrameBufferSize;
if (g_Renderer)
{
g_Renderer->OnWindowSizeChanged(width, height);
}
}
void GLFWWindowWrapper::SetSize(i32 width, i32 height)
{
glfwSetWindowSize(m_Window, width, height);
OnSizeChanged(width, height);
}
void GLFWWindowWrapper::OnSizeChanged(i32 width, i32 height)
{
m_Size = glm::vec2i(width, height);
m_FrameBufferSize = m_Size;
if (m_CurrentWindowMode == WindowMode::WINDOWED)
{
m_LastWindowedSize = m_Size;
}
if (g_Renderer)
{
g_Renderer->OnWindowSizeChanged(width, height);
}
}
void GLFWWindowWrapper::SetPosition(i32 newX, i32 newY)
{
if (m_Window)
{
glfwSetWindowPos(m_Window, newX, newY);
}
else
{
m_StartingPosition = { newX, newY };
}
OnPositionChanged(newX, newY);
}
void GLFWWindowWrapper::OnPositionChanged(i32 newX, i32 newY)
{
m_Position = { newX, newY };
if (m_CurrentWindowMode == WindowMode::WINDOWED)
{
m_LastWindowedPos = m_Position;
}
}
void GLFWWindowWrapper::PollEvents()
{
glfwPollEvents();
}
void GLFWWindowWrapper::SetCursorPos(const glm::vec2& newCursorPos)
{
glfwSetCursorPos(m_Window, newCursorPos.x, newCursorPos.y);
}
void GLFWWindowWrapper::SetCursorMode(CursorMode mode)
{
if (m_CursorMode != mode)
{
Window::SetCursorMode(mode);
i32 glfwCursorMode = 0;
switch (mode)
{
case CursorMode::NORMAL: glfwCursorMode = GLFW_CURSOR_NORMAL; break;
case CursorMode::HIDDEN: glfwCursorMode = GLFW_CURSOR_HIDDEN; break;
case CursorMode::DISABLED: glfwCursorMode = GLFW_CURSOR_DISABLED; break;
case CursorMode::_NONE:
default: PrintError("Unhandled cursor mode passed to GLFWWindowWrapper::SetCursorMode: %i\n", (i32)mode); break;
}
glfwSetInputMode(m_Window, GLFW_CURSOR, glfwCursorMode);
// Enable raw motion when cursor disabled for smoother camera controls
if (glfwCursorMode == GLFW_CURSOR_DISABLED)
{
if (glfwRawMouseMotionSupported())
{
glfwSetInputMode(m_Window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
}
}
}
}
void GLFWWindowWrapper::SetWindowMode(WindowMode mode, bool bForce)
{
if (bForce || m_CurrentWindowMode != mode)
{
m_CurrentWindowMode = mode;
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
if (!monitor)
{
PrintError("Failed to find primary monitor! Can't set window mode\n");
return;
}
const GLFWvidmode* videoMode = glfwGetVideoMode(monitor);
if (!videoMode)
{
PrintError("Failed to get monitor's video mode! Can't set window mode\n");
return;
}
switch (mode)
{
case WindowMode::FULLSCREEN:
{
glfwSetWindowMonitor(m_Window, monitor, 0, 0, videoMode->width, videoMode->height, videoMode->refreshRate);
} break;
case WindowMode::WINDOWED_FULLSCREEN:
{
glfwSetWindowMonitor(m_Window, monitor, 0, 0, videoMode->width, videoMode->height, videoMode->refreshRate);
m_LastNonFullscreenWindowMode = WindowMode::WINDOWED_FULLSCREEN;
} break;
case WindowMode::WINDOWED:
{
assert(m_LastWindowedSize.x != 0 && m_LastWindowedSize.y != 0);
if (m_LastWindowedPos.y == 0)
{
// When in windowed mode a y position of 0 means the title bar isn't
// visible. This will occur if the app launched in fullscreen since
// the last y position to never have been set to a valid value.
m_LastWindowedPos.y = 40;
}
glfwSetWindowMonitor(m_Window, nullptr, m_LastWindowedPos.x, m_LastWindowedPos.y, m_LastWindowedSize.x, m_LastWindowedSize.y, videoMode->refreshRate);
m_LastNonFullscreenWindowMode = WindowMode::WINDOWED;
} break;
case WindowMode::_NONE:
default:
{
PrintError("Unhandled window mode: %u\n", (u32)mode);
} break;
}
}
}
void GLFWWindowWrapper::ToggleFullscreen(bool bForce)
{
if (m_CurrentWindowMode == WindowMode::FULLSCREEN)
{
assert(m_LastNonFullscreenWindowMode == WindowMode::WINDOWED || m_LastNonFullscreenWindowMode == WindowMode::WINDOWED_FULLSCREEN);
SetWindowMode(m_LastNonFullscreenWindowMode, bForce);
}
else
{
SetWindowMode(WindowMode::FULLSCREEN, bForce);
}
}
void GLFWWindowWrapper::Maximize()
{
glfwMaximizeWindow(m_Window);
}
void GLFWWindowWrapper::Iconify()
{
glfwIconifyWindow(m_Window);
}
void GLFWWindowWrapper::Update()
{
Window::Update();
if (glfwWindowShouldClose(m_Window))
{
g_EngineInstance->Stop();
return;
}
GLFWgamepadstate gamepad0State;
static bool bPrevP0JoystickPresent = false;
if (glfwGetGamepadState(0, &gamepad0State) == GLFW_TRUE)
{
g_InputManager->UpdateGamepadState(0, gamepad0State.axes, gamepad0State.buttons);
bPrevP0JoystickPresent = true;
}
else
{
if (bPrevP0JoystickPresent)
{
g_InputManager->ClearGampadInput(0);
bPrevP0JoystickPresent = false;
}
}
GLFWgamepadstate gamepad1State;
static bool bPrevP1JoystickPresent = false;
if (glfwGetGamepadState(1, &gamepad1State) == GLFW_TRUE)
{
g_InputManager->UpdateGamepadState(1, gamepad1State.axes, gamepad1State.buttons);
bPrevP1JoystickPresent = true;
}
else
{
if (bPrevP1JoystickPresent)
{
g_InputManager->ClearGampadInput(1);
bPrevP1JoystickPresent = false;
}
}
}
GLFWwindow* GLFWWindowWrapper::GetWindow() const
{
return m_Window;
}
const char* GLFWWindowWrapper::GetClipboardText()
{
return glfwGetClipboardString(m_Window);
}
void GLFWWindowWrapper::SetClipboardText(const char* text)
{
glfwSetClipboardString(m_Window, text);
}
void GLFWWindowWrapper::SetWindowTitle(const std::string& title)
{
glfwSetWindowTitle(m_Window, title.c_str());
}
void GLFWWindowWrapper::SetMousePosition(glm::vec2 mousePosition)
{
glfwSetCursorPos(m_Window, (double)mousePosition.x, (double)mousePosition.y);
}
glm::vec2 GLFWWindowWrapper::GetMousePosition()
{
double posX, posY;
glfwGetCursorPos(m_Window, &posX, &posY);
return glm::vec2((real)posX, (real)posY);
}
void GLFWErrorCallback(i32 error, const char* description)
{
PrintError("GLFW Error: %i: %s\n", error, description);
}
void GLFWKeyCallback(GLFWwindow* glfwWindow, i32 key, i32 scancode, i32 action, i32 mods)
{
FLEX_UNUSED(scancode);
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
const KeyAction inputAction = GLFWActionToInputManagerAction(action);
const KeyCode inputKey = GLFWKeyToInputManagerKey(key);
const i32 inputMods = GLFWModsToInputManagerMods(mods);
window->KeyCallback(inputKey, inputAction, inputMods);
}
void GLFWCharCallback(GLFWwindow* glfwWindow, u32 character)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->CharCallback(character);
}
void GLFWMouseButtonCallback(GLFWwindow* glfwWindow, i32 button, i32 action, i32 mods)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
const KeyAction inputAction = GLFWActionToInputManagerAction(action);
const i32 inputMods = GLFWModsToInputManagerMods(mods);
const MouseButton mouseButton = GLFWButtonToInputManagerMouseButton(button);
window->MouseButtonCallback(mouseButton, inputAction, inputMods);
}
void GLFWWindowFocusCallback(GLFWwindow* glfwWindow, i32 focused)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->WindowFocusCallback(focused);
}
void GLFWWindowPosCallback(GLFWwindow* glfwWindow, i32 newX, i32 newY)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->WindowPosCallback(newX, newY);
}
void GLFWCursorPosCallback(GLFWwindow* glfwWindow, double x, double y)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->CursorPosCallback(x, y);
}
void GLFWScrollCallback(GLFWwindow* glfwWindow, double xoffset, double yoffset)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->ScrollCallback(xoffset, yoffset);
}
void GLFWWindowSizeCallback(GLFWwindow* glfwWindow, i32 width, i32 height)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
bool bMaximized = (glfwGetWindowAttrib(glfwWindow, GLFW_MAXIMIZED) == GLFW_TRUE);
bool bIconified = (glfwGetWindowAttrib(glfwWindow, GLFW_ICONIFIED) == GLFW_TRUE);
window->WindowSizeCallback(width, height, bMaximized, bIconified);
}
void GLFWFramebufferSizeCallback(GLFWwindow* glfwWindow, i32 width, i32 height)
{
Window* window = static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow));
window->FrameBufferSizeCallback(width, height);
}
void GLFWDropCallback(GLFWwindow* glfwWindow, int count, const char** paths)
{
g_Editor->OnDragDrop(count, paths);
glfwFocusWindow(glfwWindow);
}
void GLFWJoystickCallback(i32 JID, i32 event)
{
if (JID > MAX_JOYSTICK_COUNT)
{
PrintWarn("Unhandled joystick connection event, JID out of range: %i\n", JID);
return;
}
if (event == GLFW_CONNECTED)
{
Print("Joystick %i connected\n", JID);
}
else if (event == GLFW_DISCONNECTED)
{
Print("Joystick %i disconnected\n", JID);
}
g_JoysticksConnected[(u32)JID] = (event == GLFW_CONNECTED);
}
void GLFWMointorCallback(GLFWmonitor* monitor, int event)
{
i32 w, h;
glfwGetMonitorPhysicalSize(monitor, &w, &h);
if (event == GLFW_CONNECTED)
{
Print("Monitor connected: %s, %dmm x %dmm\n", glfwGetMonitorName(monitor), w, h);
}
else
{
Print("Monitor disconnected: %s, %dmm x %dmm\n", glfwGetMonitorName(monitor), w, h);
}
}
KeyAction GLFWActionToInputManagerAction(i32 glfwAction)
{
KeyAction inputAction = KeyAction::_NONE;
switch (glfwAction)
{
case GLFW_PRESS: inputAction = KeyAction::KEY_PRESS; break;
case GLFW_REPEAT: inputAction = KeyAction::KEY_REPEAT; break;
case GLFW_RELEASE: inputAction = KeyAction::KEY_RELEASE; break;
case -1: break; // We don't care about events GLFW can't handle
default: PrintError("Unhandled glfw action passed to GLFWActionToInputManagerAction in GLFWWIndowWrapper: %i\n",
glfwAction);
}
return inputAction;
}
KeyCode GLFWKeyToInputManagerKey(i32 glfwKey)
{
KeyCode inputKey = KeyCode::_NONE;
switch (glfwKey)
{
case GLFW_KEY_SPACE: inputKey = KeyCode::KEY_SPACE; break;
case GLFW_KEY_APOSTROPHE: inputKey = KeyCode::KEY_APOSTROPHE; break;
case GLFW_KEY_COMMA: inputKey = KeyCode::KEY_COMMA; break;
case GLFW_KEY_MINUS: inputKey = KeyCode::KEY_MINUS; break;
case GLFW_KEY_PERIOD: inputKey = KeyCode::KEY_PERIOD; break;
case GLFW_KEY_SLASH: inputKey = KeyCode::KEY_SLASH; break;
case GLFW_KEY_0: inputKey = KeyCode::KEY_0; break;
case GLFW_KEY_1: inputKey = KeyCode::KEY_1; break;
case GLFW_KEY_2: inputKey = KeyCode::KEY_2; break;
case GLFW_KEY_3: inputKey = KeyCode::KEY_3; break;
case GLFW_KEY_4: inputKey = KeyCode::KEY_4; break;
case GLFW_KEY_5: inputKey = KeyCode::KEY_5; break;
case GLFW_KEY_6: inputKey = KeyCode::KEY_6; break;
case GLFW_KEY_7: inputKey = KeyCode::KEY_7; break;
case GLFW_KEY_8: inputKey = KeyCode::KEY_8; break;
case GLFW_KEY_9: inputKey = KeyCode::KEY_9; break;
case GLFW_KEY_SEMICOLON: inputKey = KeyCode::KEY_SEMICOLON; break;
case GLFW_KEY_EQUAL: inputKey = KeyCode::KEY_EQUAL; break;
case GLFW_KEY_A: inputKey = KeyCode::KEY_A; break;
case GLFW_KEY_B: inputKey = KeyCode::KEY_B; break;
case GLFW_KEY_C: inputKey = KeyCode::KEY_C; break;
case GLFW_KEY_D: inputKey = KeyCode::KEY_D; break;
case GLFW_KEY_E: inputKey = KeyCode::KEY_E; break;
case GLFW_KEY_F: inputKey = KeyCode::KEY_F; break;
case GLFW_KEY_G: inputKey = KeyCode::KEY_G; break;
case GLFW_KEY_H: inputKey = KeyCode::KEY_H; break;
case GLFW_KEY_I: inputKey = KeyCode::KEY_I; break;
case GLFW_KEY_J: inputKey = KeyCode::KEY_J; break;
case GLFW_KEY_K: inputKey = KeyCode::KEY_K; break;
case GLFW_KEY_L: inputKey = KeyCode::KEY_L; break;
case GLFW_KEY_M: inputKey = KeyCode::KEY_M; break;
case GLFW_KEY_N: inputKey = KeyCode::KEY_N; break;
case GLFW_KEY_O: inputKey = KeyCode::KEY_O; break;
case GLFW_KEY_P: inputKey = KeyCode::KEY_P; break;
case GLFW_KEY_Q: inputKey = KeyCode::KEY_Q; break;
case GLFW_KEY_R: inputKey = KeyCode::KEY_R; break;
case GLFW_KEY_S: inputKey = KeyCode::KEY_S; break;
case GLFW_KEY_T: inputKey = KeyCode::KEY_T; break;
case GLFW_KEY_U: inputKey = KeyCode::KEY_U; break;
case GLFW_KEY_V: inputKey = KeyCode::KEY_V; break;
case GLFW_KEY_W: inputKey = KeyCode::KEY_W; break;
case GLFW_KEY_X: inputKey = KeyCode::KEY_X; break;
case GLFW_KEY_Y: inputKey = KeyCode::KEY_Y; break;
case GLFW_KEY_Z: inputKey = KeyCode::KEY_Z; break;
case GLFW_KEY_LEFT_BRACKET: inputKey = KeyCode::KEY_LEFT_BRACKET; break;
case GLFW_KEY_BACKSLASH: inputKey = KeyCode::KEY_BACKSLASH; break;
case GLFW_KEY_RIGHT_BRACKET: inputKey = KeyCode::KEY_RIGHT_BRACKET; break;
case GLFW_KEY_GRAVE_ACCENT: inputKey = KeyCode::KEY_GRAVE_ACCENT; break;
case GLFW_KEY_WORLD_1: inputKey = KeyCode::KEY_WORLD_1; break;
case GLFW_KEY_WORLD_2: inputKey = KeyCode::KEY_WORLD_2; break;
case GLFW_KEY_ESCAPE: inputKey = KeyCode::KEY_ESCAPE; break;
case GLFW_KEY_ENTER: inputKey = KeyCode::KEY_ENTER; break;
case GLFW_KEY_TAB: inputKey = KeyCode::KEY_TAB; break;
case GLFW_KEY_BACKSPACE: inputKey = KeyCode::KEY_BACKSPACE; break;
case GLFW_KEY_INSERT: inputKey = KeyCode::KEY_INSERT; break;
case GLFW_KEY_DELETE: inputKey = KeyCode::KEY_DELETE; break;
case GLFW_KEY_RIGHT: inputKey = KeyCode::KEY_RIGHT; break;
case GLFW_KEY_LEFT: inputKey = KeyCode::KEY_LEFT; break;
case GLFW_KEY_DOWN: inputKey = KeyCode::KEY_DOWN; break;
case GLFW_KEY_UP: inputKey = KeyCode::KEY_UP; break;
case GLFW_KEY_PAGE_UP: inputKey = KeyCode::KEY_PAGE_UP; break;
case GLFW_KEY_PAGE_DOWN: inputKey = KeyCode::KEY_PAGE_DOWN; break;
case GLFW_KEY_HOME: inputKey = KeyCode::KEY_HOME; break;
case GLFW_KEY_END: inputKey = KeyCode::KEY_END; break;
case GLFW_KEY_CAPS_LOCK: inputKey = KeyCode::KEY_CAPS_LOCK; break;
case GLFW_KEY_SCROLL_LOCK: inputKey = KeyCode::KEY_SCROLL_LOCK; break;
case GLFW_KEY_NUM_LOCK: inputKey = KeyCode::KEY_NUM_LOCK; break;
case GLFW_KEY_PRINT_SCREEN: inputKey = KeyCode::KEY_PRINT_SCREEN; break;
case GLFW_KEY_PAUSE: inputKey = KeyCode::KEY_PAUSE; break;
case GLFW_KEY_F1: inputKey = KeyCode::KEY_F1; break;
case GLFW_KEY_F2: inputKey = KeyCode::KEY_F2; break;
case GLFW_KEY_F3: inputKey = KeyCode::KEY_F3; break;
case GLFW_KEY_F4: inputKey = KeyCode::KEY_F4; break;
case GLFW_KEY_F5: inputKey = KeyCode::KEY_F5; break;
case GLFW_KEY_F6: inputKey = KeyCode::KEY_F6; break;
case GLFW_KEY_F7: inputKey = KeyCode::KEY_F7; break;
case GLFW_KEY_F8: inputKey = KeyCode::KEY_F8; break;
case GLFW_KEY_F9: inputKey = KeyCode::KEY_F9; break;
case GLFW_KEY_F10: inputKey = KeyCode::KEY_F10; break;
case GLFW_KEY_F11: inputKey = KeyCode::KEY_F11; break;
case GLFW_KEY_F12: inputKey = KeyCode::KEY_F12; break;
case GLFW_KEY_F13: inputKey = KeyCode::KEY_F13; break;
case GLFW_KEY_F14: inputKey = KeyCode::KEY_F14; break;
case GLFW_KEY_F15: inputKey = KeyCode::KEY_F15; break;
case GLFW_KEY_F16: inputKey = KeyCode::KEY_F16; break;
case GLFW_KEY_F17: inputKey = KeyCode::KEY_F17; break;
case GLFW_KEY_F18: inputKey = KeyCode::KEY_F18; break;
case GLFW_KEY_F19: inputKey = KeyCode::KEY_F19; break;
case GLFW_KEY_F20: inputKey = KeyCode::KEY_F20; break;
case GLFW_KEY_F21: inputKey = KeyCode::KEY_F21; break;
case GLFW_KEY_F22: inputKey = KeyCode::KEY_F22; break;
case GLFW_KEY_F23: inputKey = KeyCode::KEY_F23; break;
case GLFW_KEY_F24: inputKey = KeyCode::KEY_F24; break;
case GLFW_KEY_F25: inputKey = KeyCode::KEY_F25; break;
case GLFW_KEY_KP_0: inputKey = KeyCode::KEY_KP_0; break;
case GLFW_KEY_KP_1: inputKey = KeyCode::KEY_KP_1; break;
case GLFW_KEY_KP_2: inputKey = KeyCode::KEY_KP_2; break;
case GLFW_KEY_KP_3: inputKey = KeyCode::KEY_KP_3; break;
case GLFW_KEY_KP_4: inputKey = KeyCode::KEY_KP_4; break;
case GLFW_KEY_KP_5: inputKey = KeyCode::KEY_KP_5; break;
case GLFW_KEY_KP_6: inputKey = KeyCode::KEY_KP_6; break;
case GLFW_KEY_KP_7: inputKey = KeyCode::KEY_KP_7; break;
case GLFW_KEY_KP_8: inputKey = KeyCode::KEY_KP_8; break;
case GLFW_KEY_KP_9: inputKey = KeyCode::KEY_KP_9; break;
case GLFW_KEY_KP_DECIMAL: inputKey = KeyCode::KEY_KP_DECIMAL; break;
case GLFW_KEY_KP_DIVIDE: inputKey = KeyCode::KEY_KP_DIVIDE; break;
case GLFW_KEY_KP_MULTIPLY: inputKey = KeyCode::KEY_KP_MULTIPLY; break;
case GLFW_KEY_KP_SUBTRACT: inputKey = KeyCode::KEY_KP_SUBTRACT; break;
case GLFW_KEY_KP_ADD: inputKey = KeyCode::KEY_KP_ADD; break;
case GLFW_KEY_KP_ENTER: inputKey = KeyCode::KEY_KP_ENTER; break;
case GLFW_KEY_KP_EQUAL: inputKey = KeyCode::KEY_KP_EQUAL; break;
case GLFW_KEY_LEFT_SHIFT: inputKey = KeyCode::KEY_LEFT_SHIFT; break;
case GLFW_KEY_LEFT_CONTROL: inputKey = KeyCode::KEY_LEFT_CONTROL; break;
case GLFW_KEY_LEFT_ALT: inputKey = KeyCode::KEY_LEFT_ALT; break;
case GLFW_KEY_LEFT_SUPER: inputKey = KeyCode::KEY_LEFT_SUPER; break;
case GLFW_KEY_RIGHT_SHIFT: inputKey = KeyCode::KEY_RIGHT_SHIFT; break;
case GLFW_KEY_RIGHT_CONTROL: inputKey = KeyCode::KEY_RIGHT_CONTROL; break;
case GLFW_KEY_RIGHT_ALT: inputKey = KeyCode::KEY_RIGHT_ALT; break;
case GLFW_KEY_RIGHT_SUPER: inputKey = KeyCode::KEY_RIGHT_SUPER; break;
case GLFW_KEY_MENU: inputKey = KeyCode::KEY_MENU; break;
case -1: break; // We don't care about events GLFW can't handle
default:
PrintError("Unhandled glfw key passed to GLFWKeyToInputManagerKey in GLFWWIndowWrapper: %i\n",
glfwKey);
break;
}
return inputKey;
}
i32 GLFWModsToInputManagerMods(i32 glfwMods)
{
i32 inputMods = 0;
if (glfwMods & GLFW_MOD_SHIFT) inputMods |= (i32)InputModifier::SHIFT;
if (glfwMods & GLFW_MOD_ALT) inputMods |= (i32)InputModifier::ALT;
if (glfwMods & GLFW_MOD_CONTROL) inputMods |= (i32)InputModifier::CONTROL;
if (glfwMods & GLFW_MOD_SUPER) inputMods |= (i32)InputModifier::SUPER;
if (glfwMods & GLFW_MOD_CAPS_LOCK) inputMods |= (i32)InputModifier::CAPS_LOCK;
if (glfwMods & GLFW_MOD_NUM_LOCK) inputMods |= (i32)InputModifier::NUM_LOCK;
return inputMods;
}
MouseButton GLFWButtonToInputManagerMouseButton(i32 glfwButton)
{
MouseButton inputMouseButton = MouseButton::_NONE;
switch (glfwButton)
{
case GLFW_MOUSE_BUTTON_1: inputMouseButton = MouseButton::MOUSE_BUTTON_1; break;
case GLFW_MOUSE_BUTTON_2: inputMouseButton = MouseButton::MOUSE_BUTTON_2; break;
case GLFW_MOUSE_BUTTON_3: inputMouseButton = MouseButton::MOUSE_BUTTON_3; break;
case GLFW_MOUSE_BUTTON_4: inputMouseButton = MouseButton::MOUSE_BUTTON_4; break;
case GLFW_MOUSE_BUTTON_5: inputMouseButton = MouseButton::MOUSE_BUTTON_5; break;
case GLFW_MOUSE_BUTTON_6: inputMouseButton = MouseButton::MOUSE_BUTTON_6; break;
case GLFW_MOUSE_BUTTON_7: inputMouseButton = MouseButton::MOUSE_BUTTON_7; break;
case GLFW_MOUSE_BUTTON_8: inputMouseButton = MouseButton::MOUSE_BUTTON_8; break;
case -1: break; // We don't care about events GLFW can't handle
default: PrintError("Unhandled glfw button passed to GLFWButtonToInputManagerMouseButton in GLFWWIndowWrapper: %i\n",
glfwButton); break;
}
return inputMouseButton;
}
#if defined(_WINDOWS) && COMPILE_OPEN_GL
void WINAPI glDebugOutput(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
const GLchar* message, const void* userParam)
{
FLEX_UNUSED(userParam);
FLEX_UNUSED(length);
// Ignore insignificant error/warning codes and notification messages
if (id == 131169 || id == 131185 || id == 131218 || id == 131204 ||
severity == GL_DEBUG_SEVERITY_NOTIFICATION)
{
return;
}
PrintError("-----------------------------------------\n");
PrintError("GL Debug message (%u): %s\n", id, message);
switch (source)
{
case GL_DEBUG_SOURCE_API: PrintError("Source: API"); break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM: PrintError("Source: Window System"); break;
case GL_DEBUG_SOURCE_SHADER_COMPILER: PrintError("Source: Shader Compiler"); break;
case GL_DEBUG_SOURCE_THIRD_PARTY: PrintError("Source: Third Party"); break;
case GL_DEBUG_SOURCE_APPLICATION: PrintError("Source: Application"); break;
case GL_DEBUG_SOURCE_OTHER: PrintError("Source: Other"); break;
}
PrintError("\n");
switch (type)
{
case GL_DEBUG_TYPE_ERROR: PrintError("Type: Error"); break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: PrintError("Type: Deprecated Behaviour"); break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: PrintError("Type: Undefined Behaviour"); break;
case GL_DEBUG_TYPE_PORTABILITY: PrintError("Type: Portability"); break;
case GL_DEBUG_TYPE_PERFORMANCE: PrintError("Type: Performance"); break;
case GL_DEBUG_TYPE_MARKER: PrintError("Type: Marker"); break;
case GL_DEBUG_TYPE_PUSH_GROUP: PrintError("Type: Push Group"); break;
case GL_DEBUG_TYPE_POP_GROUP: PrintError("Type: Pop Group"); break;
case GL_DEBUG_TYPE_OTHER: PrintError("Type: Other"); break;
}
PrintError("\n");
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH: PrintError("Severity: high"); break;
case GL_DEBUG_SEVERITY_MEDIUM: PrintError("Severity: medium"); break;
case GL_DEBUG_SEVERITY_LOW: PrintError("Severity: low"); break;
//case GL_DEBUG_SEVERITY_NOTIFICATION: PrintError("Severity: notification"); break;
}
PrintError("\n-----------------------------------------\n");
}
#endif
} // namespace flex
| 27,849 | 11,969 |
/* (c) 2018 CYVA. For details refer to LICENSE */
#pragma once
#include <graphene/chain/protocol/base.hpp>
#include <graphene/chain/protocol/types.hpp>
#include <graphene/chain/protocol/asset.hpp>
#include <boost/preprocessor/seq/seq.hpp>
#include <fc/reflect/reflect.hpp>
#include <fc/crypto/ripemd160.hpp>
#include <fc/time.hpp>
#include <stdint.h>
#include <vector>
#include <utility>
#include <cyva/encrypt/crypto_types.hpp>
namespace graphene { namespace chain {
} } // graphene::chain
| 505 | 195 |
/****************************************************************************
*
* Copyright (C) 2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file test_List.cpp
* Tests the List container.
*/
#include <unit_test.h>
#include <containers/List.hpp>
#include <float.h>
#include <math.h>
class testContainer : public ListNode<testContainer *>
{
public:
int i{0};
};
class ListTest : public UnitTest
{
public:
virtual bool run_tests();
bool test_add();
bool test_remove();
bool test_range_based_for();
};
bool ListTest::run_tests()
{
ut_run_test(test_add);
ut_run_test(test_remove);
ut_run_test(test_range_based_for);
return (_tests_failed == 0);
}
bool ListTest::test_add()
{
List<testContainer *> list1;
// size should be 0 initially
ut_compare("size initially 0", list1.size(), 0);
ut_assert_true(list1.empty());
// insert 100
for (int i = 0; i < 100; i++) {
testContainer *t = new testContainer();
t->i = i;
list1.add(t);
ut_compare("size increasing with i", list1.size(), i + 1);
ut_assert_true(!list1.empty());
}
// verify full size (100)
ut_assert_true(list1.size() == 100);
int i = 99;
for (auto t : list1) {
// verify all elements were inserted in order
ut_compare("stored i", i, t->i);
i--;
}
// delete all elements
list1.clear();
// verify list has been cleared
ut_assert_true(list1.empty());
ut_compare("size 0", list1.size(), 0);
return true;
}
bool ListTest::test_remove()
{
List<testContainer *> list1;
// size should be 0 initially
ut_compare("size initially 0", list1.size(), 0);
ut_assert_true(list1.empty());
// insert 100
for (int i = 0; i < 100; i++) {
testContainer *t = new testContainer();
t->i = i;
list1.add(t);
ut_compare("size increasing with i", list1.size(), i + 1);
ut_assert_true(!list1.empty());
}
// verify full size (100)
ut_assert_true(list1.size() == 100);
// test removing elements
for (int remove_i = 0; remove_i < 100; remove_i++) {
// find node with i == remove_i
testContainer *removed = nullptr;
for (auto t : list1) {
if (t->i == remove_i) {
ut_assert_true(list1.remove(t));
removed = t;
}
}
delete removed;
// iterate list again to verify removal
for (auto t : list1) {
ut_assert_true(t->i != remove_i);
}
ut_assert_true(list1.size() == 100 - remove_i - 1);
}
// list should now be empty
ut_assert_true(list1.empty());
ut_compare("size 0", list1.size(), 0);
// delete all elements (should be safe on empty list)
list1.clear();
// verify list has been cleared
ut_assert_true(list1.empty());
ut_compare("size 0", list1.size(), 0);
return true;
}
bool ListTest::test_range_based_for()
{
List<testContainer *> list1;
// size should be 0 initially
ut_compare("size initially 0", list1.size(), 0);
ut_assert_true(list1.empty());
// insert 100 elements in order
for (int i = 99; i >= 0; i--) {
testContainer *t = new testContainer();
t->i = i;
list1.add(t);
ut_assert_true(!list1.empty());
}
// first element should be 0
ut_compare("first 0", list1.getHead()->i, 0);
// verify all elements were inserted in order
int i = 0;
auto t1 = list1.getHead();
while (t1 != nullptr) {
ut_compare("check count", i, t1->i);
t1 = t1->getSibling();
i++;
}
// verify full size (100)
ut_compare("size check", list1.size(), 100);
i = 0;
for (auto t2 : list1) {
ut_compare("range based for i", i, t2->i);
i++;
}
// verify full size (100)
ut_compare("size check", list1.size(), 100);
// delete all elements
list1.clear();
// verify list has been cleared
ut_assert_true(list1.empty());
ut_compare("size check", list1.size(), 0);
return true;
}
ut_declare_test_c(test_List, ListTest)
| 5,297 | 2,048 |
/*
* Copyright (c) 2017 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.
*/
namespace {
template <typename T>
DEF_SEM(JMP, T target_pc) {
WriteZExt(REG_PC, Read(target_pc));
return memory;
}
template <typename T>
DEF_SEM(JMP_FAR_MEM, T target_seg_pc) {
HYPER_CALL = AsyncHyperCall::kX86JmpFar;
uint64_t target_fword = UShr(UShl(Read(target_seg_pc), 0xf), 0xf);
auto pc = static_cast<uint32_t>(target_fword);
auto seg = static_cast<uint16_t>(UShr(target_fword, 32));
WriteZExt(REG_PC, pc);
Write(REG_CS.flat, seg);
// TODO(tathanhdinh): Update the hidden part (segment shadow) of CS,
// see Issue #334
return memory;
}
template <typename S1, typename S2>
DEF_SEM(JMP_FAR_PTR, S1 src1, S2 src2) {
HYPER_CALL = AsyncHyperCall::kX86JmpFar;
auto pc = Read(src1);
auto seg = Read(src2);
WriteZExt(REG_PC, pc);
Write(REG_CS.flat, seg);
// TODO(tathanhdinh): Update the hidden part (segment shadow) of CS,
// see Issue #334
return memory;
}
} // namespace
DEF_ISEL(JMP_RELBRd) = JMP<PC>;
DEF_ISEL(JMP_RELBRb) = JMP<PC>;
DEF_ISEL_32or64(JMP_RELBRz, JMP<PC>);
#if 64 == ADDRESS_SIZE_BITS
DEF_ISEL(JMP_MEMv_64) = JMP<M64>;
DEF_ISEL(JMP_GPRv_64) = JMP<R64>;
DEF_ISEL(JMP_FAR_MEMp2_32) = JMP_FAR_MEM<M64>;
#else
DEF_ISEL(JMP_MEMv_16) = JMP<M16>;
DEF_ISEL(JMP_MEMv_32) = JMP<M32>;
DEF_ISEL(JMP_GPRv_16) = JMP<R16>;
DEF_ISEL(JMP_GPRv_32) = JMP<R32>;
DEF_ISEL(JMP_FAR_MEMp2_32) = JMP_FAR_MEM<M32>;
DEF_ISEL(JMP_FAR_PTRp_IMMw_32) = JMP_FAR_PTR<I32, I16>;
DEF_ISEL(JMP_FAR_PTRp_IMMw_16) = JMP_FAR_PTR<I16, I16>;
#endif
/*
1807 JMP_FAR JMP_FAR_MEMp2 UNCOND_BR BASE I86 ATTRIBUTES: FAR_XFER NOTSX SCALABLE
1808 JMP_FAR JMP_FAR_PTRp_IMMw UNCOND_BR BASE I86 ATTRIBUTES: FAR_XFER NOTSX SCALABLE
*/
| 2,301 | 1,090 |
#include <CChatStealSystem.hpp>
START_ATF_NAMESPACE
CChatStealSystem::CChatStealSystem()
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*);
(org_ptr(0x1403f86a0L))(this);
};
void CChatStealSystem::ctor_CChatStealSystem()
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*);
(org_ptr(0x1403f86a0L))(this);
};
struct CChatStealSystem* CChatStealSystem::Instance()
{
using org_ptr = struct CChatStealSystem* (WINAPIV*)();
return (org_ptr(0x140094f00L))();
};
void CChatStealSystem::SendStealMsg(struct CPlayer* pPlayer, char byChatType, unsigned int dwSenderSerial, char* pwszSender, char byRaceCode, char* pwszMessage)
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*, struct CPlayer*, char, unsigned int, char*, char, char*);
(org_ptr(0x1403f8a30L))(this, pPlayer, byChatType, dwSenderSerial, pwszSender, byRaceCode, pwszMessage);
};
bool CChatStealSystem::SetGm(struct CPlayer* pGM)
{
using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, struct CPlayer*);
return (org_ptr(0x1403f88b0L))(this, pGM);
};
bool CChatStealSystem::SetTargetInfoFromBoss(char byType, char byRaceCode)
{
using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, char, char);
return (org_ptr(0x1403f8870L))(this, byType, byRaceCode);
};
bool CChatStealSystem::SetTargetInfoFromCharacter(char byType, char* szCharName)
{
using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, char, char*);
return (org_ptr(0x1403f87c0L))(this, byType, szCharName);
};
bool CChatStealSystem::SetTargetInfoFromRace(char byType, char byRaceCode)
{
using org_ptr = bool (WINAPIV*)(struct CChatStealSystem*, char, char);
return (org_ptr(0x1403f8830L))(this, byType, byRaceCode);
};
void CChatStealSystem::StealChatMsg(struct CPlayer* pPlayer, char byChatType, char* szChatMsg)
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*, struct CPlayer*, char, char*);
(org_ptr(0x1403f8900L))(this, pPlayer, byChatType, szChatMsg);
};
CChatStealSystem::~CChatStealSystem()
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*);
(org_ptr(0x1403f8700L))(this);
};
void CChatStealSystem::dtor_CChatStealSystem()
{
using org_ptr = void (WINAPIV*)(struct CChatStealSystem*);
(org_ptr(0x1403f8700L))(this);
};
END_ATF_NAMESPACE
| 2,524 | 992 |
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
/*!
* \file
**/
#ifndef BOOST_SIMD_TOOLBOX_BITWISE_FUNCTIONS_CTZ_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_BITWISE_FUNCTIONS_CTZ_HPP_INCLUDED
#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>
/*!
* \ingroup boost_simd_bitwise
* \defgroup boost_simd_bitwise_ctz ctz
*
* \par Description
* The function finds the first bit set (beginning with the least
* significant bit) in a0, and return the index of that bit.
* \par
* Bits are numbered starting at one (the least significant bit).
*
* \par Header file
*
* \code
* #include <nt2/include/functions/ctz.hpp>
* \endcode
*
*
* \synopsis
*
* \code
* namespace boost::simd
* {
* template <class A0>
* meta::call<tag::ctz_(A0)>::type
* ctz(const A0 & a0);
* }
* \endcode
*
* \param a0 the unique parameter of ctz
*
* \return always returns an integer value
*
* \par Notes
* In SIMD mode, this function acts elementwise on the inputs vectors elements
* \par
*
**/
namespace boost { namespace simd { namespace tag
{
/*!
* \brief Define the tag ctz_ of functor ctz
* in namespace boost::simd::tag for toolbox boost.simd.bitwise
**/
struct ctz_ : ext::elementwise_<ctz_> { typedef ext::elementwise_<ctz_> parent; };
}
BOOST_DISPATCH_FUNCTION_IMPLEMENTATION(tag::ctz_, ctz, 1)
} }
#endif
// modified by jt the 25/12/2010
| 1,889 | 671 |
//---------------------------------------------------------
// Copyright 2016 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_fast5_processor -- framework for iterating
// over a collection of fast5 files and performing some
// action on each read in parallel
//
#include "nanopolish_fast5_processor.h"
#include "nanopolish_common.h"
#include "nanopolish_fast5_io.h"
#include <assert.h>
#include <omp.h>
#include <vector>
Fast5Processor::Fast5Processor(const ReadDB& read_db,
const int num_threads,
const int batch_size) :
m_num_threads(num_threads),
m_batch_size(batch_size)
{
m_fast5s = read_db.get_unique_fast5s();
}
Fast5Processor::Fast5Processor(const std::string& fast5_file,
const int num_threads,
const int batch_size) :
m_num_threads(num_threads),
m_batch_size(batch_size)
{
m_fast5s.push_back(fast5_file);
}
Fast5Processor::~Fast5Processor()
{
}
void Fast5Processor::parallel_run(fast5_processor_work_function func)
{
// store number of threads so we can restore it after we're done
int prev_num_threads = omp_get_num_threads();
omp_set_num_threads(m_num_threads);
for(size_t i = 0; i < m_fast5s.size(); ++i) {
fast5_file f5_file = fast5_open(m_fast5s[i]);
if(!fast5_is_open(f5_file)) {
continue;
}
std::vector<Fast5Data> fast5_data;
std::vector<std::string> reads = fast5_get_multi_read_groups(f5_file);
for(size_t j = 0; j < reads.size(); j++) {
// groups have names like "read_<uuid>"
// we're only interested in the uuid bit
assert(reads[j].find("read_") == 0);
std::string read_name = reads[j].substr(5);
Fast5Data data;
data.is_valid = true;
data.read_name = read_name;
// metadata
data.sequencing_kit = fast5_get_sequencing_kit(f5_file, read_name);
data.experiment_type = fast5_get_experiment_type(f5_file, read_name);
// raw data
data.channel_params = fast5_get_channel_params(f5_file, read_name);
data.rt = fast5_get_raw_samples(f5_file, read_name, data.channel_params);
data.start_time = fast5_get_start_time(f5_file, read_name);
fast5_data.push_back(data);
}
fast5_close(f5_file);
// run in parallel
#pragma omp parallel for schedule(dynamic)
for(size_t j = 0; j < fast5_data.size(); ++j) {
func(fast5_data[j]);
}
// destroy fast5 data
for(size_t j = 0; j < fast5_data.size(); ++j) {
free(fast5_data[j].rt.raw);
fast5_data[j].rt.raw = NULL;
}
fast5_data.clear();
}
// restore number of threads
omp_set_num_threads(prev_num_threads);
}
| 3,145 | 1,002 |
/*
Letter Case Permutation
https://leetcode.com/problems/letter-case-permutation/
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. You can return the output in any order.
Example 1:
Input: S = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]
Example 2:
Input: S = "3z4"
Output: ["3z4","3Z4"]
Example 3:
Input: S = "12345"
Output: ["12345"]
Example 4:
Input: S = "0"
Output: ["0"]
Constraints:
S will be a string with length between 1 and 12.
S will consist only of letters or digits.
*/
class Solution {
public:
void backtrack(string &s, int i, vector<string> &ans) {
if(i == s.size()) {
ans.push_back(s);
return;
}
// handle letter / digit
backtrack(s, i + 1, ans);
if(isalpha(s[i])) {
// A: 1 0000 0001
// a: 1 0010 0001
// Z: 1 0001 1010
// z: 1 0011 1010
// a -> A / A -> a
s[i] ^= (1 << 5);
// A -> a / a -> A
backtrack(s, i + 1, ans);
}
}
vector<string> letterCasePermutation(string S) {
vector<string> ans;
backtrack(S, 0, ans);
return ans;
}
}; | 1,305 | 492 |
#ifndef VIENNACL_LINALG_DIRECT_SOLVE_HPP_
#define VIENNACL_LINALG_DIRECT_SOLVE_HPP_
/* =========================================================================
Copyright (c) 2010-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
Portions of this software are copyright by UChicago Argonne, LLC.
-----------------
ViennaCL - The Vienna Computing Library
-----------------
Project Head: Karl Rupp rupp@iue.tuwien.ac.at
(A list of authors and contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
============================================================================= */
/** @file viennacl/linalg/direct_solve.hpp
@brief Implementations of dense direct solvers are found here.
*/
#include "viennacl/forwards.h"
#include "viennacl/meta/enable_if.hpp"
#include "viennacl/vector.hpp"
#include "viennacl/matrix.hpp"
#include "viennacl/linalg/host_based/direct_solve.hpp"
#ifdef VIENNACL_WITH_OPENCL
#include "viennacl/linalg/opencl/direct_solve.hpp"
#endif
#ifdef VIENNACL_WITH_CUDA
#include "viennacl/linalg/cuda/direct_solve.hpp"
#endif
namespace viennacl
{
namespace linalg
{
//
// A \ B:
//
/** @brief Direct inplace solver for dense triangular systems. Matlab notation: A \ B
*
* @param A The system matrix
* @param B The matrix of row vectors, where the solution is directly written to
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value
>::type
inplace_solve(const M1 & A, M2 & B, SOLVERTAG)
{
assert( (viennacl::traits::size1(A) == viennacl::traits::size2(A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)"));
assert( (viennacl::traits::size1(A) == viennacl::traits::size1(B)) && bool("Size check failed in inplace_solve(): size1(A) != size1(B)"));
switch (viennacl::traits::handle(A).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(A, B, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(A, B, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(A, B, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
/** @brief Direct inplace solver for dense triangular systems with transposed right hand side
*
* @param A The system matrix
* @param proxy_B The transposed matrix of row vectors, where the solution is directly written to
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value
>::type
inplace_solve(const M1 & A,
matrix_expression< const M2, const M2, op_trans> proxy_B,
SOLVERTAG)
{
assert( (viennacl::traits::size1(A) == viennacl::traits::size2(A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)"));
assert( (viennacl::traits::size1(A) == viennacl::traits::size1(proxy_B)) && bool("Size check failed in inplace_solve(): size1(A) != size1(B^T)"));
switch (viennacl::traits::handle(A).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(A, proxy_B, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(A, proxy_B, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(A, proxy_B, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
//upper triangular solver for transposed lower triangular matrices
/** @brief Direct inplace solver for dense triangular systems that stem from transposed triangular systems
*
* @param proxy_A The system matrix proxy
* @param B The matrix holding the load vectors, where the solution is directly written to
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value
>::type
inplace_solve(const matrix_expression< const M1, const M1, op_trans> & proxy_A,
M2 & B,
SOLVERTAG)
{
assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size2(proxy_A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)"));
assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size1(B)) && bool("Size check failed in inplace_solve(): size1(A^T) != size1(B)"));
switch (viennacl::traits::handle(proxy_A.lhs()).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(proxy_A, B, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(proxy_A, B, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(proxy_A, B, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
/** @brief Direct inplace solver for dense transposed triangular systems with transposed right hand side. Matlab notation: A' \ B'
*
* @param proxy_A The system matrix proxy
* @param proxy_B The matrix holding the load vectors, where the solution is directly written to
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value
>::type
inplace_solve(const matrix_expression< const M1, const M1, op_trans> & proxy_A,
matrix_expression< const M2, const M2, op_trans> proxy_B,
SOLVERTAG)
{
assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size2(proxy_A)) && bool("Size check failed in inplace_solve(): size1(A) != size2(A)"));
assert( (viennacl::traits::size1(proxy_A) == viennacl::traits::size1(proxy_B)) && bool("Size check failed in inplace_solve(): size1(A^T) != size1(B^T)"));
switch (viennacl::traits::handle(proxy_A.lhs()).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(proxy_A, proxy_B, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(proxy_A, proxy_B, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(proxy_A, proxy_B, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
//
// A \ b
//
template <typename M1,
typename V1, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_vector<V1>::value
>::type
inplace_solve(const M1 & mat,
V1 & vec,
SOLVERTAG)
{
assert( (mat.size1() == vec.size()) && bool("Size check failed in inplace_solve(): size1(A) != size(b)"));
assert( (mat.size2() == vec.size()) && bool("Size check failed in inplace_solve(): size2(A) != size(b)"));
switch (viennacl::traits::handle(mat).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(mat, vec, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(mat, vec, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(mat, vec, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
/** @brief Direct inplace solver for dense upper triangular systems that stem from transposed lower triangular systems
*
* @param proxy The system matrix proxy
* @param vec The load vector, where the solution is directly written to
*/
template <typename M1,
typename V1, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_vector<V1>::value
>::type
inplace_solve(const matrix_expression< const M1, const M1, op_trans> & proxy,
V1 & vec,
SOLVERTAG)
{
assert( (proxy.lhs().size1() == vec.size()) && bool("Size check failed in inplace_solve(): size1(A) != size(b)"));
assert( (proxy.lhs().size2() == vec.size()) && bool("Size check failed in inplace_solve(): size2(A) != size(b)"));
switch (viennacl::traits::handle(proxy.lhs()).get_active_handle_id())
{
case viennacl::MAIN_MEMORY:
viennacl::linalg::host_based::inplace_solve(proxy, vec, SOLVERTAG());
break;
#ifdef VIENNACL_WITH_OPENCL
case viennacl::OPENCL_MEMORY:
viennacl::linalg::opencl::inplace_solve(proxy, vec, SOLVERTAG());
break;
#endif
#ifdef VIENNACL_WITH_CUDA
case viennacl::CUDA_MEMORY:
viennacl::linalg::cuda::inplace_solve(proxy, vec, SOLVERTAG());
break;
#endif
default:
throw "not implemented";
}
}
/////////////////// general wrappers for non-inplace solution //////////////////////
namespace detail
{
template <typename T>
struct extract_embedded_type
{
typedef T type;
};
template <typename T>
struct extract_embedded_type< matrix_range<T> >
{
typedef T type;
};
template <typename T>
struct extract_embedded_type< matrix_slice<T> >
{
typedef T type;
};
template <typename T>
struct extract_embedded_type< vector_range<T> >
{
typedef T type;
};
template <typename T>
struct extract_embedded_type< vector_slice<T> >
{
typedef T type;
};
}
/** @brief Convenience functions for C = solve(A, B, some_tag()); Creates a temporary result matrix and forwards the request to inplace_solve()
*
* @param A The system matrix
* @param B The matrix of load vectors
* @param tag Dispatch tag
*/
template <typename M1,
typename M2,
typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value,
typename detail::extract_embedded_type<M2>::type
>::type
solve(const M1 & A, const M2 & B, SOLVERTAG tag)
{
typedef typename detail::extract_embedded_type<M2>::type MatrixType;
// do an inplace solve on the result vector:
MatrixType result(B);
inplace_solve(A, result, tag);
return result;
}
//////////
/** @brief Convenience functions for C = solve(A, B^T, some_tag()); Creates a temporary result matrix and forwards the request to inplace_solve()
*
* @param A The system matrix
* @param proxy The transposed load vector
* @param tag Dispatch tag
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value,
typename detail::extract_embedded_type<M2>::type
>::type
solve(const M1 & A,
const matrix_expression< const M2, const M2, op_trans> & proxy,
SOLVERTAG tag)
{
typedef typename detail::extract_embedded_type<M2>::type MatrixType;
// do an inplace solve on the result vector:
MatrixType result(proxy);
inplace_solve(A, result, tag);
return result;
}
/** @brief Convenience functions for result = solve(mat, vec, some_tag()); Creates a temporary result vector and forwards the request to inplace_solve()
*
* @param mat The system matrix
* @param vec The load vector
* @param tag Dispatch tag
*/
template<typename M1,
typename V1, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_vector<V1>::value,
typename detail::extract_embedded_type<V1>::type
>::type
solve(const M1 & mat,
const V1 & vec,
SOLVERTAG const & tag)
{
// do an inplace solve on the result vector:
typename detail::extract_embedded_type<V1>::type result(vec);
inplace_solve(mat, result, tag);
return result;
}
///////////// transposed system matrix:
/** @brief Convenience functions for result = solve(trans(mat), B, some_tag()); Creates a temporary result matrix and forwards the request to inplace_solve()
*
* @param proxy The transposed system matrix proxy
* @param B The matrix of load vectors
* @param tag Dispatch tag
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value,
typename detail::extract_embedded_type<M2>::type
>::type
solve(const matrix_expression< const M1, const M1, op_trans> & proxy,
const M2 & B,
SOLVERTAG tag)
{
typedef typename detail::extract_embedded_type<M2>::type MatrixType;
// do an inplace solve on the result vector:
MatrixType result(B);
inplace_solve(proxy, result, tag);
return result;
}
/** @brief Convenience functions for result = solve(trans(mat), vec, some_tag()); Creates a temporary result vector and forwards the request to inplace_solve()
*
* @param proxy_A The transposed system matrix proxy
* @param proxy_B The transposed matrix of load vectors, where the solution is directly written to
* @param tag Dispatch tag
*/
template <typename M1,
typename M2, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_matrix<M2>::value,
typename detail::extract_embedded_type<M2>::type
>::type
solve(const matrix_expression< const M1, const M1, op_trans> & proxy_A,
const matrix_expression< const M2, const M2, op_trans> & proxy_B,
SOLVERTAG tag)
{
typedef typename detail::extract_embedded_type<M2>::type MatrixType;
// do an inplace solve on the result vector:
MatrixType result(proxy_B);
inplace_solve(proxy_A, result, tag);
return result;
}
/** @brief Convenience functions for result = solve(trans(mat), vec, some_tag()); Creates a temporary result vector and forwards the request to inplace_solve()
*
* @param proxy The transposed system matrix proxy
* @param vec The load vector, where the solution is directly written to
* @param tag Dispatch tag
*/
template<typename M1,
typename V1, typename SOLVERTAG>
typename viennacl::enable_if< viennacl::is_any_dense_nonstructured_matrix<M1>::value
&& viennacl::is_any_dense_nonstructured_vector<V1>::value,
typename detail::extract_embedded_type<V1>::type
>::type
solve(const matrix_expression< const M1,
const M1,
op_trans> & proxy,
const V1 & vec,
SOLVERTAG const & tag)
{
// do an inplace solve on the result vector:
typename detail::extract_embedded_type<V1>::type result(vec);
inplace_solve(proxy, result, tag);
return result;
}
}
}
#endif
| 18,563 | 6,066 |
/*
* Copyright (C) 2021 Alibaba Inc. All rights reserved.
* Author: Kraken Team.
*/
#include "qjs_patch.h"
#include <quickjs/cutils.h>
#include <quickjs/list.h>
#include <cstring>
typedef enum {
JS_GC_PHASE_NONE,
JS_GC_PHASE_DECREF,
JS_GC_PHASE_REMOVE_CYCLES,
} JSGCPhaseEnum;
typedef struct JSProxyData {
JSValue target;
JSValue handler;
uint8_t is_func;
uint8_t is_revoked;
} JSProxyData;
typedef enum {
JS_GC_OBJ_TYPE_JS_OBJECT,
JS_GC_OBJ_TYPE_FUNCTION_BYTECODE,
JS_GC_OBJ_TYPE_SHAPE,
JS_GC_OBJ_TYPE_VAR_REF,
JS_GC_OBJ_TYPE_ASYNC_FUNCTION,
JS_GC_OBJ_TYPE_JS_CONTEXT,
} JSGCObjectTypeEnum;
struct JSGCObjectHeader {
int ref_count; /* must come first, 32-bit */
JSGCObjectTypeEnum gc_obj_type : 4;
uint8_t mark : 4; /* used by the GC */
uint8_t dummy1; /* not used by the GC */
uint16_t dummy2; /* not used by the GC */
struct list_head link;
};
typedef struct JSShapeProperty {
uint32_t hash_next : 26; /* 0 if last in list */
uint32_t flags : 6; /* JS_PROP_XXX */
JSAtom atom; /* JS_ATOM_NULL = free property entry */
} JSShapeProperty;
struct JSShape {
/* hash table of size hash_mask + 1 before the start of the
structure (see prop_hash_end()). */
JSGCObjectHeader header;
/* true if the shape is inserted in the shape hash table. If not,
JSShape.hash is not valid */
uint8_t is_hashed;
/* If true, the shape may have small array index properties 'n' with 0
<= n <= 2^31-1. If false, the shape is guaranteed not to have
small array index properties */
uint8_t has_small_array_index;
uint32_t hash; /* current hash value */
uint32_t prop_hash_mask;
int prop_size; /* allocated properties */
int prop_count; /* include deleted properties */
int deleted_prop_count;
JSShape* shape_hash_next; /* in JSRuntime.shape_hash[h] list */
JSObject* proto;
JSShapeProperty prop[0]; /* prop_size elements */
};
struct JSRuntime {
JSMallocFunctions mf;
JSMallocState malloc_state;
const char* rt_info;
int atom_hash_size; /* power of two */
int atom_count;
int atom_size;
int atom_count_resize; /* resize hash table at this count */
uint32_t* atom_hash;
JSString** atom_array;
int atom_free_index; /* 0 = none */
int class_count; /* size of class_array */
JSClass* class_array;
struct list_head context_list; /* list of JSContext.link */
/* list of JSGCObjectHeader.link. List of allocated GC objects (used
by the garbage collector) */
struct list_head gc_obj_list;
/* list of JSGCObjectHeader.link. Used during JS_FreeValueRT() */
struct list_head gc_zero_ref_count_list;
struct list_head tmp_obj_list; /* used during GC */
JSGCPhaseEnum gc_phase : 8;
size_t malloc_gc_threshold;
#ifdef DUMP_LEAKS
struct list_head string_list; /* list of JSString.link */
#endif
/* stack limitation */
const uint8_t* stack_top;
size_t stack_size; /* in bytes */
JSValue current_exception;
/* true if inside an out of memory error, to avoid recursing */
BOOL in_out_of_memory : 8;
struct JSStackFrame* current_stack_frame;
JSInterruptHandler* interrupt_handler;
void* interrupt_opaque;
JSHostPromiseRejectionTracker* host_promise_rejection_tracker;
void* host_promise_rejection_tracker_opaque;
struct list_head job_list; /* list of JSJobEntry.link */
JSModuleNormalizeFunc* module_normalize_func;
JSModuleLoaderFunc* module_loader_func;
void* module_loader_opaque;
BOOL can_block : 8; /* TRUE if Atomics.wait can block */
/* used to allocate, free and clone SharedArrayBuffers */
JSSharedArrayBufferFunctions sab_funcs;
/* Shape hash table */
int shape_hash_bits;
int shape_hash_size;
int shape_hash_count; /* number of hashed shapes */
JSShape** shape_hash;
#ifdef CONFIG_BIGNUM
bf_context_t bf_ctx;
JSNumericOperations bigint_ops;
JSNumericOperations bigfloat_ops;
JSNumericOperations bigdecimal_ops;
uint32_t operator_count;
#endif
void* user_opaque;
};
typedef struct JSRegExp {
JSString* pattern;
JSString* bytecode; /* also contains the flags */
} JSRegExp;
typedef struct JSString JSString;
struct JSObject {
union {
JSGCObjectHeader header;
struct {
int __gc_ref_count; /* corresponds to header.ref_count */
uint8_t __gc_mark; /* corresponds to header.mark/gc_obj_type */
uint8_t extensible : 1;
uint8_t free_mark : 1; /* only used when freeing objects with cycles */
uint8_t is_exotic : 1; /* TRUE if object has exotic property handlers */
uint8_t fast_array : 1; /* TRUE if u.array is used for get/put (for JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS and typed arrays) */
uint8_t is_constructor : 1; /* TRUE if object is a constructor function */
uint8_t is_uncatchable_error : 1; /* if TRUE, error is not catchable */
uint8_t tmp_mark : 1; /* used in JS_WriteObjectRec() */
uint8_t is_HTMLDDA : 1; /* specific annex B IsHtmlDDA behavior */
uint16_t class_id; /* see JS_CLASS_x */
};
};
/* byte offsets: 16/24 */
JSShape* shape; /* prototype and property names + flag */
void* prop; /* array of properties */
/* byte offsets: 24/40 */
struct JSMapRecord* first_weak_ref; /* XXX: use a bit and an external hash table? */
/* byte offsets: 28/48 */
union {
void* opaque;
struct JSBoundFunction* bound_function; /* JS_CLASS_BOUND_FUNCTION */
struct JSCFunctionDataRecord* c_function_data_record; /* JS_CLASS_C_FUNCTION_DATA */
struct JSForInIterator* for_in_iterator; /* JS_CLASS_FOR_IN_ITERATOR */
struct JSArrayBuffer* array_buffer; /* JS_CLASS_ARRAY_BUFFER, JS_CLASS_SHARED_ARRAY_BUFFER */
struct JSTypedArray* typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_DATAVIEW */
#ifdef CONFIG_BIGNUM
struct JSFloatEnv* float_env; /* JS_CLASS_FLOAT_ENV */
struct JSOperatorSetData* operator_set; /* JS_CLASS_OPERATOR_SET */
#endif
struct JSMapState* map_state; /* JS_CLASS_MAP..JS_CLASS_WEAKSET */
struct JSMapIteratorData* map_iterator_data; /* JS_CLASS_MAP_ITERATOR, JS_CLASS_SET_ITERATOR */
struct JSArrayIteratorData* array_iterator_data; /* JS_CLASS_ARRAY_ITERATOR, JS_CLASS_STRING_ITERATOR */
struct JSRegExpStringIteratorData* regexp_string_iterator_data; /* JS_CLASS_REGEXP_STRING_ITERATOR */
struct JSGeneratorData* generator_data; /* JS_CLASS_GENERATOR */
struct JSProxyData* proxy_data; /* JS_CLASS_PROXY */
struct JSPromiseData* promise_data; /* JS_CLASS_PROMISE */
struct JSPromiseFunctionData* promise_function_data; /* JS_CLASS_PROMISE_RESOLVE_FUNCTION, JS_CLASS_PROMISE_REJECT_FUNCTION */
struct JSAsyncFunctionData* async_function_data; /* JS_CLASS_ASYNC_FUNCTION_RESOLVE, JS_CLASS_ASYNC_FUNCTION_REJECT */
struct JSAsyncFromSyncIteratorData* async_from_sync_iterator_data; /* JS_CLASS_ASYNC_FROM_SYNC_ITERATOR */
struct JSAsyncGeneratorData* async_generator_data; /* JS_CLASS_ASYNC_GENERATOR */
struct { /* JS_CLASS_BYTECODE_FUNCTION: 12/24 bytes */
/* also used by JS_CLASS_GENERATOR_FUNCTION, JS_CLASS_ASYNC_FUNCTION and JS_CLASS_ASYNC_GENERATOR_FUNCTION */
struct JSFunctionBytecode* function_bytecode;
void** var_refs;
JSObject* home_object; /* for 'super' access */
} func;
struct { /* JS_CLASS_C_FUNCTION: 12/20 bytes */
JSContext* realm;
JSCFunctionType c_function;
uint8_t length;
uint8_t cproto;
int16_t magic;
} cfunc;
/* array part for fast arrays and typed arrays */
struct { /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS, JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */
union {
uint32_t size; /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */
struct JSTypedArray* typed_array; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */
} u1;
union {
JSValue* values; /* JS_CLASS_ARRAY, JS_CLASS_ARGUMENTS */
void* ptr; /* JS_CLASS_UINT8C_ARRAY..JS_CLASS_FLOAT64_ARRAY */
int8_t* int8_ptr; /* JS_CLASS_INT8_ARRAY */
uint8_t* uint8_ptr; /* JS_CLASS_UINT8_ARRAY, JS_CLASS_UINT8C_ARRAY */
int16_t* int16_ptr; /* JS_CLASS_INT16_ARRAY */
uint16_t* uint16_ptr; /* JS_CLASS_UINT16_ARRAY */
int32_t* int32_ptr; /* JS_CLASS_INT32_ARRAY */
uint32_t* uint32_ptr; /* JS_CLASS_UINT32_ARRAY */
int64_t* int64_ptr; /* JS_CLASS_INT64_ARRAY */
uint64_t* uint64_ptr; /* JS_CLASS_UINT64_ARRAY */
float* float_ptr; /* JS_CLASS_FLOAT32_ARRAY */
double* double_ptr; /* JS_CLASS_FLOAT64_ARRAY */
} u;
uint32_t count; /* <= 2^31-1. 0 for a detached typed array */
} array; /* 12/20 bytes */
JSRegExp regexp; /* JS_CLASS_REGEXP: 8/16 bytes */
JSValue object_data; /* for JS_SetObjectData(): 8/16/16 bytes */
} u;
/* byte sizes: 40/48/72 */
};
uint16_t* JS_ToUnicode(JSContext* ctx, JSValueConst value, uint32_t* length) {
if (JS_VALUE_GET_TAG(value) != JS_TAG_STRING) {
value = JS_ToString(ctx, value);
if (JS_IsException(value))
return NULL;
} else {
value = JS_DupValue(ctx, value);
}
JSString* string = JS_VALUE_GET_STRING(value);
if (!string->is_wide_char) {
uint8_t* p = string->u.str8;
uint32_t len = *length = string->len;
auto* newBuf = (uint16_t*)malloc(sizeof(uint16_t) * len * 2);
for (size_t i = 0; i < len; i++) {
newBuf[i] = p[i];
newBuf[i + 1] = 0x00;
}
JS_FreeValue(ctx, value);
return newBuf;
} else {
*length = string->len;
}
JS_FreeValue(ctx, value);
return string->u.str16;
}
static JSString* js_alloc_string_rt(JSRuntime* rt, int max_len, int is_wide_char) {
JSString* str;
str = static_cast<JSString*>(js_malloc_rt(rt, sizeof(JSString) + (max_len << is_wide_char) + 1 - is_wide_char));
if (unlikely(!str))
return NULL;
str->header.ref_count = 1;
str->is_wide_char = is_wide_char;
str->len = max_len;
str->atom_type = 0;
str->hash = 0; /* optional but costless */
str->hash_next = 0; /* optional */
#ifdef DUMP_LEAKS
list_add_tail(&str->link, &rt->string_list);
#endif
return str;
}
static JSString* js_alloc_string(JSRuntime* runtime, JSContext* ctx, int max_len, int is_wide_char) {
JSString* p;
p = js_alloc_string_rt(runtime, max_len, is_wide_char);
if (unlikely(!p)) {
JS_ThrowOutOfMemory(ctx);
return NULL;
}
return p;
}
JSValue JS_NewUnicodeString(JSRuntime* runtime, JSContext* ctx, const uint16_t* code, uint32_t length) {
JSString* str;
str = js_alloc_string(runtime, ctx, length, 1);
if (!str)
return JS_EXCEPTION;
memcpy(str->u.str16, code, length * 2);
return JS_MKPTR(JS_TAG_STRING, str);
}
JSClassID JSValueGetClassId(JSValue obj) {
JSObject* p;
if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)
return -1;
p = JS_VALUE_GET_OBJ(obj);
return p->class_id;
}
bool JS_IsProxy(JSValue value) {
if (!JS_IsObject(value))
return false;
JSObject* p = JS_VALUE_GET_OBJ(value);
return p->class_id == JS_CLASS_PROXY;
}
JSValue JS_GetProxyTarget(JSValue value) {
JSObject* p = JS_VALUE_GET_OBJ(value);
return p->u.proxy_data->target;
} | 11,541 | 4,299 |
/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "test_utils.hpp"
template <class B>
class hyperbolic_test : public testing::Test
{
protected:
using batch_type = B;
using value_type = typename B::value_type;
static constexpr size_t size = B::size;
using vector_type = std::vector<value_type>;
size_t nb_input;
vector_type input;
vector_type acosh_input;
vector_type atanh_input;
vector_type expected;
vector_type res;
hyperbolic_test()
{
nb_input = size * 10000;
input.resize(nb_input);
acosh_input.resize(nb_input);
atanh_input.resize(nb_input);
for (size_t i = 0; i < nb_input; ++i)
{
input[i] = value_type(-1.5) + i * value_type(3) / nb_input;
acosh_input[i] = value_type(1.) + i * value_type(3) / nb_input;
atanh_input[i] = value_type(-0.95) + i * value_type(1.9) / nb_input;
}
expected.resize(nb_input);
res.resize(nb_input);
}
void test_hyperbolic_functions()
{
// sinh
{
std::transform(input.cbegin(), input.cend(), expected.begin(),
[](const value_type& v) { return std::sinh(v); });
batch_type in, out;
for (size_t i = 0; i < nb_input; i += size)
{
detail::load_batch(in, input, i);
out = sinh(in);
detail::store_batch(out, res, i);
}
size_t diff = detail::get_nb_diff(res, expected);
EXPECT_EQ(diff, 0) << print_function_name("sinh");
}
// cosh
{
std::transform(input.cbegin(), input.cend(), expected.begin(),
[](const value_type& v) { return std::cosh(v); });
batch_type in, out;
for (size_t i = 0; i < nb_input; i += size)
{
detail::load_batch(in, input, i);
out = cosh(in);
detail::store_batch(out, res, i);
}
size_t diff = detail::get_nb_diff(res, expected);
EXPECT_EQ(diff, 0) << print_function_name("cosh");
}
// tanh
{
std::transform(input.cbegin(), input.cend(), expected.begin(),
[](const value_type& v) { return std::tanh(v); });
batch_type in, out;
for (size_t i = 0; i < nb_input; i += size)
{
detail::load_batch(in, input, i);
out = tanh(in);
detail::store_batch(out, res, i);
}
size_t diff = detail::get_nb_diff(res, expected);
EXPECT_EQ(diff, 0) << print_function_name("tanh");
}
}
void test_reciprocal_functions()
{
// asinh
{
std::transform(input.cbegin(), input.cend(), expected.begin(),
[](const value_type& v) { return std::asinh(v); });
batch_type in, out;
for (size_t i = 0; i < nb_input; i += size)
{
detail::load_batch(in, input, i);
out = asinh(in);
detail::store_batch(out, res, i);
}
size_t diff = detail::get_nb_diff(res, expected);
EXPECT_EQ(diff, 0) << print_function_name("asinh");
}
// acosh
{
std::transform(acosh_input.cbegin(), acosh_input.cend(), expected.begin(),
[](const value_type& v) { return std::acosh(v); });
batch_type in, out;
for (size_t i = 0; i < nb_input; i += size)
{
detail::load_batch(in, acosh_input, i);
out = acosh(in);
detail::store_batch(out, res, i);
}
size_t diff = detail::get_nb_diff(res, expected);
EXPECT_EQ(diff, 0) << print_function_name("acosh");
}
// atanh
{
std::transform(atanh_input.cbegin(), atanh_input.cend(), expected.begin(),
[](const value_type& v) { return std::atanh(v); });
batch_type in, out;
for (size_t i = 0; i < nb_input; i += size)
{
detail::load_batch(in, atanh_input, i);
out = atanh(in);
detail::store_batch(out, res, i);
}
size_t diff = detail::get_nb_diff(res, expected);
EXPECT_EQ(diff, 0) << print_function_name("atanh");
}
}
};
TYPED_TEST_SUITE(hyperbolic_test, batch_float_types, simd_test_names);
TYPED_TEST(hyperbolic_test, hyperbolic)
{
this->test_hyperbolic_functions();
}
TYPED_TEST(hyperbolic_test, reciprocal)
{
this->test_reciprocal_functions();
}
| 5,397 | 1,652 |
#include "content_loader.h"
#include "pugixml.hpp"
#include <iostream>
#include <string>
#include "globalvariables.h"
#include "sprite.h"
enemy_content_map enemyContentMap;
void SetEnemyContentFromEnemyDirXMLFile(std::string xml_enemy_scripts_file_dir,
std::string xml_enemy_scripts_file_path)
{
// Create empty XML document within memory
pugi::xml_document doc;
// Load XML file into memory
// Remark: to fully read declaration entries you have to specify
// "pugi::parse_declaration"
pugi::xml_parse_result result = doc.load_file(xml_enemy_scripts_file_path.c_str(),
pugi::parse_default);
if (!result)
{
std::cout << "Parse error: " << result.description()
<< ", character pos= " << result.offset;
return;
}
pugi::xml_node enemyDirRoot = doc.child("EnemyDirRoot");
size_t iterator = 0;
//go through each tile type in tiles node
for (pugi::xml_node enemyNode = enemyDirRoot.first_child(); enemyNode; enemyNode = enemyNode.next_sibling())
{
std::string valName = enemyNode.attribute("name").value();
std::string valFilepath = enemyNode.attribute("scriptfilepath").value();
std::string valMediaDir = enemyNode.attribute("mediaDir").value();
std::string valXMLDefFilepath = enemyNode.attribute("xmldefpath").value();
//assuming file paths in xml file is set relative to xml filepath itself
std::string filepath = xml_enemy_scripts_file_dir + "/" + valFilepath;
std::cout << "file read:" << filepath << std::endl;
std::string mediaDir = xml_enemy_scripts_file_dir + "/" + valMediaDir;
std::string xml_def_fp = xml_enemy_scripts_file_dir + "/" + valXMLDefFilepath;
EnemyContent ec;
ec.name = valName;
ec.script_filepath = filepath;
ec.mediaDir = mediaDir;
ec.xml_def_filepath = xml_def_fp;
std::pair<std::string,EnemyContent> thisEnemyContentPair (valName,ec);
enemyContentMap.insert (thisEnemyContentPair);
iterator++;
}
}
void LoadContentFromXMLFiles()
{
std::string xml_enemy_scripts_file_dir = DATADIR_STR + "/EnemyPacks";
std::string xml_enemy_scripts_file_path = xml_enemy_scripts_file_dir + "/enemy_directory.xml";
SetEnemyContentFromEnemyDirXMLFile(xml_enemy_scripts_file_dir,xml_enemy_scripts_file_path);
}
bool loadScriptedEnemyVisualMedia(std::string xml_file_path,std::string xml_file_dir,
LTexture* cTexture,
std::vector <SDL_Rect> &walk_clips,
SDL_Renderer* gRenderer )
{
// Create empty XML document within memory
pugi::xml_document doc;
// Load XML file into memory
// Remark: to fully read declaration entries you have to specify
// "pugi::parse_declaration"
pugi::xml_parse_result result = doc.load_file(xml_file_path.c_str(),
pugi::parse_default);
if (!result)
{
std::cout << "Parse error: " << result.description() << ", character pos= " << result.offset;
return false;
}
pugi::xml_node root = doc.child("EnemyRoot");
std::string cTexFilePath = xml_file_dir + "/" + root.child("Texture").attribute("path").value();
//initialize texture
if(!cTexture->loadFromFile(cTexFilePath.c_str(),gRenderer) )
{
std::cout << "scripted enemy image loading failed! \n";
std::cout << "filepath:" << cTexFilePath << std::endl;
return false;
}
else
{
std::string valString;
//set size of walk clips vector
valString = root.child("WalkClips").child("clip_num").attribute("number").value();
size_t clipsNum = atoi(valString.c_str());
walk_clips.resize(clipsNum);
//set width and height of each uniform clips
valString = root.child("WalkClips").child("clip_width").attribute("width").value();
std::int8_t width = atoi(valString.c_str());
valString = root.child("WalkClips").child("clip_height").attribute("height").value();
std::int8_t height = atoi(valString.c_str());
SDL_Rect clip;
clip.w = width;
clip.h = height;
valString = root.child("WalkClips").child("UP_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_1] = clip;
valString = root.child("WalkClips").child("UP_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_2] = clip;
valString = root.child("WalkClips").child("UP_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_3] = clip;
valString = root.child("WalkClips").child("UP_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_4] = clip;
valString = root.child("WalkClips").child("UP_LEFT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_LEFT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_LEFT_1] = clip;
valString = root.child("WalkClips").child("UP_LEFT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_LEFT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_LEFT_2] = clip;
valString = root.child("WalkClips").child("UP_LEFT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_LEFT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_LEFT_3] = clip;
valString = root.child("WalkClips").child("UP_LEFT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_LEFT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_LEFT_4] = clip;
valString = root.child("WalkClips").child("LEFT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("LEFT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::LEFT_1] = clip;
valString = root.child("WalkClips").child("LEFT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("LEFT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::LEFT_2] = clip;
valString = root.child("WalkClips").child("LEFT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("LEFT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::LEFT_3] = clip;
valString = root.child("WalkClips").child("LEFT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("LEFT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::LEFT_4] = clip;
valString = root.child("WalkClips").child("DOWN_LEFT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_LEFT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_LEFT_1] = clip;
valString = root.child("WalkClips").child("DOWN_LEFT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_LEFT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_LEFT_2] = clip;
valString = root.child("WalkClips").child("DOWN_LEFT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_LEFT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_LEFT_3] = clip;
valString = root.child("WalkClips").child("DOWN_LEFT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_LEFT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_LEFT_4] = clip;
valString = root.child("WalkClips").child("DOWN_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_1] = clip;
valString = root.child("WalkClips").child("DOWN_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_2] = clip;
valString = root.child("WalkClips").child("UP_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_3] = clip;
valString = root.child("WalkClips").child("DOWN_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_4] = clip;
valString = root.child("WalkClips").child("RIGHT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("RIGHT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::RIGHT_1] = clip;
valString = root.child("WalkClips").child("RIGHT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("RIGHT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::RIGHT_2] = clip;
valString = root.child("WalkClips").child("RIGHT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("RIGHT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::RIGHT_3] = clip;
valString = root.child("WalkClips").child("RIGHT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("RIGHT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::RIGHT_4] = clip;
valString = root.child("WalkClips").child("DOWN_RIGHT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_RIGHT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_RIGHT_1] = clip;
valString = root.child("WalkClips").child("DOWN_RIGHT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_RIGHT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_RIGHT_2] = clip;
valString = root.child("WalkClips").child("DOWN_RIGHT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_RIGHT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_RIGHT_3] = clip;
valString = root.child("WalkClips").child("DOWN_RIGHT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("DOWN_RIGHT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::DOWN_RIGHT_4] = clip;
valString = root.child("WalkClips").child("UP_RIGHT_1").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_RIGHT_1").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_RIGHT_1] = clip;
valString = root.child("WalkClips").child("UP_RIGHT_2").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_RIGHT_2").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_RIGHT_2] = clip;
valString = root.child("WalkClips").child("UP_RIGHT_3").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_RIGHT_3").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_RIGHT_3] = clip;
valString = root.child("WalkClips").child("UP_RIGHT_4").attribute("x").value();
clip.x = atoi(valString.c_str());;
valString = root.child("WalkClips").child("UP_RIGHT_4").attribute("y").value();
clip.y = atoi(valString.c_str());;
walk_clips[Sprite::UP_RIGHT_4] = clip;
}
return true;
}
void freeScriptedEnemyVisualMedia(LTexture* cTexture)
{
if(cTexture != nullptr)
{
cTexture = nullptr;
}
}
bool setEnemyTypeAttributes(EnemyContent* thisEnemyContent, std::string xml_file_path)
{
// Create empty XML document within memory
pugi::xml_document doc;
// Load XML file into memory
// Remark: to fully read declaration entries you have to specify
// "pugi::parse_declaration"
pugi::xml_parse_result result = doc.load_file(xml_file_path.c_str(),
pugi::parse_default);
if (!result)
{
std::cout << "Parse error: " << result.description() << ", character pos= " << result.offset;
return false;
}
pugi::xml_node root = doc.child("EnemyRoot");
std::string healthStr = root.child("Attributes").attribute("health").value();
std::string speedStr = root.child("Attributes").attribute("speed").value();
thisEnemyContent->health = std::stoi(healthStr);
thisEnemyContent->speed = std::stof(speedStr);
return true;
}
| 15,043 | 5,384 |
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019 Datadog, Inc.
#include "two.h"
#include "constants.h"
#include <sstream>
Two::~Two() { Py_Finalize(); }
void Two::init(const char *pythonHome) {
if (pythonHome != NULL) {
_pythonHome = pythonHome;
}
Py_SetPythonHome(const_cast<char *>(_pythonHome));
Py_Initialize();
PyModules::iterator it;
for (it = _modules.begin(); it != _modules.end(); ++it) {
six_module_t module = it->first;
PyObject *m = Py_InitModule(getExtensionModuleName(module), &_modules[module][0]);
if (_module_constants.find(module) == _module_constants.end()) {
std::vector<PyModuleConst>::iterator cit;
for (cit = _module_constants[module].begin(); cit != _module_constants[module].begin(); ++cit) {
PyModule_AddIntConstant(m, cit->first.c_str(), cit->second);
}
}
}
// In recent versions of Python3 this is called from Py_Initialize already,
// for Python2 it has to be explicit.
PyEval_InitThreads();
}
bool Two::isInitialized() const { return Py_IsInitialized(); }
const char *Two::getPyVersion() const { return Py_GetVersion(); }
int Two::runSimpleString(const char *code) const { return PyRun_SimpleString(code); }
int Two::addModuleFunction(six_module_t module, six_module_func_t t, const char *funcName, void *func) {
if (getExtensionModuleName(module) == getUnknownModuleName()) {
setError("Unknown ExtensionModule value");
return -1;
}
int ml_flags;
switch (t) {
case DATADOG_AGENT_SIX_NOARGS:
ml_flags = METH_NOARGS;
break;
case DATADOG_AGENT_SIX_ARGS:
ml_flags = METH_VARARGS;
break;
case DATADOG_AGENT_SIX_KEYWORDS:
ml_flags = METH_VARARGS | METH_KEYWORDS;
break;
default:
setError("Unknown MethType value");
return -1;
}
PyMethodDef def = { funcName, (PyCFunction)func, ml_flags, "" };
if (_modules.find(module) == _modules.end()) {
_modules[module] = PyMethods();
// add the guard
PyMethodDef guard = { NULL, NULL };
_modules[module].push_back(guard);
}
// insert at beginning so we keep guard at the end
_modules[module].insert(_modules[module].begin(), def);
// success
return 0;
}
int Two::addModuleIntConst(six_module_t module, const char *name, long value) {
if (_module_constants.find(module) == _module_constants.end()) {
_module_constants[module] = std::vector<PyModuleConst>();
}
_module_constants[module].push_back(std::make_pair(std::string(name), value));
return 1; // ok
}
six_gilstate_t Two::GILEnsure() {
PyGILState_STATE state = PyGILState_Ensure();
if (state == PyGILState_LOCKED) {
return DATADOG_AGENT_SIX_GIL_LOCKED;
}
return DATADOG_AGENT_SIX_GIL_UNLOCKED;
}
void Two::GILRelease(six_gilstate_t state) {
if (state == DATADOG_AGENT_SIX_GIL_LOCKED) {
PyGILState_Release(PyGILState_LOCKED);
} else {
PyGILState_Release(PyGILState_UNLOCKED);
}
}
// return new reference
PyObject *Two::_importFrom(const char *module, const char *name) {
PyObject *obj_module = NULL;
PyObject *obj_symbol = NULL;
obj_module = PyImport_ImportModule(module);
if (obj_module == NULL) {
setError(_fetchPythonError());
goto error;
}
obj_symbol = PyObject_GetAttrString(obj_module, name);
if (obj_symbol == NULL) {
setError(_fetchPythonError());
goto error;
}
Py_XDECREF(obj_module);
return obj_symbol;
error:
Py_XDECREF(obj_module);
Py_XDECREF(obj_symbol);
return NULL;
}
SixPyObject *Two::getCheck(const char *module, const char *init_config_str, const char *instances_str) {
PyObject *base = NULL;
PyObject *obj_module = NULL;
PyObject *klass = NULL;
PyObject *init_config = NULL;
PyObject *instances = NULL;
PyObject *check = NULL;
PyObject *args = NULL;
PyObject *kwargs = NULL;
char load_config[] = "load_config";
char format[] = "(s)"; // use parentheses to force Tuple creation
// import the base class
base = _importFrom("datadog_checks.base.checks", "AgentCheck");
if (base == NULL) {
std::string old_err = getError();
setError("Unable to import the base class: " + old_err);
goto done;
}
// try to import python module containing the check
obj_module = PyImport_ImportModule(module);
if (obj_module == NULL) {
std::ostringstream err;
err << "unable to import module '" << module << "': " + _fetchPythonError();
setError(err.str());
goto done;
}
// find a subclass of the base check
klass = _findSubclassOf(base, obj_module);
if (klass == NULL) {
std::ostringstream err;
err << "unable to find a subclass of the base check in module '" << module << "': " << _fetchPythonError();
setError(err.str());
goto done;
}
// call `AgentCheck.load_config(init_config)`
init_config = PyObject_CallMethod(klass, load_config, format, init_config_str);
if (init_config == NULL) {
setError("error parsing init_config: " + _fetchPythonError());
goto done;
}
// call `AgentCheck.load_config(instances)`
instances = PyObject_CallMethod(klass, load_config, format, instances_str);
if (instances == NULL) {
setError("error parsing instances: " + _fetchPythonError());
goto done;
}
// create `args` and `kwargs` to invoke `AgentCheck` constructor
args = PyTuple_New(0);
kwargs = PyDict_New();
PyDict_SetItemString(kwargs, "init_config", init_config);
PyDict_SetItemString(kwargs, "instances", instances);
// call `AgentCheck` constructor
check = PyObject_Call(klass, args, kwargs);
if (check == NULL) {
setError("error creating check instance: " + _fetchPythonError());
goto done;
}
done:
Py_XDECREF(base);
Py_XDECREF(obj_module);
Py_XDECREF(klass);
Py_XDECREF(init_config);
Py_XDECREF(instances);
Py_XDECREF(args);
Py_XDECREF(kwargs);
if (check == NULL) {
return NULL;
}
return reinterpret_cast<SixPyObject *>(check);
}
PyObject *Two::_findSubclassOf(PyObject *base, PyObject *module) {
// baseClass is not a Class type
if (base == NULL || !PyType_Check(base)) {
setError("base class is not of type 'Class'");
return NULL;
}
// module is not a Module object
if (module == NULL || !PyModule_Check(module)) {
setError("module is not of type 'Module'");
return NULL;
}
PyObject *dir = PyObject_Dir(module);
if (dir == NULL) {
setError("there was an error calling dir() on module object");
return NULL;
}
PyObject *klass = NULL;
for (int i = 0; i < PyList_GET_SIZE(dir); i++) {
// get symbol name
char *symbol_name;
PyObject *symbol = PyList_GetItem(dir, i);
if (symbol != NULL) {
symbol_name = PyString_AsString(symbol);
}
// get symbol instance. It's a new ref but in case of success we don't DecRef since we return it and the caller
// will be owner
klass = PyObject_GetAttrString(module, symbol_name);
if (klass == NULL) {
continue;
}
// not a class, ignore
if (!PyType_Check(klass)) {
Py_XDECREF(klass);
continue;
}
// this is an unrelated class, ignore
if (!PyType_IsSubtype((PyTypeObject *)klass, (PyTypeObject *)base)) {
Py_XDECREF(klass);
continue;
}
// `klass` is actually `base` itself, ignore
if (PyObject_RichCompareBool(klass, base, Py_EQ)) {
Py_XDECREF(klass);
continue;
}
// does `klass` have subclasses?
char func_name[] = "__subclasses__";
PyObject *children = PyObject_CallMethod(klass, func_name, NULL);
if (children == NULL) {
Py_XDECREF(klass);
continue;
}
// how many?
int children_count = PyList_GET_SIZE(children);
Py_XDECREF(children);
// Agent integrations are supposed to have no subclasses
if (children_count > 0) {
Py_XDECREF(klass);
continue;
}
// got it, return the check class
goto done;
}
setError("cannot find a subclass");
done:
Py_XDECREF(dir);
return klass;
}
const char *Two::runCheck(SixPyObject *check) {
if (check == NULL) {
return NULL;
}
PyObject *py_check = reinterpret_cast<PyObject *>(check);
// result will be eventually returned as a copy and the corresponding Python
// string decref'ed, caller will be responsible for memory deallocation.
char *ret, *ret_copy = NULL;
char run[] = "run";
PyObject *result = NULL;
result = PyObject_CallMethod(py_check, run, NULL);
if (result == NULL) {
setError("error invoking 'run' method: " + _fetchPythonError());
goto done;
}
// `ret` points to the Python string internal storage and will be eventually
// deallocated along with the corresponding Python object.
ret = PyString_AsString(result);
if (ret == NULL) {
setError("error converting result to string: " + _fetchPythonError());
goto done;
}
ret_copy = strdup(ret);
done:
Py_XDECREF(result);
return ret_copy;
}
std::string Two::_fetchPythonError() {
std::string ret_val = "";
if (PyErr_Occurred() == NULL) {
return ret_val;
}
PyObject *ptype = NULL;
PyObject *pvalue = NULL;
PyObject *ptraceback = NULL;
// Fetch error and make sure exception values are normalized, as per python C API docs.
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
// There's a traceback, try to format it nicely
if (ptraceback != NULL) {
PyObject *traceback = PyImport_ImportModule("traceback");
if (traceback != NULL) {
char fname[] = "format_exception";
PyObject *format_exception = PyObject_GetAttrString(traceback, fname);
if (format_exception != NULL) {
PyObject *fmt_exc = PyObject_CallFunctionObjArgs(format_exception, ptype, pvalue, ptraceback, NULL);
if (fmt_exc != NULL) {
// "format_exception" returns a list of strings (one per line)
for (int i = 0; i < PyList_Size(fmt_exc); i++) {
ret_val += PyString_AsString(PyList_GetItem(fmt_exc, i));
}
}
Py_XDECREF(fmt_exc);
Py_XDECREF(format_exception);
}
Py_XDECREF(traceback);
} else {
// If we reach this point, there was an error while formatting the exception
ret_val = "can't format exception";
}
}
// we sometimes do not get a traceback but an error in pvalue
else if (pvalue != NULL) {
PyObject *pvalue_obj = PyObject_Str(pvalue);
if (pvalue_obj != NULL) {
ret_val = PyString_AsString(pvalue_obj);
Py_XDECREF(pvalue_obj);
}
} else if (ptype != NULL) {
PyObject *ptype_obj = PyObject_Str(ptype);
if (ptype_obj != NULL) {
ret_val = PyString_AsString(ptype_obj);
Py_XDECREF(ptype_obj);
}
}
if (ret_val == "") {
ret_val = "unknown error";
}
// clean up and return the string
PyErr_Clear();
Py_XDECREF(ptype);
Py_XDECREF(pvalue);
Py_XDECREF(ptraceback);
return ret_val;
}
| 11,972 | 3,841 |
class Solution {
public:
/**
* @param ratings Children's ratings
* @return the minimum candies you must give
*/
int candy(vector<int>& ratings) {
// Write your code here
vector<int> candy_list(ratings.size(), 0);
for (size_t i = 0; i < ratings.size(); ++ i) {
candy_list[i] = (i > 0 && ratings[i] > ratings[i - 1]) ? candy_list[i - 1] + 1 : 1;
}
for (size_t i = ratings.size() - 1; i < ratings.size(); -- i) {
candy_list[i] = max(candy_list[i], ((i + 1 < ratings.size() && ratings[i] > ratings[i + 1]) ? candy_list[i + 1] + 1 : 1));
}
return std::accumulate(candy_list.begin(), candy_list.end(), 0);
}
};
| 712 | 267 |
#include "dbmanager.h"
#include <QDir>
#include <QFile>
#include <QMessageBox>
#include <math.h>
DbManager::DbManager()
{
m_db = QSqlDatabase::addDatabase("QSQLITE", "Connection");
QString db_path = QDir::currentPath();
db_path = db_path + QString("/university.db");
m_db.setDatabaseName(db_path);
if (m_db.isOpen())
{
QMessageBox msgBox;
qDebug() << "opened";
}
else
{
if (!m_db.open())
qDebug() << m_db.lastError();
}
}
DbManager::~DbManager()
{
if (m_db.isOpen())
{
m_db.close();
}
}
bool DbManager::deleteProfessor(int username)
{
if (ProfessorExist(username))
{
QSqlQuery query(m_db);
query.prepare("DELETE FROM professors WHERE username = (:username)");
query.bindValue(":username", username);
bool success = query.exec();
if (!success)
{
qDebug() << "removeProf error: "
<< query.lastError();
return false;
}
return true;
}
}
Professor* DbManager::getProfessor(int username)
{
QSqlQuery query(m_db);
query.prepare("SELECT * FROM professors WHERE username = :username ");
query.bindValue(":username", username);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch professors";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int username = username;
QString password = query.value(2).toString();
QString firstname = query.value(3).toString();
QString lastname = query.value(4).toString();
int departmentcode = query.value(5).toInt();
int groupcode = query.value(6).toInt();
QString object_type = query.value(7).toString();
int is_supervisor = query.value(8).toInt();
int degree = query.value(9).toInt();
if (object_type == "faculty")
{
Faculty* ProfessorTemp = new Faculty(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
return dynamic_cast<Professor*> (ProfessorTemp);
}
else if (object_type == "adjunctprofessor")
{
AdjunctProfessor* ProfessorTemp = new AdjunctProfessor(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode);
return dynamic_cast<Professor*> (ProfessorTemp);
}
else if (object_type == "groupmanager")
{
GroupManager* ProfessorTemp = new GroupManager(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
return dynamic_cast<Professor*> (ProfessorTemp);
}
else if (object_type == "departmentacademicassistant")
{
//
}
else if (object_type == "departmenthead")
{
DepartmentHead* ProfessorTemp = new DepartmentHead(username, lastname.toStdString(), password.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
return dynamic_cast<Professor*> (ProfessorTemp);
}
}
}
bool DbManager::addProfessor(int username, const QString& password, const QString& firstname, const QString& lastname, const int& departmentcode, const int& groupcode, const QString& object_type, const int& is_supervisor, const int& degree)
{
bool success = false;
QSqlQuery query(m_db);
query.prepare("INSERT INTO professors (username,password,firstname,lastname,departmentcode,groupcode,object_type,is_supervisor,degree) VALUES (:username,:password,:firstname,:lastname,:departmentcode,:groupcode,:object_type,:is_supervisor,:degree)");
query.bindValue(":username", username);
query.bindValue(":password", QString(QCryptographicHash::hash((password.toUtf8()), QCryptographicHash::Md5).toHex()));
query.bindValue(":firstname", firstname);
query.bindValue(":lastname", lastname);
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":object_type", object_type);
query.bindValue(":is_supervisor", is_supervisor);
query.bindValue(":degree", degree);
if (query.exec())
{
success = true;
}
else
{
qDebug() << "addProfessor error: "
<< query.lastError();
}
return success;
}
bool DbManager::ProfessorExist(int username)
{
QSqlQuery query(m_db);
query.prepare("SELECT username FROM professors WHERE username = (:username)");
query.bindValue(":username", username);
if (query.exec())
{
if (query.next())
{
return true;
}
}
return false;
}
std::vector<Professor*> DbManager::allProfessors(void)
{
std::vector<Professor*> professors;
QSqlQuery query(m_db);
query.prepare("SELECT username, password, firstname, lastname, departmentcode, groupcode, object_type, is_supervisor, degree FROM professors");
while (query.next())
{
int username = query.value(0).toInt();
QString password = query.value(1).toString();
QString firstname = query.value(2).toString();
QString lastname = query.value(3).toString();
int departmentcode = query.value(4).toInt();
int groupcode = query.value(5).toInt();
QString object_type = query.value(6).toString();
int is_supervisor = query.value(7).toInt();
int degree = query.value(8).toInt();
if (object_type == "adjunctprofessor")
{
AdjunctProfessor* adjunct = new AdjunctProfessor(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode);
professors.push_back(adjunct);
}
else if (object_type == "faculty")
{
Faculty* faculty = new Faculty(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
faculty->setDegree(query.value(1).toInt());
if (query.value(0).toInt())
faculty->setAsSupervisor(true);
professors.push_back(faculty);
}
else if (object_type == "groupmanager")
{
GroupManager* groupmanager = new GroupManager(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
groupmanager->setDegree(query.value(1).toInt());
if (query.value(0).toInt())
groupmanager->setAsSupervisor();
professors.push_back(groupmanager);
}
else if (object_type == "departmentacademicassistant")
{
/*
DepartmentAcademicAssistant* departmentacademicassistant = new DepartmentAcademicAssistant(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
departmentacademicassistant->setDegree(query.value(1).toInt());
if(query.value(0).toInt())
departmentacademicassistant->setAsSupervisor();
professors.push_back(departmentacademicassistant);
*/
}
else if (object_type == "departmenthead")
{
DepartmentHead* departmenthead = new DepartmentHead(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, groupcode, is_supervisor, degree);
departmenthead->setDegree(query.value(1).toInt());
if (query.value(0).toInt())
departmenthead->setAsSupervisor();
professors.push_back(departmenthead);
}
}
return professors;
}
Student* DbManager::getStudent(int username)
{
QSqlQuery query(m_db);
query.prepare("SELECT * FROM students WHERE username = :username ");
query.bindValue(":username", username);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch students";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int username = username;
QString password = query.value(2).toString();
QString firstname = query.value(3).toString();
QString lastname = query.value(4).toString();
int departmentcode = query.value(5).toInt();
int groupcode = query.value(6).toInt();
int type = query.value(7).toInt();
QString field = query.value(8).toString();
Student* StudentTemp = new Student(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, type, field.toStdString(), groupcode);
return StudentTemp;
}
}
bool DbManager::addStudent(int username, const QString& password, const QString& firstname, const QString& lastname, const int& departmentcode, const int& groupcode, const int& type, const QString& field)
{
bool success = false;
QSqlQuery query(m_db);
query.prepare("INSERT INTO students (username, password, firstname, lastname, departmentcode, groupcode, type, field) VALUES (:username,:password,:firstname,:lastname,:departmentcode,:groupcode,:type,:field)");
query.bindValue(":username", username);
query.bindValue(":password", QString(QCryptographicHash::hash((password.toUtf8()), QCryptographicHash::Md5).toHex()));
query.bindValue(":firstname", firstname);
query.bindValue(":lastname", lastname);
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":type", type);
query.bindValue(":field", field);
if (query.exec())
{
success = true;
}
else
{
qDebug() << "addProfessor error: "
<< query.lastError();
}
return success;
}
bool DbManager::StudentExist(int username)
{
QSqlQuery query(m_db);
query.prepare("SELECT username FROM students WHERE username = (:username)");
query.bindValue(":username", username);
if (query.exec())
{
if (query.next())
{
return true;
}
}
return false;
}
std::vector<Student*> DbManager::allStudents(void)
{
std::vector<Student*> students;
QSqlQuery query(m_db);
query.prepare("SELECT username, password, firstname,lastname, departmentcode, groupcode, type, field FROM students");
while (query.next())
{
int username = query.value(1).toInt();
QString password = query.value(2).toString();
QString firstname = query.value(3).toString();
QString lastname = query.value(4).toString();
int departmentcode = query.value(5).toInt();
int groupcode = query.value(6).toInt();
int type = query.value(7).toInt();
QString field = query.value(8).toString();
Student* stu = new Student(username, password.toStdString(), firstname.toStdString(), lastname.toStdString(), departmentcode, type, field.toStdString(), groupcode);
students.push_back(stu);
}
return students;
}
bool DbManager::addCourse(const int& departmentcode, const int& groupcode,const int& coursecode, const int& credit, const QString& name, const int& type)
{
bool success = false;
QSqlQuery query(m_db);
query.prepare("INSERT INTO courses (departmentcode, groupcode, coursecode, credit, name, type) VALUES (:departmentcode,:groupcode,:coursecode,:credit,:name,:type)");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":coursecode", coursecode);
query.bindValue(":credit", credit);
query.bindValue(":name", name);
query.bindValue(":type", type);
if (query.exec())
{
success = true;
}
else
{
qDebug() << "addCourse error: "
<< query.lastError();
}
return success;
}
bool DbManager::courseExistByCode(int departmentcode,int groupcode ,int coursecode){
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode AND coursecode = :coursecode");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":coursecode", coursecode);
if (query.exec())
{
if (query.next())
{
return true;
}
}
return false;
}
bool DbManager::deleteCourseByCode(int departmentcode,int groupcode ,int coursecode){
if (courseExistByCode(departmentcode ,groupcode ,coursecode))
{
QSqlQuery query(m_db);
query.prepare("DELETE FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode AND coursecode = :coursecode");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":coursecode", coursecode);
bool success = query.exec();
if (!success)
{
qDebug() << "removeCourse error: "
<< query.lastError();
return false;
}
return true;
}
}
Course* DbManager::getCourseByCode(int departmentcode,int groupcode ,int coursecode){
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode AND coursecode = :coursecode");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
query.bindValue(":coursecode", coursecode);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int departmentcode = query.value(1).toInt();
int groupcode = query.value(2).toInt();
int coursecode = query.value(3).toInt();
int credit = query.value(4).toInt();
QString name = query.value(5).toString();
int type = query.value(6).toInt();
Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type);
return CourseTemp;
}
}
std::vector<Course*> DbManager::allCourse(void){
std::vector<Course*> courses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses");
while (query.next())
{
int departmentcode = query.value(1).toInt();
int groupcode = query.value(2).toInt();
int coursecode = query.value(3).toInt();
int credit = query.value(4).toInt();
QString name = query.value(5).toString();
int type = query.value(6).toInt();
Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type);
courses.push_back(CourseTemp);
}
return courses;
}
std::vector<Course*> DbManager::getCourseByDepartment(int departmentcode){
std::vector<Course*> courses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode");
query.bindValue(":departmentcode", departmentcode);
while (query.next())
{
int departmentcode = query.value(1).toInt();
int groupcode = query.value(2).toInt();
int coursecode = query.value(3).toInt();
int credit = query.value(4).toInt();
QString name = query.value(5).toString();
int type = query.value(6).toInt();
Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type);
courses.push_back(CourseTemp);
}
return courses;
}
std::vector<Course*> DbManager::getCourseByGroup(int departmentcode , int groupcode){
std::vector<Course*> courses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM courses WHERE departmentcode = :departmentcode AND groupcode = :groupcode ");
query.bindValue(":departmentcode", departmentcode);
query.bindValue(":groupcode", groupcode);
while (query.next())
{
int departmentcode = query.value(1).toInt();
int groupcode = query.value(2).toInt();
int coursecode = query.value(3).toInt();
int credit = query.value(4).toInt();
QString name = query.value(5).toString();
int type = query.value(6).toInt();
Course* CourseTemp = new Course(departmentcode, groupcode, coursecode, credit, name.toStdString(), type);
courses.push_back(CourseTemp);
}
return courses;
}
bool DbManager::addPresentedCourse(const int& course_id, const int& course_professor_id,const int& capacity, const int& enrolled_number, const int& waiting_number, const int& group_number, const int& term_number, std::vector<Course*> corequisit, std::vector<Course*> prerequisit)
{
QString prerequisit_string;
for(int i = 0 ; i < prerequisit.size() ; i++)
{
prerequisit_string += prerequisit[i]->getCourseID() + ";";
}
QString corequisit_string;
for(int i = 0 ; i < corequisit.size() ; i++)
{
corequisit_string += corequisit[i]->getCourseID() + ";";
}
bool success = false;
QSqlQuery query(m_db);
query.prepare("INSERT INTO presented_courses (course_id, course_professor_id, capacity, enrolled_number, waiting_number, group_number , term_number , corequisit , preriqisit) VALUES (:course_id,:course_professor_id,:capacity,:enrolled_number,:waiting_number,:group_number ,:term_number ,:corequisit ,:preriqisit)");
query.bindValue(":course_id", course_id);
query.bindValue(":course_professor_id", course_professor_id);
query.bindValue(":capacity", capacity);
query.bindValue(":enrolled_number", enrolled_number);
query.bindValue(":waiting_number", group_number);
query.bindValue(":term_number", term_number);
query.bindValue(":corequisit", corequisit_string.toUtf8());
query.bindValue(":prerequisit", prerequisit_string.toUtf8());
if (query.exec())
{
success = true;
}
else
{
qDebug() << "addPresentedCourse error: "
<< query.lastError();
}
return success;
}
bool DbManager::deletePresentedCourseByCode(const int& course_id ,const int& group_number,const int& term_number)
{
if (presentedCourseExistbyCode(course_id ,group_number ,term_number))
{
QSqlQuery query(m_db);
query.prepare("DELETE FROM presented_courses WHERE course_id = :course_id AND group_number = :group_number AND term_number = :term_number");
query.bindValue(":course_id", course_id);
query.bindValue(":group_number", group_number);
query.bindValue(":term_number", term_number);
bool success = query.exec();
if (!success)
{
qDebug() << "removePresentedCourse error: "
<< query.lastError();
return false;
}
return true;
}
}
bool DbManager::presentedCourseExistbyCode(const int& course_id ,const int& group_number,const int& term_number)
{
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses WHERE course_id = :course_id AND group_number = :group_number AND term_number = :term_number");
query.bindValue(":course_id", course_id);
query.bindValue(":group_number", group_number);
query.bindValue(":term_number", term_number);
if (query.exec())
{
if (query.next())
{
return true;
}
}
return false;
}
PresentedCourse* DbManager::getPresentedCourseByCode(const int& course_id ,const int& group_number ,const int& term_number)
{
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses WHERE course_id = :course_id AND group_number = :group_number AND term_number = :term_number");
query.bindValue(":course_id", course_id);
query.bindValue(":group_number", group_number);
query.bindValue(":term_number", term_number);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int course_id = query.value(1).toInt();
int course_professor_id = query.value(2).toInt();
int capacity = query.value(3).toInt();
int enrolled_number = query.value(4).toInt();
int waiting_number = query.value(4).toInt();
int group_number = query.value(4).toInt();
int term_number = query.value(6).toInt();
int length = QString(course_id).length();
Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
Professor* professor_temp = getProfessor(course_professor_id);
PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity);
PresentedCourseTemp->setEnrolledNumber(enrolled_number);
PresentedCourseTemp->setWaitingNumber(waiting_number);
QStringList corequisit_list = query.value(5).toString().split(';');
QStringList prerequisit_list = query.value(5).toString().split(';');
for(int i =0 ; i < corequisit_list.count();i++)
{
int length = corequisit_list.at(i).length();
Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addCorequisite(coCoursTemp);
}
for(int i =0 ; i < prerequisit_list.count();i++)
{
int length = prerequisit_list.at(i).length();
Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addPrerequisite(preCoursTemp);
}
return PresentedCourseTemp;
}
}
std::vector<PresentedCourse*> DbManager::allPresentedCourse(void){
std::vector<PresentedCourse*> presentedcourses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses");
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int course_id = query.value(1).toInt();
int course_professor_id = query.value(2).toInt();
int capacity = query.value(3).toInt();
int enrolled_number = query.value(4).toInt();
int waiting_number = query.value(4).toInt();
int group_number = query.value(4).toInt();
int term_number = query.value(6).toInt();
int length = QString(course_id).length();
Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
Professor* professor_temp = getProfessor(course_professor_id);
PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity);
PresentedCourseTemp->setEnrolledNumber(enrolled_number);
PresentedCourseTemp->setWaitingNumber(waiting_number);
presentedcourses.push_back(PresentedCourseTemp);
QStringList corequisit_list = query.value(5).toString().split(';');
QStringList prerequisit_list = query.value(5).toString().split(';');
for(int i =0 ; i < corequisit_list.count();i++)
{
int length = corequisit_list.at(i).length();
Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addCorequisite(coCoursTemp);
}
for(int i =0 ; i < prerequisit_list.count();i++)
{
int length = prerequisit_list.at(i).length();
Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addPrerequisite(preCoursTemp);
}
}
return presentedcourses;
}
std::vector<PresentedCourse*> DbManager::getPresentedCourseByCourseId(const int& _course_id ,const int& _term_number){
std::vector<PresentedCourse*> presentedcourses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses WHERE course_id = :course_id AND term_number = :term_number");
query.bindValue(":course_id", _course_id);
query.bindValue(":term_number", _term_number);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int course_id = query.value(1).toInt();
int course_professor_id = query.value(2).toInt();
int capacity = query.value(3).toInt();
int enrolled_number = query.value(4).toInt();
int waiting_number = query.value(4).toInt();
int group_number = query.value(4).toInt();
int term_number = query.value(6).toInt();
int length = QString(course_id).length();
Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
Professor* professor_temp = getProfessor(course_professor_id);
PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity);
PresentedCourseTemp->setEnrolledNumber(enrolled_number);
PresentedCourseTemp->setWaitingNumber(waiting_number);
presentedcourses.push_back(PresentedCourseTemp);
QStringList corequisit_list = query.value(5).toString().split(';');
QStringList prerequisit_list = query.value(5).toString().split(';');
for(int i =0 ; i < corequisit_list.count();i++)
{
int length = corequisit_list.at(i).length();
Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addCorequisite(coCoursTemp);
}
for(int i =0 ; i < prerequisit_list.count();i++)
{
int length = prerequisit_list.at(i).length();
Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addPrerequisite(preCoursTemp);
}
}
return presentedcourses;
}
std::vector<PresentedCourse*> DbManager::getPresentedCourseByCourseProfessorId(const int& course_professor_id ,const int& term_number){
std::vector<PresentedCourse*> presentedcourses;
QSqlQuery query(m_db);
query.prepare("SELECT * FROM presented_courses WHERE course_professor_id = :course_professor_id AND term_number = :term_number");
query.bindValue(":course_professor_id", course_professor_id);
query.bindValue(":term_number", term_number);
if (!query.exec())
{
qWarning() << __FUNCTION__ << ":" << __LINE__ << "Failed to fetch course";
qWarning() << __FUNCTION__ << ":" << __LINE__ << m_db.databaseName();
}
if (query.next())
{
int course_id = query.value(1).toInt();
int course_professor_id = query.value(2).toInt();
int capacity = query.value(3).toInt();
int enrolled_number = query.value(4).toInt();
int waiting_number = query.value(4).toInt();
int group_number = query.value(4).toInt();
int term_number = query.value(6).toInt();
int length = QString(course_id).length();
Course* corurse_temp = getCourseByCode( course_id / (int) pow(10 , length - 2) , course_id % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),course_id % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
Professor* professor_temp = getProfessor(course_professor_id);
PresentedCourse* PresentedCourseTemp = new PresentedCourse(corurse_temp ,term_number ,group_number , professor_temp ,capacity);
PresentedCourseTemp->setEnrolledNumber(enrolled_number);
PresentedCourseTemp->setWaitingNumber(waiting_number);
presentedcourses.push_back(PresentedCourseTemp);
QStringList corequisit_list = query.value(5).toString().split(';');
QStringList prerequisit_list = query.value(5).toString().split(';');
for(int i =0 ; i < corequisit_list.count();i++)
{
int length = corequisit_list.at(i).length();
Course* coCoursTemp = getCourseByCode( corequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),corequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addCorequisite(coCoursTemp);
}
for(int i =0 ; i < prerequisit_list.count();i++)
{
int length = prerequisit_list.at(i).length();
Course* preCoursTemp = getCourseByCode( prerequisit_list.at(i).toInt() / (int) pow(10 , length - 2) , prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) / (int) pow(10 , length - 2),prerequisit_list.at(i).toInt() % (int) pow(10 , length - 2) % (int) pow(10 , length - 2) );
PresentedCourseTemp->addPrerequisite(preCoursTemp);
}
}
return presentedcourses;
}
std::vector<PresentedCourse*> DbManager::getPresentedCourseByDepartment(const int& departmentcode ,const int& term_number){
std::vector<Course*> departmentcourses = getCourseByDepartment(departmentcode);
std::vector<PresentedCourse*> result ;
for(int i = 0 ; i < departmentcourses.size(); i++ ){
int course_id = departmentcourses[i]->getCourseID();
std::vector<PresentedCourse*> departmentPresentedCourse = getPresentedCourseByCourseId(course_id ,term_number);
for(int j = 0 ; j < departmentPresentedCourse.size(); j++ ){
result.push_back(departmentPresentedCourse[j]);
}
}
return result;
}
| 31,446 | 10,031 |
#include "statisticsmenu.h"
#include "game.h"
StatisticsMenu::StatisticsMenu(Game *game, QGridLayout *grid) :
Menu(game, grid) {
grid->addWidget(&statisticsLabel, 0, 1);
statisticsLabel.setVisible(false);
statisticsLabel.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
grid->addWidget(&statisticsText, 1, 0, 1, 3);
statisticsText.setReadOnly(true);
statisticsText.setVisible(false);
statisticsText.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
statisticsText.setTextInteractionFlags(Qt::NoTextInteraction);
statisticsText.setFrameStyle(QFrame::NoFrame);
grid->addWidget(&itemsButton, 2, 0);
itemsButton.setVisible(false);
itemsButton.setEnabled(false);
connect(&itemsButton, SIGNAL(released()), this, SLOT(itemsFunction()));
grid->addWidget(&coinsButton, 2, 1);
coinsButton.setVisible(false);
coinsButton.setEnabled(false);
connect(&coinsButton, SIGNAL(released()), this, SLOT(coinsFunction()));
grid->addWidget(&backButton, 3, 1);
backButton.setVisible(false);
backButton.setEnabled(false);
connect(&backButton, SIGNAL(released()), this, SLOT(backFunction()));
}
void StatisticsMenu::updateStatistics() {
qDebug() << "Statistics have been updated";
QString statText;
auto stats = game->users[game->activeUser].getStatistics(game);
auto it = stats.cbegin();
statText += "<table border=\"1\" width=\"100%\">";
while (it != stats.cend()) {
statText += QString(
"<tr>"
"<td width=\"50%\">%1</td>"
"<td width=\"50%\">%2</td>"
"</tr>"
).arg(
it->first,
it->second
);
++it;
}
statText += "</table>";
statisticsText.setText(statText);
}
void StatisticsMenu::display() {
this->pre_display();
timerUpdater = connect(&timer, SIGNAL(timeout()), this, SLOT(updateStatistics()));
timer.start(Config::STATISTICS_UPDATE_PERIOD);
updateStatistics();
statisticsLabel.setText(game->str.statistics);
statisticsLabel.setVisible(true);
statisticsText.setVisible(true);
itemsButton.setText(game->str.items);
itemsButton.setVisible(true);
itemsButton.setEnabled(true);
coinsButton.setText(game->str.coins);
coinsButton.setVisible(true);
coinsButton.setEnabled(true);
backButton.setText(game->str.back);
backButton.setVisible(true);
backButton.setEnabled(true);
displayed = true;
}
void StatisticsMenu::backFunction() {
this->hide();
game->gameMenu.display();
}
void StatisticsMenu::itemsFunction() {
this->hide();
game->itemStatisticsMenu.display();
}
void StatisticsMenu::coinsFunction() {
this->hide();
game->coinStatisticsMenu.display();
}
void StatisticsMenu::hide() {
this->pre_hide();
timer.stop();
disconnect(timerUpdater);
statisticsLabel.setVisible(false);
statisticsText.setVisible(false);
itemsButton.setVisible(false);
itemsButton.setEnabled(false);
coinsButton.setVisible(false);
coinsButton.setEnabled(false);
backButton.setVisible(false);
backButton.setEnabled(false);
displayed = false;
}
StatisticsMenu::~StatisticsMenu() {
}
| 3,235 | 1,023 |
#pragma once
#include "entityx/Entity.h"
namespace CaptainAsteroidCPP
{
namespace Comp
{
enum class Id
{
Unknown,
Asteroid,
SpaceShip,
LaserShot
};
struct Identity : public entityx::Component<Identity>
{
Identity(Id _id = Id::Unknown) : id(_id){};
Id id;
};
}// namespace Comp
}// namespace CaptainAsteroidCPP | 349 | 127 |
// Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Threading
// Name: LockCookie
// C++ Typed Name: mscorlib::System::Threading::LockCookie
#include <gtest/gtest.h>
#include <mscorlib/System/Threading/mscorlib_System_Threading_LockCookie.h>
#include <mscorlib/System/mscorlib_System_String.h>
#include <mscorlib/System/mscorlib_System_Type.h>
namespace mscorlib
{
namespace System
{
namespace Threading
{
//Public Methods Tests
// Method GetHashCode
// Signature:
TEST(mscorlib_System_Threading_LockCookie_Fixture,GetHashCode_Test)
{
}
// Method Equals
// Signature: mscorlib::System::Threading::LockCookie obj
TEST(mscorlib_System_Threading_LockCookie_Fixture,Equals_1_Test)
{
}
// Method Equals
// Signature: mscorlib::System::Object obj
TEST(mscorlib_System_Threading_LockCookie_Fixture,Equals_2_Test)
{
}
}
}
}
| 1,002 | 444 |
/*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "JSTestNamedConstructor.h"
#include "ExceptionCode.h"
#include "JSDOMBinding.h"
#include "TestNamedConstructor.h"
#include <runtime/Error.h>
#include <wtf/GetPtr.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSTestNamedConstructor);
ASSERT_HAS_TRIVIAL_DESTRUCTOR(JSTestNamedConstructor);
/* Hash table for constructor */
static const HashTableValue JSTestNamedConstructorTableValues[] =
{
{ "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsTestNamedConstructorConstructor), (intptr_t)0, NoIntrinsic },
{ 0, 0, 0, 0, NoIntrinsic }
};
static const HashTable JSTestNamedConstructorTable = { 2, 1, JSTestNamedConstructorTableValues, 0 };
/* Hash table for constructor */
static const HashTableValue JSTestNamedConstructorConstructorTableValues[] =
{
{ 0, 0, 0, 0, NoIntrinsic }
};
static const HashTable JSTestNamedConstructorConstructorTable = { 1, 0, JSTestNamedConstructorConstructorTableValues, 0 };
ASSERT_HAS_TRIVIAL_DESTRUCTOR(JSTestNamedConstructorConstructor);
const ClassInfo JSTestNamedConstructorConstructor::s_info = { "TestNamedConstructorConstructor", &Base::s_info, &JSTestNamedConstructorConstructorTable, 0, CREATE_METHOD_TABLE(JSTestNamedConstructorConstructor) };
JSTestNamedConstructorConstructor::JSTestNamedConstructorConstructor(Structure* structure, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(structure, globalObject)
{
}
void JSTestNamedConstructorConstructor::finishCreation(ExecState* exec, JSDOMGlobalObject* globalObject)
{
Base::finishCreation(exec->globalData());
ASSERT(inherits(&s_info));
putDirect(exec->globalData(), exec->propertyNames().prototype, JSTestNamedConstructorPrototype::self(exec, globalObject), DontDelete | ReadOnly);
}
bool JSTestNamedConstructorConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
return getStaticValueSlot<JSTestNamedConstructorConstructor, JSDOMWrapper>(exec, &JSTestNamedConstructorConstructorTable, static_cast<JSTestNamedConstructorConstructor*>(cell), propertyName, slot);
}
bool JSTestNamedConstructorConstructor::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
return getStaticValueDescriptor<JSTestNamedConstructorConstructor, JSDOMWrapper>(exec, &JSTestNamedConstructorConstructorTable, static_cast<JSTestNamedConstructorConstructor*>(object), propertyName, descriptor);
}
const ClassInfo JSTestNamedConstructorNamedConstructor::s_info = { "AudioConstructor", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(JSTestNamedConstructorNamedConstructor) };
JSTestNamedConstructorNamedConstructor::JSTestNamedConstructorNamedConstructor(Structure* structure, JSDOMGlobalObject* globalObject)
: DOMConstructorWithDocument(structure, globalObject)
{
}
void JSTestNamedConstructorNamedConstructor::finishCreation(ExecState* exec, JSDOMGlobalObject* globalObject)
{
Base::finishCreation(globalObject);
ASSERT(inherits(&s_info));
putDirect(exec->globalData(), exec->propertyNames().prototype, JSTestNamedConstructorPrototype::self(exec, globalObject), None);
}
EncodedJSValue JSC_HOST_CALL JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor(ExecState* exec)
{
JSTestNamedConstructorNamedConstructor* jsConstructor = static_cast<JSTestNamedConstructorNamedConstructor*>(exec->callee());
if (exec->argumentCount() < 1)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
ExceptionCode ec = 0;
const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, MissingIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, MissingIsUndefined).toString(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, MissingIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, MissingIsUndefined).toString(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& str3(ustringToString(MAYBE_MISSING_PARAMETER(exec, 2, MissingIsEmpty).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 2, MissingIsEmpty).toString(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
RefPtr<TestNamedConstructor> object = TestNamedConstructor::createForJSConstructor(jsConstructor->document(), str1, str2, str3, ec);
if (ec) {
setDOMException(exec, ec);
return JSValue::encode(JSValue());
}
return JSValue::encode(asObject(toJS(exec, jsConstructor->globalObject(), object.get())));
}
ConstructType JSTestNamedConstructorNamedConstructor::getConstructData(JSCell*, ConstructData& constructData)
{
constructData.native.function = constructJSTestNamedConstructor;
return ConstructTypeHost;
}
/* Hash table for prototype */
static const HashTableValue JSTestNamedConstructorPrototypeTableValues[] =
{
{ 0, 0, 0, 0, NoIntrinsic }
};
static const HashTable JSTestNamedConstructorPrototypeTable = { 1, 0, JSTestNamedConstructorPrototypeTableValues, 0 };
const ClassInfo JSTestNamedConstructorPrototype::s_info = { "TestNamedConstructorPrototype", &Base::s_info, &JSTestNamedConstructorPrototypeTable, 0, CREATE_METHOD_TABLE(JSTestNamedConstructorPrototype) };
JSObject* JSTestNamedConstructorPrototype::self(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMPrototype<JSTestNamedConstructor>(exec, globalObject);
}
const ClassInfo JSTestNamedConstructor::s_info = { "TestNamedConstructor", &Base::s_info, &JSTestNamedConstructorTable, 0 , CREATE_METHOD_TABLE(JSTestNamedConstructor) };
JSTestNamedConstructor::JSTestNamedConstructor(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<TestNamedConstructor> impl)
: JSDOMWrapper(structure, globalObject)
, m_impl(impl.leakRef())
{
}
void JSTestNamedConstructor::finishCreation(JSGlobalData& globalData)
{
Base::finishCreation(globalData);
ASSERT(inherits(&s_info));
}
JSObject* JSTestNamedConstructor::createPrototype(ExecState* exec, JSGlobalObject* globalObject)
{
return JSTestNamedConstructorPrototype::create(exec->globalData(), globalObject, JSTestNamedConstructorPrototype::createStructure(globalObject->globalData(), globalObject, globalObject->objectPrototype()));
}
bool JSTestNamedConstructor::getOwnPropertySlot(JSCell* cell, ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
{
JSTestNamedConstructor* thisObject = jsCast<JSTestNamedConstructor*>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);
return getStaticValueSlot<JSTestNamedConstructor, Base>(exec, &JSTestNamedConstructorTable, thisObject, propertyName, slot);
}
bool JSTestNamedConstructor::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
{
JSTestNamedConstructor* thisObject = jsCast<JSTestNamedConstructor*>(object);
ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);
return getStaticValueDescriptor<JSTestNamedConstructor, Base>(exec, &JSTestNamedConstructorTable, thisObject, propertyName, descriptor);
}
JSValue jsTestNamedConstructorConstructor(ExecState* exec, JSValue slotBase, const Identifier&)
{
JSTestNamedConstructor* domObject = static_cast<JSTestNamedConstructor*>(asObject(slotBase));
return JSTestNamedConstructor::getConstructor(exec, domObject->globalObject());
}
JSValue JSTestNamedConstructor::getConstructor(ExecState* exec, JSGlobalObject* globalObject)
{
return getDOMConstructor<JSTestNamedConstructorConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));
}
static inline bool isObservable(JSTestNamedConstructor* jsTestNamedConstructor)
{
if (jsTestNamedConstructor->hasCustomProperties())
return true;
return false;
}
bool JSTestNamedConstructorOwner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor)
{
JSTestNamedConstructor* jsTestNamedConstructor = static_cast<JSTestNamedConstructor*>(handle.get().asCell());
if (jsTestNamedConstructor->impl()->hasPendingActivity())
return true;
if (!isObservable(jsTestNamedConstructor))
return false;
UNUSED_PARAM(visitor);
return false;
}
void JSTestNamedConstructorOwner::finalize(JSC::Handle<JSC::Unknown> handle, void* context)
{
JSTestNamedConstructor* jsTestNamedConstructor = static_cast<JSTestNamedConstructor*>(handle.get().asCell());
DOMWrapperWorld* world = static_cast<DOMWrapperWorld*>(context);
uncacheWrapper(world, jsTestNamedConstructor->impl(), jsTestNamedConstructor);
jsTestNamedConstructor->releaseImpl();
}
JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, TestNamedConstructor* impl)
{
return wrap<JSTestNamedConstructor>(exec, globalObject, impl);
}
TestNamedConstructor* toTestNamedConstructor(JSC::JSValue value)
{
return value.inherits(&JSTestNamedConstructor::s_info) ? static_cast<JSTestNamedConstructor*>(asObject(value))->impl() : 0;
}
}
| 10,096 | 2,980 |
#ifndef GEOINDEX_AABB_INDEX
#define GEOINDEX_AABB_INDEX
#include <vector>
#include <algorithm> // Or #include <parallel/algorithm>.
#include <iterator>
#include "Common.hpp"
namespace geoIndex {
/** This index uses the "Axis Aligned Bounding Box" (AABB) trick to quickly find points close to the
* given reference. Imagine a box, with sides parallel to the axes. That is the AABB.
* Its position makes it very easy to discover points inside: just ensure that each coordinate
* it between the min/max coordinates inside the box. We only have to compute the "top" and "bottom" corners.
* To go even faster, we keep the point coordinates sorted, so in a single pass (on each x, y, z) we can find
* all the indexes in the box limit.
*
* At each query it builds the AABB centered on the reference point and work on what is inside.
*
* The user must call complete() between modifications and lookups. But this is a costly operation.
*
*/
template <typename POINT>
class AabbIndex {
public:
/** If you know how many points you are going to use, tell it to this constructor to
* reserve memory. */
AabbIndex(const size_t expectedCollectionSize = 0) {
indexX.reserve(expectedCollectionSize);
indexY.reserve(expectedCollectionSize);
indexZ.reserve(expectedCollectionSize);
#ifdef GEO_INDEX_SAFETY_CHECKS
// There is nothing in the index, so it is sorted (you can't misplace... nothing). You can do lookups.
readyForLookups = true;
#endif
}
/** Adds a point to the index. Remember its name too. */
void index(const POINT& p, const typename PointTraits<POINT>::index index){
#ifdef GEO_INDEX_SAFETY_CHECKS
// Adding points probably breaks the order.
readyForLookups = false;
if (std::find_if(begin(indexX),
end(indexX),
[index](const IndexAndCoordinate<POINT>& indexEntry) {
return indexEntry.pointIndex == index; }
) != end(indexX))
throw std::runtime_error("Point indexed twice");
#endif
indexX.push_back({index, p.x});
indexY.push_back({index, p.y});
indexZ.push_back({index, p.z});
}
/** "Close" the index and allows lookups.
* Basically, sort its entries. It is best done "once and forever" as testing proves it can be a significant bottleneck.
* If the user forgets to call it he will get garbage results.
*/
void completed() {
std::sort(std::begin(indexX), std::end(indexX), SortByGeometry<POINT>);
std::sort(std::begin(indexY), std::end(indexY), SortByGeometry<POINT>);
std::sort(std::begin(indexZ), std::end(indexZ), SortByGeometry<POINT>);
/* The latest STL (C++17) has a parallel sort that could be useful...
* In the meanwhile, there is this nice thing from GNU.
__gnu_parallel::sort(indexX.begin(), indexX.end());
__gnu_parallel::sort(indexY.begin(), indexY.end());
__gnu_parallel::sort(indexZ.begin(), indexZ.end());
...but depends on openMP (libgomp) - for the moment I don't do it, to keep deps simple.
The speedup we can get here should be tested.
*/
#ifdef GEO_INDEX_SAFETY_CHECKS
readyForLookups = true;
#endif
}
/** Finds the points that are within distance d from p. Cleans the output vector before filling it.
* Returns the points sorted in distance order from p (to simplify computing the k-nearest-neighbor).
* The returned structure also gives the squared distance. The client can do a sqrt and use it for its computations.
*
* Uses the AABB trick described on top of the class to speed up the search for close points.
*
* Returns only points strictly within the AABB.
*/
void pointsWithinDistance(const POINT& p,
const typename PointTraits<POINT>::coordinate d,
std::vector<IndexAndSquaredDistance<POINT> >& output) const
{
#ifdef GEO_INDEX_SAFETY_CHECKS
CheckMeaningfulDistance(d);
if (! readyForLookups)
throw std::runtime_error("Index not ready. Did you call completed() after the last call to index(...)?");
#endif
std::vector<IndexAndCoordinate<POINT> > candidatesX;
std::vector<IndexAndCoordinate<POINT> > candidatesY;
std::vector<IndexAndCoordinate<POINT> > candidatesZ;
candidatesOnDimension(indexX, d, p.x, candidatesX);
candidatesOnDimension(indexY, d, p.y, candidatesY);
candidatesOnDimension(indexZ, d, p.z, candidatesZ);
std::vector<IndexAndCoordinate<POINT> > insideAabbXY;
std::set_intersection(std::begin(candidatesX),
std::end(candidatesX),
std::begin(candidatesY),
std::end(candidatesY),
std::back_inserter(insideAabbXY),
SortByPointIndex<POINT>
);
std::vector<IndexAndCoordinate<POINT> > insideAabb;
std::set_intersection(std::begin(insideAabbXY),
std::end(insideAabbXY),
std::begin(candidatesZ),
std::end(candidatesZ),
std::back_inserter(insideAabb),
SortByPointIndex<POINT>
);
const typename PointTraits<POINT>::coordinate referenceSquareDistance = d * d;
#ifdef GEO_INDEX_SAFETY_CHECKS
CheckOverflow(referenceSquareDistance);
#endif
output.clear();
for (const auto& candidate : insideAabb) {
const auto candidateIndex = candidate.pointIndex;
const typename PointTraits<POINT>::coordinate candidateX = findCoordinateOf(candidateIndex, candidatesX);
const typename PointTraits<POINT>::coordinate candidateY = findCoordinateOf(candidateIndex, candidatesY);
const typename PointTraits<POINT>::coordinate candidateZ = findCoordinateOf(candidateIndex, candidatesZ);
const auto candidateSquareDistance = SquaredDistance(p, POINT{candidateX, candidateY, candidateZ});
if (candidateSquareDistance < referenceSquareDistance)
output.push_back({candidateIndex, candidateSquareDistance});
}
// Don't forget we have to give the closests point first.
std::sort(std::begin(output), std::end(output), SortByGeometry<POINT>);
}
private:
std::vector<IndexAndCoordinate<POINT> > indexX;
std::vector<IndexAndCoordinate<POINT> > indexY;
std::vector<IndexAndCoordinate<POINT> > indexZ;
#ifdef GEO_INDEX_SAFETY_CHECKS
bool readyForLookups;
#endif
static bool CompareEntryWithCoordinate(const IndexAndCoordinate<POINT>& indexEntry,
const typename PointTraits<POINT>::coordinate searchedValue) {
return indexEntry.geometricValue < searchedValue;
}
static bool CompareEntryWithIndex(const IndexAndCoordinate<POINT>& indexEntry,
const typename PointTraits<POINT>::index searchedValue) {
return indexEntry.pointIndex < searchedValue;
}
/** Scan the given index and returns the indices of the "interesting" points.*/
void candidatesOnDimension(const std::vector<IndexAndCoordinate<POINT> >& indexForDimension,
const typename PointTraits<POINT>::coordinate searchDistance,
const typename PointTraits<POINT>::coordinate referenceCoordnate,
std::vector<IndexAndCoordinate<POINT> >& candidates) const
{
const typename PointTraits<POINT>::coordinate minAcceptedCoordinate = referenceCoordnate - searchDistance;
const typename PointTraits<POINT>::coordinate maxAcceptedCoordinate = referenceCoordnate + searchDistance;
const auto beginCandidates = std::lower_bound(std::begin(indexForDimension),
std::end(indexForDimension),
minAcceptedCoordinate,
CompareEntryWithCoordinate);
const auto endCandidates = std::lower_bound(beginCandidates, // the bigger values must be after, skip some elements.
std::end(indexForDimension),
maxAcceptedCoordinate,
CompareEntryWithCoordinate);
candidates.clear();
candidates.reserve(std::distance(beginCandidates, endCandidates));
for (auto i = beginCandidates; i != endCandidates; ++i)
candidates.push_back(*i);
// TODO: would it be faster with sets? THIS IS A MAJOR BOTTLENECK... in callgrind only?
//std::sort(std::begin(candidates), std::end(candidates), SortByPointIndex<POINT>);
std::sort(std::begin(candidates), std::end(candidates), [](const IndexAndGeometry<POINT>& lhs,
const IndexAndGeometry<POINT>& rhs)
{return lhs.pointIndex < rhs.pointIndex;});
}
/** This index does not store the full collection of points (but maybe it should, or should have a reference to it,
* to avoid this kind of issues - or maybe we should move the distance test outside the indexes).
* Assume that groupOfCandidates is sorted by point index and point indices do not repeat. */
typename PointTraits<POINT>::coordinate findCoordinateOf(const typename PointTraits<POINT>::index pointIndex,
const std::vector<IndexAndCoordinate<POINT> >& groupOfCandidates) const
{
const auto indexEntry = std::lower_bound(std::begin(groupOfCandidates),
std::end(groupOfCandidates),
pointIndex,
CompareEntryWithIndex);
return indexEntry->geometricValue;
}
};
}
#endif
| 10,710 | 2,889 |
#include <iostream>
#include <graphics.h>
using namespace std;
int main()
{
initwindow(800, 800);
double startPointX = 100;
double startPointY = 600;
double windowSizeX = 600;
double windowSizeY = 500;
double columnWidth = 70;
double distanceBetweenColumns = 70;
double D = 60;
double bi[] = {5, 26};
double ai[] = {15, 20};
double mi[] = {10, 12};
double amin = ai[0];
double amax = ai[0];
double bmin = bi[0];
double bmax = bi[0];
double sum[4];
double maxSum;
for(int i = 0; i < 2; i++)
{
sum[i] = ai[i] + bi[i] + mi[i];
}
maxSum = sum[0];
for(int i = 1; i < 3; i++)
{
if (sum[i] > maxSum)
{
maxSum = sum[i];
}
}
float scaleFactor = maxSum / windowSizeY;
// koordinatna sistema
line(startPointX, startPointY, startPointX + windowSizeX, startPointY);
line(startPointX, startPointY, startPointX, startPointY - windowSizeY);
// chertite na deleniyata
// double value;
//
// for(p = 1; p < windowSizeY / D; p++)
// {
// line(startPointX, startPointY - p * D, startPointX - 3, startPointY - p * D);
// value = p * D * scaleFactor;
// cout << value << endl;
// }
for(int i = 1; i <= 2; i++)
{
bar(startPointX + i * (columnWidth + distanceBetweenColumns) - columnWidth,
startPointY - ai[i - 1] / scaleFactor,
startPointX + i * (columnWidth + distanceBetweenColumns),
startPointY);
setfillstyle(i, i);
bar(startPointX + i * (columnWidth + distanceBetweenColumns) - columnWidth,
startPointY - (ai[i - 1] + bi[i - 1]) / scaleFactor,
startPointX + i * (columnWidth + distanceBetweenColumns),
startPointY - ai[i - 1] / scaleFactor);
setfillstyle(i + 1, i + 1);
bar(startPointX + i * (columnWidth + distanceBetweenColumns) - columnWidth,
startPointY - (ai[i - 1] + bi[i - 1] + mi[i - 1]) / scaleFactor,
startPointX + i * (columnWidth + distanceBetweenColumns),
startPointY - (ai[i - 1] + bi[i - 1]) / scaleFactor);
setfillstyle(i + 2, i + 2);
}
getch();
return 0;
}
| 2,162 | 882 |
#include "openCV.h"
using namespace cv;
class GUI {
int lowH, lowS, lowV = 90;
int highH = 180;
int highS = 255, highV = 255;
void lowHChange(int pos, void*) {
int lowH = pos;
}
void lowSChange(int pos, void*) {
int lowS = pos;
}
void lowVChange(int pos, void*) {
int lowV = pos;
}
void highHChange(int pos, void*) {
int highH = pos;
}
void highSChange(int pos, void*) {
int highS = pos;
}
void highVChange(int pos, void*) {
int highV = pos;
}
/*cv::namedWindow("HSV Value Selection");
const String HSVwindowName = "HSV Value Selection";
createTrackbar("Low H", HSVwindowName, 0, 180, lowHChange);
createTrackbar("Low S", HSVwindowName, 0, 255, lowSChange);
createTrackbar("Low V", HSVwindowName, 0, 255, lowVChange);
createTrackbar("High H", HSVwindowName, &highH, 180, highHChange);
createTrackbar("High S", HSVwindowName, &highS, 255, highSChange);
createTrackbar("High V", HSVwindowName, &highV, 255, highVChange);
*/
}; | 977 | 426 |
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include "DataStructures/DataBox/PrefixHelpers.hpp"
#include "DataStructures/DataBox/Prefixes.hpp"
#include "IO/Observer/Helpers.hpp"
#include "ParallelAlgorithms/LinearSolver/Gmres/ElementActions.hpp"
#include "ParallelAlgorithms/LinearSolver/Gmres/InitializeElement.hpp"
#include "ParallelAlgorithms/LinearSolver/Gmres/ResidualMonitor.hpp"
#include "ParallelAlgorithms/LinearSolver/Observe.hpp"
#include "ParallelAlgorithms/LinearSolver/Tags.hpp"
#include "Utilities/TMPL.hpp"
/// Items related to the GMRES linear solver
///
/// \see `LinearSolver::gmres::Gmres`
namespace LinearSolver::gmres {
/*!
* \ingroup LinearSolverGroup
* \brief A GMRES solver for nonsymmetric linear systems of equations
* \f$Ax=b\f$.
*
* \details The only operation we need to supply to the algorithm is the
* result of the operation \f$A(p)\f$ (see \ref LinearSolverGroup). Each step of
* the algorithm expects that \f$A(q)\f$ is computed and stored in the DataBox
* as `db::add_tag_prefix<LinearSolver::Tags::OperatorAppliedTo, operand_tag>`.
* To perform a solve, add the `solve` action list to an array parallel
* component. Pass the actions that compute \f$A(q)\f$, as well as any further
* actions you wish to run in each step of the algorithm, as the first template
* parameter to `solve`. If you add the `solve` action list multiple times, use
* the second template parameter to label each solve with a different type.
*
* This linear solver supports preconditioning. Enable preconditioning by
* setting the `Preconditioned` template parameter to `true`. If you do, run a
* preconditioner (e.g. another parallel linear solver) in each step. The
* preconditioner should approximately solve the linear problem \f$A(q)=b\f$
* where \f$q\f$ is the `operand_tag` and \f$b\f$ is the
* `preconditioner_source_tag`. Make sure the tag
* `db::add_tag_prefix<LinearSolver::Tags::OperatorAppliedTo, operand_tag>`
* is updated with the preconditioned result in each step of the algorithm, i.e.
* that it is \f$A(q)\f$ where \f$q\f$ is the preconditioner's approximate
* solution to \f$A(q)=b\f$. The preconditioner always begins at an initial
* guess of zero. It does not need to compute the operator applied to the
* initial guess, since it's zero as well due to the linearity of the operator.
*
* Note that the operand \f$q\f$ for which \f$A(q)\f$ needs to be computed is
* not the field \f$x\f$ we are solving for but
* `db::add_tag_prefix<LinearSolver::Tags::Operand, FieldsTag>`. This field is
* initially set to the residual \f$q_0 = b - A(x_0)\f$ where \f$x_0\f$ is the
* initial value of the `FieldsTag`.
*
* When the algorithm step is performed after the operator action \f$A(q)\f$ has
* been computed and stored in the DataBox, the GMRES algorithm implemented here
* will converge the field \f$x\f$ towards the solution and update the operand
* \f$q\f$ in the process. This requires reductions over all elements that are
* received by a `ResidualMonitor` singleton parallel component, processed, and
* then broadcast back to all elements. Since the reductions are performed to
* find a vector that is orthogonal to those used in previous steps, the number
* of reductions increases linearly with iterations. No restarting mechanism is
* currently implemented. The actions are implemented in the `gmres::detail`
* namespace and constitute the full algorithm in the following order:
* 1. `PerformStep` (on elements): Start an Arnoldi orthogonalization by
* computing the inner product between \f$A(q)\f$ and the first of the
* previously determined set of orthogonal vectors.
* 2. `StoreOrthogonalization` (on `ResidualMonitor`): Keep track of the
* computed inner product in a Hessenberg matrix, then broadcast.
* 3. `OrthogonalizeOperand` (on elements): Proceed with the Arnoldi
* orthogonalization by computing inner products and reducing to
* `StoreOrthogonalization` on the `ResidualMonitor` until the new orthogonal
* vector is constructed. Then compute its magnitude and reduce.
* 4. `StoreOrthogonalization` (on `ResidualMonitor`): Perform a QR
* decomposition of the Hessenberg matrix to produce a residual vector.
* Broadcast to `NormalizeOperandAndUpdateField` along with a termination
* flag if the `Convergence::Tags::Criteria` are met.
* 5. `NormalizeOperandAndUpdateField` (on elements): Set the operand \f$q\f$ as
* the new orthogonal vector and normalize. Use the residual vector and the set
* of orthogonal vectors to determine the solution \f$x\f$.
*
* \par Array sections
* This linear solver supports running over a subset of the elements in the
* array parallel component (see `Parallel::Section`). Set the
* `ArraySectionIdTag` template parameter to restrict the solver to elements in
* that section. Only a single section must be associated with the
* `ArraySectionIdTag`. The default is `void`, which means running over all
* elements in the array. Note that the actions in the `ApplyOperatorActions`
* list passed to `solve` will _not_ be restricted to run only on section
* elements, so all elements in the array may participate in preconditioning
* (see LinearSolver::multigrid::Multigrid).
*
* \see ConjugateGradient for a linear solver that is more efficient when the
* linear operator \f$A\f$ is symmetric.
*/
template <typename Metavariables, typename FieldsTag, typename OptionsGroup,
bool Preconditioned,
typename SourceTag =
db::add_tag_prefix<::Tags::FixedSource, FieldsTag>,
typename ArraySectionIdTag = void>
struct Gmres {
using fields_tag = FieldsTag;
using options_group = OptionsGroup;
using source_tag = SourceTag;
static constexpr bool preconditioned = Preconditioned;
/// Apply the linear operator to this tag in each iteration
using operand_tag = std::conditional_t<
Preconditioned,
db::add_tag_prefix<
LinearSolver::Tags::Preconditioned,
db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>>,
db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>>;
/// Invoke a linear solver on the `operand_tag` sourced by the
/// `preconditioner_source_tag` before applying the operator in each step
using preconditioner_source_tag =
db::add_tag_prefix<LinearSolver::Tags::Operand, fields_tag>;
/*!
* \brief The parallel components used by the GMRES linear solver
*/
using component_list = tmpl::list<
detail::ResidualMonitor<Metavariables, FieldsTag, OptionsGroup>>;
using initialize_element =
detail::InitializeElement<FieldsTag, OptionsGroup, Preconditioned>;
using register_element = tmpl::list<>;
using observed_reduction_data_tags = observers::make_reduction_data_tags<
tmpl::list<observe_detail::reduction_data>>;
template <typename ApplyOperatorActions, typename Label = OptionsGroup>
using solve = tmpl::list<
detail::PrepareSolve<FieldsTag, OptionsGroup, Preconditioned, Label,
SourceTag, ArraySectionIdTag>,
detail::NormalizeInitialOperand<FieldsTag, OptionsGroup, Preconditioned,
Label, ArraySectionIdTag>,
detail::PrepareStep<FieldsTag, OptionsGroup, Preconditioned, Label,
ArraySectionIdTag>,
ApplyOperatorActions,
detail::PerformStep<FieldsTag, OptionsGroup, Preconditioned, Label,
ArraySectionIdTag>,
detail::OrthogonalizeOperand<FieldsTag, OptionsGroup, Preconditioned,
Label, ArraySectionIdTag>,
detail::NormalizeOperandAndUpdateField<
FieldsTag, OptionsGroup, Preconditioned, Label, ArraySectionIdTag>>;
};
} // namespace LinearSolver::gmres
| 7,808 | 2,231 |
// ivectorbin/ivector-mean.cc
// Copyright 2013-2014 Daniel Povey
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
int main(int argc, char *argv[]) {
using namespace kaldi;
typedef kaldi::int32 int32;
try {
const char *usage =
"With 3 or 4 arguments, averages iVectors over all the\n"
"utterances of each speaker using the spk2utt file.\n"
"Input the spk2utt file and a set of iVectors indexed by\n"
"utterance; output is iVectors indexed by speaker. If 4\n"
"arguments are given, extra argument is a table for the number\n"
"of utterances per speaker (can be useful for PLDA). If 2\n"
"arguments are given, computes the mean of all input files and\n"
"writes out the mean vector.\n"
"\n"
"Usage: ivector-mean <spk2utt-rspecifier> <ivector-rspecifier> "
"<ivector-wspecifier> [<num-utt-wspecifier>]\n"
"or: ivector-mean <ivector-rspecifier> <mean-wxfilename>\n"
"e.g.: ivector-mean data/spk2utt exp/ivectors.ark exp/spk_ivectors.ark "
"exp/spk_num_utts.ark\n"
"or: ivector-mean exp/ivectors.ark exp/mean.vec\n"
"See also: ivector-subtract-global-mean\n";
ParseOptions po(usage);
bool binary_write = false;
po.Register("binary", &binary_write,
"If true, write output in binary "
"(only applicable when writing files, not archives/tables.");
po.Read(argc, argv);
if (po.NumArgs() < 2 || po.NumArgs() > 4) {
po.PrintUsage();
exit(1);
}
if (po.NumArgs() == 2) {
// Compute the mean of the input vectors and write it out.
std::string ivector_rspecifier = po.GetArg(1),
mean_wxfilename = po.GetArg(2);
int32 num_done = 0;
SequentialBaseFloatVectorReader ivector_reader(ivector_rspecifier);
Vector<double> sum;
for (; !ivector_reader.Done(); ivector_reader.Next()) {
if (sum.Dim() == 0) sum.Resize(ivector_reader.Value().Dim());
sum.AddVec(1.0, ivector_reader.Value());
num_done++;
}
if (num_done == 0) {
KALDI_ERR << "No iVectors read";
} else {
sum.Scale(1.0 / num_done);
WriteKaldiObject(sum, mean_wxfilename, binary_write);
return 0;
}
} else {
std::string spk2utt_rspecifier = po.GetArg(1),
ivector_rspecifier = po.GetArg(2),
ivector_wspecifier = po.GetArg(3),
num_utts_wspecifier = po.GetOptArg(4);
double spk_sumsq = 0.0;
Vector<double> spk_sum;
int64 num_spk_done = 0, num_spk_err = 0, num_utt_done = 0,
num_utt_err = 0;
RandomAccessBaseFloatVectorReader ivector_reader(ivector_rspecifier);
SequentialTokenVectorReader spk2utt_reader(spk2utt_rspecifier);
BaseFloatVectorWriter ivector_writer(ivector_wspecifier);
Int32Writer num_utts_writer(num_utts_wspecifier);
for (; !spk2utt_reader.Done(); spk2utt_reader.Next()) {
std::string spk = spk2utt_reader.Key();
const std::vector<std::string> &uttlist = spk2utt_reader.Value();
if (uttlist.empty()) {
KALDI_ERR << "Speaker with no utterances.";
}
Vector<BaseFloat> spk_mean;
int32 utt_count = 0;
for (size_t i = 0; i < uttlist.size(); i++) {
std::string utt = uttlist[i];
if (!ivector_reader.HasKey(utt)) {
KALDI_WARN << "No iVector present in input for utterance " << utt;
num_utt_err++;
} else {
if (utt_count == 0) {
spk_mean = ivector_reader.Value(utt);
} else {
spk_mean.AddVec(1.0, ivector_reader.Value(utt));
}
num_utt_done++;
utt_count++;
}
}
if (utt_count == 0) {
KALDI_WARN << "Not producing output for speaker " << spk
<< " since no utterances had iVectors";
num_spk_err++;
} else {
spk_mean.Scale(1.0 / utt_count);
ivector_writer.Write(spk, spk_mean);
if (num_utts_wspecifier != "") num_utts_writer.Write(spk, utt_count);
num_spk_done++;
spk_sumsq += VecVec(spk_mean, spk_mean);
if (spk_sum.Dim() == 0) spk_sum.Resize(spk_mean.Dim());
spk_sum.AddVec(1.0, spk_mean);
}
}
KALDI_LOG << "Computed mean of " << num_spk_done << " speakers ("
<< num_spk_err << " with no utterances), consisting of "
<< num_utt_done << " utterances (" << num_utt_err
<< " absent from input).";
if (num_spk_done != 0) {
spk_sumsq /= num_spk_done;
spk_sum.Scale(1.0 / num_spk_done);
double mean_length = spk_sum.Norm(2.0), spk_length = sqrt(spk_sumsq),
norm_spk_length = spk_length / sqrt(spk_sum.Dim());
KALDI_LOG << "Norm of mean of speakers is " << mean_length
<< ", root-mean-square speaker-iVector length divided by "
<< "sqrt(dim) is " << norm_spk_length;
}
return (num_spk_done != 0 ? 0 : 1);
}
} catch (const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 5,929 | 2,075 |
#pragma once
#include "scene_view.hpp"
#include "mesh_renderer.hpp"
namespace glpp::asset::render {
template<class ShadingModel>
class scene_renderer_t {
public:
using material_key_t = size_t;
using renderer_t = mesh_renderer_t<ShadingModel>;
scene_renderer_t(const ShadingModel& model, const scene_t& scene);
void render(const scene_view_t& view);
void render(const scene_view_t& view, const glpp::core::render::camera_t& camera);
renderer_t& renderer(material_key_t index);
const renderer_t& renderer(material_key_t index) const;
private:
std::vector<renderer_t> m_renderers;
};
template<class ShadingModel>
scene_renderer_t<ShadingModel>::scene_renderer_t(const ShadingModel& model, const scene_t& scene)
{
m_renderers.reserve(scene.materials.size());
std::transform(
scene.materials.begin(),
scene.materials.end(),
std::back_inserter(m_renderers),
[&](const material_t& material) {
return mesh_renderer_t<ShadingModel>{ model, material };
}
);
}
template<class ShadingModel>
void scene_renderer_t<ShadingModel>::render(const scene_view_t& view) {
for(auto i = 0u; i < m_renderers.size(); ++i) {
const auto& meshes = view.meshes_by_material(i);
auto& renderer = m_renderers[i];
for(const auto& mesh : meshes) {
renderer.update_model_matrix(mesh.model_matrix);
renderer.render(mesh);
}
}
}
template<class ShadingModel>
void scene_renderer_t<ShadingModel>::render(const scene_view_t& view, const glpp::core::render::camera_t& camera) {
for(auto i = 0u; i < m_renderers.size(); ++i) {
const auto& meshes = view.meshes_by_material(i);
auto& renderer = m_renderers[i];
for(const auto& mesh : meshes) {
renderer.update_model_matrix(mesh.model_matrix);
renderer.render(mesh, camera);
}
}
}
template<class ShadingModel>
typename scene_renderer_t<ShadingModel>::renderer_t& scene_renderer_t<ShadingModel>::renderer(material_key_t index) {
return m_renderers[index];
}
template<class ShadingModel>
const typename scene_renderer_t<ShadingModel>::renderer_t& scene_renderer_t<ShadingModel>::renderer(material_key_t index) const {
return m_renderers[index];
}
}
| 2,122 | 803 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8SVGLength.h"
#include "bindings/core/v8/V8SVGElement.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8DOMConfiguration.h"
#include "bindings/v8/V8HiddenValue.h"
#include "bindings/v8/V8ObjectConstructor.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
static void initializeScriptWrappableForInterface(SVGLengthTearOff* object)
{
if (ScriptWrappable::wrapperCanBeStoredInObject(object))
ScriptWrappable::fromObject(object)->setTypeInfo(&V8SVGLength::wrapperTypeInfo);
else
ASSERT_NOT_REACHED();
}
} // namespace WebCore
void webCoreInitializeScriptWrappableForInterface(WebCore::SVGLengthTearOff* object)
{
WebCore::initializeScriptWrappableForInterface(object);
}
namespace WebCore {
const WrapperTypeInfo V8SVGLength::wrapperTypeInfo = { gin::kEmbedderBlink, V8SVGLength::domTemplate, V8SVGLength::derefObject, 0, 0, V8SVGLength::visitDOMWrapper, V8SVGLength::installPerContextEnabledMethods, 0, WrapperTypeObjectPrototype, RefCountedObject };
namespace SVGLengthTearOffV8Internal {
template <typename T> void V8_USE(T) { }
static void unitTypeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGLengthTearOff* impl = V8SVGLength::toNative(holder);
v8SetReturnValueUnsigned(info, impl->unitType());
}
static void unitTypeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGLengthTearOffV8Internal::unitTypeAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void valueAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGLengthTearOff* impl = V8SVGLength::toNative(holder);
ExceptionState exceptionState(ExceptionState::GetterContext, "value", "SVGLength", holder, info.GetIsolate());
float v8Value = impl->value(exceptionState);
if (UNLIKELY(exceptionState.throwIfNeeded()))
return;
v8SetReturnValue(info, v8Value);
}
static void valueAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGLengthTearOffV8Internal::valueAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void valueAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "value", "SVGLength", holder, info.GetIsolate());
SVGLengthTearOff* impl = V8SVGLength::toNative(holder);
TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue()));
impl->setValue(cppValue, exceptionState);
exceptionState.throwIfNeeded();
}
static void valueAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGLengthTearOffV8Internal::valueAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void valueInSpecifiedUnitsAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGLengthTearOff* impl = V8SVGLength::toNative(holder);
v8SetReturnValue(info, impl->valueInSpecifiedUnits());
}
static void valueInSpecifiedUnitsAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGLengthTearOffV8Internal::valueInSpecifiedUnitsAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void valueInSpecifiedUnitsAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "valueInSpecifiedUnits", "SVGLength", holder, info.GetIsolate());
SVGLengthTearOff* impl = V8SVGLength::toNative(holder);
TONATIVE_VOID(float, cppValue, static_cast<float>(v8Value->NumberValue()));
impl->setValueInSpecifiedUnits(cppValue, exceptionState);
exceptionState.throwIfNeeded();
}
static void valueInSpecifiedUnitsAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGLengthTearOffV8Internal::valueInSpecifiedUnitsAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void valueAsStringAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
SVGLengthTearOff* impl = V8SVGLength::toNative(holder);
v8SetReturnValueString(info, impl->valueAsString(), info.GetIsolate());
}
static void valueAsStringAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter");
SVGLengthTearOffV8Internal::valueAsStringAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void valueAsStringAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
v8::Handle<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "valueAsString", "SVGLength", holder, info.GetIsolate());
SVGLengthTearOff* impl = V8SVGLength::toNative(holder);
TOSTRING_VOID(V8StringResource<WithNullCheck>, cppValue, v8Value);
impl->setValueAsString(cppValue, exceptionState);
exceptionState.throwIfNeeded();
}
static void valueAsStringAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter");
SVGLengthTearOffV8Internal::valueAsStringAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void newValueSpecifiedUnitsMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "newValueSpecifiedUnits", "SVGLength", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
throwMinimumArityTypeError(exceptionState, 2, info.Length());
return;
}
SVGLengthTearOff* impl = V8SVGLength::toNative(info.Holder());
unsigned unitType;
float valueInSpecifiedUnits;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(unitType, toUInt16(info[0], exceptionState), exceptionState);
TONATIVE_VOID_INTERNAL(valueInSpecifiedUnits, static_cast<float>(info[1]->NumberValue()));
}
impl->newValueSpecifiedUnits(unitType, valueInSpecifiedUnits, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void newValueSpecifiedUnitsMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGLengthTearOffV8Internal::newValueSpecifiedUnitsMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
static void convertToSpecifiedUnitsMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "convertToSpecifiedUnits", "SVGLength", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
throwMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
SVGLengthTearOff* impl = V8SVGLength::toNative(info.Holder());
unsigned unitType;
{
v8::TryCatch block;
V8RethrowTryCatchScope rethrow(block);
TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(unitType, toUInt16(info[0], exceptionState), exceptionState);
}
impl->convertToSpecifiedUnits(unitType, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void convertToSpecifiedUnitsMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
SVGLengthTearOffV8Internal::convertToSpecifiedUnitsMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
} // namespace SVGLengthTearOffV8Internal
void V8SVGLength::visitDOMWrapper(void* object, const v8::Persistent<v8::Object>& wrapper, v8::Isolate* isolate)
{
SVGLengthTearOff* impl = fromInternalPointer(object);
v8::Local<v8::Object> creationContext = v8::Local<v8::Object>::New(isolate, wrapper);
V8WrapperInstantiationScope scope(creationContext, isolate);
SVGElement* contextElement = impl->contextElement();
if (contextElement) {
if (!DOMDataStore::containsWrapper<V8SVGElement>(contextElement, isolate))
wrap(contextElement, creationContext, isolate);
DOMDataStore::setWrapperReference<V8SVGElement>(wrapper, contextElement, isolate);
}
setObjectGroup(object, wrapper, isolate);
}
static const V8DOMConfiguration::AttributeConfiguration V8SVGLengthAttributes[] = {
{"unitType", SVGLengthTearOffV8Internal::unitTypeAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"value", SVGLengthTearOffV8Internal::valueAttributeGetterCallback, SVGLengthTearOffV8Internal::valueAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"valueInSpecifiedUnits", SVGLengthTearOffV8Internal::valueInSpecifiedUnitsAttributeGetterCallback, SVGLengthTearOffV8Internal::valueInSpecifiedUnitsAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
{"valueAsString", SVGLengthTearOffV8Internal::valueAsStringAttributeGetterCallback, SVGLengthTearOffV8Internal::valueAsStringAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */},
};
static const V8DOMConfiguration::MethodConfiguration V8SVGLengthMethods[] = {
{"newValueSpecifiedUnits", SVGLengthTearOffV8Internal::newValueSpecifiedUnitsMethodCallback, 0, 2},
{"convertToSpecifiedUnits", SVGLengthTearOffV8Internal::convertToSpecifiedUnitsMethodCallback, 0, 1},
};
static void configureV8SVGLengthTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "SVGLength", v8::Local<v8::FunctionTemplate>(), V8SVGLength::internalFieldCount,
V8SVGLengthAttributes, WTF_ARRAY_LENGTH(V8SVGLengthAttributes),
0, 0,
V8SVGLengthMethods, WTF_ARRAY_LENGTH(V8SVGLengthMethods),
isolate);
v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate();
v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate();
static const V8DOMConfiguration::ConstantConfiguration V8SVGLengthConstants[] = {
{"SVG_LENGTHTYPE_UNKNOWN", 0},
{"SVG_LENGTHTYPE_NUMBER", 1},
{"SVG_LENGTHTYPE_PERCENTAGE", 2},
{"SVG_LENGTHTYPE_EMS", 3},
{"SVG_LENGTHTYPE_EXS", 4},
{"SVG_LENGTHTYPE_PX", 5},
{"SVG_LENGTHTYPE_CM", 6},
{"SVG_LENGTHTYPE_MM", 7},
{"SVG_LENGTHTYPE_IN", 8},
{"SVG_LENGTHTYPE_PT", 9},
{"SVG_LENGTHTYPE_PC", 10},
};
V8DOMConfiguration::installConstants(functionTemplate, prototypeTemplate, V8SVGLengthConstants, WTF_ARRAY_LENGTH(V8SVGLengthConstants), isolate);
COMPILE_ASSERT(0 == SVGLengthTearOff::SVG_LENGTHTYPE_UNKNOWN, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_UNKNOWNDoesntMatchWithImplementation);
COMPILE_ASSERT(1 == SVGLengthTearOff::SVG_LENGTHTYPE_NUMBER, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_NUMBERDoesntMatchWithImplementation);
COMPILE_ASSERT(2 == SVGLengthTearOff::SVG_LENGTHTYPE_PERCENTAGE, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_PERCENTAGEDoesntMatchWithImplementation);
COMPILE_ASSERT(3 == SVGLengthTearOff::SVG_LENGTHTYPE_EMS, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_EMSDoesntMatchWithImplementation);
COMPILE_ASSERT(4 == SVGLengthTearOff::SVG_LENGTHTYPE_EXS, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_EXSDoesntMatchWithImplementation);
COMPILE_ASSERT(5 == SVGLengthTearOff::SVG_LENGTHTYPE_PX, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_PXDoesntMatchWithImplementation);
COMPILE_ASSERT(6 == SVGLengthTearOff::SVG_LENGTHTYPE_CM, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_CMDoesntMatchWithImplementation);
COMPILE_ASSERT(7 == SVGLengthTearOff::SVG_LENGTHTYPE_MM, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_MMDoesntMatchWithImplementation);
COMPILE_ASSERT(8 == SVGLengthTearOff::SVG_LENGTHTYPE_IN, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_INDoesntMatchWithImplementation);
COMPILE_ASSERT(9 == SVGLengthTearOff::SVG_LENGTHTYPE_PT, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_PTDoesntMatchWithImplementation);
COMPILE_ASSERT(10 == SVGLengthTearOff::SVG_LENGTHTYPE_PC, TheValueOfSVGLengthTearOff_SVG_LENGTHTYPE_PCDoesntMatchWithImplementation);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Handle<v8::FunctionTemplate> V8SVGLength::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8SVGLengthTemplate);
}
bool V8SVGLength::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Handle<v8::Object> V8SVGLength::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
SVGLengthTearOff* V8SVGLength::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value)
{
return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0;
}
v8::Handle<v8::Object> wrap(SVGLengthTearOff* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8SVGLength>(impl, isolate));
return V8SVGLength::createWrapper(impl, creationContext, isolate);
}
v8::Handle<v8::Object> V8SVGLength::createWrapper(PassRefPtr<SVGLengthTearOff> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8SVGLength>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo();
// Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have
// the same object de-ref functions, though, so use that as the basis of the check.
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8SVGLength>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Dependent);
return wrapper;
}
void V8SVGLength::derefObject(void* object)
{
fromInternalPointer(object)->deref();
}
template<>
v8::Handle<v8::Value> toV8NoInline(SVGLengthTearOff* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl, creationContext, isolate);
}
} // namespace WebCore
| 16,867 | 5,771 |
/*
Copyright (c) 2015-2016, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/stack_allocator.hpp"
#include <cstdarg> // for va_list, va_copy, va_end
namespace libtorrent {
namespace aux {
allocation_slot stack_allocator::copy_string(string_view str)
{
int const ret = int(m_storage.size());
m_storage.resize(ret + numeric_cast<int>(str.size()) + 1);
std::memcpy(&m_storage[ret], str.data(), str.size());
m_storage[ret + int(str.length())] = '\0';
return allocation_slot(ret);
}
allocation_slot stack_allocator::copy_string(char const* str)
{
int const ret = int(m_storage.size());
int const len = int(std::strlen(str));
m_storage.resize(ret + len + 1);
std::memcpy(&m_storage[ret], str, numeric_cast<std::size_t>(len));
m_storage[ret + len] = '\0';
return allocation_slot(ret);
}
allocation_slot stack_allocator::format_string(char const* fmt, va_list v)
{
int const pos = int(m_storage.size());
int len = 512;
for(;;)
{
m_storage.resize(pos + len + 1);
va_list args;
va_copy(args, v);
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif
int const ret = std::vsnprintf(m_storage.data() + pos, static_cast<std::size_t>(len + 1), fmt, args);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
va_end(args);
if (ret < 0)
{
m_storage.resize(pos);
return copy_string("(format error)");
}
if (ret > len)
{
// try again
len = ret;
continue;
}
break;
}
// +1 is to include the 0-terminator
m_storage.resize(pos + len + 1);
return allocation_slot(pos);
}
allocation_slot stack_allocator::copy_buffer(span<char const> buf)
{
int const ret = int(m_storage.size());
int const size = int(buf.size());
if (size < 1) return {};
m_storage.resize(ret + size);
std::memcpy(&m_storage[ret], buf.data(), numeric_cast<std::size_t>(size));
return allocation_slot(ret);
}
allocation_slot stack_allocator::allocate(int const bytes)
{
if (bytes < 1) return {};
int const ret = m_storage.end_index();
m_storage.resize(ret + bytes);
return allocation_slot(ret);
}
char* stack_allocator::ptr(allocation_slot const idx)
{
if(idx.val() < 0) return nullptr;
TORRENT_ASSERT(idx.val() < int(m_storage.size()));
return &m_storage[idx.val()];
}
char const* stack_allocator::ptr(allocation_slot const idx) const
{
if(idx.val() < 0) return nullptr;
TORRENT_ASSERT(idx.val() < int(m_storage.size()));
return &m_storage[idx.val()];
}
void stack_allocator::swap(stack_allocator& rhs)
{
m_storage.swap(rhs.m_storage);
}
void stack_allocator::reset()
{
m_storage.clear();
}
}
}
| 4,137 | 1,612 |
/*
Copyright (c) 2009-2015, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef EL_PSEUDOSPECTRA_IRA_HPP
#define EL_PSEUDOSPECTRA_IRA_HPP
#include "./Lanczos.hpp"
namespace El {
namespace pspec {
template<typename Real>
inline void
ComputeNewEstimates
( const vector<Matrix<Complex<Real>>>& HList,
const Matrix<Int>& activeConverged,
Matrix<Real>& activeEsts,
Int n )
{
DEBUG_ONLY(CallStackEntry cse("pspec::ComputeNewEstimates"))
const Real normCap = NormCap<Real>();
const Int numShifts = activeEsts.Height();
if( numShifts == 0 )
return;
Matrix<Complex<Real>> H, HTL;
Matrix<Complex<Real>> w(n,1);
for( Int j=0; j<numShifts; ++j )
{
H = HList[j];
HTL = H( IR(0,n), IR(0,n) );
if( !activeConverged.Get(j,0) )
{
if( !HasNan(HTL) )
{
lapack::HessenbergEig
( n, HTL.Buffer(), HTL.LDim(), w.Buffer() );
Real estSquared=0;
for( Int k=0; k<n; ++k )
if( w.GetRealPart(k,0) > estSquared )
estSquared = w.GetRealPart(k,0);
activeEsts.Set( j, 0, Min(Sqrt(estSquared),normCap) );
}
else
activeEsts.Set( j, 0, normCap );
}
}
}
template<typename Real>
inline void
ComputeNewEstimates
( const vector<Matrix<Complex<Real>>>& HList,
const DistMatrix<Int,MR,STAR>& activeConverged,
DistMatrix<Real,MR,STAR>& activeEsts,
Int n )
{
DEBUG_ONLY(CallStackEntry cse("pspec::ComputeNewEstimates"))
ComputeNewEstimates
( HList, activeConverged.LockedMatrix(), activeEsts.Matrix(), n );
}
template<typename Real>
inline void
Restart
( const vector<Matrix<Complex<Real>>>& HList,
const Matrix<Int>& activeConverged,
vector<Matrix<Complex<Real>>>& VList )
{
DEBUG_ONLY(CallStackEntry cse("pspec::Restart"))
const Int n = VList[0].Height();
const Int numShifts = VList[0].Width();
if( numShifts == 0 )
return;
const Int basisSize = HList[0].Width();
Matrix<Complex<Real>> H, HTL, Q(basisSize,basisSize);
Matrix<Complex<Real>> w(basisSize,1), u(n,1);
for( Int j=0; j<numShifts; ++j )
{
H = HList[j];
HTL = H( IR(0,basisSize), IR(0,basisSize) );
if( !activeConverged.Get(j,0) )
{
if( !HasNan(HTL) )
{
// TODO: Switch to lapack::HessenbergEig
lapack::Eig
( basisSize, HTL.Buffer(), HTL.LDim(), w.Buffer(),
Q.Buffer(), Q.LDim() );
Real maxReal=0;
Int maxIdx=0;
for( Int k=0; k<basisSize; ++k )
{
if( w.GetRealPart(k,0) > maxReal )
{
maxReal = w.GetRealPart(k,0);
maxIdx = k;
}
}
Zeros( u, n, 1 );
for( Int k=0; k<basisSize; ++k )
{
const Matrix<Complex<Real>>& V = VList[k];
auto v = V( IR(0,n), IR(j,j+1) );
Axpy( Q.Get(k,maxIdx), v, u );
}
Matrix<Complex<Real>>& V = VList[0];
auto v = V( IR(0,n), IR(j,j+1) );
v = u;
}
}
}
}
template<typename Real>
inline void
Restart
( const vector<Matrix<Complex<Real>>>& HList,
const Matrix<Int>& activeConverged,
vector<Matrix<Real>>& VRealList,
vector<Matrix<Real>>& VImagList )
{
DEBUG_ONLY(CallStackEntry cse("pspec::Restart"))
const Int n = VRealList[0].Height();
const Int numShifts = VRealList[0].Width();
if( numShifts == 0 )
return;
const Int basisSize = HList[0].Width();
Matrix<Complex<Real>> H, HTL, Q(basisSize,basisSize);
Matrix<Complex<Real>> w(basisSize,1), u(n,1), v(n,1);
for( Int j=0; j<numShifts; ++j )
{
H = HList[j];
HTL = H( IR(0,basisSize), IR(0,basisSize) );
if( !activeConverged.Get(j,0) )
{
if( !HasNan(HTL) )
{
// TODO: Switch to lapack::HessenbergEig
lapack::Eig
( basisSize, HTL.Buffer(), HTL.LDim(), w.Buffer(),
Q.Buffer(), Q.LDim() );
Real maxReal=0;
Int maxIdx=0;
for( Int k=0; k<basisSize; ++k )
{
if( w.GetRealPart(k,0) > maxReal )
{
maxReal = w.GetRealPart(k,0);
maxIdx = k;
}
}
Zeros( u, n, 1 );
for( Int k=0; k<basisSize; ++k )
{
const Matrix<Real>& VReal = VRealList[k];
const Matrix<Real>& VImag = VImagList[k];
auto vReal = VReal( IR(0,n), IR(j,j+1) );
auto vImag = VImag( IR(0,n), IR(j,j+1) );
for( Int i=0; i<n; ++i )
v.Set( i, 0, Complex<Real>(vReal.Get(i,0),
vImag.Get(i,0)) );
Axpy( Q.Get(k,maxIdx), v, u );
}
Matrix<Real>& VReal = VRealList[0];
Matrix<Real>& VImag = VImagList[0];
auto vReal = VReal( IR(0,n), IR(j,j+1) );
auto vImag = VImag( IR(0,n), IR(j,j+1) );
for( Int i=0; i<n; ++i )
{
vReal.Set( i, 0, u.GetRealPart(i,0) );
vImag.Set( i, 0, u.GetImagPart(i,0) );
}
}
}
}
}
template<typename Real>
inline void
Restart
( const vector<Matrix<Complex<Real>>>& HList,
const DistMatrix<Int,MR,STAR>& activeConverged,
vector<DistMatrix<Complex<Real>>>& VList )
{
DEBUG_ONLY(CallStackEntry cse("pspec::Restart"))
const Int basisSize = HList[0].Width();
vector<Matrix<Complex<Real>>> VLocList(basisSize+1);
for( Int j=0; j<basisSize+1; ++j )
VLocList[j] = View( VList[j].Matrix() );
Restart( HList, activeConverged.LockedMatrix(), VLocList );
}
template<typename Real>
inline void
Restart
( const vector<Matrix<Complex<Real>>>& HList,
const DistMatrix<Int,MR,STAR>& activeConverged,
vector<DistMatrix<Real>>& VRealList,
vector<DistMatrix<Real>>& VImagList )
{
DEBUG_ONLY(CallStackEntry cse("pspec::Restart"))
const Int basisSize = HList[0].Width();
vector<Matrix<Real>> VRealLocList(basisSize+1),
VImagLocList(basisSize+1);
for( Int j=0; j<basisSize+1; ++j )
{
VRealLocList[j] = View( VRealList[j].Matrix() );
VImagLocList[j] = View( VImagList[j].Matrix() );
}
Restart
( HList, activeConverged.LockedMatrix(), VRealLocList, VImagLocList );
}
template<typename Real>
inline Matrix<Int>
IRA
( const Matrix<Complex<Real>>& U, const Matrix<Complex<Real>>& shifts,
Matrix<Real>& invNorms, PseudospecCtrl<Real> psCtrl=PseudospecCtrl<Real>() )
{
DEBUG_ONLY(CallStackEntry cse("pspec::IRA"))
using namespace pspec;
typedef Complex<Real> C;
const Int n = U.Height();
const Int numShifts = shifts.Height();
const Int maxIts = psCtrl.maxIts;
const Int basisSize = psCtrl.basisSize;
const bool deflate = psCtrl.deflate;
const bool progress = psCtrl.progress;
// Keep track of the number of iterations per shift
Matrix<Int> itCounts;
Ones( itCounts, numShifts, 1 );
// Keep track of the pivoting history if deflation is requested
Matrix<Int> preimage;
Matrix<C> pivShifts( shifts );
if( deflate )
{
preimage.Resize( numShifts, 1 );
for( Int j=0; j<numShifts; ++j )
preimage.Set( j, 0, j );
}
// MultiShiftTrm requires write access for now...
Matrix<C> UCopy( U );
// The Hessenberg variant currently requires explicit access to the adjoint
Matrix<C> UAdj;
if( !psCtrl.schur )
Adjoint( U, UAdj );
// Simultaneously run IRA for different shifts
vector<Matrix<C>> VList(basisSize+1), activeVList(basisSize+1);
for( Int j=0; j<basisSize+1; ++j )
Zeros( VList[j], n, numShifts );
Gaussian( VList[0], n, numShifts );
vector<Matrix<Complex<Real>>> HList(numShifts);
Matrix<Real> realComponents;
Matrix<Complex<Real>> components;
Matrix<Int> activeConverged;
Zeros( activeConverged, numShifts, 1 );
psCtrl.snapCtrl.ResetCounts();
Timer timer, subtimer;
Int numIts=0, numDone=0;
Matrix<Real> estimates(numShifts,1);
Zeros( estimates, numShifts, 1 );
Matrix<Real> lastActiveEsts;
Matrix<Int> activePreimage;
while( true )
{
const Int numActive = ( deflate ? numShifts-numDone : numShifts );
auto activeShifts = pivShifts( IR(0,numActive), IR(0,1) );
auto activeEsts = estimates( IR(0,numActive), IR(0,1) );
auto activeItCounts = itCounts( IR(0,numActive), IR(0,1) );
for( Int j=0; j<basisSize+1; ++j )
View( activeVList[j], VList[j], IR(0,n), IR(0,numActive) );
if( deflate )
{
View( activePreimage, preimage, IR(0,numActive), IR(0,1) );
Zeros( activeConverged, numActive, 1 );
}
HList.resize( numActive );
for( Int j=0; j<numActive; ++j )
Zeros( HList[j], basisSize+1, basisSize );
if( progress )
timer.Start();
ColumnNorms( activeVList[0], realComponents );
InvBetaScale( realComponents, activeVList[0] );
for( Int j=0; j<basisSize; ++j )
{
lastActiveEsts = activeEsts;
activeVList[j+1] = activeVList[j];
if( psCtrl.schur )
{
if( progress )
subtimer.Start();
MultiShiftTrsm
( LEFT, UPPER, NORMAL,
C(1), UCopy, activeShifts, activeVList[j+1] );
MultiShiftTrsm
( LEFT, UPPER, ADJOINT,
C(1), UCopy, activeShifts, activeVList[j+1] );
if( progress )
{
const double msTime = subtimer.Stop();
const Int numActiveShifts = activeShifts.Height();
const double gflops = (8.*n*n*numActiveShifts)/(msTime*1e9);
cout << " MultiShiftTrsm's: " << msTime
<< " seconds, " << gflops << " GFlops" << endl;
}
}
else
{
if( progress )
subtimer.Start();
MultiShiftHessSolve
( UPPER, NORMAL,
C(1), U, activeShifts, activeVList[j+1] );
Matrix<C> activeShiftsConj;
Conjugate( activeShifts, activeShiftsConj );
MultiShiftHessSolve
( LOWER, NORMAL,
C(1), UAdj, activeShiftsConj, activeVList[j+1] );
if( progress )
{
const double msTime = subtimer.Stop();
const Int numActiveShifts = activeShifts.Height();
const double gflops =
(32.*n*n*numActiveShifts)/(msTime*1.e9);
cout << " MultiShiftHessSolve's: " << msTime
<< " seconds, " << gflops << " GFlops" << endl;
}
}
// Orthogonalize with respect to the old iterate
if( j > 0 )
{
ExtractList( HList, components, j, j-1 );
// TODO: Conjugate components?
PlaceList( HList, components, j-1, j );
ColumnSubtractions
( components, activeVList[j-1], activeVList[j+1] );
}
// Orthogonalize with respect to the last iterate
InnerProducts( activeVList[j], activeVList[j+1], components );
PlaceList( HList, components, j, j );
ColumnSubtractions
( components, activeVList[j], activeVList[j+1] );
// Explicitly (re)orthogonalize against all previous vectors
for( Int i=0; i<j-1; ++i )
{
InnerProducts
( activeVList[i], activeVList[j+1], components );
PlaceList( HList, components, i, j );
ColumnSubtractions
( components, activeVList[i], activeVList[j+1] );
}
if( j > 0 )
{
InnerProducts
( activeVList[j-1], activeVList[j+1], components );
UpdateList( HList, components, j-1, j );
ColumnSubtractions
( components, activeVList[j-1], activeVList[j+1] );
}
// Compute the norm of what is left
ColumnNorms( activeVList[j+1], realComponents );
PlaceList( HList, realComponents, j+1, j );
// TODO: Handle lucky breakdowns
InvBetaScale( realComponents, activeVList[j+1] );
ComputeNewEstimates( HList, activeConverged, activeEsts, j+1 );
// We will have the same estimate two iterations in a row when
// restarting
if( j != 0 )
activeConverged =
FindConverged
( lastActiveEsts, activeEsts, activeItCounts, psCtrl.tol );
psCtrl.snapCtrl.Iterate();
}
if( progress )
subtimer.Start();
Restart( HList, activeConverged, activeVList );
if( progress )
cout << "IRA restart: " << subtimer.Stop()
<< " seconds" << endl;
const Int numActiveDone = ZeroNorm( activeConverged );
if( deflate )
numDone += numActiveDone;
else
numDone = numActiveDone;
numIts += basisSize;
if( progress )
{
const double iterTime = timer.Stop();
cout << "iteration " << numIts << ": " << iterTime
<< " seconds, " << numDone << " of " << numShifts
<< " converged" << endl;
}
if( numIts >= maxIts )
break;
if( numDone == numShifts )
break;
else if( deflate && numActiveDone != 0 )
{
Deflate
( activeShifts, activePreimage, activeVList[0], activeEsts,
activeConverged, activeItCounts, progress );
lastActiveEsts = activeEsts;
}
// Save snapshots of the estimates at the requested rate
Snapshot
( preimage, estimates, itCounts, numIts, deflate, psCtrl.snapCtrl );
}
invNorms = estimates;
if( deflate )
RestoreOrdering( preimage, invNorms, itCounts );
FinalSnapshot( invNorms, itCounts, psCtrl.snapCtrl );
return itCounts;
}
template<typename Real>
inline Matrix<Int>
IRA
( const Matrix<Real>& U, const Matrix<Complex<Real>>& shifts,
Matrix<Real>& invNorms, PseudospecCtrl<Real> psCtrl=PseudospecCtrl<Real>() )
{
DEBUG_ONLY(CallStackEntry cse("pspec::IRA"))
using namespace pspec;
typedef Complex<Real> C;
const Int n = U.Height();
const Int numShifts = shifts.Height();
const Int maxIts = psCtrl.maxIts;
const Int basisSize = psCtrl.basisSize;
const bool deflate = psCtrl.deflate;
const bool progress = psCtrl.progress;
// Keep track of the number of iterations per shift
Matrix<Int> itCounts;
Ones( itCounts, numShifts, 1 );
// Keep track of the pivoting history if deflation is requested
Matrix<Int> preimage;
Matrix<C> pivShifts( shifts );
if( deflate )
{
preimage.Resize( numShifts, 1 );
for( Int j=0; j<numShifts; ++j )
preimage.Set( j, 0, j );
}
// Simultaneously run IRA for different shifts
vector<Matrix<Real>> VRealList(basisSize+1),
VImagList(basisSize+1),
activeVRealList(basisSize+1),
activeVImagList(basisSize+1);
for( Int j=0; j<basisSize+1; ++j )
{
Zeros( VRealList[j], n, numShifts );
Zeros( VImagList[j], n, numShifts );
}
// The variance will be off from that of the usual complex case
Gaussian( VRealList[0], n, numShifts );
Gaussian( VImagList[0], n, numShifts );
vector<Matrix<Complex<Real>>> HList(numShifts);
Matrix<Real> realComponents;
Matrix<Complex<Real>> components;
Matrix<Int> activeConverged;
Zeros( activeConverged, numShifts, 1 );
psCtrl.snapCtrl.ResetCounts();
Timer timer, subtimer;
Int numIts=0, numDone=0;
Matrix<Real> estimates(numShifts,1);
Zeros( estimates, numShifts, 1 );
Matrix<Real> lastActiveEsts;
Matrix<Int> activePreimage;
while( true )
{
const Int numActive = ( deflate ? numShifts-numDone : numShifts );
auto activeShifts = pivShifts( IR(0,numActive), IR(0,1) );
auto activeEsts = estimates( IR(0,numActive), IR(0,1) );
auto activeItCounts = itCounts( IR(0,numActive), IR(0,1) );
for( Int j=0; j<basisSize+1; ++j )
{
activeVRealList[j] = VRealList[j]( IR(0,n), IR(0,numActive) );
activeVImagList[j] = VImagList[j]( IR(0,n), IR(0,numActive) );
}
if( deflate )
{
activePreimage = preimage( IR(0,numActive), IR(0,1) );
Zeros( activeConverged, numActive, 1 );
}
HList.resize( numActive );
for( Int j=0; j<numActive; ++j )
Zeros( HList[j], basisSize+1, basisSize );
if( progress )
timer.Start();
ColumnNorms( activeVRealList[0], activeVImagList[0], realComponents );
InvBetaScale( realComponents, activeVRealList[0] );
InvBetaScale( realComponents, activeVImagList[0] );
for( Int j=0; j<basisSize; ++j )
{
lastActiveEsts = activeEsts;
activeVRealList[j+1] = activeVRealList[j];
activeVImagList[j+1] = activeVImagList[j];
if( progress )
subtimer.Start();
MultiShiftQuasiTrsm
( LEFT, UPPER, NORMAL, C(1), U, activeShifts,
activeVRealList[j+1], activeVImagList[j+1] );
MultiShiftQuasiTrsm
( LEFT, UPPER, ADJOINT, C(1), U, activeShifts,
activeVRealList[j+1], activeVImagList[j+1] );
if( progress )
{
const double msTime = subtimer.Stop();
const Int numActiveShifts = activeShifts.Height();
const double gflops = (4.*n*n*numActiveShifts)/(msTime*1.e9);
cout << " MultiShiftQuasiTrsm's: " << msTime
<< " seconds, " << gflops << " GFlops" << endl;
}
// Orthogonalize with respect to the old iterate
if( j > 0 )
{
ExtractList( HList, components, j, j-1 );
// TODO: Conjugate components?
PlaceList( HList, components, j-1, j );
ColumnSubtractions
( components, activeVRealList[j-1], activeVImagList[j-1],
activeVRealList[j+1], activeVImagList[j+1] );
}
// Orthogonalize with respect to the last iterate
InnerProducts
( activeVRealList[j ], activeVImagList[j ],
activeVRealList[j+1], activeVImagList[j+1], components );
PlaceList( HList, components, j, j );
ColumnSubtractions
( components, activeVRealList[j ], activeVImagList[j ],
activeVRealList[j+1], activeVImagList[j+1] );
// Explicitly (re)orthogonalize against all previous vectors
for( Int i=0; i<j-1; ++i )
{
InnerProducts
( activeVRealList[i ], activeVImagList[i ],
activeVRealList[j+1], activeVImagList[j+1], components );
PlaceList( HList, components, i, j );
ColumnSubtractions
( components, activeVRealList[i ], activeVImagList[i ],
activeVRealList[j+1], activeVImagList[j+1] );
}
if( j > 0 )
{
InnerProducts
( activeVRealList[j-1], activeVImagList[j-1],
activeVRealList[j+1], activeVImagList[j+1], components );
UpdateList( HList, components, j-1, j );
ColumnSubtractions
( components, activeVRealList[j-1], activeVImagList[j-1],
activeVRealList[j+1], activeVImagList[j+1] );
}
// Compute the norm of what is left
ColumnNorms
( activeVRealList[j+1], activeVImagList[j+1], realComponents );
PlaceList( HList, realComponents, j+1, j );
// TODO: Handle lucky breakdowns
InvBetaScale( realComponents, activeVRealList[j+1] );
InvBetaScale( realComponents, activeVImagList[j+1] );
ComputeNewEstimates( HList, activeConverged, activeEsts, j+1 );
// We will have the same estimate two iterations in a row when
// restarting
if( j != 0 )
activeConverged =
FindConverged
( lastActiveEsts, activeEsts, activeItCounts, psCtrl.tol );
psCtrl.snapCtrl.Iterate();
}
if( progress )
subtimer.Start();
Restart( HList, activeConverged, activeVRealList, activeVImagList );
if( progress )
cout << "IRA restart: " << subtimer.Stop()
<< " seconds" << endl;
const Int numActiveDone = ZeroNorm( activeConverged );
if( deflate )
numDone += numActiveDone;
else
numDone = numActiveDone;
numIts += basisSize;
if( progress )
{
const double iterTime = timer.Stop();
cout << "iteration " << numIts << ": " << iterTime
<< " seconds, " << numDone << " of " << numShifts
<< " converged" << endl;
}
if( numIts >= maxIts )
break;
if( numDone == numShifts )
break;
else if( deflate && numActiveDone != 0 )
{
Deflate
( activeShifts, activePreimage,
activeVRealList[0], activeVImagList[0], activeEsts,
activeConverged, activeItCounts, progress );
lastActiveEsts = activeEsts;
}
// Save snapshots of the estimates at the requested rate
Snapshot
( preimage, estimates, itCounts, numIts, deflate, psCtrl.snapCtrl );
}
invNorms = estimates;
if( deflate )
RestoreOrdering( preimage, invNorms, itCounts );
FinalSnapshot( invNorms, itCounts, psCtrl.snapCtrl );
return itCounts;
}
template<typename Real>
inline DistMatrix<Int,VR,STAR>
IRA
( const AbstractDistMatrix<Complex<Real>>& UPre,
const AbstractDistMatrix<Complex<Real>>& shiftsPre,
AbstractDistMatrix<Real>& invNormsPre,
PseudospecCtrl<Real> psCtrl=PseudospecCtrl<Real>() )
{
DEBUG_ONLY(CallStackEntry cse("pspec::IRA"))
using namespace pspec;
typedef Complex<Real> C;
auto UPtr = ReadProxy<C,MC,MR>( &UPre );
auto& U = *UPtr;
auto shiftsPtr = ReadProxy<C,VR,STAR>( &shiftsPre );
auto& shifts = *shiftsPtr;
auto invNormsPtr = WriteProxy<Real,VR,STAR>( &invNormsPre );
auto& invNorms = *invNormsPtr;
const Int n = U.Height();
const Int numShifts = shifts.Height();
const Grid& g = U.Grid();
const Int maxIts = psCtrl.maxIts;
const Int basisSize = psCtrl.basisSize;
const bool deflate = psCtrl.deflate;
const bool progress = psCtrl.progress;
// Keep track of the number of iterations per shift
DistMatrix<Int,VR,STAR> itCounts(g);
Ones( itCounts, numShifts, 1 );
// Keep track of the pivoting history if deflation is requested
DistMatrix<Int,VR,STAR> preimage(g);
DistMatrix<C, VR,STAR> pivShifts( shifts );
if( deflate )
{
preimage.AlignWith( shifts );
preimage.Resize( numShifts, 1 );
const Int numLocShifts = preimage.LocalHeight();
for( Int iLoc=0; iLoc<numLocShifts; ++iLoc )
{
const Int i = preimage.GlobalRow(iLoc);
preimage.SetLocal( iLoc, 0, i );
}
}
// The Hessenberg case currently requires explicit access to the adjoint
DistMatrix<C,VC,STAR> U_VC_STAR(g), UAdj_VC_STAR(g);
if( !psCtrl.schur )
{
U_VC_STAR = U;
Adjoint( U, UAdj_VC_STAR );
}
// Simultaneously run IRA for different shifts
vector<DistMatrix<C>> VList(basisSize+1), activeVList(basisSize+1);
for( Int j=0; j<basisSize+1; ++j )
{
VList[j].SetGrid( g );
Zeros( VList[j], n, numShifts );
}
Gaussian( VList[0], n, numShifts );
const Int numMRShifts = VList[0].LocalWidth();
vector<Matrix<Complex<Real>>> HList(numMRShifts);
Matrix<Real> realComponents;
Matrix<Complex<Real>> components;
DistMatrix<Int,MR,STAR> activeConverged(g);
Zeros( activeConverged, numShifts, 1 );
psCtrl.snapCtrl.ResetCounts();
Timer timer, subtimer;
Int numIts=0, numDone=0;
DistMatrix<Real,MR,STAR> estimates(g), lastActiveEsts(g);
estimates.AlignWith( shifts );
Zeros( estimates, numShifts, 1 );
DistMatrix<Int,VR,STAR> activePreimage(g);
while( true )
{
const Int numActive = ( deflate ? numShifts-numDone : numShifts );
auto activeShifts = pivShifts( IR(0,numActive), IR(0,1) );
auto activeEsts = estimates( IR(0,numActive), IR(0,1) );
auto activeItCounts = itCounts( IR(0,numActive), IR(0,1) );
for( Int j=0; j<basisSize+1; ++j )
View( activeVList[j], VList[j], IR(0,n), IR(0,numActive) );
if( deflate )
{
View( activePreimage, preimage, IR(0,numActive), IR(0,1) );
Zeros( activeConverged, numActive, 1 );
}
HList.resize( activeEsts.LocalHeight() );
for( Int jLoc=0; jLoc<HList.size(); ++jLoc )
Zeros( HList[jLoc], basisSize+1, basisSize );
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
timer.Start();
}
ColumnNorms( activeVList[0], realComponents );
InvBetaScale( realComponents, activeVList[0] );
for( Int j=0; j<basisSize; ++j )
{
lastActiveEsts = activeEsts;
activeVList[j+1] = activeVList[j];
if( psCtrl.schur )
{
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
subtimer.Start();
}
MultiShiftTrsm
( LEFT, UPPER, NORMAL,
C(1), U, activeShifts, activeVList[j+1] );
MultiShiftTrsm
( LEFT, UPPER, ADJOINT,
C(1), U, activeShifts, activeVList[j+1] );
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
{
const double msTime = subtimer.Stop();
const Int numActiveShifts = activeShifts.Height();
const double gflops =
(8.*n*n*numActiveShifts)/(msTime*1.e9);
cout << " MultiShiftTrsm's: " << msTime
<< " seconds, " << gflops << " GFlops" << endl;
}
}
}
else
{
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
subtimer.Start();
}
// NOTE: This redistribution sequence might not be necessary
DistMatrix<C,STAR,VR> activeV_STAR_VR( activeVList[j+1] );
MultiShiftHessSolve
( UPPER, NORMAL, C(1), U_VC_STAR, activeShifts,
activeV_STAR_VR );
DistMatrix<C,VR,STAR> activeShiftsConj(g);
Conjugate( activeShifts, activeShiftsConj );
MultiShiftHessSolve
( LOWER, NORMAL, C(1), UAdj_VC_STAR, activeShiftsConj,
activeV_STAR_VR );
activeVList[j+1] = activeV_STAR_VR;
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
{
const double msTime = subtimer.Stop();
const Int numActiveShifts = activeShifts.Height();
const double gflops =
(32.*n*n*numActiveShifts)/(msTime*1.e9);
cout << " MultiShiftHessSolve's: " << msTime
<< " seconds, " << gflops << " GFlops" << endl;
}
}
}
// Orthogonalize with respect to the old iterate
if( j > 0 )
{
ExtractList( HList, components, j, j-1 );
// TODO: Conjugate components?
PlaceList( HList, components, j-1, j );
ColumnSubtractions
( components, activeVList[j-1], activeVList[j+1] );
}
// Orthogonalize with respect to the last iterate
InnerProducts( activeVList[j], activeVList[j+1], components );
PlaceList( HList, components, j, j );
ColumnSubtractions
( components, activeVList[j], activeVList[j+1] );
// Explicitly (re)orthogonalize against all previous vectors
for( Int i=0; i<j-1; ++i )
{
InnerProducts
( activeVList[i], activeVList[j+1], components );
PlaceList( HList, components, i, j );
ColumnSubtractions
( components, activeVList[i], activeVList[j+1] );
}
if( j > 0 )
{
InnerProducts
( activeVList[j-1], activeVList[j+1], components );
UpdateList( HList, components, j-1, j );
ColumnSubtractions
( components, activeVList[j-1], activeVList[j+1] );
}
// Compute the norm of what is left
ColumnNorms( activeVList[j+1], realComponents );
PlaceList( HList, realComponents, j+1, j );
// TODO: Handle lucky breakdowns
InvBetaScale( realComponents, activeVList[j+1] );
ComputeNewEstimates( HList, activeConverged, activeEsts, j+1 );
// We will have the same estimate two iterations in a row when
// restarting
if( j != 0 )
activeConverged =
FindConverged
( lastActiveEsts, activeEsts, activeItCounts, psCtrl.tol );
psCtrl.snapCtrl.Iterate();
}
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
subtimer.Start();
}
Restart( HList, activeConverged, activeVList );
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
cout << "IRA computations: " << subtimer.Stop()
<< " seconds" << endl;
}
const Int numActiveDone = ZeroNorm( activeConverged );
if( deflate )
numDone += numActiveDone;
else
numDone = numActiveDone;
numIts += basisSize;
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
{
const double iterTime = timer.Stop();
cout << "iteration " << numIts << ": " << iterTime
<< " seconds, " << numDone << " of " << numShifts
<< " converged" << endl;
}
}
if( numIts >= maxIts )
break;
if( numDone == numShifts )
break;
else if( deflate && numActiveDone != 0 )
{
Deflate
( activeShifts, activePreimage, activeVList[0], activeEsts,
activeConverged, activeItCounts, progress );
lastActiveEsts = activeEsts;
}
// Save snapshots of the estimates at the requested rate
Snapshot
( preimage, estimates, itCounts, numIts, deflate, psCtrl.snapCtrl );
}
invNorms = estimates;
if( deflate )
RestoreOrdering( preimage, invNorms, itCounts );
FinalSnapshot( invNorms, itCounts, psCtrl.snapCtrl );
return itCounts;
}
template<typename Real>
inline DistMatrix<Int,VR,STAR>
IRA
( const AbstractDistMatrix<Real>& UPre,
const AbstractDistMatrix<Complex<Real>>& shiftsPre,
AbstractDistMatrix<Real>& invNormsPre,
PseudospecCtrl<Real> psCtrl=PseudospecCtrl<Real>() )
{
DEBUG_ONLY(CallStackEntry cse("pspec::IRA"))
using namespace pspec;
typedef Complex<Real> C;
auto UPtr = ReadProxy<Real,MC,MR>( &UPre );
auto& U = *UPtr;
auto shiftsPtr = ReadProxy<C,VR,STAR>( &shiftsPre );
auto& shifts = *shiftsPtr;
auto invNormsPtr = WriteProxy<Real,VR,STAR>( &invNormsPre );
auto& invNorms = *invNormsPtr;
const Int n = U.Height();
const Int numShifts = shifts.Height();
const Grid& g = U.Grid();
const Int maxIts = psCtrl.maxIts;
const Int basisSize = psCtrl.basisSize;
const bool deflate = psCtrl.deflate;
const bool progress = psCtrl.progress;
// Keep track of the number of iterations per shift
DistMatrix<Int,VR,STAR> itCounts(g);
Ones( itCounts, numShifts, 1 );
// Keep track of the pivoting history if deflation is requested
DistMatrix<Int,VR,STAR> preimage(g);
DistMatrix<C, VR,STAR> pivShifts( shifts );
if( deflate )
{
preimage.AlignWith( shifts );
preimage.Resize( numShifts, 1 );
const Int numLocShifts = preimage.LocalHeight();
for( Int iLoc=0; iLoc<numLocShifts; ++iLoc )
{
const Int i = preimage.GlobalRow(iLoc);
preimage.SetLocal( iLoc, 0, i );
}
}
// Simultaneously run IRA for different shifts
vector<DistMatrix<Real>> VRealList(basisSize+1),
VImagList(basisSize+1),
activeVRealList(basisSize+1),
activeVImagList(basisSize+1);
for( Int j=0; j<basisSize+1; ++j )
{
VRealList[j].SetGrid( g );
VImagList[j].SetGrid( g );
Zeros( VRealList[j], n, numShifts );
Zeros( VImagList[j], n, numShifts );
}
// The variance will be off from that of the usual complex case
Gaussian( VRealList[0], n, numShifts );
Gaussian( VImagList[0], n, numShifts );
const Int numMRShifts = VRealList[0].LocalWidth();
vector<Matrix<Complex<Real>>> HList(numMRShifts);
Matrix<Real> realComponents;
Matrix<Complex<Real>> components;
DistMatrix<Int,MR,STAR> activeConverged(g);
Zeros( activeConverged, numShifts, 1 );
psCtrl.snapCtrl.ResetCounts();
Timer timer, subtimer;
Int numIts=0, numDone=0;
DistMatrix<Real,MR,STAR> estimates(g), lastActiveEsts(g);
estimates.AlignWith( shifts );
Zeros( estimates, numShifts, 1 );
DistMatrix<Int,VR,STAR> activePreimage(g);
while( true )
{
const Int numActive = ( deflate ? numShifts-numDone : numShifts );
auto activeShifts = pivShifts( IR(0,numActive), IR(0,1) );
auto activeEsts = estimates( IR(0,numActive), IR(0,1) );
auto activeItCounts = itCounts( IR(0,numActive), IR(0,1) );
for( Int j=0; j<basisSize+1; ++j )
{
View( activeVRealList[j], VRealList[j], IR(0,n), IR(0,numActive) );
View( activeVImagList[j], VImagList[j], IR(0,n), IR(0,numActive) );
}
if( deflate )
{
View( activePreimage, preimage, IR(0,numActive), IR(0,1) );
Zeros( activeConverged, numActive, 1 );
}
HList.resize( activeEsts.LocalHeight() );
for( Int jLoc=0; jLoc<HList.size(); ++jLoc )
Zeros( HList[jLoc], basisSize+1, basisSize );
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
timer.Start();
}
ColumnNorms( activeVRealList[0], activeVImagList[0], realComponents );
InvBetaScale( realComponents, activeVRealList[0] );
InvBetaScale( realComponents, activeVImagList[0] );
for( Int j=0; j<basisSize; ++j )
{
lastActiveEsts = activeEsts;
activeVRealList[j+1] = activeVRealList[j];
activeVImagList[j+1] = activeVImagList[j];
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
subtimer.Start();
}
MultiShiftQuasiTrsm
( LEFT, UPPER, NORMAL, C(1), U, activeShifts,
activeVRealList[j+1], activeVImagList[j+1] );
MultiShiftQuasiTrsm
( LEFT, UPPER, ADJOINT, C(1), U, activeShifts,
activeVRealList[j+1], activeVImagList[j+1] );
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
{
const double msTime = subtimer.Stop();
const Int numActiveShifts = activeShifts.Height();
const double gflops =
(4.*n*n*numActiveShifts)/(msTime*1.e9);
cout << " MultiShiftQuasiTrsm's: " << msTime
<< " seconds, " << gflops << " GFlops" << endl;
}
}
// Orthogonalize with respect to the old iterate
if( j > 0 )
{
ExtractList( HList, components, j, j-1 );
// TODO: Conjugate components?
PlaceList( HList, components, j-1, j );
ColumnSubtractions
( components, activeVRealList[j-1], activeVImagList[j-1],
activeVRealList[j+1], activeVImagList[j+1] );
}
// Orthogonalize with respect to the last iterate
InnerProducts
( activeVRealList[j+0], activeVImagList[j+0],
activeVRealList[j+1], activeVImagList[j+1], components );
PlaceList( HList, components, j, j );
ColumnSubtractions
( components, activeVRealList[j+0], activeVImagList[j+0],
activeVRealList[j+1], activeVImagList[j+1] );
// Explicitly (re)orthogonalize against all previous vectors
for( Int i=0; i<j-1; ++i )
{
InnerProducts
( activeVRealList[i ], activeVImagList[i ],
activeVRealList[j+1], activeVImagList[j+1], components );
PlaceList( HList, components, i, j );
ColumnSubtractions
( components, activeVRealList[i ], activeVImagList[i ],
activeVRealList[j+1], activeVImagList[j+1] );
}
if( j > 0 )
{
InnerProducts
( activeVRealList[j-1], activeVImagList[j-1],
activeVRealList[j+1], activeVImagList[j+1], components );
UpdateList( HList, components, j-1, j );
ColumnSubtractions
( components, activeVRealList[j-1], activeVImagList[j-1],
activeVRealList[j+1], activeVImagList[j+1] );
}
// Compute the norm of what is left
ColumnNorms
( activeVRealList[j+1], activeVImagList[j+1], realComponents );
PlaceList( HList, realComponents, j+1, j );
// TODO: Handle lucky breakdowns
InvBetaScale( realComponents, activeVRealList[j+1] );
InvBetaScale( realComponents, activeVImagList[j+1] );
ComputeNewEstimates( HList, activeConverged, activeEsts, j+1 );
// We will have the same estimate two iterations in a row when
// restarting
if( j != 0 )
activeConverged =
FindConverged
( lastActiveEsts, activeEsts, activeItCounts, psCtrl.tol );
psCtrl.snapCtrl.Iterate();
}
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
subtimer.Start();
}
Restart( HList, activeConverged, activeVRealList, activeVImagList );
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
cout << "IRA computations: " << subtimer.Stop()
<< " seconds" << endl;
}
const Int numActiveDone = ZeroNorm( activeConverged );
if( deflate )
numDone += numActiveDone;
else
numDone = numActiveDone;
numIts += basisSize;
if( progress )
{
mpi::Barrier( g.Comm() );
if( g.Rank() == 0 )
{
const double iterTime = timer.Stop();
cout << "iteration " << numIts << ": " << iterTime
<< " seconds, " << numDone << " of " << numShifts
<< " converged" << endl;
}
}
if( numIts >= maxIts )
break;
if( numDone == numShifts )
break;
else if( deflate && numActiveDone != 0 )
{
Deflate
( activeShifts, activePreimage,
activeVRealList[0], activeVImagList[0], activeEsts,
activeConverged, activeItCounts, progress );
lastActiveEsts = activeEsts;
}
// Save snapshots of the estimates at the requested rate
Snapshot
( preimage, estimates, itCounts, numIts, deflate, psCtrl.snapCtrl );
}
invNorms = estimates;
if( deflate )
RestoreOrdering( preimage, invNorms, itCounts );
FinalSnapshot( invNorms, itCounts, psCtrl.snapCtrl );
return itCounts;
}
} // namespace pspec
} // namespace El
#endif // ifndef EL_PSEUDOSPECTRA_IRA_HPP
| 43,016 | 13,676 |
#include "storage.h"
using namespace core;
Storage::Storage() :
Object()
{
LOGGER_FUNCTION_BEGIN;
LOGGER_DEBUG("New %s", __FUNCTION__);
try {
// set props defaults
Add(AttributeBool::New(CKA_TOKEN, false, PVF_13));
Add(AttributeBool::New(CKA_PRIVATE, false, PVF_13));
Add(AttributeBool::New(CKA_MODIFIABLE, true, PVF_13));
Add(AttributeBytes::New(CKA_LABEL, NULL, 0, PVF_8)); // PVF_8 - no in spec
Add(AttributeBool::New(CKA_COPYABLE, true, PVF_12));
}
CATCH_EXCEPTION
} | 545 | 210 |
//
// Created by jaredhuang on 2021/02/23.
//
#include "HttpDnsBridge.h"
#ifdef __cplusplus
extern "C" {
#endif
// 初始化,主要是如果用了命名空间会变成_ZN3mna9MnaBridge12MNASetBridgeEPFiPKcE之类的格式
__attribute__ ((visibility ("default"))) HTTPDNSSendToUnity HTTPDNSGetBridge() {
return self_dns::HttpDnsBridge::HTTPDNSGetBridge();
}
__attribute__ ((visibility ("default"))) void HTTPDNSSetBridge(HTTPDNSSendToUnity bridge) {
self_dns::HttpDnsBridge::HTTPDNSSetBridge(bridge);
}
#ifdef __cplusplus
}
#endif
HTTPDNSSendToUnity self_dns::HttpDnsBridge::httpDnsSendToUnity = 0;
void self_dns::HttpDnsBridge::HTTPDNSSetBridge(HTTPDNSSendToUnity bridge) {
self_dns::HttpDnsBridge::httpDnsSendToUnity = bridge;
}
HTTPDNSSendToUnity self_dns::HttpDnsBridge::HTTPDNSGetBridge() {
return self_dns::HttpDnsBridge::httpDnsSendToUnity;
} | 859 | 378 |
// Copy of AbilityTask_WaitAttributeChange that passes the old and new values on change
#include "Tasks/GASExtAT_WaitAttributeChangeWithValues.h"
#include <AbilitySystemComponent.h>
#include <AbilitySystemGlobals.h>
#include <GameplayEffectExtension.h>
UGASExtAT_WaitAttributeChangeWithValues::UGASExtAT_WaitAttributeChangeWithValues( const FObjectInitializer & object_initializer ) :
Super( object_initializer )
{
bTriggerOnce = false;
ComparisonType = EGASExtWaitAttributeChangeComparisonType::None;
ComparisonValue = 0.0f;
ExternalOwner = nullptr;
}
UGASExtAT_WaitAttributeChangeWithValues * UGASExtAT_WaitAttributeChangeWithValues::WaitForAttributeChangeWithValues( UGameplayAbility * owning_ability, FGameplayAttribute attribute, FGameplayTag with_src_tag, FGameplayTag without_src_tag, bool trigger_once, AActor * optional_external_owner )
{
UGASExtAT_WaitAttributeChangeWithValues * my_obj = NewAbilityTask< UGASExtAT_WaitAttributeChangeWithValues >( owning_ability );
my_obj->WithTag = with_src_tag;
my_obj->WithoutTag = without_src_tag;
my_obj->Attribute = attribute;
my_obj->ComparisonType = EGASExtWaitAttributeChangeComparisonType::None;
my_obj->bTriggerOnce = trigger_once;
my_obj->ExternalOwner = optional_external_owner ? UAbilitySystemGlobals::GetAbilitySystemComponentFromActor( optional_external_owner ) : nullptr;
return my_obj;
}
UGASExtAT_WaitAttributeChangeWithValues * UGASExtAT_WaitAttributeChangeWithValues::WaitForAttributeChangeWithComparisonAndValues( UGameplayAbility * owning_ability, FGameplayAttribute in_attribute, FGameplayTag in_with_tag, FGameplayTag in_without_tag, EGASExtWaitAttributeChangeComparisonType in_comparison_type, float in_comparison_value, bool trigger_once, AActor * optional_external_owner )
{
UGASExtAT_WaitAttributeChangeWithValues * my_obj = NewAbilityTask< UGASExtAT_WaitAttributeChangeWithValues >( owning_ability );
my_obj->WithTag = in_with_tag;
my_obj->WithoutTag = in_without_tag;
my_obj->Attribute = in_attribute;
my_obj->ComparisonType = in_comparison_type;
my_obj->ComparisonValue = in_comparison_value;
my_obj->bTriggerOnce = trigger_once;
my_obj->ExternalOwner = optional_external_owner ? UAbilitySystemGlobals::GetAbilitySystemComponentFromActor( optional_external_owner ) : nullptr;
return my_obj;
}
void UGASExtAT_WaitAttributeChangeWithValues::Activate()
{
if ( UAbilitySystemComponent * asc = GetFocusedASC() )
{
OnAttributeChangeDelegateHandle = asc->GetGameplayAttributeValueChangeDelegate( Attribute ).AddUObject( this, &UGASExtAT_WaitAttributeChangeWithValues::OnAttributeChange );
}
}
void UGASExtAT_WaitAttributeChangeWithValues::OnAttributeChange( const FOnAttributeChangeData & callback_data )
{
const float new_value = callback_data.NewValue;
const float old_value = callback_data.OldValue;
const FGameplayEffectModCallbackData * data = callback_data.GEModData;
if ( data == nullptr )
{
// There may be no execution data associated with this change, for example a GE being removed.
// In this case, we auto fail any WithTag requirement and auto pass any WithoutTag requirement
if ( WithTag.IsValid() )
{
return;
}
}
else
{
if ( ( WithTag.IsValid() && !data->EffectSpec.CapturedSourceTags.GetAggregatedTags()->HasTag( WithTag ) ) ||
( WithoutTag.IsValid() && data->EffectSpec.CapturedSourceTags.GetAggregatedTags()->HasTag( WithoutTag ) ) )
{
// Failed tag check
return;
}
}
bool passed_comparison = true;
switch ( ComparisonType )
{
case EGASExtWaitAttributeChangeComparisonType::ExactlyEqualTo:
passed_comparison = ( new_value == ComparisonValue );
break;
case EGASExtWaitAttributeChangeComparisonType::GreaterThan:
passed_comparison = ( new_value > ComparisonValue );
break;
case EGASExtWaitAttributeChangeComparisonType::GreaterThanOrEqualTo:
passed_comparison = ( new_value >= ComparisonValue );
break;
case EGASExtWaitAttributeChangeComparisonType::LessThan:
passed_comparison = ( new_value < ComparisonValue );
break;
case EGASExtWaitAttributeChangeComparisonType::LessThanOrEqualTo:
passed_comparison = ( new_value <= ComparisonValue );
break;
case EGASExtWaitAttributeChangeComparisonType::NotEqualTo:
passed_comparison = ( new_value != ComparisonValue );
break;
default:
break;
}
if ( passed_comparison )
{
if ( ShouldBroadcastAbilityTaskDelegates() )
{
OnChange.Broadcast( old_value, new_value );
}
if ( bTriggerOnce )
{
EndTask();
}
}
}
UAbilitySystemComponent * UGASExtAT_WaitAttributeChangeWithValues::GetFocusedASC()
{
return ExternalOwner ? ExternalOwner : AbilitySystemComponent;
}
void UGASExtAT_WaitAttributeChangeWithValues::OnDestroy( bool ability_ended )
{
if ( UAbilitySystemComponent * asc = GetFocusedASC() )
{
asc->GetGameplayAttributeValueChangeDelegate( Attribute ).Remove( OnAttributeChangeDelegateHandle );
}
Super::OnDestroy( ability_ended );
}
| 5,495 | 1,607 |
extern "C"
{
#include <psp2/libdbg.h>
}
#include <sstream>
#include <vector>
#include "EGL/eglInstance.h"
#include "ES/buffer.h"
#include "ES/program.h"
#include "ES/texture.h"
#include "gfx/text_renderer.h"
#include "io.h"
#include "logger.h"
EGLInstance::EGLInstance(Logger* in_logger_ptr)
:m_display (nullptr),
m_egl_config_ptr (nullptr),
m_egl_context (nullptr),
m_egl_surface (nullptr),
m_gl_extensions_ptr(nullptr),
m_logger_ptr (in_logger_ptr),
m_never_bound (true)
{
/* Stub */
}
EGLInstance::~EGLInstance()
{
m_text_renderer_ptr.reset();
if (m_egl_context != nullptr)
{
::eglDestroyContext(m_display,
m_egl_context);
}
if (m_egl_surface != nullptr)
{
::eglDestroySurface(m_display,
m_egl_surface);
}
}
bool EGLInstance::bind_to_current_thread()
{
bool result = false;
result = ::eglMakeCurrent(m_display,
m_egl_surface,
m_egl_surface,
m_egl_context) == EGL_TRUE;
if (m_never_bound)
{
/* Log base GL info & available GL extensions. */
auto es_extensions_ptr = ::eglQueryString(m_display,
EGL_EXTENSIONS);
auto renderer_ptr = ::glGetString (GL_RENDERER);
auto vendor_ptr = ::glGetString (GL_VENDOR);
auto version_ptr = ::glGetString (GL_VERSION);
m_gl_extensions_ptr = reinterpret_cast<const char*>(::glGetString(GL_EXTENSIONS) );
#if 0
m_logger_ptr->log(false, /* in_flush_and_wait */
"Renderer version: %s\n"
"Renderer: %s\n"
"Vendor: %s\n",
version_ptr,
renderer_ptr,
vendor_ptr);
m_logger_ptr->log(false, /* in_flush_and_wait */
"ES Extensions: %s\n",
es_extensions_ptr);
m_logger_ptr->log(false, /* in_flush_and_wait */
"GL Extensions: %s\n",
m_gl_extensions_ptr);
#endif
/* Init extension entrypoints */
if (strstr(m_gl_extensions_ptr,
"GL_EXT_draw_instanced") != nullptr)
{
const ExtensionEntrypoint entrypoints[] =
{
{"glDrawArraysInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_draw_instanced.glDrawArraysInstancedEXT)},
{"glDrawElementsInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_draw_instanced.glDrawElementsInstancedEXT)},
};
if (!init_extension_entrypoints(entrypoints,
sizeof(entrypoints) / sizeof(entrypoints[0])) )
{
SCE_DBG_ASSERT(false);
result = false;
goto end;
}
}
if (strstr(m_gl_extensions_ptr,
"GL_EXT_instanced_arrays") != nullptr)
{
const ExtensionEntrypoint entrypoints[] =
{
{"glDrawArraysInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_instanced_arrays.glDrawArraysInstancedEXT)},
{"glDrawElementsInstancedEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_instanced_arrays.glDrawElementsInstancedEXT)},
{"glVertexAttribDivisorEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_instanced_arrays.glVertexAttribDivisorEXT)},
};
if (!init_extension_entrypoints(entrypoints,
sizeof(entrypoints) / sizeof(entrypoints[0])) )
{
SCE_DBG_ASSERT(false);
result = false;
goto end;
}
}
if (strstr(m_gl_extensions_ptr,
"GL_EXT_texture_storage") != nullptr)
{
const ExtensionEntrypoint entrypoints[] =
{
{"glTexStorage2DEXT", reinterpret_cast<void**>(&m_entrypoints_gl_ext_texture_storage.glTexStorage2DEXT)},
};
if (!init_extension_entrypoints(entrypoints,
sizeof(entrypoints) / sizeof(entrypoints[0])) )
{
SCE_DBG_ASSERT(false);
result = false;
goto end;
}
}
if (strstr(m_gl_extensions_ptr,
"GL_SCE_piglet_shader_binary") != nullptr)
{
const ExtensionEntrypoint entrypoints[] =
{
{"glPigletGetShaderBinarySCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_piglet_shader_binary.glPigletGetShaderBinarySCE) },
};
if (!init_extension_entrypoints(entrypoints,
sizeof(entrypoints) / sizeof(entrypoints[0])) )
{
SCE_DBG_ASSERT(false);
result = false;
goto end;
}
}
if (strstr(m_gl_extensions_ptr,
"GL_SCE_texture_resource") != nullptr)
{
const ExtensionEntrypoint entrypoints[] =
{
{"glMapTextureResourceSCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_texture_resource_entrypoints.glMapTextureResourceSCE)},
{"glTexImageResourceSCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_texture_resource_entrypoints.glTexImageResourceSCE)},
{"glUnmapTextureResourceSCE", reinterpret_cast<void**>(&m_entrypoints_gl_sce_texture_resource_entrypoints.glUnmapTextureResourceSCE)},
};
if (!init_extension_entrypoints(entrypoints,
sizeof(entrypoints) / sizeof(entrypoints[0])) )
{
SCE_DBG_ASSERT(false);
result = false;
goto end;
}
}
/* Init text renderer */
m_text_renderer_ptr = TextRenderer::create(this,
m_logger_ptr);
SCE_DBG_ASSERT(m_text_renderer_ptr != nullptr);
/* Done */
m_never_bound = false;
}
SCE_DBG_ASSERT(result);
end:
return result;
}
std::unique_ptr<EGLInstance> EGLInstance::create(Logger* in_logger_ptr,
const bool& in_require_depth_buffer,
const bool& in_require_stencil_buffer)
{
std::unique_ptr<EGLInstance> result_ptr;
result_ptr.reset(
new EGLInstance(in_logger_ptr)
);
SCE_DBG_ASSERT(result_ptr != nullptr);
if (result_ptr != nullptr)
{
if (!result_ptr->init(in_require_depth_buffer,
in_require_stencil_buffer) )
{
SCE_DBG_ASSERT(false);
result_ptr.reset();
}
}
return result_ptr;
}
const EXTDrawInstancedEntrypoints* EGLInstance::get_ext_draw_instanced_entrypoints_ptr() const
{
return &m_entrypoints_gl_ext_draw_instanced;
}
const EXTInstancedArraysEntrypoints* EGLInstance::get_ext_instanced_arrays_entrypoints_ptr() const
{
return &m_entrypoints_gl_ext_instanced_arrays;
}
const EXTTextureStorageEntrypoints* EGLInstance::get_ext_texture_storage_entrypoints_ptr() const
{
return &m_entrypoints_gl_ext_texture_storage;
}
const uint32_t* EGLInstance::get_rt_extents_wh() const
{
static const uint32_t rt[] = {960, 544};
return rt;
}
const SCEPigletShaderBinaryEntrypoints* EGLInstance::get_sce_piglet_shader_binary_entrypoints_ptr() const
{
return &m_entrypoints_gl_sce_piglet_shader_binary;
}
const SCETextureResourceEntrypoints* EGLInstance::get_sce_texture_resource_entrypoints_ptr() const
{
return &m_entrypoints_gl_sce_texture_resource_entrypoints;
}
TextRenderer* EGLInstance::get_text_renderer_ptr() const
{
SCE_DBG_ASSERT(m_text_renderer_ptr != nullptr);
return m_text_renderer_ptr.get();
}
bool EGLInstance::init(const bool& in_require_depth_buffer,
const bool& in_require_stencil_buffer)
{
EGLBoolean result;
m_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
SCE_DBG_ASSERT(m_display != EGL_NO_DISPLAY);
result = eglInitialize(m_display,
nullptr, /* major */
nullptr); /* minor */
SCE_DBG_ASSERT(result == EGL_TRUE);
/* Enumerate available EGL configs */
{
std::vector<EGLConfig> egl_config_vec;
EGLint n_egl_configs = 0;
result = eglGetConfigs(m_display,
nullptr, /* configs */
0, /* config_size */
&n_egl_configs);
SCE_DBG_ASSERT(result == EGL_TRUE);
egl_config_vec.resize (n_egl_configs);
m_egl_config_vec.resize(n_egl_configs);
result = eglGetConfigs(m_display,
egl_config_vec.data(),
n_egl_configs,
&n_egl_configs);
SCE_DBG_ASSERT(result == EGL_TRUE);
for (uint32_t n_egl_config = 0;
n_egl_config < n_egl_configs;
++n_egl_config)
{
const auto current_egl_config = egl_config_vec.at (n_egl_config);
auto& current_egl_config_props = m_egl_config_vec.at(n_egl_config);
current_egl_config_props.egl_config = current_egl_config;
const struct
{
EGLint attribute;
EGLint* result_ptr;
} config_attribs[] =
{
{EGL_ALPHA_SIZE, ¤t_egl_config_props.n_alpha_bits},
{EGL_BLUE_SIZE, ¤t_egl_config_props.n_blue_bits},
{EGL_CONFIG_ID, ¤t_egl_config_props.egl_config_id},
{EGL_DEPTH_SIZE, ¤t_egl_config_props.n_depth_bits},
{EGL_GREEN_SIZE, ¤t_egl_config_props.n_green_bits},
{EGL_RED_SIZE, ¤t_egl_config_props.n_red_bits},
{EGL_STENCIL_SIZE, ¤t_egl_config_props.n_stencil_bits}
};
for (const auto& current_config_attrib : config_attribs)
{
result = eglGetConfigAttrib(m_display,
current_egl_config,
current_config_attrib.attribute,
current_config_attrib.result_ptr);
SCE_DBG_ASSERT(result == EGL_TRUE);
}
}
}
/* On 3.60, we are reported 3 different configs, the only difference between the three being presence (or lack)
* of depth and/or stencil buffer.
*
* Pick the right EGLConfig instance, depending on the input arguments.
**/
{
uint32_t best_score = 0xFFFFFFFFu;
for (const auto& current_egl_config : m_egl_config_vec)
{
uint32_t score = 0;
if (( in_require_depth_buffer && current_egl_config.n_depth_bits != 0) ||
(!in_require_depth_buffer && current_egl_config.n_depth_bits == 0) )
{
++score;
}
if (( in_require_stencil_buffer && current_egl_config.n_stencil_bits != 0) ||
(!in_require_stencil_buffer && current_egl_config.n_stencil_bits == 0) )
{
++score;
}
if ((best_score == 0xFFFFFFFFu) ||
(best_score < score) )
{
best_score = score;
m_egl_config_ptr = ¤t_egl_config;
}
}
}
SCE_DBG_ASSERT(m_egl_config_ptr != nullptr);
/* Create an ES context. */
{
static const EGLint attrib_list[] =
{
EGL_CONTEXT_MAJOR_VERSION, 2,
EGL_CONTEXT_MINOR_VERSION, 0,
EGL_NONE
};
m_egl_context = eglCreateContext(m_display,
m_egl_config_ptr->egl_config,
EGL_NO_CONTEXT, /* share_context */
attrib_list);
SCE_DBG_ASSERT(m_egl_context != EGL_NO_CONTEXT);
}
/* Create a rendering surface.
*
* NOTE: If the resolution is ever changed, make sure to update get_rt_extents_wh() too.
**/
m_egl_surface = eglCreateWindowSurface(m_display,
m_egl_config_ptr->egl_config,
VITA_WINDOW_960X544,
nullptr); /* attrib_list */
SCE_DBG_ASSERT(m_egl_surface != EGL_NO_SURFACE);
/* NOTE: Do not bind the context to the calling thread. It is caller's responsibility to invoke bind()
* from the right thread later on.
*/
return (m_egl_context != nullptr &&
m_egl_surface != nullptr);
}
bool EGLInstance::init_extension_entrypoints(const ExtensionEntrypoint* in_ext_entrypoint_ptr,
const uint32_t& in_n_ext_entrypoints)
{
bool result = false;
for (uint32_t n_entrypoint = 0;
n_entrypoint < in_n_ext_entrypoints;
++n_entrypoint)
{
const auto& current_entrypoint = in_ext_entrypoint_ptr[n_entrypoint];
*current_entrypoint.func_ptr_ptr = reinterpret_cast<void*>(::eglGetProcAddress(current_entrypoint.func_name_ptr) );
if (*current_entrypoint.func_ptr_ptr == nullptr)
{
SCE_DBG_ASSERT(false);
goto end;
}
}
result = true;
end:
return result;
}
void EGLInstance::swap_buffers()
{
::eglSwapBuffers(m_display,
m_egl_surface);
} | 14,159 | 4,413 |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ll N;
cin >> N;
ll L = 0, X = 1;
while (N - X >= 0) {
N -= X;
L++;
X *= 26;
}
string ans(L, 'a');
for (int i = L - 1; i >= 0; i--) {
ans[i] += N % 26;
N /= 26;
}
cout << ans << endl;
return 0;
}
| 298 | 167 |
/*
* Copyright 2011 Wolfgang Koller - http://www.gofg.at/
*
* 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"device.h"
#include "../pluginregistry.h"
#if QT_VERSION < 0x050000
#include <QSystemDeviceInfo>
#include <QSystemInfo>
#else
#include <QDeviceInfo>
#include <QtSystemInfo>
#endif
#include <QDebug>
#define CORDOVA "2.2.0"
#ifdef QTM_NAMESPACE
QTM_USE_NAMESPACE
#endif
// Create static instance of ourself
Device* Device::m_device = new Device();
/**
* Constructor - NOTE: Never do anything except registering the plugin
*/
Device::Device() : CPlugin() {
PluginRegistry::getRegistry()->registerPlugin( "com.cordova.Device", this );
}
/**
* Called by the javascript constructor in order to receive all required device info(s)
*/
void Device::getInfo( int scId, int ecId ) {
Q_UNUSED(ecId)
#if QT_VERSION < 0x050000
QSystemDeviceInfo *systemDeviceInfo = new QSystemDeviceInfo(this);
QSystemInfo *systemInfo = new QSystemInfo(this);
#else
QDeviceInfo *systemDeviceInfo = new QDeviceInfo(this);
QDeviceInfo *systemInfo = new QDeviceInfo(this);
#endif
#ifdef Q_OS_SYMBIAN
QString platform = "Symbian";
#endif
#ifdef Q_OS_WIN
QString platform = "Windows";
#endif
#ifdef Q_OS_WINCE
QString platform = "Windows CE";
#endif
#ifdef Q_OS_LINUX
QString platform = "Linux";
#endif
#if QT_VERSION < 0x050000
this->callback( scId, "'" + systemDeviceInfo->model() + "', '" + CORDOVA + "', '" + platform + "', '" + systemDeviceInfo->uniqueDeviceID() + "', '" + systemInfo->version( QSystemInfo::Os ) + "'" );
#else
qDebug() << Q_FUNC_INFO << ":" << systemInfo->imei(0) << "; " << systemInfo->manufacturer() << "; " << systemInfo->model() << "; " << systemInfo->productName() << "; " << systemInfo->uniqueDeviceID() << "; " << systemInfo->version(QDeviceInfo::Os) << "; " << systemInfo->version(QDeviceInfo::Firmware);
this->callback( scId, "'" + systemDeviceInfo->model() + "', '" + CORDOVA + "', '" + platform + "', '" + systemDeviceInfo->uniqueDeviceID() + "', '" + systemInfo->version( QDeviceInfo::Os ) + "'" );
#endif
}
| 2,614 | 884 |
/*
* GDevelop Core
* Copyright 2008-2016 Florian Rival (Florian.Rival@gmail.com). All rights
* reserved. This project is released under the MIT License.
*/
#include "GDCore/IDE/Events/EventsBehaviorRenamer.h"
#include <map>
#include <memory>
#include <vector>
#include "GDCore/Events/Event.h"
#include "GDCore/Events/EventsList.h"
#include "GDCore/Events/Parsers/ExpressionParser2.h"
#include "GDCore/Events/Parsers/ExpressionParser2NodePrinter.h"
#include "GDCore/Events/Parsers/ExpressionParser2NodeWorker.h"
#include "GDCore/Extensions/Metadata/MetadataProvider.h"
#include "GDCore/Extensions/Metadata/ParameterMetadataTools.h"
#include "GDCore/IDE/Events/ExpressionValidator.h"
#include "GDCore/Project/Layout.h"
#include "GDCore/Project/Project.h"
#include "GDCore/String.h"
#include "GDCore/Tools/Log.h"
namespace gd {
/**
* \brief Go through the nodes and rename any reference to an object behavior.
*
* \see gd::ExpressionParser2
*/
class GD_CORE_API ExpressionBehaviorRenamer
: public ExpressionParser2NodeWorker {
public:
ExpressionBehaviorRenamer(const gd::ObjectsContainer& globalObjectsContainer_,
const gd::ObjectsContainer& objectsContainer_,
const gd::String& objectName_,
const gd::String& oldBehaviorName_,
const gd::String& newBehaviorName_)
: hasDoneRenaming(false),
globalObjectsContainer(globalObjectsContainer_),
objectsContainer(objectsContainer_),
objectName(objectName_),
oldBehaviorName(oldBehaviorName_),
newBehaviorName(newBehaviorName_){};
virtual ~ExpressionBehaviorRenamer(){};
bool HasDoneRenaming() const { return hasDoneRenaming; }
protected:
void OnVisitSubExpressionNode(SubExpressionNode& node) override {
node.expression->Visit(*this);
}
void OnVisitOperatorNode(OperatorNode& node) override {
node.leftHandSide->Visit(*this);
node.rightHandSide->Visit(*this);
}
void OnVisitUnaryOperatorNode(UnaryOperatorNode& node) override {
node.factor->Visit(*this);
}
void OnVisitNumberNode(NumberNode& node) override {}
void OnVisitTextNode(TextNode& node) override {}
void OnVisitVariableNode(VariableNode& node) override {
if (node.child) node.child->Visit(*this);
}
void OnVisitVariableAccessorNode(VariableAccessorNode& node) override {
if (node.child) node.child->Visit(*this);
}
void OnVisitVariableBracketAccessorNode(
VariableBracketAccessorNode& node) override {
node.expression->Visit(*this);
if (node.child) node.child->Visit(*this);
}
void OnVisitIdentifierNode(IdentifierNode& node) override {}
void OnVisitObjectFunctionNameNode(ObjectFunctionNameNode& node) override {
if (!node.behaviorFunctionName.empty()) {
// Behavior function name
if (node.objectName == objectName && node.objectFunctionOrBehaviorName == oldBehaviorName) {
node.objectFunctionOrBehaviorName = newBehaviorName;
hasDoneRenaming = true;
}
}
}
void OnVisitFunctionCallNode(FunctionCallNode& node) override {
if (!node.behaviorName.empty()) {
// Behavior function call
if (node.objectName == objectName && node.behaviorName == oldBehaviorName) {
node.behaviorName = newBehaviorName;
hasDoneRenaming = true;
}
}
for (auto& parameter : node.parameters) {
parameter->Visit(*this);
}
}
void OnVisitEmptyNode(EmptyNode& node) override {}
private:
bool hasDoneRenaming;
const gd::ObjectsContainer& globalObjectsContainer;
const gd::ObjectsContainer& objectsContainer;
const gd::String& objectName; // The object name for which the behavior
// must be replaced.
const gd::String& oldBehaviorName;
const gd::String& newBehaviorName;
};
bool EventsBehaviorRenamer::DoVisitInstruction(gd::Instruction& instruction,
bool isCondition) {
const auto& metadata = isCondition
? gd::MetadataProvider::GetConditionMetadata(
platform, instruction.GetType())
: gd::MetadataProvider::GetActionMetadata(
platform, instruction.GetType());
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
instruction.GetParameters(),
metadata.GetParameters(),
[&](const gd::ParameterMetadata& parameterMetadata,
const gd::String& parameterValue,
size_t parameterIndex,
const gd::String& lastObjectName) {
const gd::String& type = parameterMetadata.type;
if (gd::ParameterMetadata::IsBehavior(type)) {
if (lastObjectName == objectName) {
if (parameterValue == oldBehaviorName) {
instruction.SetParameter(parameterIndex,
gd::Expression(newBehaviorName));
}
}
} else {
gd::ExpressionParser2 parser(
platform, GetGlobalObjectsContainer(), GetObjectsContainer());
auto node =
gd::ParameterMetadata::IsExpression("number", type)
? parser.ParseExpression("number", parameterValue)
: (gd::ParameterMetadata::IsExpression("string", type)
? parser.ParseExpression("string", parameterValue)
: std::unique_ptr<gd::ExpressionNode>());
if (node) {
ExpressionBehaviorRenamer renamer(GetGlobalObjectsContainer(),
GetObjectsContainer(),
objectName,
oldBehaviorName,
newBehaviorName);
node->Visit(renamer);
if (renamer.HasDoneRenaming()) {
instruction.SetParameter(
parameterIndex,
ExpressionParser2NodePrinter::PrintNode(*node));
}
}
}
});
return false;
}
EventsBehaviorRenamer::~EventsBehaviorRenamer() {}
} // namespace gd
| 6,213 | 1,660 |
#include"net/Server.h"
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include"base/Util.h"
Server::Server(Eventloop* loop,int threadnum,uint16_t port)
:loop_(loop),
threadnum_(threadnum),
eventloopthreadpool_(new Eventloopthreadpool(loop_,threadnum_)),
started_(false),
port_(port),
listenfd_(socket_bind_and_listen(port_)),
acceptchannel_(new Channel(loop_,listenfd_)),
nextconnid_(0)
{
//SIGPIPE
if(setSocketNonBlocking(listenfd_) < 0)
{
perror("set nonblock error");
abort();
}
}
void Server::start()
{
if(!started_)
{
eventloopthreadpool_->start();
acceptchannel_->set_events(EPOLLIN|EPOLLET);
acceptchannel_->setreadcallback(bind(&Server::newconnection,this));
loop_->addchannel(acceptchannel_);
started_ = true;
}
}
void Server::newconnection()
{
struct sockaddr_in client_addr;
memset(&client_addr,0,sizeof(struct sockaddr_in));
socklen_t client_addr_len = sizeof(client_addr);
int accept_fd = 0;
while((accept_fd = accept(listenfd_,(struct sockaddr*)&client_addr,&client_addr_len)) > 0 )
{
if(accept_fd >= MAXFDS) //限制并发链接数
{
close(accept_fd);
continue;
}
if(setSocketNonBlocking(accept_fd) < 0)
{
return;
}
setSocketNodelay(accept_fd);
char buf[32];
snprintf(buf,sizeof(buf),"#%d",nextconnid_);
++nextconnid_;
std::string connname = buf;
setSocketNodelay(accept_fd);
Eventloop* ioloop = eventloopthreadpool_->getnextloop();
TcpconnectionPtr conn = make_shared<Tcpconnection>(ioloop,connname,accept_fd); //不使用new by 陈硕??????
connections_[connname] = conn;
conn->setConnectioncallback(connectioncallback_);
conn->setMessagecallback(messagecallback_); //Rpc messagecallback 由connectioncallback 绑定
conn->setClosecallback(std::bind(&Server::removeconnection, this, std::placeholders::_1));//Fixme::unsafe
ioloop->runinloop(std::bind(&Tcpconnection::connectEstablished,conn));
}
}
void Server::removeconnection(const TcpconnectionPtr& conn)
{
loop_->runinloop(std::bind(&Server::removeconnectioninloop,this,conn));
}
void Server::removeconnectioninloop(const TcpconnectionPtr& conn)
{
loop_->assertinloopthread();
size_t n = connections_.erase(conn->name());
assert( n == 1);
Eventloop* ioloop = conn->getloop();
ioloop->queueinloop(std::bind(&Tcpconnection::connectDestroyed,conn));
}
| 2,586 | 867 |
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/PlatformIncl.h>
#include <AzCore/Asset/AssetManagerComponent.h>
#include <AzCore/Component/ComponentApplication.h>
#include <AzCore/Component/ComponentApplicationBus.h>
#include <AzCore/IO/Path/Path.h>
#include <AzCore/Settings/SettingsRegistryMergeUtils.h>
#include <AzCore/IO/Streamer/StreamerComponent.h>
#include <AzCore/Jobs/JobManagerComponent.h>
#include <AzCore/Memory/PoolAllocator.h>
#include <AzCore/UserSettings/UserSettingsComponent.h>
#include <AzFramework/Asset/CustomAssetTypeComponent.h>
#include <AzToolsFramework/UI/PropertyEditor/PropertyManagerComponent.h>
#include <AzQtComponents/Components/GlobalEventFilter.h>
#include <AzQtComponents/Components/StyledDockWidget.h>
#include <AzQtComponents/Components/O3DEStylesheet.h>
#include <AzQtComponents/Utilities/HandleDpiAwareness.h>
#include <AzQtComponents/Components/WindowDecorationWrapper.h>
#include "ComponentDemoWidget.h"
#include <AzCore/Memory/SystemAllocator.h>
#include <QApplication>
#include <QMainWindow>
#include <QSettings>
#include <iostream>
const QString g_ui_1_0_SettingKey = QStringLiteral("useUI_1_0");
static void LogToDebug([[maybe_unused]] QtMsgType Type, [[maybe_unused]] const QMessageLogContext& Context, const QString& message)
{
#ifdef Q_OS_WIN
OutputDebugStringW(L"Qt: ");
OutputDebugStringW(reinterpret_cast<const wchar_t*>(message.utf16()));
OutputDebugStringW(L"\n");
#else
std::wcerr << L"Qt: " << message.toStdWString() << std::endl;
#endif
}
/*
* Sets up and tears down everything we need for an AZ::ComponentApplication.
* This is required for the ReflectedPropertyEditorPage.
*/
class ComponentApplicationWrapper
{
public:
explicit ComponentApplicationWrapper()
{
AZ::ComponentApplication::Descriptor appDesc;
m_systemEntity = m_componentApp.Create(appDesc);
AZ::AllocatorInstance<AZ::PoolAllocator>::Create();
AZ::AllocatorInstance<AZ::ThreadPoolAllocator>::Create();
m_componentApp.RegisterComponentDescriptor(AZ::AssetManagerComponent::CreateDescriptor());
m_componentApp.RegisterComponentDescriptor(AZ::JobManagerComponent::CreateDescriptor());
m_componentApp.RegisterComponentDescriptor(AZ::StreamerComponent::CreateDescriptor());
m_componentApp.RegisterComponentDescriptor(AZ::UserSettingsComponent::CreateDescriptor());
m_componentApp.RegisterComponentDescriptor(AzFramework::CustomAssetTypeComponent::CreateDescriptor());
m_componentApp.RegisterComponentDescriptor(AzToolsFramework::Components::PropertyManagerComponent::CreateDescriptor());
m_systemEntity->CreateComponent<AZ::AssetManagerComponent>();
m_systemEntity->CreateComponent<AZ::JobManagerComponent>();
m_systemEntity->CreateComponent<AZ::StreamerComponent>();
m_systemEntity->CreateComponent<AZ::UserSettingsComponent>();
m_systemEntity->CreateComponent<AzFramework::CustomAssetTypeComponent>();
m_systemEntity->CreateComponent<AzToolsFramework::Components::PropertyManagerComponent>();
m_systemEntity->Init();
m_systemEntity->Activate();
m_serializeContext = m_componentApp.GetSerializeContext();
m_serializeContext->CreateEditContext();
}
~ComponentApplicationWrapper()
{
m_serializeContext->DestroyEditContext();
m_systemEntity->Deactivate();
std::vector<AZ::Component*> components =
{
m_systemEntity->FindComponent<AZ::AssetManagerComponent>(),
m_systemEntity->FindComponent<AZ::JobManagerComponent>(),
m_systemEntity->FindComponent<AZ::StreamerComponent>(),
m_systemEntity->FindComponent<AZ::UserSettingsComponent>(),
m_systemEntity->FindComponent<AzFramework::CustomAssetTypeComponent>(),
m_systemEntity->FindComponent<AzToolsFramework::Components::PropertyManagerComponent>()
};
for (auto component : components)
{
m_systemEntity->RemoveComponent(component);
delete component;
}
m_componentApp.UnregisterComponentDescriptor(AZ::AssetManagerComponent::CreateDescriptor());
m_componentApp.UnregisterComponentDescriptor(AZ::JobManagerComponent::CreateDescriptor());
m_componentApp.UnregisterComponentDescriptor(AZ::StreamerComponent::CreateDescriptor());
m_componentApp.UnregisterComponentDescriptor(AZ::UserSettingsComponent::CreateDescriptor());
m_componentApp.UnregisterComponentDescriptor(AzFramework::CustomAssetTypeComponent::CreateDescriptor());
m_componentApp.UnregisterComponentDescriptor(AzToolsFramework::Components::PropertyManagerComponent::CreateDescriptor());
AZ::AllocatorInstance<AZ::ThreadPoolAllocator>::Destroy();
AZ::AllocatorInstance<AZ::PoolAllocator>::Destroy();
m_componentApp.Destroy();
}
private:
// ComponentApplication must not be a pointer - it cannot be dynamically allocated
AZ::ComponentApplication m_componentApp;
AZ::Entity* m_systemEntity = nullptr;
AZ::SerializeContext* m_serializeContext = nullptr;
};
int main(int argc, char **argv)
{
ComponentApplicationWrapper componentApplicationWrapper;
QApplication::setOrganizationName("O3DE");
QApplication::setOrganizationDomain("o3de.org");
QApplication::setApplicationName("O3DEWidgetGallery");
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
qInstallMessageHandler(LogToDebug);
AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::PerScreenDpiAware);
QApplication app(argc, argv);
auto globalEventFilter = new AzQtComponents::GlobalEventFilter(&app);
app.installEventFilter(globalEventFilter);
AzQtComponents::StyleManager styleManager(&app);
AZ::IO::FixedMaxPath engineRootPath;
if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
{
settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
}
styleManager.initialize(&app, engineRootPath);
auto wrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionNone);
auto widget = new ComponentDemoWidget(wrapper);
wrapper->setGuest(widget);
widget->resize(550, 900);
widget->show();
wrapper->enableSaveRestoreGeometry("windowGeometry");
wrapper->restoreGeometryFromSettings();
QObject::connect(widget, &ComponentDemoWidget::refreshStyle, &styleManager, [&styleManager]() {
styleManager.Refresh();
});
app.setQuitOnLastWindowClosed(true);
app.exec();
}
| 7,118 | 1,976 |
/*
//
// Draw multiple thick lines on the image
//
// Inputs:
// InputImg: Input image (Grayscale or Color)
// CoordPnt: Coordinates of end points of lines [r1 r2 c1 c2]
// (n x 4 double array, n: # of lines)
// Thickness: Thickness of lines (The value is integer, but the type is double.)
// (n x 1 double array, n: # of lines)
// LineColor: Line colors (The values should be integers from 0 to 255)
// (n x 4 double array, n: # of lines)
// (Data type: double, ex. [255 255 255]: white )
// (The channels of 'InputImg' and 'LineColor' should be consistent)
//
//
// Outputs:
// OutputImg: Output image (The same format with InputImg)
//
//
// Copyright, Gunhee Kim (gunhee@cs.cmu.edu)
// Computer Science Department, Carnegie Mellon University,
// October 19 2009
*/
#include <mex.h>
#include <math.h>
//#include <string.h>
#define UINT8 unsigned char
#define UINT32 unsigned int
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define pow2(x) ((x)*(x))
void Bresenham(int x1, int x2, int y1, int yt) ;
void plot(int x1, int y1) ;
void draw_thick_line(int x1, int x2, int y1, int y2) ;
double *LineColor, *LineThickness ;
UINT8 *OutputImg ;
int nPnt, nChannel, indLine ;
int dimR, dimC, nDim ;
void mexFunction(
int nlhs, // Number of left hand side (output) arguments
mxArray *plhs[], // Array of left hand side arguments
int nrhs, // Number of right hand side (input) arguments
const mxArray *prhs[] // Array of right hand side arguments
) {
UINT8 *InputImg ;
double *CoordPnt, *InCoord ;
int i, dimPnt, add_r1, add_r2, add_c1, add_c2 ;
/* Check for proper number of arguments. */
if (nrhs <4)
{
mexErrMsgTxt("Four inputs are required.");
}
else if (nlhs > 1)
{
mexErrMsgTxt("Too many output assigned.");
}
InputImg = (UINT8 *)mxGetPr(prhs[0]); // Input image (Data type: uint8*)
InCoord = (double *) mxGetPr(prhs[1]); // [r1 r2 c1 c2] (Data type: double*)
nPnt = (int) mxGetM(prhs[1]);
dimPnt = (int) mxGetN(prhs[1]);
LineThickness = (double *)mxGetPr(prhs[2]); // Line Thickness (Data type: double*)
LineColor = (double *)mxGetPr(prhs[3]); // Line color (Data type: double*)
nChannel = (int)mxGetN(prhs[3]);
// Dimensions of input image
dimR = (int)mxGetM(prhs[0]);
dimC = (int)mxGetN(prhs[0]);
nDim = (int)mxGetNumberOfDimensions(prhs[0]);
/*
// If the channels of Input image and line color are different, terminate it.
if (((nDim==2) && (nChannel==3)) || ((nDim==3) && (nChannel==1)) ) {
mexErrMsgTxt("The channels of Input image and line color are different !");
}
*/
// If the input image is color image
if(nChannel==3)
dimC = dimC/nChannel;
//mexPrintf("%d %d %d %d %d %d\n", nChannel, dimR, dimC, nDim, dimPnt, nPnt) ;
// Set output
plhs[0] = mxCreateNumericArray(mxGetNumberOfDimensions(prhs[0]),
mxGetDimensions(prhs[0]),mxUINT8_CLASS,mxREAL);
OutputImg = (UINT8*)mxGetPr(plhs[0]);
// copy InputImg to OutputImg
for (i=0; i<dimR*dimC*nChannel; i++)
OutputImg[i] = InputImg[i] -1 ;
// decrease coordinates by 1
CoordPnt = (double *) mxCalloc(nPnt*dimPnt, sizeof(double));
// If the coordinate< 0 or > image dimension, reduce it.
for (i=0; i<nPnt*dimPnt/2; i++)
{
CoordPnt[i] = InCoord[i] -1 ;
if (CoordPnt[i]<0) CoordPnt[i] = 0 ;
if (CoordPnt[i]>dimR) CoordPnt[i] = dimR ;
}
for (i=nPnt*dimPnt/2; i<nPnt*dimPnt; i++)
{
CoordPnt[i] = InCoord[i] -1 ;
if (CoordPnt[i]<0) CoordPnt[i] = 0 ;
if (CoordPnt[i]>dimC) CoordPnt[i] = dimC ;
}
// adding indices for each dim.
add_r1 = 0 ;
add_r2 = nPnt ;
add_c1 = 2*nPnt ;
add_c2 = 3*nPnt ;
// Main loop
for (i=0; i<nPnt; i++) {
// lineIdx
indLine = i ;
draw_thick_line((int)CoordPnt[i+add_c1], // c1 = x1
(int)CoordPnt[i+add_c2], // c2 = x2
(int)CoordPnt[i+add_r1], // r1 = y1
(int)CoordPnt[i+add_r2] // r2 = y2
) ;
}
mxFree(CoordPnt) ;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// End of the function "Main" function
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set the values
void plot(int x1, int y1)
{
int idx = y1 + dimR*x1 ;
for (int i=0; i<nChannel; i++)
OutputImg[dimR*dimC*i+idx] = (UINT8)LineColor[indLine+i*nPnt] ;
}
// draw thick lines
// (reference) Computer Graphics by A.P. Godse
void draw_thick_line(int x1, int x2, int y1, int y2)
{
int i;
float wy, wx ;
int thickness = (int)LineThickness[indLine] ;
Bresenham(x1, x2, y1, y2) ;
if (abs((float)(y2-y1)/(float)(x2-x1)) < 1) {
wy = (float)(thickness-1)*sqrt((float)(pow2(x2-x1)+pow2(y2-y1))) / (2.*(float)abs(x2-x1)) ;
//mexPrintf("wy: %f %d %f \n", 2.*(float)abs(x2-x1), thickness, wy) ;
for (i=0; i<wy; i++) {
if ( ((y1-i)>-1) && ((y2-i)>-1) )
Bresenham(x1, x2, y1-i, y2-i) ;
if ( ((y1+i)<dimR) && ((y2+i)<dimR) )
Bresenham(x1, x2, y1+i, y2+i) ;
}
}
else {
wx = (float)(thickness-1)*sqrt((float)(pow2(x2-x1)+pow2(y2-y1))) / (2.*(float)abs(y2-y1)) ;
//mexPrintf("wx: %f %d %f \n", 2.*(float)abs(y2-y1), thickness, wx) ;
for (i=0; i<wx; i++) {
if ( ((x1-i)>-1) && ((x2-i)>-1) )
Bresenham(x1-i, x2-i, y1, y2) ;
if ( ((x1+i)<dimC) && ((x2+i)<dimC) )
Bresenham(x1+i, x2+i, y1, y2) ;
}
}
}
// The following code is Bresenham's Line Algorithm.
// (Reference) http://roguebasin.roguelikedevelopment.org/index.php?title=Bresenham's_Line_Algorithm
////////////////////////////////////////////////////////////////////////////////
void Bresenham(int x1,
int x2,
int y1,
int y2)
{
int delta_x = abs(x2 - x1) << 1;
int delta_y = abs(y2 - y1) << 1;
// if x1 == x2 or y1 == y2, then it does not matter what we set here
signed char ix = x2 > x1?1:-1;
signed char iy = y2 > y1?1:-1;
plot(x1, y1);
if (delta_x >= delta_y)
{
// error may go below zero
int error = delta_y - (delta_x >> 1);
while (x1 != x2)
{
if (error >= 0)
{
if (error || (ix > 0))
{
y1 += iy;
error -= delta_x;
}
// else do nothing
}
// else do nothing
x1 += ix;
error += delta_y;
plot(x1, y1);
}
}
else
{
// error may go below zero
int error = delta_x - (delta_y >> 1);
while (y1 != y2)
{
if (error >= 0)
{
if (error || (iy > 0))
{
x1 += ix;
error -= delta_y;
}
// else do nothing
}
// else do nothing
y1 += iy;
error += delta_x;
plot(x1, y1);
}
}
}
| 7,557 | 2,960 |
// Copyright 2020 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "src/ast/struct_block_decoration.h"
#include "src/reader/wgsl/parser_impl_test_helper.h"
namespace tint {
namespace reader {
namespace wgsl {
namespace {
struct DecorationData {
const char* input;
bool is_block;
};
inline std::ostream& operator<<(std::ostream& out, DecorationData data) {
out << std::string(data.input);
return out;
}
class DecorationTest : public ParserImplTestWithParam<DecorationData> {};
TEST_P(DecorationTest, Parses) {
auto params = GetParam();
auto p = parser(params.input);
auto deco = p->decoration();
ASSERT_FALSE(p->has_error());
EXPECT_TRUE(deco.matched);
EXPECT_FALSE(deco.errored);
ASSERT_NE(deco.value, nullptr);
auto* struct_deco = deco.value->As<ast::Decoration>();
ASSERT_NE(struct_deco, nullptr);
EXPECT_EQ(struct_deco->Is<ast::StructBlockDecoration>(), params.is_block);
}
INSTANTIATE_TEST_SUITE_P(ParserImplTest,
DecorationTest,
testing::Values(DecorationData{"block", true}));
TEST_F(ParserImplTest, Decoration_NoMatch) {
auto p = parser("not-a-stage");
auto deco = p->decoration();
EXPECT_FALSE(deco.matched);
EXPECT_FALSE(deco.errored);
ASSERT_EQ(deco.value, nullptr);
}
} // namespace
} // namespace wgsl
} // namespace reader
} // namespace tint
| 1,892 | 639 |
#ifndef UTILS_UTILS_HPP
#define UTILS_UTILS_HPP
// Copyright (c) 2016, Dmitry Koplyarov <koplyarov.da@gmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <chrono>
#include <thread>
namespace wigwag
{
class thread
{
public:
using thread_func = std::function<void(const std::atomic<bool>&)>;
private:
std::atomic<bool> _alive;
thread_func _thread_func;
std::string _error_message;
std::thread _impl;
public:
thread(const thread_func& f)
: _alive(true),
_thread_func(f)
{ _impl = std::thread(std::bind(&thread::func, this)); }
~thread()
{
_alive = false;
if (_impl.joinable())
_impl.join();
else
std::cerr << "WARNING: thread is not joinable!" << std::endl;
if (!_error_message.empty())
TS_FAIL(("Uncaught exception in thread: " + _error_message).c_str());
}
static void sleep(int64_t ms)
{ std::this_thread::sleep_for(std::chrono::milliseconds(ms)); }
private:
void func()
{
try
{ _thread_func(_alive); }
catch (const std::exception& ex)
{ _error_message = ex.what(); }
}
};
template < typename Lockable_ >
std::unique_lock<Lockable_> lock(Lockable_& lockable)
{ return std::unique_lock<Lockable_>(lockable); }
}
#endif
| 2,196 | 734 |
/**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* Likey = cense along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include <gtest/gtest.h>
#include "RunManagerTestFixture.hpp"
#include <runmanager/Test/ToolBin.hxx>
#include <resources.hxx>
#include "../JobFactory.hpp"
#include "../RunManager.hpp"
#include "../Workflow.hpp"
#include "../ErrorEstimation.hpp"
#include "../../../model/Model.hpp"
#include "../../../model/Building.hpp"
#include "../../../utilities/idf/IdfFile.hpp"
#include "../../../utilities/idf/IdfObject.hpp"
#include "../../../utilities/data/EndUses.hpp"
#include "../../../utilities/data/Attribute.hpp"
#include "../../../utilities/sql/SqlFile.hpp"
#include "../../../isomodel/UserModel.hpp"
#include "../../../isomodel/ForwardTranslator.hpp"
#include <boost/filesystem/path.hpp>
#include <QDir>
#include <QElapsedTimer>
#include <boost/filesystem.hpp>
using openstudio::Attribute;
using openstudio::IdfFile;
using openstudio::IdfObject;
using openstudio::IddObjectType;
using openstudio::SqlFile;
openstudio::SqlFile runSimulation(openstudio::model::Model t_model, bool t_estimate)
{
if (t_estimate)
{
openstudio::runmanager::RunManager::simplifyModelForPerformance(t_model);
}
openstudio::path outdir = openstudio::toPath(QDir::tempPath()) / openstudio::toPath("ErrorEstimationRunTest");
boost::filesystem::create_directories(outdir);
openstudio::path db = outdir / openstudio::toPath("ErrorEstimationRunDB");
openstudio::runmanager::RunManager kit(db, true);
openstudio::path infile = outdir / openstudio::toPath("in.osm");
openstudio::path weatherdir = resourcesPath() / openstudio::toPath("runmanager") / openstudio::toPath("USA_CO_Golden-NREL.724666_TMY3.epw");
t_model.save(infile, true);
openstudio::runmanager::Workflow workflow("modeltoidf->expandobjects->energyplus");
workflow.setInputFiles(infile, weatherdir);
// Build list of tools
openstudio::runmanager::Tools tools
= openstudio::runmanager::ConfigOptions::makeTools(
energyPlusExePath().parent_path(),
openstudio::path(),
openstudio::path(),
openstudio::path(),
openstudio::path());
workflow.add(tools);
int offset = 7;
if (t_estimate) offset = 1;
workflow.parallelizeEnergyPlus(kit.getConfigOptions().getMaxLocalJobs(), offset);
openstudio::runmanager::Job job = workflow.create(outdir);
kit.enqueue(job, true);
kit.waitForFinished();
openstudio::path sqlpath = job.treeOutputFiles().getLastByExtension("sql").fullPath;
openstudio::SqlFile sqlfile(sqlpath);
return sqlfile;
}
double compareSqlFile(const openstudio::SqlFile &sf1, const openstudio::SqlFile &sf2)
{
return *sf1.netSiteEnergy() - *sf2.netSiteEnergy();
}
double compare(double v1, double v2)
{
return v1-v2;
}
double compareUses(const openstudio::runmanager::FuelUses &t_fuse1, const openstudio::runmanager::FuelUses &t_fuse2)
{
double gas1 = t_fuse1.fuelUse(openstudio::FuelType::Gas);
double elec1 = t_fuse1.fuelUse(openstudio::FuelType::Electricity);
double gas2 = t_fuse2.fuelUse(openstudio::FuelType::Gas);
double elec2 = t_fuse2.fuelUse(openstudio::FuelType::Electricity);
LOG_FREE(Info, "compareUses", "Gas1 " << gas1 << " gas2 " << gas2 << " Gas Difference " << gas1 - gas2);
LOG_FREE(Info, "compareUses", "Elec1 " << elec1 << " elec2 " << elec2 << " Elec Difference " << elec1 - elec2);
double totalerror = (gas1+elec1) - (gas2+elec2);
LOG_FREE(Info, "compareUses", "Total Error" << totalerror);
return totalerror;
}
std::pair<double, double> runSimulation(openstudio::runmanager::ErrorEstimation &t_ee, double t_rotation)
{
openstudio::model::Model m = openstudio::model::exampleModel();
openstudio::model::Building b = *m.building();
b.setNorthAxis(b.northAxis() + t_rotation);
QElapsedTimer et;
et.start();
openstudio::SqlFile sqlfile1(runSimulation(m, false));
qint64 originaltime = et.restart();
openstudio::SqlFile sqlfile2(runSimulation(m, true));
qint64 reducedtime = et.elapsed();
openstudio::path weatherpath = resourcesPath() / openstudio::toPath("runmanager") / openstudio::toPath("USA_CO_Golden-NREL.724666_TMY3.epw");
openstudio::isomodel::ForwardTranslator translator;
openstudio::isomodel::UserModel userModel = translator.translateModel(m);
userModel.setWeatherFilePath(weatherpath);
openstudio::isomodel::SimModel simModel = userModel.toSimModel();
openstudio::isomodel::ISOResults isoResults = simModel.simulate();
LOG_FREE(Info, "runSimulation", "OriginalTime " << originaltime << " reduced " << reducedtime);
std::vector<double> variables;
variables.push_back(t_rotation);
openstudio::runmanager::FuelUses fuses0(0);
try {
fuses0 = t_ee.approximate(variables);
} catch (const std::exception &e) {
LOG_FREE(Info, "runSimulation", "Unable to generate estimate: " << e.what());
}
openstudio::runmanager::FuelUses fuses3 = t_ee.add(userModel, isoResults, "ISO", variables);
openstudio::runmanager::FuelUses fuses2 = t_ee.add(sqlfile2, "Estimation", variables);
openstudio::runmanager::FuelUses fuses1 = t_ee.add(sqlfile1, "FullRun", variables);
LOG_FREE(Info, "runSimulation", "Comparing Full Run to linear approximation");
compareUses(fuses1, fuses0);
LOG_FREE(Info, "runSimulation", "Comparing Full Run to error adjusted ISO run");
return std::make_pair(compare(*sqlfile1.netSiteEnergy(), isoResults.totalEnergyUse()), compareUses(fuses1, fuses3));
}
TEST_F(RunManagerTestFixture, ErrorEstimationTest)
{
openstudio::runmanager::ErrorEstimation ee(1);
ee.setConfidence("FullRun", 1.0);
ee.setConfidence("Estimation", 0.75);
ee.setConfidence("ISO", 0.50);
std::pair<double, double> run1 = runSimulation(ee, 0);
LOG(Info, "Run1 initialerror: " << run1.first*1000000000 << " adjustederror: " << run1.second);
std::pair<double, double> run2 = runSimulation(ee, 90);
LOG(Info, "Run2 initialerror: " << run2.first*1000000000 << " adjustederror: " << run2.second);
std::pair<double, double> run3 = runSimulation(ee, 180);
LOG(Info, "Run3 initialerror: " << run3.first*1000000000 << " adjustederror: " << run3.second);
std::pair<double, double> run4 = runSimulation(ee, 270);
LOG(Info, "Run4 initialerror: " << run4.first*1000000000 << " adjustederror: " << run4.second);
// std::pair<double, double> run5 = runSimulation(ee, 225);
// LOG(Info, "Run5 initialerror: " << run5.first*1000000000 << " adjustederror: " << run5.second);
}
TEST_F(RunManagerTestFixture, LinearApproximationTestSimple)
{
LinearApproximation la(1);
std::vector<double> vals;
vals.push_back(0);
la.addVals(vals, 0);
vals[0] = 2;
la.addVals(vals, 2);
EXPECT_DOUBLE_EQ(2.0, la.approximate(vals));
vals[0] = 0;
EXPECT_DOUBLE_EQ(0.0, la.approximate(vals));
vals[0] = 1;
EXPECT_DOUBLE_EQ(1.0, la.approximate(vals));
}
TEST_F(RunManagerTestFixture, LinearApproximationTestHuge)
{
const size_t size = 200;
LinearApproximation la(size);
std::vector<double> vals(size);
// just establish a baseline
for (size_t i = 0; i < size; ++i)
{
vals[i] = i;
}
// let's say that this equals 100
la.addVals(vals, 100);
// and we should be able to get back the value we just put in
EXPECT_EQ(100.0, la.approximate(vals));
// now we'll modify one variable at a time
for (size_t i = 0; i < size; ++i)
{
std::vector<double> newvals(vals);
double origVariable = newvals[i];
double newVariable = origVariable * 2.0;
newvals[i] = newVariable;
double valueAtThisPoint = 100.0 + newvals[i];
la.addVals(newvals, valueAtThisPoint);
EXPECT_DOUBLE_EQ(valueAtThisPoint, la.approximate(newvals));
newvals[i] = (origVariable + newVariable) / 2;
EXPECT_DOUBLE_EQ((valueAtThisPoint + 100.0) / 2, la.approximate(newvals));
}
vals[size/10] = 62.4;
vals[size/8] = 99;
vals[size/6] = 99;
vals[size/4] = 102;
vals[size/2] = 102;
la.approximate(vals);
}
| 9,107 | 3,399 |
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkNormalizeImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include <iostream>
#include "itkImageRegionIterator.h"
#include "itkNormalizeImageFilter.h"
#include "itkRandomImageSource.h"
#include "itkStatisticsImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkFilterWatcher.h"
int itkNormalizeImageFilterTest(int, char* [] )
{
std::cout << "itkNormalizeImageFilterTest Start" << std::endl;
typedef itk::Image<short,3> ShortImage;
typedef itk::Image<float,3> FloatImage;
ShortImage::Pointer image = ShortImage::New();
// Generate a real image
typedef itk::RandomImageSource<ShortImage> SourceType;
SourceType::Pointer source = SourceType::New();
ShortImage::SizeValueType randomSize[3] = {18, 17, 67};
source->SetSize( randomSize );
float minValue = -1000.0;
float maxValue = 1000.0;
source->SetMin( static_cast<ShortImage::PixelType>( minValue ) );
source->SetMax( static_cast<ShortImage::PixelType>( maxValue ) );
typedef itk::NormalizeImageFilter<ShortImage,FloatImage> NormalizeType;
NormalizeType::Pointer normalize = NormalizeType::New();
FilterWatcher watch(normalize, "Streaming");
normalize->SetInput(source->GetOutput());
typedef itk::StreamingImageFilter<FloatImage,FloatImage> StreamingType;
StreamingType::Pointer streaming = StreamingType::New();
streaming->SetNumberOfStreamDivisions(5);
streaming->SetInput (normalize->GetOutput());
streaming->Update();
// Force the filter to re-execute
source->Modified();
typedef itk::StatisticsImageFilter<FloatImage> StatisticsType;
StatisticsType::Pointer statistics = StatisticsType::New();
statistics->SetInput(streaming->GetOutput());
statistics->UpdateLargestPossibleRegion();
std::cout << "Mean is: " << statistics->GetMean() << " Sigma is: " << statistics->GetSigma() << std::endl;
return EXIT_SUCCESS;
}
| 2,570 | 808 |
/*
Copyright (C) 2010 Lukasz Wolnik
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Lukasz Wolnik lukasz.wolnik@o2.pl
*/
#include "StdAfx.h"
#include "effect.h"
#include "graphics.h"
using namespace nit;
IEffect::IEffect(Graphics* gfx, wchar_t* filename) : effect(0)
{
ID3DXBuffer* errors = 0;
IDirect3DDevice9* device = gfx->GetDevice();
D3DXCreateEffectFromFile(device, filename, 0, 0, D3DXSHADER_DEBUG, 0, &effect, &errors);
// TODO
//
// Remove dependency to dxerr.lib from March 2009 DirectX SDK
if (errors)
{
MessageBoxA(NULL, (char*)errors->GetBufferPointer(), 0, 0);
}
gfx->AddOnLostDevice(&MakeDelegate(this, &IEffect::OnLostDevice));
gfx->AddOnResetDevice(&MakeDelegate(this, &IEffect::OnResetDevice));
}
IEffect::~IEffect()
{
effect->Release();
}
void IEffect::Begin(unsigned int* num_passes)
{
effect->Begin(num_passes, 0);
}
void IEffect::BeginPass(unsigned int pass)
{
effect->BeginPass(pass);
}
void IEffect::CommitChanges()
{
effect->CommitChanges();
}
void IEffect::End()
{
effect->End();
}
void IEffect::EndPass()
{
effect->EndPass();
}
void IEffect::GetParameterByName(char* name)
{
params[name] = effect->GetParameterByName(0, name);
}
void IEffect::GetTechniqueByName(char* name)
{
params[name] = effect->GetTechniqueByName(name);
}
void IEffect::OnLostDevice()
{
effect->OnLostDevice();
}
void IEffect::OnResetDevice()
{
effect->OnResetDevice();
}
void IEffect::SetFloat(char* name, const float f)
{
effect->SetFloat(params[name], f);
}
void IEffect::SetMatrix(char* name, const D3DXMATRIX *matrix)
{
effect->SetMatrix(params[name], matrix);
}
void IEffect::SetTechnique(char* name)
{
effect->SetTechnique(params[name]);
}
void IEffect::SetTexture(char* name, IDirect3DTexture9* texture)
{
effect->SetTexture(params[name], texture);
}
void IEffect::SetVector(char* name, const D3DXVECTOR4* vector)
{
effect->SetVector(params[name], vector);
} | 2,688 | 934 |
// Copyright 2016 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "packager/media/base/audio_stream_info.h"
#include "packager/media/base/media_sample.h"
#include "packager/media/base/text_stream_info.h"
#include "packager/media/base/video_stream_info.h"
#include "packager/media/codecs/aac_audio_specific_config.h"
#include "packager/media/codecs/nal_unit_to_byte_stream_converter.h"
#include "packager/media/formats/mp2t/pes_packet.h"
#include "packager/media/formats/mp2t/pes_packet_generator.h"
namespace shaka {
namespace media {
inline bool operator==(const SubsampleEntry& lhs, const SubsampleEntry& rhs) {
return lhs.clear_bytes == rhs.clear_bytes &&
lhs.cipher_bytes == rhs.cipher_bytes;
}
namespace mp2t {
using ::testing::_;
using ::testing::DoAll;
using ::testing::Eq;
using ::testing::IsEmpty;
using ::testing::Pointee;
using ::testing::Return;
using ::testing::SetArgPointee;
namespace {
const uint32_t kZeroTransportStreamTimestampOffset = 0;
// Bogus data for testing.
const uint8_t kAnyData[] = {
0x56, 0x87, 0x88, 0x33, 0x98, 0xAF, 0xE5,
};
const bool kIsKeyFrame = true;
const bool kEscapeEncryptedNalu = true;
// Only Codec and extra data matter for this test. Other values are
// bogus.
const Codec kH264Codec = Codec::kCodecH264;
const Codec kAacCodec = Codec::kCodecAAC;
// TODO(rkuroiwa): It might make sense to inject factory functions to create
// NalUnitToByteStreamConverter and AACAudioSpecificConfig so that these
// extra data don't need to be copy pasted from other tests.
const uint8_t kVideoExtraData[] = {
0x01, // configuration version (must be 1)
0x00, // AVCProfileIndication (bogus)
0x00, // profile_compatibility (bogus)
0x00, // AVCLevelIndication (bogus)
0xFF, // Length size minus 1 == 3
0xE1, // 1 sps.
0x00, 0x1D, // SPS length == 29
0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xB4,
0x2F, 0xF9, 0x7F, 0xF0, 0x00, 0x80, 0x00, 0x91,
0x00, 0x00, 0x03, 0x03, 0xE9, 0x00, 0x00, 0xEA,
0x60, 0x0F, 0x16, 0x2D, 0x96,
0x01, // 1 pps.
0x00, 0x0A, // PPS length == 10
0x68, 0xFE, 0xFD, 0xFC, 0xFB, 0x11, 0x12, 0x13, 0x14, 0x15,
};
// Basic profile.
const uint8_t kAudioExtraData[] = {0x12, 0x10};
const int kTrackId = 0;
const uint32_t kTimeScale = 90000;
const uint64_t kDuration = 180000;
const char kCodecString[] = "avc1";
const char kLanguage[] = "eng";
const uint32_t kWidth = 1280;
const uint32_t kHeight = 720;
const uint32_t kPixelWidth = 1;
const uint32_t kPixelHeight = 1;
const uint8_t kTransferCharacteristics = 0;
const uint16_t kTrickPlayFactor = 1;
const uint8_t kNaluLengthSize = 1;
const bool kIsEncrypted = false;
const uint8_t kSampleBits = 16;
const uint8_t kNumChannels = 2;
const uint32_t kSamplingFrequency = 44100;
const uint64_t kSeekPreroll = 0;
const uint64_t kCodecDelay = 0;
const uint32_t kMaxBitrate = 320000;
const uint32_t kAverageBitrate = 256000;
class MockNalUnitToByteStreamConverter : public NalUnitToByteStreamConverter {
public:
MOCK_METHOD2(Initialize,
bool(const uint8_t* decoder_configuration_data,
size_t decoder_configuration_data_size));
MOCK_METHOD6(ConvertUnitToByteStreamWithSubsamples,
bool(const uint8_t* sample,
size_t sample_size,
bool is_key_frame,
bool escape_encrypted_nalu,
std::vector<uint8_t>* output,
std::vector<SubsampleEntry>* subsamples));
};
class MockAACAudioSpecificConfig : public AACAudioSpecificConfig {
public:
MOCK_METHOD1(Parse, bool(const std::vector<uint8_t>& data));
MOCK_CONST_METHOD3(ConvertToADTS,
bool(const uint8_t* data,
size_t data_size,
std::vector<uint8_t>* audio_frame));
};
std::shared_ptr<VideoStreamInfo> CreateVideoStreamInfo(Codec codec) {
std::shared_ptr<VideoStreamInfo> stream_info(new VideoStreamInfo(
kTrackId, kTimeScale, kDuration, codec,
H26xStreamFormat::kAnnexbByteStream, kCodecString, kVideoExtraData,
arraysize(kVideoExtraData), kWidth, kHeight, kPixelWidth, kPixelHeight,
kTransferCharacteristics, kTrickPlayFactor, kNaluLengthSize, kLanguage,
kIsEncrypted));
return stream_info;
}
std::shared_ptr<AudioStreamInfo> CreateAudioStreamInfo(Codec codec) {
std::shared_ptr<AudioStreamInfo> stream_info(new AudioStreamInfo(
kTrackId, kTimeScale, kDuration, codec, kCodecString, kAudioExtraData,
arraysize(kAudioExtraData), kSampleBits, kNumChannels, kSamplingFrequency,
kSeekPreroll, kCodecDelay, kMaxBitrate, kAverageBitrate, kLanguage,
kIsEncrypted));
return stream_info;
}
} // namespace
class PesPacketGeneratorTest : public ::testing::Test {
protected:
PesPacketGeneratorTest() : generator_(kZeroTransportStreamTimestampOffset) {}
void UseMockNalUnitToByteStreamConverter(
std::unique_ptr<MockNalUnitToByteStreamConverter>
mock_nal_unit_to_byte_stream_converter) {
generator_.converter_ = std::move(mock_nal_unit_to_byte_stream_converter);
}
void UseMockAACAudioSpecificConfig(
std::unique_ptr<MockAACAudioSpecificConfig> mock) {
generator_.adts_converter_ = std::move(mock);
}
PesPacketGenerator generator_;
};
TEST_F(PesPacketGeneratorTest, InitializeVideo) {
std::shared_ptr<VideoStreamInfo> stream_info(
CreateVideoStreamInfo(kH264Codec));
EXPECT_TRUE(generator_.Initialize(*stream_info));
}
TEST_F(PesPacketGeneratorTest, InitializeVideoNonH264) {
std::shared_ptr<VideoStreamInfo> stream_info(
CreateVideoStreamInfo(Codec::kCodecVP9));
EXPECT_FALSE(generator_.Initialize(*stream_info));
}
TEST_F(PesPacketGeneratorTest, InitializeAudio) {
std::shared_ptr<AudioStreamInfo> stream_info(
CreateAudioStreamInfo(kAacCodec));
EXPECT_TRUE(generator_.Initialize(*stream_info));
}
TEST_F(PesPacketGeneratorTest, InitializeAudioNonAac) {
std::shared_ptr<AudioStreamInfo> stream_info(
CreateAudioStreamInfo(Codec::kCodecOpus));
EXPECT_FALSE(generator_.Initialize(*stream_info));
}
// Text is not supported yet.
TEST_F(PesPacketGeneratorTest, InitializeTextInfo) {
std::shared_ptr<TextStreamInfo> stream_info(new TextStreamInfo(
kTrackId, kTimeScale, kDuration, kCodecText, kCodecString, std::string(),
kWidth, kHeight, kLanguage));
EXPECT_FALSE(generator_.Initialize(*stream_info));
}
TEST_F(PesPacketGeneratorTest, AddVideoSample) {
std::shared_ptr<VideoStreamInfo> stream_info(
CreateVideoStreamInfo(kH264Codec));
EXPECT_TRUE(generator_.Initialize(*stream_info));
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
std::shared_ptr<MediaSample> sample =
MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame);
const uint32_t kPts = 12345;
const uint32_t kDts = 12300;
sample->set_pts(kPts);
sample->set_dts(kDts);
std::vector<uint8_t> expected_data(kAnyData, kAnyData + arraysize(kAnyData));
std::unique_ptr<MockNalUnitToByteStreamConverter> mock(
new MockNalUnitToByteStreamConverter());
EXPECT_CALL(*mock, ConvertUnitToByteStreamWithSubsamples(
_, arraysize(kAnyData), kIsKeyFrame,
kEscapeEncryptedNalu, _, Pointee(IsEmpty())))
.WillOnce(DoAll(SetArgPointee<4>(expected_data), Return(true)));
UseMockNalUnitToByteStreamConverter(std::move(mock));
EXPECT_TRUE(generator_.PushSample(*sample));
EXPECT_EQ(1u, generator_.NumberOfReadyPesPackets());
std::unique_ptr<PesPacket> pes_packet = generator_.GetNextPesPacket();
ASSERT_TRUE(pes_packet);
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
EXPECT_EQ(0xe0, pes_packet->stream_id());
EXPECT_EQ(kPts, pes_packet->pts());
EXPECT_EQ(kDts, pes_packet->dts());
EXPECT_EQ(expected_data, pes_packet->data());
EXPECT_TRUE(generator_.Flush());
}
TEST_F(PesPacketGeneratorTest, AddEncryptedVideoSample) {
std::shared_ptr<VideoStreamInfo> stream_info(
CreateVideoStreamInfo(kH264Codec));
EXPECT_TRUE(generator_.Initialize(*stream_info));
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
std::shared_ptr<MediaSample> sample =
MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame);
const uint32_t kPts = 12345;
const uint32_t kDts = 12300;
sample->set_pts(kPts);
sample->set_dts(kDts);
const std::vector<uint8_t> key_id(16, 0);
const std::vector<uint8_t> iv(8, 0);
const std::vector<SubsampleEntry> subsamples = {
SubsampleEntry(0x12, 0x110), SubsampleEntry(0x122, 0x11000)};
std::unique_ptr<DecryptConfig> decrypt_config(
new DecryptConfig(key_id, iv, subsamples));
sample->set_is_encrypted(true);
sample->set_decrypt_config(std::move(decrypt_config));
std::vector<uint8_t> expected_data(kAnyData, kAnyData + arraysize(kAnyData));
std::unique_ptr<MockNalUnitToByteStreamConverter> mock(
new MockNalUnitToByteStreamConverter());
EXPECT_CALL(*mock, ConvertUnitToByteStreamWithSubsamples(
_, arraysize(kAnyData), kIsKeyFrame,
kEscapeEncryptedNalu, _, Pointee(Eq(subsamples))))
.WillOnce(DoAll(SetArgPointee<4>(expected_data), Return(true)));
UseMockNalUnitToByteStreamConverter(std::move(mock));
EXPECT_TRUE(generator_.PushSample(*sample));
EXPECT_EQ(1u, generator_.NumberOfReadyPesPackets());
std::unique_ptr<PesPacket> pes_packet = generator_.GetNextPesPacket();
ASSERT_TRUE(pes_packet);
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
EXPECT_EQ(0xe0, pes_packet->stream_id());
EXPECT_EQ(kPts, pes_packet->pts());
EXPECT_EQ(kDts, pes_packet->dts());
EXPECT_EQ(expected_data, pes_packet->data());
EXPECT_TRUE(generator_.Flush());
}
TEST_F(PesPacketGeneratorTest, AddVideoSampleFailedToConvert) {
std::shared_ptr<VideoStreamInfo> stream_info(
CreateVideoStreamInfo(kH264Codec));
EXPECT_TRUE(generator_.Initialize(*stream_info));
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
std::shared_ptr<MediaSample> sample =
MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame);
std::vector<uint8_t> expected_data(kAnyData, kAnyData + arraysize(kAnyData));
std::unique_ptr<MockNalUnitToByteStreamConverter> mock(
new MockNalUnitToByteStreamConverter());
EXPECT_CALL(*mock, ConvertUnitToByteStreamWithSubsamples(
_, arraysize(kAnyData), kIsKeyFrame,
kEscapeEncryptedNalu, _, Pointee(IsEmpty())))
.WillOnce(Return(false));
UseMockNalUnitToByteStreamConverter(std::move(mock));
EXPECT_FALSE(generator_.PushSample(*sample));
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
EXPECT_TRUE(generator_.Flush());
}
TEST_F(PesPacketGeneratorTest, AddAudioSample) {
std::shared_ptr<AudioStreamInfo> stream_info(
CreateAudioStreamInfo(kAacCodec));
EXPECT_TRUE(generator_.Initialize(*stream_info));
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
std::shared_ptr<MediaSample> sample =
MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame);
std::vector<uint8_t> expected_data(kAnyData, kAnyData + arraysize(kAnyData));
std::unique_ptr<MockAACAudioSpecificConfig> mock(
new MockAACAudioSpecificConfig());
EXPECT_CALL(*mock, ConvertToADTS(sample->data(), sample->data_size(), _))
.WillOnce(DoAll(SetArgPointee<2>(expected_data), Return(true)));
UseMockAACAudioSpecificConfig(std::move(mock));
EXPECT_TRUE(generator_.PushSample(*sample));
EXPECT_EQ(1u, generator_.NumberOfReadyPesPackets());
std::unique_ptr<PesPacket> pes_packet = generator_.GetNextPesPacket();
ASSERT_TRUE(pes_packet);
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
EXPECT_EQ(0xc0, pes_packet->stream_id());
EXPECT_EQ(expected_data, pes_packet->data());
EXPECT_TRUE(generator_.Flush());
}
TEST_F(PesPacketGeneratorTest, AddAudioSampleFailedToConvert) {
std::shared_ptr<AudioStreamInfo> stream_info(
CreateAudioStreamInfo(kAacCodec));
EXPECT_TRUE(generator_.Initialize(*stream_info));
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
std::shared_ptr<MediaSample> sample =
MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame);
std::unique_ptr<MockAACAudioSpecificConfig> mock(
new MockAACAudioSpecificConfig());
EXPECT_CALL(*mock, ConvertToADTS(_, _, _)).WillOnce(Return(false));
UseMockAACAudioSpecificConfig(std::move(mock));
EXPECT_FALSE(generator_.PushSample(*sample));
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
EXPECT_TRUE(generator_.Flush());
}
// Because TS has to use 90000 as its timescale, make sure that the timestamps
// are scaled.
TEST_F(PesPacketGeneratorTest, TimeStampScaling) {
const uint32_t kTestTimescale = 1000;
std::shared_ptr<VideoStreamInfo> stream_info(new VideoStreamInfo(
kTrackId, kTestTimescale, kDuration, kH264Codec,
H26xStreamFormat::kAnnexbByteStream, kCodecString, kVideoExtraData,
arraysize(kVideoExtraData), kWidth, kHeight, kPixelWidth, kPixelHeight,
kTransferCharacteristics, kTrickPlayFactor, kNaluLengthSize, kLanguage,
kIsEncrypted));
EXPECT_TRUE(generator_.Initialize(*stream_info));
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
std::shared_ptr<MediaSample> sample =
MediaSample::CopyFrom(kAnyData, arraysize(kAnyData), kIsKeyFrame);
const uint32_t kPts = 5000;
const uint32_t kDts = 4000;
sample->set_pts(kPts);
sample->set_dts(kDts);
std::unique_ptr<MockNalUnitToByteStreamConverter> mock(
new MockNalUnitToByteStreamConverter());
EXPECT_CALL(*mock, ConvertUnitToByteStreamWithSubsamples(
_, arraysize(kAnyData), kIsKeyFrame,
kEscapeEncryptedNalu, _, Pointee(IsEmpty())))
.WillOnce(Return(true));
UseMockNalUnitToByteStreamConverter(std::move(mock));
EXPECT_TRUE(generator_.PushSample(*sample));
EXPECT_EQ(1u, generator_.NumberOfReadyPesPackets());
std::unique_ptr<PesPacket> pes_packet = generator_.GetNextPesPacket();
ASSERT_TRUE(pes_packet);
EXPECT_EQ(0u, generator_.NumberOfReadyPesPackets());
// Since 90000 (MPEG2 timescale) / 1000 (input timescale) is 90, the
// timestamps should be multipled by 90.
EXPECT_EQ(kPts * 90, pes_packet->pts());
EXPECT_EQ(kDts * 90, pes_packet->dts());
EXPECT_TRUE(generator_.Flush());
}
} // namespace mp2t
} // namespace media
} // namespace shaka
| 14,655 | 5,447 |
#ifdef DSP_CPP
static void dsp_state_save(unsigned char **out, void *in, size_t size) {
memcpy(*out, in, size);
*out += size;
}
static void dsp_state_load(unsigned char **in, void *out, size_t size) {
memcpy(out, *in, size);
*in += size;
}
void DSP::serialize(serializer &s) {
Processor::serialize(s);
s.array(samplebuffer);
unsigned char state[SPC_DSP::state_size];
unsigned char *p = state;
memset(&state, 0, SPC_DSP::state_size);
if(s.mode() == serializer::Save) {
spc_dsp.copy_state(&p, dsp_state_save);
s.array(state);
} else if(s.mode() == serializer::Load) {
s.array(state);
spc_dsp.copy_state(&p, dsp_state_load);
} else {
s.array(state);
}
}
#endif
| 709 | 295 |
/**
* EdDSA crypto routines, metaheader.
*/
namespace decaf { enum Prehashed { PURE, PREHASHED }; }
$("\n".join([
"#include <decaf/ed%s.hxx>" % g for g in sorted([c["bits"] for _,c in curve.iteritems()])
]))
| 215 | 86 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtCore module 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 "qplatformdefs.h"
#include <stdlib.h>
#include <string.h>
/*
Define the container allocation functions in a separate file, so that our
users can easily override them.
*/
QT_BEGIN_NAMESPACE
#if !QT_DEPRECATED_SINCE(5, 0)
// Make sure they're defined to be exported
Q_CORE_EXPORT void *qMalloc(size_t size) Q_ALLOC_SIZE(1);
Q_CORE_EXPORT void qFree(void *ptr);
Q_CORE_EXPORT void *qRealloc(void *ptr, size_t size) Q_ALLOC_SIZE(2);
#endif
void *qMalloc(size_t size)
{
return ::malloc(size);
}
void qFree(void *ptr)
{
::free(ptr);
}
void *qRealloc(void *ptr, size_t size)
{
return ::realloc(ptr, size);
}
void *qMallocAligned(size_t size, size_t alignment)
{
return qReallocAligned(0, size, 0, alignment);
}
void *qReallocAligned(void *oldptr, size_t newsize, size_t oldsize, size_t alignment)
{
// fake an aligned allocation
void *actualptr = oldptr ? static_cast<void **>(oldptr)[-1] : 0;
if (alignment <= sizeof(void*)) {
// special, fast case
void **newptr = static_cast<void **>(realloc(actualptr, newsize + sizeof(void*)));
if (!newptr)
return 0;
if (newptr == actualptr) {
// realloc succeeded without reallocating
return oldptr;
}
*newptr = newptr;
return newptr + 1;
}
// malloc returns pointers aligned at least at sizeof(size_t) boundaries
// but usually more (8- or 16-byte boundaries).
// So we overallocate by alignment-sizeof(size_t) bytes, so we're guaranteed to find a
// somewhere within the first alignment-sizeof(size_t) that is properly aligned.
// However, we need to store the actual pointer, so we need to allocate actually size +
// alignment anyway.
void *real = realloc(actualptr, newsize + alignment);
if (!real)
return 0;
quintptr faked = reinterpret_cast<quintptr>(real) + alignment;
faked &= ~(alignment - 1);
void **faked_ptr = reinterpret_cast<void **>(faked);
if (oldptr) {
qptrdiff oldoffset = static_cast<char *>(oldptr) - static_cast<char *>(actualptr);
qptrdiff newoffset = reinterpret_cast<char *>(faked_ptr) - static_cast<char *>(real);
if (oldoffset != newoffset)
memmove(faked_ptr, static_cast<char *>(real) + oldoffset, qMin(oldsize, newsize));
}
// now save the value of the real pointer at faked-sizeof(void*)
// by construction, alignment > sizeof(void*) and is a power of 2, so
// faked-sizeof(void*) is properly aligned for a pointer
faked_ptr[-1] = real;
return faked_ptr;
}
void qFreeAligned(void *ptr)
{
if (!ptr)
return;
void **ptr2 = static_cast<void **>(ptr);
free(ptr2[-1]);
}
QT_END_NAMESPACE
| 4,664 | 1,449 |
/*******************************************************************************
* Copyright 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <assert.h>
#include <float.h>
#include <math.h>
#include "c_types_map.hpp"
#include "dnnl_thread.hpp"
#include "math_utils.hpp"
#include "type_helpers.hpp"
#include "ref_resampling.hpp"
#include "resampling_utils.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
static inline dim_t get_offset(
const memory_desc_wrapper &data_d, int n, int c, int d, int h, int w) {
if (data_d.ndims() == 5)
return data_d.off(n, c, d, h, w);
else if (data_d.ndims() == 4)
return data_d.off(n, c, h, w);
else
return data_d.off(n, c, w);
}
using namespace resampling_utils;
template <impl::data_type_t data_type>
void ref_resampling_fwd_t<data_type>::execute_forward(
const exec_ctx_t &ctx) const {
if (this->pd()->has_zero_dim_memory()) return;
const auto src = CTX_IN_MEM(const data_t *, DNNL_ARG_SRC);
auto dst = CTX_OUT_MEM(data_t *, DNNL_ARG_DST);
const memory_desc_wrapper src_d(pd()->src_md());
const memory_desc_wrapper dst_d(pd()->dst_md());
const auto alg = pd()->desc()->alg_kind;
const int MB = pd()->MB();
const int C = pd()->C();
const int ID = pd()->ID();
const int IH = pd()->IH();
const int IW = pd()->IW();
const int OD = pd()->OD();
const int OH = pd()->OH();
const int OW = pd()->OW();
const float FD = pd()->FD();
const float FH = pd()->FH();
const float FW = pd()->FW();
auto lin_interp = [&](float c0, float c1, float w) {
return c0 * w + c1 * (1 - w);
};
auto bilin_interp = [&](float c00, float c01, float c10, float c11,
float w0, float w1) {
return lin_interp(
lin_interp(c00, c10, w0), lin_interp(c01, c11, w0), w1);
};
auto trilin_interp = [&](float c000, float c010, float c100, float c110,
float c001, float c011, float c101, float c111,
float w0, float w1, float w2) {
return lin_interp(bilin_interp(c000, c010, c100, c110, w0, w1),
bilin_interp(c001, c011, c101, c111, w0, w1), w2);
};
parallel_nd(MB, C, OD, OH, OW,
[&](dim_t mb, dim_t ch, dim_t od, dim_t oh, dim_t ow) {
if (alg == alg_kind::resampling_nearest) {
dim_t id = nearest_idx(od, FD), ih = nearest_idx(oh, FH),
iw = nearest_idx(ow, FW);
dst[get_offset(dst_d, mb, ch, od, oh, ow)]
= src[get_offset(src_d, mb, ch, id, ih, iw)];
} else if (alg == alg_kind::resampling_linear) {
// Trilinear interpolation (linear interpolation on a 3D spatial
// tensor) can be expressed as linear interpolation along
// dimension x followed by interpolation along dimension y and z
// C011--C11--C111
// - - |
// - - |
//C001--C01--C111 |
// - .C - C110
// - - -
// - - -
//C000--C00--C100
auto id = linear_coeffs_t(od, FD, ID);
auto iw = linear_coeffs_t(ow, FW, IW);
auto ih = linear_coeffs_t(oh, FH, IH);
dim_t src_l[8] = {0};
for_(int i = 0; i < 2; i++)
for_(int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++) {
src_l[4 * i + 2 * j + k] = src[get_offset(src_d, mb, ch,
id.idx[i], ih.idx[j], iw.idx[k])];
}
dst[get_offset(dst_d, mb, ch, od, oh, ow)]
= trilin_interp(src_l[0], src_l[1], src_l[2],
src_l[3], src_l[4], src_l[5], src_l[6],
src_l[7], id.wei[0], ih.wei[0], iw.wei[0]);
}
});
}
template struct ref_resampling_fwd_t<data_type::f32>;
template struct ref_resampling_fwd_t<data_type::bf16>;
template <impl::data_type_t data_type>
void ref_resampling_bwd_t<data_type>::execute_backward(
const exec_ctx_t &ctx) const {
if (this->pd()->has_zero_dim_memory()) return;
const auto diff_dst = CTX_IN_MEM(const data_t *, DNNL_ARG_DIFF_DST);
auto diff_src = CTX_OUT_MEM(data_t *, DNNL_ARG_DIFF_SRC);
const memory_desc_wrapper diff_src_d(pd()->diff_src_md());
const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md());
const auto alg = pd()->desc()->alg_kind;
const int MB = pd()->MB();
const int C = pd()->C();
const int ID = pd()->ID();
const int IH = pd()->IH();
const int IW = pd()->IW();
const int OD = pd()->OD();
const int OH = pd()->OH();
const int OW = pd()->OW();
const float FD = pd()->FD();
const float FH = pd()->FH();
const float FW = pd()->FW();
parallel_nd(MB, C, ID, IH, IW,
[&](dim_t mb, dim_t ch, dim_t id, dim_t ih, dim_t iw) {
diff_src[get_offset(diff_src_d, mb, ch, id, ih, iw)] = 0.f;
});
parallel_nd(MB, C, [&](dim_t mb, dim_t ch) {
for_(int od = 0; od < OD; ++od)
for_(int oh = 0; oh < OH; ++oh)
for (int ow = 0; ow < OW; ++ow) {
if (alg == alg_kind::resampling_nearest) {
dim_t id = nearest_idx(od, FD), ih = nearest_idx(oh, FH),
iw = nearest_idx(ow, FW);
diff_src[get_offset(diff_src_d, mb, ch, id, ih, iw)]
+= diff_dst[get_offset(diff_dst_d, mb, ch, od, oh, ow)];
} else if (alg == alg_kind::resampling_linear) {
auto id = linear_coeffs_t(od, FD, ID);
auto iw = linear_coeffs_t(ow, FW, IW);
auto ih = linear_coeffs_t(oh, FH, IH);
// accessor for source values on a cubic lattice
data_t dd
= diff_dst[get_offset(diff_dst_d, mb, ch, od, oh, ow)];
for_(int i = 0; i < 2; i++)
for_(int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++) {
auto off = get_offset(diff_src_d, mb, ch, id.idx[i],
ih.idx[j], iw.idx[k]);
diff_src[off] += dd * id.wei[i] * ih.wei[j] * iw.wei[k];
}
}
}
});
}
template struct ref_resampling_bwd_t<data_type::f32>;
template struct ref_resampling_bwd_t<data_type::bf16>;
} // namespace cpu
} // namespace impl
} // namespace dnnl
// vim: et ts=4 sw=4 cindent cino+=l0,\:4,N-s
| 7,452 | 2,689 |
/**
* @file test_os_char_driver.cpp
* @brief Tests os_char_driver template
* @author Kacper Kowalski - kacper.s.kowalski@gmail.com
*/
#include "os_char_driver.hpp"
#include "os_task.hpp"
#include "unity.h"
#include <array>
#include <csignal>
#include <functional>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
using namespace jungles;
#define SIGNAL_TX SIGRTMIN
#define SIGNAL_RX (SIGRTMIN + 1)
// --------------------------------------------------------------------------------------------------------------------
// DECLARATION OF THE TEST CASES
// --------------------------------------------------------------------------------------------------------------------
static void UNIT_TEST_1_block_on_read_and_unblock_on_message_received();
static void UNIT_TEST_2_blocking_write_multiple_string_types();
// --------------------------------------------------------------------------------------------------------------------
// DECLARATION OF PRIVATE FUNCTIONS AND VARIABLES
// --------------------------------------------------------------------------------------------------------------------
static std::function<void(void)> tx_isr_handler, rx_isr_handler;
static std::function<void(char)> byte_sender;
static void helper_set_tx_isr_handler(std::function<void(void)> f);
static void helper_set_rx_isr_handler(std::function<void(void)> f);
static void helper_set_byte_sender(std::function<void(char)> f);
static bool tx_isr_enabled;
static void tx_isr_handler_callback(int signal);
static void rx_isr_handler_callback(int signal);
static void tx_it_enable();
static void tx_it_disable();
static void rx_it_enable();
static void rx_it_disable();
static void byte_send(char c);
// --------------------------------------------------------------------------------------------------------------------
// EXECUTION OF THE TESTS
// --------------------------------------------------------------------------------------------------------------------
void test_os_char_driver()
{
std::signal(SIGNAL_TX, tx_isr_handler_callback);
std::signal(SIGNAL_RX, rx_isr_handler_callback);
RUN_TEST(UNIT_TEST_1_block_on_read_and_unblock_on_message_received);
RUN_TEST(UNIT_TEST_2_blocking_write_multiple_string_types);
std::signal(SIGNAL_TX, SIG_DFL);
std::signal(SIGNAL_RX, SIG_DFL);
}
// --------------------------------------------------------------------------------------------------------------------
// DEFINITION OF THE TEST CASES
// --------------------------------------------------------------------------------------------------------------------
static void UNIT_TEST_1_block_on_read_and_unblock_on_message_received()
{
os_char_driver<64, 16> chardrv{tx_it_enable, tx_it_disable, rx_it_enable, rx_it_disable, byte_send};
auto reader_task_handle = os_task_get_current_task_handle();
os_task sync_reader_task(
[reader_task_handle, &chardrv]() {
// Ensure readline() will be called
os_task_yield();
os_task_yield();
os_task_yield();
for (unsigned state = os_task_state_running;
state != os_task_state_blocked && state != os_task_state_blocked;
state = os_task_get_state(reader_task_handle))
os_delay_ms(1);
helper_set_rx_isr_handler([&chardrv]() {
static constexpr char test_string_rcvd[] = "makapaka";
static const char *it = test_string_rcvd;
static constexpr const char *end =
test_string_rcvd + std::distance(std::begin(test_string_rcvd), std::end(test_string_rcvd));
if (it != end)
{
chardrv.rx_isr_handler(*it++);
std::raise(SIGNAL_RX);
}
});
std::raise(SIGNAL_RX);
},
"sync_reader",
256,
1);
auto line = chardrv.readline(os_no_timeout);
TEST_ASSERT_EQUAL_STRING("makapaka", line.c_str());
os_task_yield();
}
static void UNIT_TEST_2_blocking_write_multiple_string_types()
{
os_char_driver<64, 16> chardrv{tx_it_enable, tx_it_disable, rx_it_enable, rx_it_disable, byte_send};
std::string s{"std::string"};
std::vector v{'s', 't', 'd', ':', ':', 'v', 'e', 'c', 't', 'o', 'r'};
std::array<char, 10> a{'s', 't', 'd', ':', ':', 'a', 'r', 'r', 'a', 'y'};
std::string sv{"std::string_view"};
std::string result;
helper_set_byte_sender([&result](char c) { result += c; });
helper_set_tx_isr_handler([&chardrv]() { chardrv.tx_isr_handler(); });
chardrv.write(s, v, a, sv);
TEST_ASSERT_EQUAL_STRING("std::stringstd::vectorstd::arraystd::string_view", result.c_str());
}
// --------------------------------------------------------------------------------------------------------------------
// DEFINITION OF PRIVATE FUNCTIONS
// --------------------------------------------------------------------------------------------------------------------
static void helper_set_tx_isr_handler(std::function<void(void)> f)
{
tx_isr_handler = f;
}
static void helper_set_rx_isr_handler(std::function<void(void)> f)
{
rx_isr_handler = f;
}
static void tx_isr_handler_callback(int signal)
{
tx_isr_handler();
if (tx_isr_enabled)
std::raise(SIGNAL_TX);
}
static void rx_isr_handler_callback(int signal)
{
rx_isr_handler();
}
static void helper_set_byte_sender(std::function<void(char)> f)
{
byte_sender = f;
}
static void tx_it_enable()
{
tx_isr_enabled = true;
std::raise(SIGNAL_TX);
}
static void tx_it_disable()
{
tx_isr_enabled = false;
}
static void rx_it_enable()
{
}
static void rx_it_disable()
{
}
static void byte_send(char c)
{
byte_sender(c);
}
| 5,767 | 1,838 |
#include "mvTextureContainer.h"
#include "mvPythonExceptions.h"
#include "mvLog.h"
#include "mvStaticTexture.h"
#include "mvDynamicTexture.h"
namespace Marvel {
void mvTextureContainer::InsertParser(std::map<std::string, mvPythonParser>* parsers)
{
mvPythonParser parser(mvPyDataType::String, "Undocumented function", { "Textures", "Widgets" });
mvAppItem::AddCommonArgs(parser, (CommonParserArgs)(
MV_PARSER_ARG_ID |
MV_PARSER_ARG_SHOW)
);
parser.finalize();
parsers->insert({ s_command, parser });
}
mvTextureContainer::mvTextureContainer(const std::string& name)
:
mvAppItem(name)
{
m_show = false;
}
void mvTextureContainer::draw(ImDrawList* drawlist, float x, float y)
{
for (auto& item : m_children[1])
item->draw(drawlist, ImGui::GetCursorPosX(), ImGui::GetCursorPosY());
if (m_show)
show_debugger();
}
bool mvTextureContainer::canChildBeAdded(mvAppItemType type)
{
if (type == mvAppItemType::mvStaticTexture) return true;
if (type == mvAppItemType::mvDynamicTexture) return true;
mvThrowPythonError(1000, "Drawing children must be draw commands only.");
MV_ITEM_REGISTRY_ERROR("Drawing children must be draw commands only.");
assert(false);
return false;
}
void mvTextureContainer::onChildRemoved(mvRef<mvAppItem> item)
{
m_selection = -1;
}
void mvTextureContainer::onChildrenRemoved()
{
m_selection = -1;
}
void mvTextureContainer::show_debugger()
{
ImGui::PushID(this);
ImGui::SetNextWindowSize(ImVec2(500, 500), ImGuiCond_FirstUseEver);
if (ImGui::Begin(m_label.c_str(), &m_show))
{
ImGui::Text("Textures");
ImGui::BeginChild("##TextureStorageChild", ImVec2(400, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar);
int index = 0;
for (auto& texture : m_children[1])
{
bool status = false;
void* textureRaw = nullptr;
if(texture->getType() == mvAppItemType::mvStaticTexture)
textureRaw = static_cast<mvStaticTexture*>(texture.get())->getRawTexture();
else
textureRaw = static_cast<mvDynamicTexture*>(texture.get())->getRawTexture();
ImGui::Image(textureRaw, ImVec2(25, 25));
ImGui::SameLine();
if (ImGui::Selectable(texture->m_name.c_str(), &status))
m_selection = index;
++index;
}
ImGui::EndChild();
if (m_selection != -1)
{
ImGui::SameLine();
ImGui::BeginGroup();
ImGui::BeginGroup();
ImGui::Text("Width: %d", m_children[1][m_selection]->getWidth());
ImGui::Text("Height: %d", m_children[1][m_selection]->getHeight());
ImGui::Text("Type: %s", m_children[1][m_selection]->getType() == mvAppItemType::mvStaticTexture ? "static" : "dynamic");
ImGui::EndGroup();
ImGui::SameLine();
void* textureRaw = nullptr;
if (m_children[1][m_selection]->getType() == mvAppItemType::mvStaticTexture)
textureRaw = static_cast<mvStaticTexture*>(m_children[1][m_selection].get())->getRawTexture();
else
textureRaw = static_cast<mvDynamicTexture*>(m_children[1][m_selection].get())->getRawTexture();
ImGui::Image(textureRaw, ImVec2((float)m_children[1][m_selection]->getWidth(), (float)m_children[1][m_selection]->getHeight()));
ImPlot::PushStyleColor(ImPlotCol_FrameBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f));
if (ImPlot::BeginPlot("##texture plot", 0, 0, ImVec2(-1, -1),
ImPlotFlags_NoTitle | ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_Equal))
{
ImPlot::PlotImage(m_children[1][m_selection]->m_name.c_str(), textureRaw, ImPlotPoint(0.0, 0.0),
ImPlotPoint(m_children[1][m_selection]->getWidth(), m_children[1][m_selection]->getHeight()));
ImPlot::EndPlot();
}
ImPlot::PopStyleColor();
ImGui::EndGroup();
}
}
ImGui::End();
ImGui::PopID();
}
} | 3,742 | 1,546 |
#include "ArrayLiteral.hh"
void ArrayLiteral::add_expression(ptr_t<Expression> &expression) {
m_expressions.push_back(std::move(expression));
}
void ArrayLiteral::analyze(Scope *scope) {
m_type.change_kind(Kind::ARRAY);
if (m_expressions.empty()) {
m_type.change_primitive(Primitive::DONT_CARE);
return;
}
m_expressions.front()->analyze(scope);
Type first = m_expressions.front()->type();
for (unsigned i = 1; i < m_expressions.size(); ++i) {
auto ¤t = m_expressions.at(i);
current->analyze(scope);
if (!current->is_literal()) {
error::add_semantic_error("Array literals require literal values", source_ref);
}
if (current->type() != first) {
error::add_semantic_error("Mismatched types in array literal", source_ref);
}
}
m_type.change_primitive(first.primitive());
}
std::string ArrayLiteral::dump(unsigned indent) const {
std::ostringstream oss {};
oss << util::indent(indent) << name() << " [" << std::endl;
for (auto &x : m_expressions) {
oss << x->dump(indent + 1) << std::endl;
}
oss << util::indent(indent) << "]";
return oss.str();
}
| 1,215 | 409 |
#include "squid.h"
/*
*
* SQUID Web Proxy Cache http://www.squid-cache.org/
* ----------------------------------------------------------
*
* Squid is the result of efforts by numerous individuals from
* the Internet community; see the CONTRIBUTORS file for full
* details. Many organizations have provided support for Squid's
* development; see the SPONSORS file for full details. Squid is
* Copyrighted (C) 2001 by the Regents of the University of
* California; see the COPYRIGHT file for full details. Squid
* incorporates software developed and/or copyrighted by other
* sources; see the CREDITS file for full details.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
*/
#include "acl/AclDenyInfoList.h"
#include "CacheDigest.h"
#include "defines.h"
#include "hash.h"
#include "IoStats.h"
#include "rfc2181.h"
#if HAVE_STDIO_H
#include <stdio.h>
#endif
char *ConfigFile = NULL;
char tmp_error_buf[ERROR_BUF_SZ];
char ThisCache[RFC2181_MAXHOSTNAMELEN << 1];
char ThisCache2[RFC2181_MAXHOSTNAMELEN << 1];
char config_input_line[BUFSIZ];
const char *DefaultConfigFile = DEFAULT_CONFIG_FILE;
const char *cfg_filename = NULL;
const char *dash_str = "-";
const char *null_string = "";
const char *version_string = VERSION;
const char *appname_string = PACKAGE;
char const *visible_appname_string = NULL;
int Biggest_FD = -1;
int Number_FD = 0;
int Opening_FD = 0;
int NDnsServersAlloc = 0;
int RESERVED_FD;
int Squid_MaxFD = SQUID_MAXFD;
int config_lineno = 0;
int do_mallinfo = 0;
int opt_reuseaddr = 1;
int neighbors_do_private_keys = 1;
int opt_catch_signals = 1;
int opt_foreground_rebuild = 0;
char *opt_forwarded_for = NULL;
int opt_reload_hit_only = 0;
int opt_udp_hit_obj = 0;
int opt_create_swap_dirs = 0;
int opt_store_doublecheck = 0;
int syslog_enable = 0;
int DnsSocketA = -1;
int DnsSocketB = -1;
int n_disk_objects = 0;
IoStats IOStats;
AclDenyInfoList *DenyInfoList = NULL;
struct timeval squid_start;
int starting_up = 1;
int shutting_down = 0;
int reconfiguring = 0;
time_t hit_only_mode_until = 0;
double request_failure_ratio = 0.0;
int store_hash_buckets = 0;
hash_table *store_table = NULL;
int hot_obj_count = 0;
int CacheDigestHashFuncCount = 4;
CacheDigest *store_digest = NULL;
const char *StoreDigestFileName = "store_digest";
const char *StoreDigestMimeStr = "application/cache-digest";
const char *MultipartMsgBoundaryStr = "Unique-Squid-Separator";
#if USE_HTTP_VIOLATIONS
int refresh_nocache_hack = 0;
#endif
int store_open_disk_fd = 0;
int store_swap_low = 0;
int store_swap_high = 0;
size_t store_pages_max = 0;
int64_t store_maxobjsize = -1;
hash_table *proxy_auth_username_cache = NULL;
int incoming_sockets_accepted;
#if _SQUID_MSWIN_
unsigned int WIN32_Socks_initialized = 0;
#endif
#if _SQUID_WINDOWS_
unsigned int WIN32_OS_version = 0;
char *WIN32_OS_string = NULL;
char *WIN32_Service_name = NULL;
char *WIN32_Command_Line = NULL;
char *WIN32_Service_Command_Line = NULL;
unsigned int WIN32_run_mode = _WIN_SQUID_RUN_MODE_INTERACTIVE;
#endif
#if HAVE_SBRK
void *sbrk_start = 0;
#endif
int ssl_ex_index_server = -1;
int ssl_ctx_ex_index_dont_verify_domain = -1;
int ssl_ex_index_cert_error_check = -1;
int ssl_ex_index_ssl_error_detail = -1;
int ssl_ex_index_ssl_peeked_cert = -1;
int ssl_ex_index_ssl_errors = -1;
const char *external_acl_message = NULL;
int opt_send_signal = -1;
int opt_no_daemon = 0;
int opt_parse_cfg_only = 0;
/// current Squid process number (e.g., 4).
/// Zero for SMP-unaware code and in no-SMP mode.
int KidIdentifier = 0;
| 4,208 | 1,597 |
#include "..\Inc\CRCinematicController.h"
float CinematicController::GetCurrentTime()
{
clock_t currentTime;
currentTime = clock();
return (float)currentTime/CLOCKS_PER_SEC;
}
void CinematicController::Init()
{
end = true;
filmStartTime = -1;
}
void CinematicController::Update()
{
float stage0Cost = 6.0f;
float stage1Cost = 3.0f;
float stage2Cost = 6.0f;
if (!end)
{
float currentTime = GetCurrentTime();
if (currentTime - filmStartTime >= stage0Cost + stage1Cost + stage2Cost)
{
end = true;
}
else
{
float process = (currentTime - filmStartTime) / (stage0Cost + stage1Cost + stage2Cost);
process = Math::Min(process, 1.0f);
float sunStartTime = 14.8f;
float sunEndTime = 16.6f;
float fogStartPrec = 55.0f;
float fogEndPrec = 60.0f;
float currentSunTime = (1.0f - process) * sunStartTime + process * sunEndTime;
WeatherSystem::Instance()->SetHour(currentSunTime);
float currentFogPrec = (1.0f - process) * fogStartPrec + process * fogEndPrec;
WeatherSystem::Instance()->SetFogPrecipitation(currentFogPrec);
if (currentTime - filmStartTime <= stage0Cost)
{
float3 camStartPos = float3(11.868318f, 5.0f, -8.464635f);
float3 camEndPos = float3(11.868318f, 3.151639f, -8.464635f);
process = (currentTime - filmStartTime) / stage0Cost;
process = Math::Min(process, 1.0f);
process = (-Math::Cos(process * PI) + 1.0f) * 0.5f;
float3 camCurrentPos = (1.0f - process) * camStartPos + process * camEndPos;
CameraManager::Instance()->GetCurrentCamera()->SetPosition(camCurrentPos);
}
else if (currentTime - filmStartTime <= stage0Cost + stage1Cost)
{
float3 camStartPos = float3(11.868318f, 3.151639f, -8.464635f);
float3 camEndPos = float3(9.648738f, 3.151639f, -4.547123f);
float3 camStartRota = float3(3.600040f, -54.599995f, 0.0f);
float3 camEndRota = float3(1.500041f, -43.599918f, 0.0f);
float camStartFov = 55.0f;
float camEndFov = 60.0f;
process = (currentTime - filmStartTime - stage0Cost) / stage1Cost;
process = Math::Min(process, 1.0f);
process = (-Math::Cos(process * PI) + 1.0f) * 0.5f;
float3 camCurrentPos = (1.0f - process) * camStartPos + process * camEndPos;
CameraManager::Instance()->GetCurrentCamera()->SetPosition(camCurrentPos);
float3 camCurrentRota = (1.0f - process) * camStartRota + process * camEndRota;
CameraManager::Instance()->GetCurrentCamera()->SetRotation(camCurrentRota);
float camCurrentFov = (1.0f - process) * camStartFov + process * camEndFov;
CameraManager::Instance()->GetCurrentCamera()->SetFov(camCurrentFov);
}
else
{
float3 camStartPos = float3(9.648738f, 3.151639f, -4.547123f);
float3 camEndPos = float3(11.303256f, 3.151639f, -2.809704f);
process = (currentTime - filmStartTime - stage0Cost - stage1Cost) / stage2Cost;
process = Math::Min(process, 1.0f);
process = (-Math::Cos(process * PI) + 1.0f) * 0.5f;
float3 camCurrentPos = (1.0f - process) * camStartPos + process * camEndPos;
CameraManager::Instance()->GetCurrentCamera()->SetPosition(camCurrentPos);
}
}
}
}
void CinematicController::KeyInputCallback(GLFWwindow * window, int key, int scanCode, int action, int mods)
{
switch (key)
{
default:
break;
case GLFW_KEY_F1:
{
if (action == GLFW_PRESS)
MenuManager::Instance()->ToogleMenu();
}
break;
case GLFW_KEY_P:
{
if (action == GLFW_PRESS)
{
ControllerManager::Instance()->Pop();
}
}
break;
case GLFW_KEY_SPACE:
{
if (action == GLFW_PRESS && end)
{
WeatherSystem::Instance()->SetHour(14.8f);
WeatherSystem::Instance()->SetFogPrecipitation(55.0f);
CameraManager::Instance()->GetCurrentCamera()->SetFov(55.0f);
CameraManager::Instance()->GetCurrentCamera()->SetPosition(float3(11.868318f, 5.0f, -8.464635f));
CameraManager::Instance()->GetCurrentCamera()->SetRotation(float3(3.600040f, -54.599995f, 0.0f));
filmStartTime = GetCurrentTime();
end = false;
}
}
break;
case GLFW_KEY_BACKSPACE:
{
if (action == GLFW_PRESS)
{
filmStartTime = GetCurrentTime();
}
}
break;
}
}
void CinematicController::MouseMotionCallback(GLFWwindow * window, double x, double y)
{
}
void CinematicController::ScrollCallback(GLFWwindow * window, double xOffset, double yOffset)
{
}
| 4,301 | 1,919 |