hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
c8c84c07fdf7eba54f87f0fb5902abc3edadd060
3,125
hpp
C++
src/Renderer/VulkanRendererImpl.hpp
mxtt-mmxix/York-Engine
a4592757b2fe52b4737c87ba59546dce2e90b9dd
[ "BSD-2-Clause" ]
null
null
null
src/Renderer/VulkanRendererImpl.hpp
mxtt-mmxix/York-Engine
a4592757b2fe52b4737c87ba59546dce2e90b9dd
[ "BSD-2-Clause" ]
null
null
null
src/Renderer/VulkanRendererImpl.hpp
mxtt-mmxix/York-Engine
a4592757b2fe52b4737c87ba59546dce2e90b9dd
[ "BSD-2-Clause" ]
null
null
null
/* * BSD 2-Clause License * * Copyright (c) 2022 Matthew McCall * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // // Created by Matthew McCall on 1/8/22. // #ifndef YORK_VULKANRENDERERIMPL_HPP #define YORK_VULKANRENDERERIMPL_HPP #include "york/Renderer/RendererImpl.hpp" #include "york/Renderer/Vertex.hpp" #include "york/Event.hpp" #include "Vulkan/Buffer.hpp" #include "Vulkan/CommandPool.hpp" #include "Vulkan/FrameData.hpp" #include "Vulkan/Framebuffer.hpp" #include "Vulkan/Pipeline.hpp" #include "Vulkan/Semaphore.hpp" namespace york { /** * The Renderer allows you to draw content to a Window. */ class VulkanRendererImpl : public EventHandler, public RendererImpl { public: /** * Create a Renderer bound to a window. * * @param window The window to bind to. */ explicit VulkanRendererImpl(Window& window); /** * Draws to the window bound to. * * By default the renderer uses tripled buffer v-sync. */ bool draw() override; void onEvent(Event &e) override; ~VulkanRendererImpl() override; private: vulkan::Surface m_surface; vulkan::PhysicalDevice m_physicalDevice; vulkan::Device m_device; vulkan::SwapChain m_swapChain; vulkan::RenderPass m_renderPass; vulkan::Pipeline m_pipeline; vulkan::CommandPool m_commandPool; vulkan::Buffer m_vertexBuffer; Vector<vulkan::Framebuffer> m_framebuffers; Vector<vulkan::Fence> m_fences; Vector<vulkan::Semaphore> m_imageAvailableSemaphores, m_renderFinishedSemaphores; Vector<vulkan::Shader> m_defaultShaders; Vector<vk::CommandBuffer> m_commandBuffers; Vector<Vertex> m_vertices; std::uint32_t m_frameIndex = 0; std::uint32_t m_maxFrames = 0; bool resize = false; void recreateSwapChain(); }; } #endif // YORK_VULKANRENDERERIMPL_HPP
30.637255
85
0.73824
mxtt-mmxix
c8c9158acca4f039fb52fe16fea629017db67bd7
263
cpp
C++
LeetCode/Problems/Algorithms/#70_ClimbingStairs_sol5_dp_O(N)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#70_ClimbingStairs_sol5_dp_O(N)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#70_ClimbingStairs_sol5_dp_O(N)_time_O(1)_extra_space.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int climbStairs(int n) { vector<int> f(2); f[0] = 1; f[1] = 1; for(int i = 2; i <= n; ++i){ f[i % 2] = f[(i - 1) % 2] + f[(i - 2) % 2]; } return f[n % 2]; } };
21.916667
56
0.323194
Tudor67
c8ca97ce5aeeb3d8b036d29649275e2f49bba83a
1,688
cpp
C++
openscenario/openscenario_interpreter/src/syntax/longitudinal_action.cpp
WJaworskiRobotec/scenario_simulator_v2
c23497ac8716dcefef20d4b5a4ff1185e01f48e6
[ "Apache-2.0" ]
45
2021-04-12T22:43:25.000Z
2022-02-27T23:57:53.000Z
openscenario/openscenario_interpreter/src/syntax/longitudinal_action.cpp
WJaworskiRobotec/scenario_simulator_v2
c23497ac8716dcefef20d4b5a4ff1185e01f48e6
[ "Apache-2.0" ]
140
2021-04-13T04:28:19.000Z
2022-03-30T12:44:32.000Z
openscenario/openscenario_interpreter/src/syntax/longitudinal_action.cpp
WJaworskiRobotec/scenario_simulator_v2
c23497ac8716dcefef20d4b5a4ff1185e01f48e6
[ "Apache-2.0" ]
13
2021-05-22T02:24:49.000Z
2022-03-25T05:16:31.000Z
// Copyright 2015-2021 Tier IV, Inc. 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 <openscenario_interpreter/reader/element.hpp> #include <openscenario_interpreter/syntax/longitudinal_action.hpp> namespace openscenario_interpreter { inline namespace syntax { LongitudinalAction::LongitudinalAction(const pugi::xml_node & node, Scope & scope) // clang-format off : ComplexType( choice(node, std::make_pair( "SpeedAction", [&](const auto & node) { return make<SpeedAction>(node, scope); }), std::make_pair("LongitudinalDistanceAction", [&](const auto & node) { throw UNSUPPORTED_ELEMENT_SPECIFIED(node.name()); return unspecified; }))) // clang-format on { } auto LongitudinalAction::endsImmediately() const -> bool { return apply<bool>([](const auto & action) { return action.endsImmediately(); }, *this); } auto LongitudinalAction::run() -> void { return apply<void>([](auto && action) { return action.run(); }, *this); } auto LongitudinalAction::start() -> void { return apply<void>([](auto && action) { return action.start(); }, *this); } } // namespace syntax } // namespace openscenario_interpreter
35.166667
150
0.719787
WJaworskiRobotec
c8cbba8523b7d615d28bf710acc233688249f5e0
49,224
cpp
C++
src/caffe/test/test_convolution_layer.cpp
Amanda-Barbara/nvcaffe
5155a708b235a818ce300aa3f9fc235ece9a35fb
[ "BSD-2-Clause" ]
758
2015-03-08T20:54:38.000Z
2022-01-11T03:14:51.000Z
src/caffe/test/test_convolution_layer.cpp
Matsuko9/caffe
17e347e42e664b87d80f63bfbbb89bec5e559242
[ "BSD-2-Clause" ]
493
2015-04-28T00:08:53.000Z
2021-08-04T07:26:54.000Z
src/caffe/test/test_convolution_layer.cpp
Matsuko9/caffe
17e347e42e664b87d80f63bfbbb89bec5e559242
[ "BSD-2-Clause" ]
389
2015-03-05T12:11:44.000Z
2022-03-13T21:49:42.000Z
#include <algorithm> #include <vector> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/layers/conv_layer.hpp" #ifdef USE_CUDNN #include "caffe/layers/cudnn_conv_layer.hpp" #endif #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" namespace caffe { // Reference convolution for checking results: // accumulate through explicit loops over input, output, and filters. template<typename Dtype> void caffe_conv(const TBlob<Dtype>* in, ConvolutionParameter* conv_param, const vector<shared_ptr<Blob>>& weights, TBlob<Dtype>* out) { const bool has_depth = (out->num_axes() == 5); if (!has_depth) { CHECK_EQ(4, out->num_axes()); } // Kernel size, stride, and pad int kernel_h, kernel_w; if (conv_param->has_kernel_h() || conv_param->has_kernel_w()) { kernel_h = conv_param->kernel_h(); kernel_w = conv_param->kernel_w(); } else { kernel_h = kernel_w = conv_param->kernel_size(0); } int pad_h, pad_w; if (conv_param->has_pad_h() || conv_param->has_pad_w()) { pad_h = conv_param->pad_h(); pad_w = conv_param->pad_w(); } else { pad_h = pad_w = conv_param->pad_size() ? conv_param->pad(0) : 0; } int stride_h, stride_w; if (conv_param->has_stride_h() || conv_param->has_stride_w()) { stride_h = conv_param->stride_h(); stride_w = conv_param->stride_w(); } else { stride_h = stride_w = conv_param->stride_size() ? conv_param->stride(0) : 1; } int dilation_h, dilation_w; dilation_h = dilation_w = conv_param->dilation_size() ? conv_param->dilation(0) : 1; int kernel_d, pad_d, stride_d, dilation_d; if (has_depth) { kernel_d = kernel_h; stride_d = stride_h; pad_d = pad_h; dilation_d = dilation_h; } else { kernel_d = stride_d = dilation_d = 1; pad_d = 0; } // Groups int groups = conv_param->group(); int o_g = out->shape(1) / groups; int k_g = in->shape(1) / groups; int o_head, k_head; // Convolution vector<int> weight_offset(4 + has_depth); vector<int> in_offset(4 + has_depth); vector<int> out_offset(4 + has_depth); Dtype* out_data = out->mutable_cpu_data(); for (int n = 0; n < out->shape(0); n++) { for (int g = 0; g < groups; g++) { o_head = o_g * g; k_head = k_g * g; for (int o = 0; o < o_g; o++) { for (int k = 0; k < k_g; k++) { for (int z = 0; z < (has_depth ? out->shape(2) : 1); z++) { for (int y = 0; y < out->shape(2 + has_depth); y++) { for (int x = 0; x < out->shape(3 + has_depth); x++) { for (int r = 0; r < kernel_d; r++) { for (int p = 0; p < kernel_h; p++) { for (int q = 0; q < kernel_w; q++) { int in_z = z * stride_d - pad_d + r * dilation_d; int in_y = y * stride_h - pad_h + p * dilation_h; int in_x = x * stride_w - pad_w + q * dilation_w; if (in_z >= 0 && in_z < (has_depth ? in->shape(2) : 1) && in_y >= 0 && in_y < in->shape(2 + has_depth) && in_x >= 0 && in_x < in->shape(3 + has_depth)) { weight_offset[0] = o + o_head; weight_offset[1] = k; if (has_depth) { weight_offset[2] = r; } weight_offset[2 + has_depth] = p; weight_offset[3 + has_depth] = q; in_offset[0] = n; in_offset[1] = k + k_head; if (has_depth) { in_offset[2] = in_z; } in_offset[2 + has_depth] = in_y; in_offset[3 + has_depth] = in_x; out_offset[0] = n; out_offset[1] = o + o_head; if (has_depth) { out_offset[2] = z; } out_offset[2 + has_depth] = y; out_offset[3 + has_depth] = x; out_data[out->offset(out_offset)] += in->data_at(in_offset) * weights[0]->data_at(weight_offset); } } } } } } } } } } } // Bias if (conv_param->bias_term()) { const Dtype* bias_data = weights[1]->cpu_data<Dtype>(); for (int n = 0; n < out->shape(0); n++) { for (int o = 0; o < out->shape(1); o++) { for (int z = 0; z < (has_depth ? out->shape(2) : 1); z++) { for (int y = 0; y < out->shape(2 + has_depth); y++) { for (int x = 0; x < out->shape(3 + has_depth); x++) { out_offset[0] = n; out_offset[1] = o; if (has_depth) { out_offset[2] = z; } out_offset[2 + has_depth] = y; out_offset[3 + has_depth] = x; out_data[out->offset(out_offset)] += bias_data[o]; } } } } } } } template void caffe_conv(const TBlob<float>* in, ConvolutionParameter* conv_param, const vector<shared_ptr<Blob>>& weights, TBlob<float>* out); template void caffe_conv(const TBlob<double>* in, ConvolutionParameter* conv_param, const vector<shared_ptr<Blob>>& weights, TBlob<double>* out); template<typename TypeParam> class ConvolutionLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: ConvolutionLayerTest() : blob_bottom_(new TBlob<Dtype>(2, 3, 6, 4)), blob_bottom_2_(new TBlob<Dtype>(2, 3, 6, 4)), blob_top_(new TBlob<Dtype>()), blob_top_2_(new TBlob<Dtype>()) {} virtual void SetUp() { // fill the values FillerParameter filler_param; filler_param.set_value(1.); GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); filler.Fill(this->blob_bottom_2_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~ConvolutionLayerTest() { delete blob_bottom_; delete blob_bottom_2_; delete blob_top_; delete blob_top_2_; } virtual TBlob<Dtype>* MakeReferenceTop(TBlob<Dtype>* top) { this->ref_blob_top_.reset(new TBlob<Dtype>()); this->ref_blob_top_->ReshapeLike(*top); return this->ref_blob_top_.get(); } TBlob<Dtype>* const blob_bottom_; TBlob<Dtype>* const blob_bottom_2_; TBlob<Dtype>* const blob_top_; TBlob<Dtype>* const blob_top_2_; shared_ptr<TBlob<Dtype>> ref_blob_top_; vector<Blob*> blob_bottom_vec_; vector<Blob*> blob_top_vec_; }; TYPED_TEST_CASE(ConvolutionLayerTest, TestDtypesAndDevices); TYPED_TEST(ConvolutionLayerTest, TestSetup) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(4); this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); shared_ptr<Layer<Dtype, Dtype>> layer(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), 2); EXPECT_EQ(this->blob_top_->channels(), 4); EXPECT_EQ(this->blob_top_->height(), 2); EXPECT_EQ(this->blob_top_->width(), 1); EXPECT_EQ(this->blob_top_2_->num(), 2); EXPECT_EQ(this->blob_top_2_->channels(), 4); EXPECT_EQ(this->blob_top_2_->height(), 2); EXPECT_EQ(this->blob_top_2_->width(), 1); // setting group should not change the shape convolution_param->set_num_output(3); convolution_param->set_group(3); layer.reset(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), 2); EXPECT_EQ(this->blob_top_->channels(), 3); EXPECT_EQ(this->blob_top_->height(), 2); EXPECT_EQ(this->blob_top_->width(), 1); EXPECT_EQ(this->blob_top_2_->num(), 2); EXPECT_EQ(this->blob_top_2_->channels(), 3); EXPECT_EQ(this->blob_top_2_->height(), 2); EXPECT_EQ(this->blob_top_2_->width(), 1); } TYPED_TEST(ConvolutionLayerTest, TestSimpleConvolution) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(4); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); shared_ptr<Layer<Dtype, Dtype>> layer(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], tol<Dtype>(1e-4, 2e-2)); } caffe_conv(this->blob_bottom_2_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_2_)); top_data = this->blob_top_2_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], tol<Dtype>(1e-4, 2e-2)); } } TYPED_TEST(ConvolutionLayerTest, TestDilatedConvolution) { typedef typename TypeParam::Dtype Dtype; vector<int> bottom_shape; bottom_shape.push_back(2); bottom_shape.push_back(3); bottom_shape.push_back(8); bottom_shape.push_back(7); this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) { this->blob_bottom_vec_[i]->Reshape(bottom_shape); } LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_dilation(2); convolution_param->set_num_output(4); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); shared_ptr<Layer<Dtype, Dtype>> layer(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } caffe_conv(this->blob_bottom_2_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_2_)); top_data = this->blob_top_2_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } } TYPED_TEST(ConvolutionLayerTest, Test0DConvolution) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); const int kNumOutput = 3; convolution_param->set_num_output(kNumOutput); convolution_param->set_axis(3); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); shared_ptr<Layer<Dtype, Dtype>> layer(new ConvolutionLayer<Dtype, Dtype>(layer_param)); vector<int> top_shape = this->blob_bottom_->shape(); top_shape[3] = kNumOutput; layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(top_shape, this->blob_top_->shape()); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. vector<int> weight_offset(2); const Blob* weight = layer->blobs()[0].get(); const Blob* bias = layer->blobs()[1].get(); const int num = this->blob_top_->count(3); const int dim = this->blob_top_->shape(3); const int bottom_dim = this->blob_bottom_->shape(3); for (int n = 0; n < num; ++n) { for (int d = 0; d < dim; ++d) { weight_offset[0] = d; Dtype value = bias->cpu_data<Dtype>()[d]; for (int bottom_d = 0; bottom_d < bottom_dim; ++bottom_d) { weight_offset[1] = bottom_d; value += weight->data_at(weight_offset) * this->blob_bottom_->cpu_data()[n * bottom_dim + bottom_d]; } EXPECT_NEAR(value, this->blob_top_->cpu_data()[n * dim + d], tol<Dtype>(1e-4, 1e-2)); } } } TYPED_TEST(ConvolutionLayerTest, TestSimple3DConvolution) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); vector<int> bottom_shape(5); bottom_shape[0] = this->blob_bottom_vec_[0]->shape(0); bottom_shape[1] = this->blob_bottom_vec_[0]->shape(1); bottom_shape[2] = 5; bottom_shape[3] = this->blob_bottom_vec_[0]->shape(2); bottom_shape[4] = this->blob_bottom_vec_[0]->shape(3); FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) { this->blob_bottom_vec_[i]->Reshape(bottom_shape); filler.Fill(this->blob_bottom_vec_[i]); } LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(4); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); shared_ptr<Layer<Dtype, Dtype>> layer(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], tol<Dtype>(1e-3, 1e-1)); } caffe_conv(this->blob_bottom_2_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_2_)); top_data = this->blob_top_2_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], tol<Dtype>(1e-3, 1e-1)); } } TYPED_TEST(ConvolutionLayerTest, TestDilated3DConvolution) { typedef typename TypeParam::Dtype Dtype; this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); vector<int> bottom_shape(5); bottom_shape[0] = this->blob_bottom_vec_[0]->shape(0); bottom_shape[1] = this->blob_bottom_vec_[0]->shape(1); bottom_shape[2] = 6; bottom_shape[3] = 7; bottom_shape[4] = 8; FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) { this->blob_bottom_vec_[i]->Reshape(bottom_shape); filler.Fill(this->blob_bottom_vec_[i]); } LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_dilation(2); convolution_param->set_num_output(4); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); shared_ptr<Layer<Dtype, Dtype>> layer(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { Dtype rel_err = std::max(Dtype(1.), Dtype(fabs(top_data[i]))) * tol<Dtype>(1e-4, 5e-2); EXPECT_NEAR(top_data[i], ref_top_data[i], rel_err); } caffe_conv(this->blob_bottom_2_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_2_)); top_data = this->blob_top_2_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { Dtype rel_err = std::max(Dtype(1.), Dtype(fabs(top_data[i]))) * tol<Dtype>(1e-4, 3e-2); EXPECT_NEAR(top_data[i], ref_top_data[i], rel_err); } } TYPED_TEST(ConvolutionLayerTest, Test1x1Convolution) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(1); convolution_param->add_stride(1); convolution_param->set_num_output(4); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); shared_ptr<Layer<Dtype, Dtype>> layer(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], tol<Dtype>(1e-4, 5e-3)); } } TYPED_TEST(ConvolutionLayerTest, TestSimpleConvolutionGroup) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(3); convolution_param->set_group(3); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); shared_ptr<Layer<Dtype, Dtype>> layer(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const Dtype* top_data; const Dtype* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], tol<Dtype>(1e-4, 1e-2)); } } TYPED_TEST(ConvolutionLayerTest, TestSobelConvolution) { // Test separable convolution by computing the Sobel operator // as a single filter then comparing the result // as the convolution of two rectangular filters. typedef typename TypeParam::Dtype Dtype; // Fill bottoms with identical Gaussian noise. shared_ptr<GaussianFiller<Dtype>> filler; FillerParameter filler_param; filler_param.set_value(1.); filler.reset(new GaussianFiller<Dtype>(filler_param)); filler->Fill(this->blob_bottom_); this->blob_bottom_2_->CopyFrom(*this->blob_bottom_); // Compute Sobel G_x operator as 3 x 3 convolution. LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(1); convolution_param->set_bias_term(false); shared_ptr<Layer<Dtype, Dtype>> layer(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->blobs().resize(1); layer->blobs()[0].reset(new TBlob<Dtype>(1, 3, 3, 3)); Dtype* weights = layer->blobs()[0]->template mutable_cpu_data<Dtype>(); for (int c = 0; c < 3; ++c) { int i = c * 9; // 3 x 3 filter weights[i + 0] = -1; weights[i + 1] = 0; weights[i + 2] = 1; weights[i + 3] = -2; weights[i + 4] = 0; weights[i + 5] = 2; weights[i + 6] = -1; weights[i + 7] = 0; weights[i + 8] = 1; } layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Compute Sobel G_x operator as separable 3 x 1 and 1 x 3 convolutions. // (1) the [1 2 1] column filter vector<Blob*> sep_blob_bottom_vec; vector<Blob*> sep_blob_top_vec; shared_ptr<TBlob<Dtype>> blob_sep(new TBlob<Dtype>()); sep_blob_bottom_vec.push_back(this->blob_bottom_2_); sep_blob_top_vec.push_back(this->blob_top_2_); convolution_param->clear_kernel_size(); convolution_param->clear_stride(); convolution_param->set_kernel_h(3); convolution_param->set_kernel_w(1); convolution_param->set_stride_h(2); convolution_param->set_stride_w(1); convolution_param->set_num_output(1); convolution_param->set_bias_term(false); layer.reset(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->blobs().resize(1); layer->blobs()[0].reset(new TBlob<Dtype>(1, 3, 3, 1)); Dtype* weights_1 = layer->blobs()[0]->template mutable_cpu_data<Dtype>(); for (int c = 0; c < 3; ++c) { int i = c * 3; // 3 x 1 filter weights_1[i + 0] = 1; weights_1[i + 1] = 2; weights_1[i + 2] = 1; } layer->SetUp(sep_blob_bottom_vec, sep_blob_top_vec); layer->Forward(sep_blob_bottom_vec, sep_blob_top_vec); // (2) the [-1 0 1] row filter blob_sep->CopyFrom(*this->blob_top_2_, false, true); sep_blob_bottom_vec.clear(); sep_blob_bottom_vec.push_back(blob_sep.get()); convolution_param->set_kernel_h(1); convolution_param->set_kernel_w(3); convolution_param->set_stride_h(1); convolution_param->set_stride_w(2); convolution_param->set_num_output(1); convolution_param->set_bias_term(false); layer.reset(new ConvolutionLayer<Dtype, Dtype>(layer_param)); layer->blobs().resize(1); layer->blobs()[0].reset(new TBlob<Dtype>(1, 1, 1, 3)); Dtype* weights_2 = layer->blobs()[0]->template mutable_cpu_data<Dtype>(); weights_2[0] = -1; weights_2[1] = 0; weights_2[2] = 1; layer->SetUp(sep_blob_bottom_vec, sep_blob_top_vec); layer->Forward(sep_blob_bottom_vec, sep_blob_top_vec); // Test equivalence of full and separable filters. const Dtype* top_data = this->blob_top_->cpu_data(); const Dtype* sep_top_data = this->blob_top_2_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], sep_top_data[i], tol<Dtype>(1e-4, 2e-2)); } } TYPED_TEST(ConvolutionLayerTest, TestNDAgainst2D) { typedef typename TypeParam::Dtype Dtype; const int kernel_h = 11; const int kernel_w = 13; vector<int> bottom_shape(4); bottom_shape[0] = 15; bottom_shape[1] = 18; bottom_shape[2] = kernel_h * 2; bottom_shape[3] = kernel_w * 2; FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) { this->blob_bottom_vec_[i]->Reshape(bottom_shape); filler.Fill(this->blob_bottom_vec_[i]); } LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->set_num_output(12); convolution_param->set_bias_term(false); convolution_param->set_group(6); convolution_param->set_kernel_h(kernel_h); convolution_param->set_kernel_w(kernel_w); convolution_param->mutable_weight_filler()->set_type("gaussian"); TBlob<Dtype> weights; TBlob<Dtype> top_diff; // Shape and fill weights and top_diff. bool copy_diff; bool reshape; { ConvolutionLayer<Dtype, Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); top_diff.ReshapeLike(*this->blob_top_); filler.Fill(&top_diff); ASSERT_EQ(1, layer.blobs().size()); copy_diff = false; reshape = true; weights.CopyFrom(*layer.blobs()[0], copy_diff, reshape); } vector<bool> propagate_down(1, true); TBlob<Dtype> result_2d; TBlob<Dtype> backward_result_2d; TBlob<Dtype> backward_weight_result_2d; // Test with 2D im2col { caffe_set<Dtype>(this->blob_top_->count(), TypedConsts<Dtype>::zero, this->blob_top_->mutable_cpu_data()); caffe_set<Dtype>(this->blob_bottom_->count(), TypedConsts<Dtype>::zero, this->blob_bottom_->mutable_cpu_diff()); caffe_set<Dtype>(weights.count(), TypedConsts<Dtype>::zero, weights.mutable_cpu_diff()); // Do SetUp and Forward; save Forward result in result_2d. convolution_param->set_force_nd_im2col(false); ConvolutionLayer<Dtype, Dtype> layer_2d(layer_param); layer_2d.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(1, layer_2d.blobs().size()); copy_diff = false; reshape = false; layer_2d.blobs()[0]->CopyFrom(weights, copy_diff, reshape); layer_2d.Forward(this->blob_bottom_vec_, this->blob_top_vec_); copy_diff = false; reshape = true; result_2d.CopyFrom(*this->blob_top_, copy_diff, reshape); // Copy pre-generated top diff into actual top diff; // do Backward and save result in backward_result_2d. ASSERT_EQ(this->blob_top_->shape(), top_diff.shape()); caffe_copy<Dtype>(top_diff.count(), top_diff.cpu_data(), this->blob_top_->mutable_cpu_diff()); layer_2d.Backward(this->blob_top_vec_, propagate_down, this->blob_bottom_vec_); copy_diff = true; reshape = true; backward_result_2d.CopyFrom(*this->blob_bottom_, copy_diff, reshape); backward_weight_result_2d.CopyFrom(weights, copy_diff, reshape); } TBlob<Dtype> result_nd; TBlob<Dtype> backward_result_nd; TBlob<Dtype> backward_weight_result_nd; // Test with ND im2col { caffe_set<Dtype>(this->blob_top_->count(), TypedConsts<Dtype>::zero, this->blob_top_->mutable_cpu_data()); caffe_set<Dtype>(this->blob_bottom_->count(), TypedConsts<Dtype>::zero, this->blob_bottom_->mutable_cpu_diff()); caffe_set<Dtype>(weights.count(), TypedConsts<Dtype>::zero, weights.mutable_cpu_diff()); // Do SetUp and Forward; save Forward result in result_nd. convolution_param->set_force_nd_im2col(true); ConvolutionLayer<Dtype, Dtype> layer_nd(layer_param); layer_nd.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_EQ(1, layer_nd.blobs().size()); copy_diff = false; reshape = false; layer_nd.blobs()[0]->CopyFrom(weights, copy_diff, reshape); layer_nd.Forward(this->blob_bottom_vec_, this->blob_top_vec_); copy_diff = false; reshape = true; result_nd.CopyFrom(*this->blob_top_, copy_diff, reshape); // Copy pre-generated top diff into actual top diff; // do Backward and save result in backward_result_nd. ASSERT_EQ(this->blob_top_->shape(), top_diff.shape()); caffe_copy<Dtype>(top_diff.count(), top_diff.cpu_data(), this->blob_top_->mutable_cpu_diff()); layer_nd.Backward(this->blob_top_vec_, propagate_down, this->blob_bottom_vec_); copy_diff = true; reshape = true; backward_result_nd.CopyFrom(*this->blob_bottom_, copy_diff, reshape); backward_weight_result_nd.CopyFrom(weights, copy_diff, reshape); } ASSERT_EQ(result_nd.count(), result_2d.count()); for (int i = 0; i < result_2d.count(); ++i) { EXPECT_EQ(result_2d.cpu_data()[i], result_nd.cpu_data()[i]); } ASSERT_EQ(backward_result_nd.count(), backward_result_2d.count()); for (int i = 0; i < backward_result_2d.count(); ++i) { if (is_type<Dtype>(FLOAT16)) EXPECT_NEAR(backward_result_2d.cpu_diff()[i], backward_result_nd.cpu_diff()[i], 0.2F); else EXPECT_EQ(backward_result_2d.cpu_diff()[i], backward_result_nd.cpu_diff()[i]); } ASSERT_EQ(backward_weight_result_nd.count(), backward_weight_result_2d.count()); for (int i = 0; i < backward_weight_result_2d.count(); ++i) { EXPECT_EQ(backward_weight_result_2d.cpu_diff()[i], backward_weight_result_nd.cpu_diff()[i]); } } TYPED_TEST(ConvolutionLayerTest, TestGradient) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(2); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); ConvolutionLayer<Dtype, Dtype> layer(layer_param); GradientChecker<Dtype> checker(tol<Dtype>(1e-2, 1e-1), tol<Dtype>(1e-3, 4e-1)); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(ConvolutionLayerTest, TestDilatedGradient) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); vector<int> bottom_shape; bottom_shape.push_back(2); bottom_shape.push_back(3); bottom_shape.push_back(5); bottom_shape.push_back(6); for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) { this->blob_bottom_vec_[i]->Reshape(bottom_shape); } convolution_param->add_kernel_size(3); convolution_param->add_dilation(2); convolution_param->set_num_output(2); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); ConvolutionLayer<Dtype, Dtype> layer(layer_param); GradientChecker<Dtype> checker(tol<Dtype>(1e-2, 1e-1), tol<Dtype>(1e-3, 1e-1)); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(ConvolutionLayerTest, TestGradient3D) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); vector<int> bottom_shape(5); bottom_shape[0] = this->blob_bottom_vec_[0]->shape(0); bottom_shape[1] = this->blob_bottom_vec_[0]->shape(1); bottom_shape[2] = 5; bottom_shape[3] = this->blob_bottom_vec_[0]->shape(2); bottom_shape[4] = this->blob_bottom_vec_[0]->shape(3); FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); for (int i = 0; i < this->blob_bottom_vec_.size(); ++i) { this->blob_bottom_vec_[i]->Reshape(bottom_shape); filler.Fill(this->blob_bottom_vec_[i]); } convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(2); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); ConvolutionLayer<Dtype, Dtype> layer(layer_param); GradientChecker<Dtype> checker(tol<Dtype>(6e-2, 1.e-1), tol<Dtype>(1e-3, 3e-1)); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(ConvolutionLayerTest, Test1x1Gradient) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); convolution_param->add_kernel_size(1); convolution_param->add_stride(1); convolution_param->set_num_output(2); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); ConvolutionLayer<Dtype, Dtype> layer(layer_param); GradientChecker<Dtype> checker(5e-2, tol<Dtype>(1e-3, 1e-1)); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(ConvolutionLayerTest, TestGradientGroup) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; layer_param.set_forward_type(tp<Dtype>()); layer_param.set_backward_type(tp<Dtype>()); layer_param.set_forward_math(tp<Dtype>()); layer_param.set_backward_math(tp<Dtype>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(3); convolution_param->set_group(3); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); ConvolutionLayer<Dtype, Dtype> layer(layer_param); GradientChecker<Dtype> checker(5e-2, tol<Dtype>(1e-3, 2e-1)); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } #ifdef USE_CUDNN template<typename Dtype> class CuDNNConvolutionLayerTest : public GPUDeviceTest<Dtype> { protected: CuDNNConvolutionLayerTest() : blob_bottom_(new TBlob<Dtype>(2, 3, 6, 4)), blob_bottom_2_(new TBlob<Dtype>(2, 3, 6, 4)), blob_top_(new TBlob<Dtype>()), blob_top_2_(new TBlob<Dtype>()) {} virtual void SetUp() { // fill the values FillerParameter filler_param; filler_param.set_value(1.); GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); filler.Fill(this->blob_bottom_2_); blob_bottom_vec_.push_back(blob_bottom_); blob_top_vec_.push_back(blob_top_); } virtual ~CuDNNConvolutionLayerTest() { delete blob_bottom_; delete blob_bottom_2_; delete blob_top_; delete blob_top_2_; } virtual TBlob<Dtype>* MakeReferenceTop(TBlob<Dtype>* top) { this->ref_blob_top_.reset(new TBlob<Dtype>()); this->ref_blob_top_->ReshapeLike(*top); return this->ref_blob_top_.get(); } TBlob<Dtype>* const blob_bottom_; TBlob<Dtype>* const blob_bottom_2_; TBlob<Dtype>* const blob_top_; TBlob<Dtype>* const blob_top_2_; shared_ptr<TBlob<Dtype>> ref_blob_top_; vector<Blob*> blob_bottom_vec_; vector<Blob*> blob_top_vec_; }; TYPED_TEST_CASE(CuDNNConvolutionLayerTest, TestDtypes); TYPED_TEST(CuDNNConvolutionLayerTest, TestSetupCuDNN) { this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); LayerParameter layer_param; layer_param.set_forward_type(tp<TypeParam>()); layer_param.set_backward_type(tp<TypeParam>()); layer_param.set_forward_math(tp<TypeParam>()); layer_param.set_backward_math(tp<TypeParam>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(4); this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); shared_ptr<Layer<TypeParam, TypeParam>> layer( new CuDNNConvolutionLayer<TypeParam, TypeParam>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), 2); EXPECT_EQ(this->blob_top_->channels(), 4); EXPECT_EQ(this->blob_top_->height(), 2); EXPECT_EQ(this->blob_top_->width(), 1); EXPECT_EQ(this->blob_top_2_->num(), 2); EXPECT_EQ(this->blob_top_2_->channels(), 4); EXPECT_EQ(this->blob_top_2_->height(), 2); EXPECT_EQ(this->blob_top_2_->width(), 1); // setting group should not change the shape convolution_param->set_num_output(3); convolution_param->set_group(3); layer.reset(new CuDNNConvolutionLayer<TypeParam, TypeParam>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), 2); EXPECT_EQ(this->blob_top_->channels(), 3); EXPECT_EQ(this->blob_top_->height(), 2); EXPECT_EQ(this->blob_top_->width(), 1); EXPECT_EQ(this->blob_top_2_->num(), 2); EXPECT_EQ(this->blob_top_2_->channels(), 3); EXPECT_EQ(this->blob_top_2_->height(), 2); EXPECT_EQ(this->blob_top_2_->width(), 1); } TYPED_TEST(CuDNNConvolutionLayerTest, TestSimpleConvolutionCuDNN) { this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); LayerParameter layer_param; layer_param.set_forward_type(tp<TypeParam>()); layer_param.set_backward_type(tp<TypeParam>()); layer_param.set_forward_math(tp<TypeParam>()); layer_param.set_backward_math(tp<TypeParam>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(4); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); shared_ptr<Layer<TypeParam, TypeParam>> layer( new CuDNNConvolutionLayer<TypeParam, TypeParam>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const TypeParam* top_data; const TypeParam* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], tol<TypeParam>(1e-4, 2e-2)); } caffe_conv(this->blob_bottom_2_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_2_)); top_data = this->blob_top_2_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], tol<TypeParam>(1e-4, 2e-2)); } } TYPED_TEST(CuDNNConvolutionLayerTest, TestSimpleConvolutionGroupCuDNN) { LayerParameter layer_param; layer_param.set_forward_type(tp<TypeParam>()); layer_param.set_backward_type(tp<TypeParam>()); layer_param.set_forward_math(tp<TypeParam>()); layer_param.set_backward_math(tp<TypeParam>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(3); convolution_param->set_group(3); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("constant"); convolution_param->mutable_bias_filler()->set_value(0.1); shared_ptr<Layer<TypeParam, TypeParam>> layer( new CuDNNConvolutionLayer<TypeParam, TypeParam>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Check against reference convolution. const TypeParam* top_data; const TypeParam* ref_top_data; caffe_conv(this->blob_bottom_, convolution_param, layer->blobs(), this->MakeReferenceTop(this->blob_top_)); top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], tol<TypeParam>(1e-4, 1e-2)) << i << " of " << this->blob_top_->count(); } } TYPED_TEST(CuDNNConvolutionLayerTest, TestSobelConvolutionCuDNN) { // Test separable convolution by computing the Sobel operator // as a single filter then comparing the result // as the convolution of two rectangular filters. // Fill bottoms with identical Gaussian noise. shared_ptr<GaussianFiller<TypeParam>> filler; FillerParameter filler_param; filler_param.set_value(1.); filler.reset(new GaussianFiller<TypeParam>(filler_param)); filler->Fill(this->blob_bottom_); this->blob_bottom_2_->CopyFrom(*this->blob_bottom_); // Compute Sobel G_x operator as 3 x 3 convolution. LayerParameter layer_param; layer_param.set_forward_type(tp<TypeParam>()); layer_param.set_backward_type(tp<TypeParam>()); layer_param.set_forward_math(tp<TypeParam>()); layer_param.set_backward_math(tp<TypeParam>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(1); convolution_param->set_bias_term(false); shared_ptr<Layer<TypeParam, TypeParam>> layer( new CuDNNConvolutionLayer<TypeParam, TypeParam>(layer_param)); layer->blobs().resize(1); layer->blobs()[0].reset(new TBlob<TypeParam>(1, 3, 3, 3)); TypeParam* weights = layer->blobs()[0]->template mutable_cpu_data<TypeParam>(); for (int c = 0; c < 3; ++c) { int i = c * 9; // 3 x 3 filter weights[i + 0] = -1; weights[i + 1] = 0; weights[i + 2] = 1; weights[i + 3] = -2; weights[i + 4] = 0; weights[i + 5] = 2; weights[i + 6] = -1; weights[i + 7] = 0; weights[i + 8] = 1; } layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); // Compute Sobel G_x operator as separable 3 x 1 and 1 x 3 convolutions. // (1) the [1 2 1] column filter vector<Blob*> sep_blob_bottom_vec; vector<Blob*> sep_blob_top_vec; shared_ptr<TBlob<TypeParam>> blob_sep(new TBlob<TypeParam>()); sep_blob_bottom_vec.push_back(this->blob_bottom_2_); sep_blob_top_vec.push_back(this->blob_top_2_); convolution_param->clear_kernel_size(); convolution_param->clear_stride(); convolution_param->set_kernel_h(3); convolution_param->set_kernel_w(1); convolution_param->set_stride_h(2); convolution_param->set_stride_w(1); convolution_param->set_num_output(1); convolution_param->set_bias_term(false); layer.reset(new CuDNNConvolutionLayer<TypeParam, TypeParam>(layer_param)); layer->blobs().resize(1); layer->blobs()[0].reset(new TBlob<TypeParam>(1, 3, 3, 1)); TypeParam* weights_1 = layer->blobs()[0]->template mutable_cpu_data<TypeParam>(); for (int c = 0; c < 3; ++c) { int i = c * 3; // 3 x 1 filter weights_1[i + 0] = 1; weights_1[i + 1] = 2; weights_1[i + 2] = 1; } layer->SetUp(sep_blob_bottom_vec, sep_blob_top_vec); layer->Forward(sep_blob_bottom_vec, sep_blob_top_vec); // (2) the [-1 0 1] row filter blob_sep->CopyFrom(*this->blob_top_2_, false, true); sep_blob_bottom_vec.clear(); sep_blob_bottom_vec.push_back(blob_sep.get()); convolution_param->set_kernel_h(1); convolution_param->set_kernel_w(3); convolution_param->set_stride_h(1); convolution_param->set_stride_w(2); convolution_param->set_num_output(1); convolution_param->set_bias_term(false); layer.reset(new CuDNNConvolutionLayer<TypeParam, TypeParam>(layer_param)); layer->blobs().resize(1); layer->blobs()[0].reset(new TBlob<TypeParam>(1, 1, 1, 3)); TypeParam* weights_2 = layer->blobs()[0]->template mutable_cpu_data<TypeParam>(); weights_2[0] = -1; weights_2[1] = 0; weights_2[2] = 1; layer->SetUp(sep_blob_bottom_vec, sep_blob_top_vec); layer->Forward(sep_blob_bottom_vec, sep_blob_top_vec); // Test equivalence of full and separable filters. const TypeParam* top_data = this->blob_top_->cpu_data(); const TypeParam* sep_top_data = this->blob_top_2_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], sep_top_data[i], tol<TypeParam>(1e-4, 2e-2)); } } TYPED_TEST(CuDNNConvolutionLayerTest, TestGradientCuDNN) { LayerParameter layer_param; layer_param.set_forward_type(tp<TypeParam>()); layer_param.set_backward_type(tp<TypeParam>()); layer_param.set_forward_math(tp<TypeParam>()); layer_param.set_backward_math(tp<TypeParam>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); this->blob_bottom_vec_.push_back(this->blob_bottom_2_); this->blob_top_vec_.push_back(this->blob_top_2_); // convolution_param->set_cudnn_convolution_algo_seeker( // ConvolutionParameter_CuDNNConvolutionAlgorithmSeeker_FINDEX); convolution_param->set_conv_algos_override("1,1,1"); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(2); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); CuDNNConvolutionLayer<TypeParam, TypeParam> layer(layer_param); GradientChecker<TypeParam> checker(tol<TypeParam>(4e-3, 1e-1), tol<TypeParam>(1e-3, 5e-1)); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(CuDNNConvolutionLayerTest, TestGradientGroupCuDNN) { LayerParameter layer_param; layer_param.set_forward_type(tp<TypeParam>()); layer_param.set_backward_type(tp<TypeParam>()); layer_param.set_forward_math(tp<TypeParam>()); layer_param.set_backward_math(tp<TypeParam>()); ConvolutionParameter* convolution_param = layer_param.mutable_convolution_param(); convolution_param->add_kernel_size(3); convolution_param->add_stride(2); convolution_param->set_num_output(3); convolution_param->set_group(3); convolution_param->set_cudnn_convolution_algo_seeker( ConvolutionParameter_CuDNNConvolutionAlgorithmSeeker_FINDEX); convolution_param->mutable_weight_filler()->set_type("gaussian"); convolution_param->mutable_bias_filler()->set_type("gaussian"); CuDNNConvolutionLayer<TypeParam, TypeParam> layer(layer_param); GradientChecker<TypeParam> checker(tol<TypeParam>(5e-2, 1e-1), tol<TypeParam>(1e-2, 5e-1)); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_); } #endif } // namespace caffe
43.216857
98
0.714855
Amanda-Barbara
c8cd66f298091f7fe74213346ca09586eccc8eba
506
cpp
C++
CHAPTER11/C11E12.cpp
lrpinnto/stroustrup-exercises
a471a0d7b49b51b7c26e005ff9e66f3f6db199dd
[ "MIT" ]
null
null
null
CHAPTER11/C11E12.cpp
lrpinnto/stroustrup-exercises
a471a0d7b49b51b7c26e005ff9e66f3f6db199dd
[ "MIT" ]
null
null
null
CHAPTER11/C11E12.cpp
lrpinnto/stroustrup-exercises
a471a0d7b49b51b7c26e005ff9e66f3f6db199dd
[ "MIT" ]
null
null
null
#include "../stroustrup/std_lib_facilities.h" //CHAPTER 11 EX 12 int main() { cout<<"Enter a text file: "; string iname; cin>>iname; ifstream ifs {iname}; if (!ifs) error("can't open input file",iname); ifs.exceptions(ifs.exceptions()|ios_base::badbit); string line; while(getline(ifs, line)) { string invertedline; for (int i = line.size(); i >= 0; i--) { invertedline+=line[i]; } cout<<invertedline<<'\n'; } }
21.083333
54
0.55336
lrpinnto
c8cf8fad3cc65b8131302bde5e253a654d48bac8
5,870
cpp
C++
build/linux-build/Sources/src/kha/kore/Sound.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/kha/kore/Sound.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/kha/kore/Sound.cpp
HedgehogFog/TimeOfDeath
b78abacf940e1a88c8b987d99764ebb6876c5dc6
[ "MIT" ]
null
null
null
// Generated by Haxe 4.0.0-preview.5 #include <hxcpp.h> #ifndef INCLUDED_StringTools #include <hxinc/StringTools.h> #endif #ifndef INCLUDED_haxe_Log #include <hxinc/haxe/Log.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <hxinc/haxe/io/Bytes.h> #endif #ifndef INCLUDED_kha_Resource #include <hxinc/kha/Resource.h> #endif #ifndef INCLUDED_kha_Sound #include <hxinc/kha/Sound.h> #endif #ifndef INCLUDED_kha_arrays_Float32ArrayPrivate #include <hxinc/kha/arrays/Float32ArrayPrivate.h> #endif #ifndef INCLUDED_kha_kore_Sound #include <hxinc/kha/kore/Sound.h> #endif #ifndef INCLUDED_sys_io_File #include <hxinc/sys/io/File.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_cccf4343f8efafc4_33_new,"kha.kore.Sound","new",0x4b148154,"kha.kore.Sound.new","kha/kore/Sound.hx",33,0x7012c0fc) HX_LOCAL_STACK_FRAME(_hx_pos_cccf4343f8efafc4_25_initWav,"kha.kore.Sound","initWav",0x7a2fa2f0,"kha.kore.Sound.initWav","kha/kore/Sound.hx",25,0x7012c0fc) HX_LOCAL_STACK_FRAME(_hx_pos_cccf4343f8efafc4_30_initOgg,"kha.kore.Sound","initOgg",0x7a299613,"kha.kore.Sound.initOgg","kha/kore/Sound.hx",30,0x7012c0fc) HX_LOCAL_STACK_FRAME(_hx_pos_cccf4343f8efafc4_47__createData,"kha.kore.Sound","_createData",0x3883a959,"kha.kore.Sound._createData","kha/kore/Sound.hx",47,0x7012c0fc) namespace kha{ namespace kore{ void Sound_obj::__construct(::String filename){ HX_STACKFRAME(&_hx_pos_cccf4343f8efafc4_33_new) HXLINE( 34) super::__construct(); HXLINE( 35) if (::StringTools_obj::endsWith(filename,HX_(".wav",be,71,c2,1e))) { HXLINE( 36) this->initWav(filename); } else { HXLINE( 38) if (::StringTools_obj::endsWith(filename,HX_(".ogg",e1,64,bc,1e))) { HXLINE( 39) this->initOgg(filename); } else { HXLINE( 42) ::haxe::Log_obj::trace((HX_("Unknown sound format: ",04,53,85,0f) + filename),hx::SourceInfo(HX_("kha/kore/Sound.hx",fc,c0,12,70),42,HX_("kha.kore.Sound",62,87,c4,f4),HX_("new",60,d0,53,00))); } } } Dynamic Sound_obj::__CreateEmpty() { return new Sound_obj; } void *Sound_obj::_hx_vtable = 0; Dynamic Sound_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Sound_obj > _hx_result = new Sound_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool Sound_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x21ee7440) { return inClassId==(int)0x00000001 || inClassId==(int)0x21ee7440; } else { return inClassId==(int)0x6dd9d24b; } } void Sound_obj::initWav(::String filename){ HX_STACKFRAME(&_hx_pos_cccf4343f8efafc4_25_initWav) Kore::Sound* sound = new Kore::Sound(filename.c_str()); this->_createData(sound->size * 2); Kore::s16* left = (Kore::s16*)&sound->left[0]; Kore::s16* right = (Kore::s16*)&sound->right[0]; for (int i = 0; i < sound->size; i += 1) { uncompressedData->self.data[i * 2 + 0] = (float)(left [i] / 32767.0); uncompressedData->self.data[i * 2 + 1] = (float)(right[i] / 32767.0); } delete sound; } HX_DEFINE_DYNAMIC_FUNC1(Sound_obj,initWav,(void)) void Sound_obj::initOgg(::String filename){ HX_STACKFRAME(&_hx_pos_cccf4343f8efafc4_30_initOgg) HXDLIN( 30) this->compressedData = ::sys::io::File_obj::getBytes(filename); } HX_DEFINE_DYNAMIC_FUNC1(Sound_obj,initOgg,(void)) void Sound_obj::_createData(int size){ HX_GC_STACKFRAME(&_hx_pos_cccf4343f8efafc4_47__createData) HXDLIN( 47) ::kha::arrays::Float32ArrayPrivate this1 = ::kha::arrays::Float32ArrayPrivate_obj::__alloc( HX_CTX ,size); HXDLIN( 47) this->uncompressedData = this1; } HX_DEFINE_DYNAMIC_FUNC1(Sound_obj,_createData,(void)) hx::ObjectPtr< Sound_obj > Sound_obj::__new(::String filename) { hx::ObjectPtr< Sound_obj > __this = new Sound_obj(); __this->__construct(filename); return __this; } hx::ObjectPtr< Sound_obj > Sound_obj::__alloc(hx::Ctx *_hx_ctx,::String filename) { Sound_obj *__this = (Sound_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Sound_obj), true, "kha.kore.Sound")); *(void **)__this = Sound_obj::_hx_vtable; __this->__construct(filename); return __this; } Sound_obj::Sound_obj() { } hx::Val Sound_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 7: if (HX_FIELD_EQ(inName,"initWav") ) { return hx::Val( initWav_dyn() ); } if (HX_FIELD_EQ(inName,"initOgg") ) { return hx::Val( initOgg_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"_createData") ) { return hx::Val( _createData_dyn() ); } } return super::__Field(inName,inCallProp); } #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo *Sound_obj_sMemberStorageInfo = 0; static hx::StaticInfo *Sound_obj_sStaticStorageInfo = 0; #endif static ::String Sound_obj_sMemberFields[] = { HX_("initWav",fc,67,91,cb), HX_("initOgg",1f,5b,8b,cb), HX_("_createData",65,e4,7a,27), ::String(null()) }; hx::Class Sound_obj::__mClass; void Sound_obj::__register() { Sound_obj _hx_dummy; Sound_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("kha.kore.Sound",62,87,c4,f4); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(Sound_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< Sound_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Sound_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Sound_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace kha } // end namespace kore
33.352273
208
0.716014
HedgehogFog
c8d14feb6268f98a7fb72de26fd839f876530618
680
hpp
C++
vm/test/test_symbol.hpp
DCarper/rubinius
6d1f079d0e792fda5606de65c81c8d622366a822
[ "BSD-3-Clause" ]
1
2015-11-05T01:23:05.000Z
2015-11-05T01:23:05.000Z
vm/test/test_symbol.hpp
slawosz/rubinius
6cb4a19a33e942110ae14a1721cf4b48036fcc06
[ "BSD-3-Clause" ]
null
null
null
vm/test/test_symbol.hpp
slawosz/rubinius
6cb4a19a33e942110ae14a1721cf4b48036fcc06
[ "BSD-3-Clause" ]
1
2021-09-18T04:55:38.000Z
2021-09-18T04:55:38.000Z
#include "vm/test/test.hpp" #include "builtin/symbol.hpp" class TestSymbol : public CxxTest::TestSuite, public VMTest { public: void setUp() { create(); } void tearDown() { destroy(); } void test_index() { Symbol* sym = state->symbol("blah"); TS_ASSERT_EQUALS(sym->index(state)->to_native(), sym->index()); } void test_to_str() { Symbol* sym = state->symbol("blah"); String* str = sym->to_str(state); TS_ASSERT(!strncmp("blah", str->c_str(state), 4)); } void test_all_symbols() { Array* symbols = Symbol::all_symbols(state); TS_ASSERT(kind_of<Array>(symbols)); TS_ASSERT(state->shared.symbols.size() > 0); } };
19.428571
67
0.626471
DCarper
c8d364dc2ff97005be0bde0643dec9b6c96d0a42
1,225
cpp
C++
Hiring Challenges/Google-APAC-Kickstart/Practice Round APAC Test 2017/Problem A - Lazy Spelling Bee/Problem A.cpp
cnm06/Competitive-Programming
94242ae458570d503b8218f37624b88cc5020d23
[ "MIT" ]
2
2020-03-18T13:49:27.000Z
2020-03-19T08:22:47.000Z
Hiring Challenges/Google-APAC-Kickstart/Practice Round APAC Test 2017/Problem A - Lazy Spelling Bee/Problem A.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
null
null
null
Hiring Challenges/Google-APAC-Kickstart/Practice Round APAC Test 2017/Problem A - Lazy Spelling Bee/Problem A.cpp
Quadrified/Competitive-Programming
bccb69952cc5260fb3647b3301ddac1023dacac8
[ "MIT" ]
1
2020-03-19T08:22:50.000Z
2020-03-19T08:22:50.000Z
#include <bits/stdc++.h> using namespace std; int main() { freopen("A-large-practice.in", "r", stdin); freopen("output.txt", "w", stdout); long long int n, i , j, ans, c; string s; cin>>n; for(i=0;i<n;i++){ cin>>s; ans = 1; if(s.length()==1){ ans = 1; } else if(s.length()==2){ if(s[0]==s[1]){ ans = 1; } else { ans = 4; } } else { if(s[1]!=s[0]){ ans = ans * 2; ans = ans % 1000000007; } for(j=1;j<s.length()-1;j++){ if(s[j]==s[j-1] && s[j]==s[j+1] && s[j-1]==s[j+1]){ ans = ans * 1; } else if(s[j]==s[j-1] || s[j]==s[j+1] || s[j-1]==s[j+1]){ ans = ans * 2; } else { ans = ans * 3; } ans = ans % 1000000007; } if(s[j]!=s[j-1]){ ans = ans * 2; ans = ans % 1000000007; } } cout<<"Case #"<<i+1<<": "<<ans<<endl; } return 0; }
25
72
0.298776
cnm06
c8d6b64af2d57a988993ccd4c2e739b14d5d9f99
19,697
hpp
C++
libraries/app/include/graphene/app/api.hpp
BlockLink/HX-core
646bdb19d7be7b4fd1ee94c777ef8e42d9aea783
[ "MIT" ]
1
2018-12-12T08:38:09.000Z
2018-12-12T08:38:09.000Z
libraries/app/include/graphene/app/api.hpp
BlockLink/HX-core
646bdb19d7be7b4fd1ee94c777ef8e42d9aea783
[ "MIT" ]
null
null
null
libraries/app/include/graphene/app/api.hpp
BlockLink/HX-core
646bdb19d7be7b4fd1ee94c777ef8e42d9aea783
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/app/database_api.hpp> #include <graphene/chain/protocol/types.hpp> #include <graphene/chain/protocol/confidential.hpp> #include <graphene/market_history/market_history_plugin.hpp> #include <graphene/debug_witness/debug_api.hpp> #include <graphene/net/node.hpp> #include <fc/api.hpp> #include <fc/optional.hpp> #include <fc/crypto/elliptic.hpp> #include <fc/network/ip.hpp> #include <graphene/crosschain/crosschain.hpp> #include <boost/container/flat_set.hpp> #include <functional> #include <map> #include <string> #include <vector> namespace graphene { namespace app { using namespace graphene::chain; using namespace graphene::market_history; using namespace fc::ecc; using namespace std; class application; struct verify_range_result { bool success; uint64_t min_val; uint64_t max_val; }; struct verify_range_proof_rewind_result { bool success; uint64_t min_val; uint64_t max_val; uint64_t value_out; fc::ecc::blind_factor_type blind_out; string message_out; }; struct account_asset_balance { string name; account_id_type account_id; share_type amount; }; struct asset_holders { asset_id_type asset_id; int count; }; /** * @brief The history_api class implements the RPC API for transaction * * This API contains methods to access transactions */ class transaction_api { public: transaction_api(application& app); ~transaction_api(); optional<graphene::chain::full_transaction> get_transaction(transaction_id_type trx_id); vector<transaction_id_type> list_transactions(uint32_t blocknum=0,uint32_t nums=-1); void set_tracked_addr(const address& addr); private: application & _app; }; /** * @brief The history_api class implements the RPC API for account history * * This API contains methods to access account histories */ class history_api { public: history_api(application& app):_app(app){} /** * @brief Get operations relevant to the specificed account * @param account The account whose history should be queried * @param stop ID of the earliest operation to retrieve * @param limit Maximum number of operations to retrieve (must not exceed 100) * @param start ID of the most recent operation to retrieve * @return A list of operations performed by account, ordered from most recent to oldest. */ vector<operation_history_object> get_account_history(account_id_type account, operation_history_id_type stop = operation_history_id_type(), unsigned limit = 100, operation_history_id_type start = operation_history_id_type())const; /** * @brief Get only asked operations relevant to the specified account * @param account The account whose history should be queried * @param operation_id The ID of the operation we want to get operations in the account( 0 = transfer , 1 = limit order create, ...) * @param stop ID of the earliest operation to retrieve * @param limit Maximum number of operations to retrieve (must not exceed 100) * @param start ID of the most recent operation to retrieve * @return A list of operations performed by account, ordered from most recent to oldest. */ vector<operation_history_object> get_account_history_operations(account_id_type account, int operation_id, operation_history_id_type start = operation_history_id_type(), operation_history_id_type stop = operation_history_id_type(), unsigned limit = 100)const; /** * @breif Get operations relevant to the specified account referenced * by an event numbering specific to the account. The current number of operations * for the account can be found in the account statistics (or use 0 for start). * @param account The account whose history should be queried * @param stop Sequence number of earliest operation. 0 is default and will * query 'limit' number of operations. * @param limit Maximum number of operations to retrieve (must not exceed 100) * @param start Sequence number of the most recent operation to retrieve. * 0 is default, which will start querying from the most recent operation. * @return A list of operations performed by account, ordered from most recent to oldest. */ vector<operation_history_object> get_relative_account_history( account_id_type account, uint32_t stop = 0, unsigned limit = 100, uint32_t start = 0) const; vector<order_history_object> get_fill_order_history( asset_id_type a, asset_id_type b, uint32_t limit )const; vector<bucket_object> get_market_history( asset_id_type a, asset_id_type b, uint32_t bucket_seconds, fc::time_point_sec start, fc::time_point_sec end )const; flat_set<uint32_t> get_market_history_buckets()const; private: application& _app; }; /** * @brief Block api */ class block_api { public: block_api(graphene::chain::database& db); ~block_api(); vector<optional<signed_block>> get_blocks(uint32_t block_num_from, uint32_t block_num_to)const; private: graphene::chain::database& _db; }; /** * @brief The network_broadcast_api class allows broadcasting of transactions. */ class network_broadcast_api : public std::enable_shared_from_this<network_broadcast_api> { public: network_broadcast_api(application& a); struct transaction_confirmation { transaction_id_type id; uint32_t block_num; uint32_t trx_num; processed_transaction trx; }; typedef std::function<void(variant/*transaction_confirmation*/)> confirmation_callback; /** * @brief Broadcast a transaction to the network * @param trx The transaction to broadcast * * The transaction will be checked for validity in the local database prior to broadcasting. If it fails to * apply locally, an error will be thrown and the transaction will not be broadcast. */ void broadcast_transaction(const signed_transaction& trx); /** this version of broadcast transaction registers a callback method that will be called when the transaction is * included into a block. The callback method includes the transaction id, block number, and transaction number in the * block. */ void broadcast_transaction_with_callback( confirmation_callback cb, const signed_transaction& trx); /** this version of broadcast transaction registers a callback method that will be called when the transaction is * included into a block. The callback method includes the transaction id, block number, and transaction number in the * block. */ fc::variant broadcast_transaction_synchronous(const signed_transaction& trx); void broadcast_block( const signed_block& block ); /** * @brief Not reflected, thus not accessible to API clients. * * This function is registered to receive the applied_block * signal from the chain database when a block is received. * It then dispatches callbacks to clients who have requested * to be notified when a particular txid is included in a block. */ void on_applied_block( const signed_block& b ); private: boost::signals2::scoped_connection _applied_block_connection; map<transaction_id_type,confirmation_callback> _callbacks; application& _app; }; /** * @brief The network_node_api class allows maintenance of p2p connections. */ class network_node_api { public: network_node_api(application& a); /** * @brief Return general network information, such as p2p port */ fc::variant_object get_info() const; /** * @brief add_node Connect to a new peer * @param ep The IP/Port of the peer to connect to */ void add_node(const fc::ip::endpoint& ep); /** * @brief Get status of all current connections to peers */ std::vector<net::peer_status> get_connected_peers() const; /** * @brief Get advanced node parameters, such as desired and max * number of connections */ fc::variant_object get_advanced_node_parameters() const; /** * @brief Set advanced node parameters, such as desired and max * number of connections * @param params a JSON object containing the name/value pairs for the parameters to set */ void set_advanced_node_parameters(const fc::variant_object& params); /** * @brief Return list of potential peers */ std::vector<net::potential_peer_record> get_potential_peers() const; private: application& _app; }; class crypto_api { public: crypto_api(); fc::ecc::blind_signature blind_sign( const extended_private_key_type& key, const fc::ecc::blinded_hash& hash, int i ); signature_type unblind_signature( const extended_private_key_type& key, const extended_public_key_type& bob, const fc::ecc::blind_signature& sig, const fc::sha256& hash, int i ); fc::ecc::commitment_type blind( const fc::ecc::blind_factor_type& blind, uint64_t value ); fc::ecc::blind_factor_type blind_sum( const std::vector<blind_factor_type>& blinds_in, uint32_t non_neg ); bool verify_sum( const std::vector<commitment_type>& commits_in, const std::vector<commitment_type>& neg_commits_in, int64_t excess ); verify_range_result verify_range( const fc::ecc::commitment_type& commit, const std::vector<char>& proof ); std::vector<char> range_proof_sign( uint64_t min_value, const commitment_type& commit, const blind_factor_type& commit_blind, const blind_factor_type& nonce, int8_t base10_exp, uint8_t min_bits, uint64_t actual_value ); verify_range_proof_rewind_result verify_range_proof_rewind( const blind_factor_type& nonce, const fc::ecc::commitment_type& commit, const std::vector<char>& proof ); range_proof_info range_get_info( const std::vector<char>& proof ); }; /** * @brief */ class asset_api { public: asset_api(graphene::chain::database& db); ~asset_api(); vector<account_asset_balance> get_asset_holders( asset_id_type asset_id, uint32_t start, uint32_t limit )const; int get_asset_holders_count( asset_id_type asset_id )const; vector<asset_holders> get_all_asset_holders() const; private: graphene::chain::database& _db; }; class crosschain_api { public: crosschain_api(const string& config,const vector<string>& crosschain_symbols); ~crosschain_api(); string get_config(); bool contain_symbol(const string& symbol); private: string _config; std::vector<string> _crosschain_symbols; }; class localnode_api { private: application& _app; public: localnode_api(application& app) :_app(app) {}; ~localnode_api() {}; void witness_node_stop(); }; class miner_api { private: boost::program_options::variables_map option; application& _app; public: miner_api(application& app):_app(app){}; ~miner_api() {}; void start_miner(bool start); }; /** * @brief The login_api class implements the bottom layer of the RPC API * * All other APIs must be requested from this API. */ class login_api { public: login_api(application& a); ~login_api(); /** * @brief Authenticate to the RPC server * @param user Username to login with * @param password Password to login with * @return True if logged in successfully; false otherwise * * @note This must be called prior to requesting other APIs. Other APIs may not be accessible until the client * has sucessfully authenticated. */ bool login(const string& user, const string& password); /// @brief Retrieve the network block API fc::api<block_api> block()const; /// @brief Retrieve the network broadcast API fc::api<network_broadcast_api> network_broadcast()const; /// @brief Retrieve the database API fc::api<database_api> database()const; /// @brief Retrieve the history API fc::api<history_api> history()const; /// @brief Retrieve the network node API fc::api<network_node_api> network_node()const; /// @brief Retrieve the cryptography API fc::api<crypto_api> crypto()const; /// @brief Retrieve the asset API fc::api<asset_api> asset()const; /// @brief Retrieve the debug API (if available) fc::api<graphene::debug_miner::debug_api> debug()const; fc::api<crosschain_api> crosschain_config() const; fc::api<transaction_api> transaction() const; fc::api<miner_api> miner() const; fc::api<localnode_api> localnode() const; /// @brief Called to enable an API, not reflected. void enable_api( const string& api_name ); private: application& _app; optional< fc::api<block_api> > _block_api; optional< fc::api<transaction_api> > _transaction_api; optional< fc::api<database_api> > _database_api; optional< fc::api<network_broadcast_api> > _network_broadcast_api; optional< fc::api<network_node_api> > _network_node_api; optional< fc::api<history_api> > _history_api; optional< fc::api<crypto_api> > _crypto_api; optional< fc::api<asset_api> > _asset_api; optional< fc::api<graphene::debug_miner::debug_api> > _debug_api; optional <fc::api<crosschain_api >> _crosschain_api; optional <fc::api<miner_api>> _miner_api; optional <fc::api<localnode_api>> _localnode_api; }; }} // graphene::app FC_REFLECT( graphene::app::network_broadcast_api::transaction_confirmation, (id)(block_num)(trx_num)(trx) ) FC_REFLECT( graphene::app::verify_range_result, (success)(min_val)(max_val) ) FC_REFLECT( graphene::app::verify_range_proof_rewind_result, (success)(min_val)(max_val)(value_out)(blind_out)(message_out) ) //FC_REFLECT_TYPENAME( fc::ecc::compact_signature ); //FC_REFLECT_TYPENAME( fc::ecc::commitment_type ); FC_REFLECT( graphene::app::account_asset_balance, (name)(account_id)(amount) ); FC_REFLECT( graphene::app::asset_holders, (asset_id)(count) ); FC_API(graphene::app::history_api, (get_account_history) (get_account_history_operations) (get_relative_account_history) (get_fill_order_history) (get_market_history) (get_market_history_buckets) ) FC_API(graphene::app::crosschain_api, (get_config) (contain_symbol) ) FC_API(graphene::app::block_api, (get_blocks) ) FC_API(graphene::app::miner_api, (start_miner) ) FC_API(graphene::app::localnode_api, (witness_node_stop) ) FC_API(graphene::app::transaction_api, (get_transaction) (list_transactions) (set_tracked_addr) ) FC_API(graphene::app::network_broadcast_api, (broadcast_transaction) (broadcast_transaction_with_callback) (broadcast_transaction_synchronous) (broadcast_block) ) FC_API(graphene::app::network_node_api, (get_info) (add_node) (get_connected_peers) (get_potential_peers) (get_advanced_node_parameters) (set_advanced_node_parameters) ) FC_API(graphene::app::crypto_api, (blind_sign) (unblind_signature) (blind) (blind_sum) (verify_sum) (verify_range) (range_proof_sign) (verify_range_proof_rewind) (range_get_info) ) FC_API(graphene::app::asset_api, (get_asset_holders) (get_asset_holders_count) (get_all_asset_holders) ) FC_API(graphene::app::login_api, (login) (block) (network_broadcast) (database) (history) (network_node) (crypto) (asset) (debug) (crosschain_config) (transaction) (miner) (localnode) )
37.95183
143
0.611819
BlockLink
c8d83b80e986578833fa84ca5c0fbfb51570cf2c
3,722
cpp
C++
Projetos/Aula15/main.cpp
chaua/programacao-avancada
4f580006d6e7e79e1bb6b32a62702eda3daa5874
[ "MIT" ]
15
2018-04-05T00:15:01.000Z
2022-03-26T00:08:32.000Z
Projetos/Aula15/main.cpp
chaua/programacao-avancada
4f580006d6e7e79e1bb6b32a62702eda3daa5874
[ "MIT" ]
null
null
null
Projetos/Aula15/main.cpp
chaua/programacao-avancada
4f580006d6e7e79e1bb6b32a62702eda3daa5874
[ "MIT" ]
7
2018-03-23T00:11:56.000Z
2020-05-05T02:55:44.000Z
#include <iostream> #include <iomanip> #include <string> #include <list> #include <vector> #include <algorithm> using namespace std; class Aluno { public: Aluno(string nome, float n1, float n2) : _nome(nome), _nota1(n1), _nota2(n2) {} float media() const { return (_nota1 + _nota2) / 2; } string getNome() { return _nome; } bool operator<(const Aluno &outro) const { return media() < outro.media(); } friend ostream& operator<<(ostream &os, Aluno &aluno) { os << setw(12) << aluno._nome << " - " << aluno.media(); return os; } private: string _nome; float _nota1; float _nota2; }; // == Ponteiros para funcao == // - atribui o endereco da funcao para uma variavel // - permite a passagem de funcoes por parametro int soma(int a, int b) { return a + b; } int mult(int a, int b) { return a * b; } // == Functors == // - eh um objeto que se comporta como uma funcao // - obtido atraves da sobrecarga do operador () class ComparaAlunosNome { public: bool operator()(Aluno &a1, Aluno &a2) { return a1.getNome() < a2.getNome(); } }; class ComparaAlunosNota { public: bool operator()(Aluno &a1, Aluno &a2) { return a1.media() > a2.media(); } }; int main() { vector<Aluno> alunos; alunos.push_back(Aluno("Joao", 8.9, 1.2)); alunos.push_back(Aluno("Pedro", 3.3, 9.2)); alunos.push_back(Aluno("Marcia", 10, 9.1)); alunos.push_back(Aluno("Mariana", 8.5, 5.6)); alunos.push_back(Aluno("Ana", 8.8, 7.0)); alunos.push_back(Aluno("Jose", 8.0, 8.0)); cout << "Alunos: " << endl; for (int i = 0; i < alunos.size(); i++) { cout << alunos[i] << endl; } sort(alunos.begin(), alunos.end()); cout << "Alunos - ordenados por nota: " << endl; for (int i = 0; i < alunos.size(); i++){ cout << alunos[i] << endl; } // Exemplo de ponteiro para funcao int (*ptr)(int, int); ptr = &soma; cout << ptr(10, 20) << endl; ptr = &mult; cout << ptr(10, 20) << endl; // Ordenando objetos via comparator ComparaAlunosNome compara; compara(alunos[0], alunos[1]); sort(alunos.begin(), alunos.end(), compara); cout << "Alunos - ordenados por nome: " << endl; for (int i = 0; i < alunos.size(); i++) { cout << alunos[i] << endl; } // Ordenando objetos via comparator sort(alunos.begin(), alunos.end(), ComparaAlunosNota()); cout << "Alunos - ordenados por nota: " << endl; for (int i = 0; i < alunos.size(); i++) { cout << alunos[i] << endl; } // == Funcoes lambda == // - Conceito herdado do paradigma funcionalista (Lisp, ADA) // - Permitem a criacao de funcoes locais, sem nome, para serem usadas apenas uma vez // // SINTAXE: // [captura](parametros) -> tipo_retorno { corpo da funcao } // // - captura: variaveis do escopo externo que sao visiveis no escopo interno // - parametros: lista de parametros da funcao // - tipo_retorno: valor que a funcao retorna int x = 0; auto lambda = [&x](int a, int b) -> int { x = 1000; return soma(a, b); }; cout << "lambda: " << lambda(3, 7) << endl; cout << "x.....: " << x << endl; // Ordenando os alunos com funcao lambda sort(alunos.begin(), alunos.end(), [](Aluno &a1, Aluno &a2) -> bool { return a1.media() < a2.media(); }); cout << "Ordenando os alunos com funcao lambda" << endl; for_each(alunos.begin(), alunos.end(), [](Aluno &aluno) { cout << aluno << endl; }); }
24.649007
90
0.551854
chaua
c8db3e38576e1a1087d7f289695e786508236492
1,869
hpp
C++
include/ioh/problem/bbob/griewank_rosenbrock.hpp
tobiasvandriessel/IOHexperimenter
da22d89fe1673ea67962829d12873e01387f6895
[ "BSD-3-Clause" ]
null
null
null
include/ioh/problem/bbob/griewank_rosenbrock.hpp
tobiasvandriessel/IOHexperimenter
da22d89fe1673ea67962829d12873e01387f6895
[ "BSD-3-Clause" ]
null
null
null
include/ioh/problem/bbob/griewank_rosenbrock.hpp
tobiasvandriessel/IOHexperimenter
da22d89fe1673ea67962829d12873e01387f6895
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "bbob_problem.hpp" namespace ioh::problem::bbob { class GriewankRosenBrock final : public BBOProblem<GriewankRosenBrock> { std::vector<double> x_shift_; protected: double evaluate(const std::vector<double> &x) override { auto result = 0.0; for (auto i = 0; i < meta_data_.n_variables - 1; ++i) { const auto c1 = 100.0 * pow(pow(x.at(i), 2.0) - x.at(i + 1), 2.0); const auto c2 = pow(1.0 - x.at(i), 2.0); const auto z = c1 + c2; result += z / 4000. - cos(z); } return 10. + 10. * result / static_cast<double>(meta_data_.n_variables - 1); } std::vector<double> transform_variables(std::vector<double> x) override { using namespace transformation::variables; affine(x, transformation_state_.second_rotation, transformation_state_.transformation_base); subtract(x, x_shift_); return x; } public: GriewankRosenBrock(const int instance, const int n_variables) : BBOProblem(19, instance, n_variables, "GriewankRosenBrock"), x_shift_(n_variables, -0.5) { const auto factor = std::max(1., sqrt(n_variables) / 8.); for (auto i = 0; i < n_variables; ++i) { auto sum = 0.0; for (auto j = 0; j < n_variables; ++j) { transformation_state_.second_rotation[i][j] *= factor; sum += transformation_state_.second_rotation.at(j).at(i); } objective_.x[i] = sum / (2. * factor); } } }; }
35.942308
96
0.486891
tobiasvandriessel
c8df57d3fc9aba20ad75c9e8575b2e0cdf9e4143
3,820
cpp
C++
vcl/display/window/window.cpp
PPonc/inf443-vcl
4d7bb0130c4bc44e089059464223eca318fdbd00
[ "MIT" ]
null
null
null
vcl/display/window/window.cpp
PPonc/inf443-vcl
4d7bb0130c4bc44e089059464223eca318fdbd00
[ "MIT" ]
null
null
null
vcl/display/window/window.cpp
PPonc/inf443-vcl
4d7bb0130c4bc44e089059464223eca318fdbd00
[ "MIT" ]
null
null
null
#include "../opengl/opengl.hpp" #include "window.hpp" #include "../../base/base.hpp" #include <iostream> #ifndef GLFW_TRUE #define GLFW_TRUE 1 #define GLFW_FALSE 0 #endif namespace vcl { static std::string glfw_error_string(int error) { switch(error) { case GLFW_NOT_INITIALIZED: return "GLFW_NOT_INITIALIZED"; case GLFW_INVALID_ENUM: return "GLFW_INVALID_ENUM"; case GLFW_INVALID_VALUE: return "GLFW_INVALID_VALUE"; case GLFW_API_UNAVAILABLE: return "GLFW_API_UNAVAILABLE"; case GLFW_VERSION_UNAVAILABLE: return "GLFW_VERSION_UNAVAILABLE"; case GLFW_FORMAT_UNAVAILABLE: return "GLFW_FORMAT_UNAVAILABLE"; case GLFW_PLATFORM_ERROR: return "GLFW_PLATFORM_ERROR"; default: return "UNKNOWN GLFW ERROR (Shouldn't happen)"; } return "IMPOSSIBLE GLFW ERROR! (Should never happen)"; } static void glfw_error_callback(int error, const char* description) { std::cerr<<"Received GLFW error"<<std::endl; std::cerr<<"\t Error "<<glfw_error_string(error)<<" ("<<error<<")"<<std::endl; std::cerr<<"\t Description - "<<description<<std::endl; } GLFWwindow* create_window(int width, int height, std::string const& window_title, int opengl_version_major, int opengl_version_minor, GLFWmonitor* monitor, GLFWwindow* share) { // Set GLFW callback to catch and display error glfwSetErrorCallback(glfw_error_callback); // Initialize GLFW const int glfw_init_value = glfwInit(); if( glfw_init_value != GLFW_TRUE ) { std::string s = "\nError: Failed to Initialize GLFW.\n"; s += "If you are using WSL or Linux without graphical server, you need to start a X-server\n"; std::cout<<s<<std::endl; abort(); } // Set GLFW parameter before creating the window glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); // change to GLFW_OPENGL_ES_API for WebGL glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE); // Use only modern OpenGL glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, opengl_version_major); // Expect OpenGL 3.3 or greater glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, opengl_version_minor); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); // Required for MacOS glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); // Allow possible debug glfwWindowHint(GLFW_FOCUSED, GLFW_TRUE); // Take focuss when created glfwWindowHint(GLFW_SAMPLES, 8); // Multisampling glfwWindowHint(GLFW_FLOATING, GLFW_FALSE); // Windows is not always on top // Creation of the window GLFWwindow* window = glfwCreateWindow(width, height, window_title.c_str(), monitor, share); if( window==nullptr ) { std::cerr<<"Failed to create GLFW Window"<<std::endl; std::cerr<<"\t Possible error cause: Incompatible OpenGL version (requesting OpenGL "<<opengl_version_major<<"."<<opengl_version_minor<<")"<<std::endl; std::cerr<<"\t Check your current system OpenGL version (ex. glxinfo)"<<std::endl; abort(); } glfwMakeContextCurrent(window); // Initialize GLAD to get access to OpenGL functions const int glad_init_value = gladLoadGL(); if( glad_init_value == 0 ) { std::cout<<"Failed to Init GLAD"<<std::endl; abort(); } // Allows RGB texture in simple format glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_PACK_ALIGNMENT, 1); return window; } }
37.087379
176
0.634293
PPonc
c8e12cde2ffd0cb3447ae122a36621ec53e34bef
39,992
cpp
C++
src/ThirdParty/yaml/test/integration/node_spec_test.cpp
xiaomingfun/TmingEngine
b81b822a4771c07908e1a72f5118a34552579d9e
[ "Apache-2.0" ]
27
2018-05-21T14:28:10.000Z
2021-12-31T03:12:35.000Z
src/ThirdParty/yaml/test/integration/node_spec_test.cpp
xiaomingfun/TmingEngine
b81b822a4771c07908e1a72f5118a34552579d9e
[ "Apache-2.0" ]
1
2019-05-28T15:27:52.000Z
2019-05-28T15:27:52.000Z
src/ThirdParty/yaml/test/integration/node_spec_test.cpp
xiaomingfun/TmingEngine
b81b822a4771c07908e1a72f5118a34552579d9e
[ "Apache-2.0" ]
13
2019-11-08T12:48:44.000Z
2022-01-04T04:13:33.000Z
#include "specexamples.h" #include "yaml-cpp/yaml.h" // IWYU pragma: keep #include "gtest/gtest.h" #define EXPECT_THROW_PARSER_EXCEPTION(statement, message) \ ASSERT_THROW(statement, ParserException); \ try { \ statement; \ } catch (const ParserException& e) { \ EXPECT_EQ(e.msg, message); \ } namespace YAML { namespace { TEST(NodeSpecTest, Ex2_1_SeqScalars) { Node doc = Load(ex2_1); EXPECT_TRUE(doc.IsSequence()); EXPECT_EQ(3, doc.size()); EXPECT_EQ("Mark McGwire", doc[0].as<std::string>()); EXPECT_EQ("Sammy Sosa", doc[1].as<std::string>()); EXPECT_EQ("Ken Griffey", doc[2].as<std::string>()); } TEST(NodeSpecTest, Ex2_2_MappingScalarsToScalars) { Node doc = Load(ex2_2); EXPECT_TRUE(doc.IsMap()); EXPECT_EQ(3, doc.size()); EXPECT_EQ("65", doc["hr"].as<std::string>()); EXPECT_EQ("0.278", doc["avg"].as<std::string>()); EXPECT_EQ("147", doc["rbi"].as<std::string>()); } TEST(NodeSpecTest, Ex2_3_MappingScalarsToSequences) { Node doc = Load(ex2_3); EXPECT_TRUE(doc.IsMap()); EXPECT_EQ(2, doc.size()); EXPECT_EQ(3, doc["american"].size()); EXPECT_EQ("Boston Red Sox", doc["american"][0].as<std::string>()); EXPECT_EQ("Detroit Tigers", doc["american"][1].as<std::string>()); EXPECT_EQ("New York Yankees", doc["american"][2].as<std::string>()); EXPECT_EQ(3, doc["national"].size()); EXPECT_EQ("New York Mets", doc["national"][0].as<std::string>()); EXPECT_EQ("Chicago Cubs", doc["national"][1].as<std::string>()); EXPECT_EQ("Atlanta Braves", doc["national"][2].as<std::string>()); } TEST(NodeSpecTest, Ex2_4_SequenceOfMappings) { Node doc = Load(ex2_4); EXPECT_EQ(2, doc.size()); EXPECT_EQ(3, doc[0].size()); EXPECT_EQ("Mark McGwire", doc[0]["name"].as<std::string>()); EXPECT_EQ("65", doc[0]["hr"].as<std::string>()); EXPECT_EQ("0.278", doc[0]["avg"].as<std::string>()); EXPECT_EQ(3, doc[1].size()); EXPECT_EQ("Sammy Sosa", doc[1]["name"].as<std::string>()); EXPECT_EQ("63", doc[1]["hr"].as<std::string>()); EXPECT_EQ("0.288", doc[1]["avg"].as<std::string>()); } TEST(NodeSpecTest, Ex2_5_SequenceOfSequences) { Node doc = Load(ex2_5); EXPECT_EQ(3, doc.size()); EXPECT_EQ(3, doc[0].size()); EXPECT_EQ("name", doc[0][0].as<std::string>()); EXPECT_EQ("hr", doc[0][1].as<std::string>()); EXPECT_EQ("avg", doc[0][2].as<std::string>()); EXPECT_EQ(3, doc[1].size()); EXPECT_EQ("Mark McGwire", doc[1][0].as<std::string>()); EXPECT_EQ("65", doc[1][1].as<std::string>()); EXPECT_EQ("0.278", doc[1][2].as<std::string>()); EXPECT_EQ(3, doc[2].size()); EXPECT_EQ("Sammy Sosa", doc[2][0].as<std::string>()); EXPECT_EQ("63", doc[2][1].as<std::string>()); EXPECT_EQ("0.288", doc[2][2].as<std::string>()); } TEST(NodeSpecTest, Ex2_6_MappingOfMappings) { Node doc = Load(ex2_6); EXPECT_EQ(2, doc.size()); EXPECT_EQ(2, doc["Mark McGwire"].size()); EXPECT_EQ("65", doc["Mark McGwire"]["hr"].as<std::string>()); EXPECT_EQ("0.278", doc["Mark McGwire"]["avg"].as<std::string>()); EXPECT_EQ(2, doc["Sammy Sosa"].size()); EXPECT_EQ("63", doc["Sammy Sosa"]["hr"].as<std::string>()); EXPECT_EQ("0.288", doc["Sammy Sosa"]["avg"].as<std::string>()); } TEST(NodeSpecTest, Ex2_7_TwoDocumentsInAStream) { std::vector<Node> docs = LoadAll(ex2_7); EXPECT_EQ(2, docs.size()); { Node doc = docs[0]; EXPECT_EQ(3, doc.size()); EXPECT_EQ("Mark McGwire", doc[0].as<std::string>()); EXPECT_EQ("Sammy Sosa", doc[1].as<std::string>()); EXPECT_EQ("Ken Griffey", doc[2].as<std::string>()); } { Node doc = docs[1]; EXPECT_EQ(2, doc.size()); EXPECT_EQ("Chicago Cubs", doc[0].as<std::string>()); EXPECT_EQ("St Louis Cardinals", doc[1].as<std::string>()); } } TEST(NodeSpecTest, Ex2_8_PlayByPlayFeed) { std::vector<Node> docs = LoadAll(ex2_8); EXPECT_EQ(2, docs.size()); { Node doc = docs[0]; EXPECT_EQ(3, doc.size()); EXPECT_EQ("20:03:20", doc["time"].as<std::string>()); EXPECT_EQ("Sammy Sosa", doc["player"].as<std::string>()); EXPECT_EQ("strike (miss)", doc["action"].as<std::string>()); } { Node doc = docs[1]; EXPECT_EQ(3, doc.size()); EXPECT_EQ("20:03:47", doc["time"].as<std::string>()); EXPECT_EQ("Sammy Sosa", doc["player"].as<std::string>()); EXPECT_EQ("grand slam", doc["action"].as<std::string>()); } } TEST(NodeSpecTest, Ex2_9_SingleDocumentWithTwoComments) { Node doc = Load(ex2_9); EXPECT_EQ(2, doc.size()); EXPECT_EQ(2, doc["hr"].size()); EXPECT_EQ("Mark McGwire", doc["hr"][0].as<std::string>()); EXPECT_EQ("Sammy Sosa", doc["hr"][1].as<std::string>()); EXPECT_EQ(2, doc["rbi"].size()); EXPECT_EQ("Sammy Sosa", doc["rbi"][0].as<std::string>()); EXPECT_EQ("Ken Griffey", doc["rbi"][1].as<std::string>()); } TEST(NodeSpecTest, Ex2_10_SimpleAnchor) { Node doc = Load(ex2_10); EXPECT_EQ(2, doc.size()); EXPECT_EQ(2, doc["hr"].size()); EXPECT_EQ("Mark McGwire", doc["hr"][0].as<std::string>()); EXPECT_EQ("Sammy Sosa", doc["hr"][1].as<std::string>()); EXPECT_EQ(2, doc["rbi"].size()); EXPECT_EQ("Sammy Sosa", doc["rbi"][0].as<std::string>()); EXPECT_EQ("Ken Griffey", doc["rbi"][1].as<std::string>()); } TEST(NodeSpecTest, Ex2_11_MappingBetweenSequences) { Node doc = Load(ex2_11); std::vector<std::string> tigers_cubs; tigers_cubs.push_back("Detroit Tigers"); tigers_cubs.push_back("Chicago cubs"); std::vector<std::string> yankees_braves; yankees_braves.push_back("New York Yankees"); yankees_braves.push_back("Atlanta Braves"); EXPECT_EQ(2, doc.size()); EXPECT_EQ(1, doc[tigers_cubs].size()); EXPECT_EQ("2001-07-23", doc[tigers_cubs][0].as<std::string>()); EXPECT_EQ(3, doc[yankees_braves].size()); EXPECT_EQ("2001-07-02", doc[yankees_braves][0].as<std::string>()); EXPECT_EQ("2001-08-12", doc[yankees_braves][1].as<std::string>()); EXPECT_EQ("2001-08-14", doc[yankees_braves][2].as<std::string>()); } TEST(NodeSpecTest, Ex2_12_CompactNestedMapping) { Node doc = Load(ex2_12); EXPECT_EQ(3, doc.size()); EXPECT_EQ(2, doc[0].size()); EXPECT_EQ("Super Hoop", doc[0]["item"].as<std::string>()); EXPECT_EQ(1, doc[0]["quantity"].as<int>()); EXPECT_EQ(2, doc[1].size()); EXPECT_EQ("Basketball", doc[1]["item"].as<std::string>()); EXPECT_EQ(4, doc[1]["quantity"].as<int>()); EXPECT_EQ(2, doc[2].size()); EXPECT_EQ("Big Shoes", doc[2]["item"].as<std::string>()); EXPECT_EQ(1, doc[2]["quantity"].as<int>()); } TEST(NodeSpecTest, Ex2_13_InLiteralsNewlinesArePreserved) { Node doc = Load(ex2_13); EXPECT_TRUE(doc.as<std::string>() == "\\//||\\/||\n" "// || ||__"); } TEST(NodeSpecTest, Ex2_14_InFoldedScalarsNewlinesBecomeSpaces) { Node doc = Load(ex2_14); EXPECT_TRUE(doc.as<std::string>() == "Mark McGwire's year was crippled by a knee injury."); } TEST(NodeSpecTest, Ex2_15_FoldedNewlinesArePreservedForMoreIndentedAndBlankLines) { Node doc = Load(ex2_15); EXPECT_TRUE(doc.as<std::string>() == "Sammy Sosa completed another fine season with great stats.\n\n" " 63 Home Runs\n" " 0.288 Batting Average\n\n" "What a year!"); } TEST(NodeSpecTest, Ex2_16_IndentationDeterminesScope) { Node doc = Load(ex2_16); EXPECT_EQ(3, doc.size()); EXPECT_EQ("Mark McGwire", doc["name"].as<std::string>()); EXPECT_TRUE(doc["accomplishment"].as<std::string>() == "Mark set a major league home run record in 1998.\n"); EXPECT_TRUE(doc["stats"].as<std::string>() == "65 Home Runs\n0.278 Batting Average\n"); } TEST(NodeSpecTest, Ex2_17_QuotedScalars) { Node doc = Load(ex2_17); EXPECT_EQ(6, doc.size()); EXPECT_EQ("Sosa did fine.\xe2\x98\xba", doc["unicode"].as<std::string>()); EXPECT_EQ("\b1998\t1999\t2000\n", doc["control"].as<std::string>()); EXPECT_EQ("\x0d\x0a is \r\n", doc["hex esc"].as<std::string>()); EXPECT_EQ("\"Howdy!\" he cried.", doc["single"].as<std::string>()); EXPECT_EQ(" # Not a 'comment'.", doc["quoted"].as<std::string>()); EXPECT_EQ("|\\-*-/|", doc["tie-fighter"].as<std::string>()); } TEST(NodeSpecTest, Ex2_18_MultiLineFlowScalars) { Node doc = Load(ex2_18); EXPECT_EQ(2, doc.size()); EXPECT_TRUE(doc["plain"].as<std::string>() == "This unquoted scalar spans many lines."); EXPECT_TRUE(doc["quoted"].as<std::string>() == "So does this quoted scalar.\n"); } // TODO: 2.19 - 2.22 schema tags TEST(NodeSpecTest, Ex2_23_VariousExplicitTags) { Node doc = Load(ex2_23); EXPECT_EQ(3, doc.size()); EXPECT_EQ("tag:yaml.org,2002:str", doc["not-date"].Tag()); EXPECT_EQ("2002-04-28", doc["not-date"].as<std::string>()); EXPECT_EQ("tag:yaml.org,2002:binary", doc["picture"].Tag()); EXPECT_TRUE(doc["picture"].as<std::string>() == "R0lGODlhDAAMAIQAAP//9/X\n" "17unp5WZmZgAAAOfn515eXv\n" "Pz7Y6OjuDg4J+fn5OTk6enp\n" "56enmleECcgggoBADs=\n"); EXPECT_EQ("!something", doc["application specific tag"].Tag()); EXPECT_TRUE(doc["application specific tag"].as<std::string>() == "The semantics of the tag\n" "above may be different for\n" "different documents."); } TEST(NodeSpecTest, Ex2_24_GlobalTags) { Node doc = Load(ex2_24); EXPECT_EQ("tag:clarkevans.com,2002:shape", doc.Tag()); EXPECT_EQ(3, doc.size()); EXPECT_EQ("tag:clarkevans.com,2002:circle", doc[0].Tag()); EXPECT_EQ(2, doc[0].size()); EXPECT_EQ(2, doc[0]["center"].size()); EXPECT_EQ(73, doc[0]["center"]["x"].as<int>()); EXPECT_EQ(129, doc[0]["center"]["y"].as<int>()); EXPECT_EQ(7, doc[0]["radius"].as<int>()); EXPECT_EQ("tag:clarkevans.com,2002:line", doc[1].Tag()); EXPECT_EQ(2, doc[1].size()); EXPECT_EQ(2, doc[1]["start"].size()); EXPECT_EQ(73, doc[1]["start"]["x"].as<int>()); EXPECT_EQ(129, doc[1]["start"]["y"].as<int>()); EXPECT_EQ(2, doc[1]["finish"].size()); EXPECT_EQ(89, doc[1]["finish"]["x"].as<int>()); EXPECT_EQ(102, doc[1]["finish"]["y"].as<int>()); EXPECT_EQ("tag:clarkevans.com,2002:label", doc[2].Tag()); EXPECT_EQ(3, doc[2].size()); EXPECT_EQ(2, doc[2]["start"].size()); EXPECT_EQ(73, doc[2]["start"]["x"].as<int>()); EXPECT_EQ(129, doc[2]["start"]["y"].as<int>()); EXPECT_EQ("0xFFEEBB", doc[2]["color"].as<std::string>()); EXPECT_EQ("Pretty vector drawing.", doc[2]["text"].as<std::string>()); } TEST(NodeSpecTest, Ex2_25_UnorderedSets) { Node doc = Load(ex2_25); EXPECT_EQ("tag:yaml.org,2002:set", doc.Tag()); EXPECT_EQ(3, doc.size()); EXPECT_TRUE(doc["Mark McGwire"].IsNull()); EXPECT_TRUE(doc["Sammy Sosa"].IsNull()); EXPECT_TRUE(doc["Ken Griffey"].IsNull()); } TEST(NodeSpecTest, Ex2_16_OrderedMappings) { Node doc = Load(ex2_26); EXPECT_EQ("tag:yaml.org,2002:omap", doc.Tag()); EXPECT_EQ(3, doc.size()); EXPECT_EQ(1, doc[0].size()); EXPECT_EQ(65, doc[0]["Mark McGwire"].as<int>()); EXPECT_EQ(1, doc[1].size()); EXPECT_EQ(63, doc[1]["Sammy Sosa"].as<int>()); EXPECT_EQ(1, doc[2].size()); EXPECT_EQ(58, doc[2]["Ken Griffey"].as<int>()); } TEST(NodeSpecTest, Ex2_27_Invoice) { Node doc = Load(ex2_27); EXPECT_EQ("tag:clarkevans.com,2002:invoice", doc.Tag()); EXPECT_EQ(8, doc.size()); EXPECT_EQ(34843, doc["invoice"].as<int>()); EXPECT_EQ("2001-01-23", doc["date"].as<std::string>()); EXPECT_EQ(3, doc["bill-to"].size()); EXPECT_EQ("Chris", doc["bill-to"]["given"].as<std::string>()); EXPECT_EQ("Dumars", doc["bill-to"]["family"].as<std::string>()); EXPECT_EQ(4, doc["bill-to"]["address"].size()); EXPECT_TRUE(doc["bill-to"]["address"]["lines"].as<std::string>() == "458 Walkman Dr.\nSuite #292\n"); EXPECT_TRUE(doc["bill-to"]["address"]["city"].as<std::string>() == "Royal Oak"); EXPECT_EQ("MI", doc["bill-to"]["address"]["state"].as<std::string>()); EXPECT_EQ("48046", doc["bill-to"]["address"]["postal"].as<std::string>()); EXPECT_EQ(3, doc["ship-to"].size()); EXPECT_EQ("Chris", doc["ship-to"]["given"].as<std::string>()); EXPECT_EQ("Dumars", doc["ship-to"]["family"].as<std::string>()); EXPECT_EQ(4, doc["ship-to"]["address"].size()); EXPECT_TRUE(doc["ship-to"]["address"]["lines"].as<std::string>() == "458 Walkman Dr.\nSuite #292\n"); EXPECT_TRUE(doc["ship-to"]["address"]["city"].as<std::string>() == "Royal Oak"); EXPECT_EQ("MI", doc["ship-to"]["address"]["state"].as<std::string>()); EXPECT_EQ("48046", doc["ship-to"]["address"]["postal"].as<std::string>()); EXPECT_EQ(2, doc["product"].size()); EXPECT_EQ(4, doc["product"][0].size()); EXPECT_EQ("BL394D", doc["product"][0]["sku"].as<std::string>()); EXPECT_EQ(4, doc["product"][0]["quantity"].as<int>()); EXPECT_TRUE(doc["product"][0]["description"].as<std::string>() == "Basketball"); EXPECT_EQ("450.00", doc["product"][0]["price"].as<std::string>()); EXPECT_EQ(4, doc["product"][1].size()); EXPECT_EQ("BL4438H", doc["product"][1]["sku"].as<std::string>()); EXPECT_EQ(1, doc["product"][1]["quantity"].as<int>()); EXPECT_TRUE(doc["product"][1]["description"].as<std::string>() == "Super Hoop"); EXPECT_EQ("2392.00", doc["product"][1]["price"].as<std::string>()); EXPECT_EQ("251.42", doc["tax"].as<std::string>()); EXPECT_EQ("4443.52", doc["total"].as<std::string>()); EXPECT_EQ( "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.", doc["comments"].as<std::string>()); } TEST(NodeSpecTest, Ex2_28_LogFile) { std::vector<Node> docs = LoadAll(ex2_28); EXPECT_EQ(3, docs.size()); { Node doc = docs[0]; EXPECT_EQ(3, doc.size()); EXPECT_EQ("2001-11-23 15:01:42 -5", doc["Time"].as<std::string>()); EXPECT_EQ("ed", doc["User"].as<std::string>()); EXPECT_TRUE(doc["Warning"].as<std::string>() == "This is an error message for the log file"); } { Node doc = docs[1]; EXPECT_EQ(3, doc.size()); EXPECT_EQ("2001-11-23 15:02:31 -5", doc["Time"].as<std::string>()); EXPECT_EQ("ed", doc["User"].as<std::string>()); EXPECT_TRUE(doc["Warning"].as<std::string>() == "A slightly different error message."); } { Node doc = docs[2]; EXPECT_EQ(4, doc.size()); EXPECT_EQ("2001-11-23 15:03:17 -5", doc["Date"].as<std::string>()); EXPECT_EQ("ed", doc["User"].as<std::string>()); EXPECT_EQ("Unknown variable \"bar\"", doc["Fatal"].as<std::string>()); EXPECT_EQ(2, doc["Stack"].size()); EXPECT_EQ(3, doc["Stack"][0].size()); EXPECT_EQ("TopClass.py", doc["Stack"][0]["file"].as<std::string>()); EXPECT_EQ("23", doc["Stack"][0]["line"].as<std::string>()); EXPECT_TRUE(doc["Stack"][0]["code"].as<std::string>() == "x = MoreObject(\"345\\n\")\n"); EXPECT_EQ(3, doc["Stack"][1].size()); EXPECT_EQ("MoreClass.py", doc["Stack"][1]["file"].as<std::string>()); EXPECT_EQ("58", doc["Stack"][1]["line"].as<std::string>()); EXPECT_EQ("foo = bar", doc["Stack"][1]["code"].as<std::string>()); } } // TODO: 5.1 - 5.2 BOM TEST(NodeSpecTest, Ex5_3_BlockStructureIndicators) { Node doc = Load(ex5_3); EXPECT_EQ(2, doc.size()); EXPECT_EQ(2, doc["sequence"].size()); EXPECT_EQ("one", doc["sequence"][0].as<std::string>()); EXPECT_EQ("two", doc["sequence"][1].as<std::string>()); EXPECT_EQ(2, doc["mapping"].size()); EXPECT_EQ("blue", doc["mapping"]["sky"].as<std::string>()); EXPECT_EQ("green", doc["mapping"]["sea"].as<std::string>()); } TEST(NodeSpecTest, Ex5_4_FlowStructureIndicators) { Node doc = Load(ex5_4); EXPECT_EQ(2, doc.size()); EXPECT_EQ(2, doc["sequence"].size()); EXPECT_EQ("one", doc["sequence"][0].as<std::string>()); EXPECT_EQ("two", doc["sequence"][1].as<std::string>()); EXPECT_EQ(2, doc["mapping"].size()); EXPECT_EQ("blue", doc["mapping"]["sky"].as<std::string>()); EXPECT_EQ("green", doc["mapping"]["sea"].as<std::string>()); } TEST(NodeSpecTest, Ex5_5_CommentIndicator) { Node doc = Load(ex5_5); EXPECT_TRUE(doc.IsNull()); } TEST(NodeSpecTest, Ex5_6_NodePropertyIndicators) { Node doc = Load(ex5_6); EXPECT_EQ(2, doc.size()); EXPECT_TRUE(doc["anchored"].as<std::string>() == "value"); // TODO: assert tag EXPECT_EQ("value", doc["alias"].as<std::string>()); } TEST(NodeSpecTest, Ex5_7_BlockScalarIndicators) { Node doc = Load(ex5_7); EXPECT_EQ(2, doc.size()); EXPECT_EQ("some\ntext\n", doc["literal"].as<std::string>()); EXPECT_EQ("some text\n", doc["folded"].as<std::string>()); } TEST(NodeSpecTest, Ex5_8_QuotedScalarIndicators) { Node doc = Load(ex5_8); EXPECT_EQ(2, doc.size()); EXPECT_EQ("text", doc["single"].as<std::string>()); EXPECT_EQ("text", doc["double"].as<std::string>()); } // TODO: 5.9 directive // TODO: 5.10 reserved indicator TEST(NodeSpecTest, Ex5_11_LineBreakCharacters) { Node doc = Load(ex5_11); EXPECT_TRUE(doc.as<std::string>() == "Line break (no glyph)\nLine break (glyphed)\n"); } TEST(NodeSpecTest, Ex5_12_TabsAndSpaces) { Node doc = Load(ex5_12); EXPECT_EQ(2, doc.size()); EXPECT_EQ("Quoted\t", doc["quoted"].as<std::string>()); EXPECT_TRUE(doc["block"].as<std::string>() == "void main() {\n" "\tprintf(\"Hello, world!\\n\");\n" "}"); } TEST(NodeSpecTest, Ex5_13_EscapedCharacters) { Node doc = Load(ex5_13); EXPECT_TRUE(doc.as<std::string>() == "Fun with \x5C \x22 \x07 \x08 \x1B \x0C \x0A \x0D \x09 \x0B " + std::string("\x00", 1) + " \x20 \xA0 \x85 \xe2\x80\xa8 \xe2\x80\xa9 A A A"); } TEST(NodeSpecTest, Ex5_14_InvalidEscapedCharacters) { EXPECT_THROW_PARSER_EXCEPTION(Load(ex5_14), std::string(ErrorMsg::INVALID_ESCAPE) + "c"); } TEST(NodeSpecTest, Ex6_1_IndentationSpaces) { Node doc = Load(ex6_1); EXPECT_EQ(1, doc.size()); EXPECT_EQ(2, doc["Not indented"].size()); EXPECT_TRUE(doc["Not indented"]["By one space"].as<std::string>() == "By four\n spaces\n"); EXPECT_EQ(3, doc["Not indented"]["Flow style"].size()); EXPECT_TRUE(doc["Not indented"]["Flow style"][0].as<std::string>() == "By two"); EXPECT_TRUE(doc["Not indented"]["Flow style"][1].as<std::string>() == "Also by two"); EXPECT_TRUE(doc["Not indented"]["Flow style"][2].as<std::string>() == "Still by two"); } TEST(NodeSpecTest, Ex6_2_IndentationIndicators) { Node doc = Load(ex6_2); EXPECT_EQ(1, doc.size()); EXPECT_EQ(2, doc["a"].size()); EXPECT_EQ("b", doc["a"][0].as<std::string>()); EXPECT_EQ(2, doc["a"][1].size()); EXPECT_EQ("c", doc["a"][1][0].as<std::string>()); EXPECT_EQ("d", doc["a"][1][1].as<std::string>()); } TEST(NodeSpecTest, Ex6_3_SeparationSpaces) { Node doc = Load(ex6_3); EXPECT_EQ(2, doc.size()); EXPECT_EQ(1, doc[0].size()); EXPECT_EQ("bar", doc[0]["foo"].as<std::string>()); EXPECT_EQ(2, doc[1].size()); EXPECT_EQ("baz", doc[1][0].as<std::string>()); EXPECT_EQ("baz", doc[1][1].as<std::string>()); } TEST(NodeSpecTest, Ex6_4_LinePrefixes) { Node doc = Load(ex6_4); EXPECT_EQ(3, doc.size()); EXPECT_EQ("text lines", doc["plain"].as<std::string>()); EXPECT_EQ("text lines", doc["quoted"].as<std::string>()); EXPECT_EQ("text\n \tlines\n", doc["block"].as<std::string>()); } TEST(NodeSpecTest, Ex6_5_EmptyLines) { Node doc = Load(ex6_5); EXPECT_EQ(2, doc.size()); EXPECT_EQ("Empty line\nas a line feed", doc["Folding"].as<std::string>()); EXPECT_EQ("Clipped empty lines\n", doc["Chomping"].as<std::string>()); } TEST(NodeSpecTest, Ex6_6_LineFolding) { Node doc = Load(ex6_6); EXPECT_EQ("trimmed\n\n\nas space", doc.as<std::string>()); } TEST(NodeSpecTest, Ex6_7_BlockFolding) { Node doc = Load(ex6_7); EXPECT_EQ("foo \n\n\t bar\n\nbaz\n", doc.as<std::string>()); } TEST(NodeSpecTest, Ex6_8_FlowFolding) { Node doc = Load(ex6_8); EXPECT_EQ(" foo\nbar\nbaz ", doc.as<std::string>()); } TEST(NodeSpecTest, Ex6_9_SeparatedComment) { Node doc = Load(ex6_9); EXPECT_EQ(1, doc.size()); EXPECT_EQ("value", doc["key"].as<std::string>()); } TEST(NodeSpecTest, Ex6_10_CommentLines) { Node doc = Load(ex6_10); EXPECT_TRUE(doc.IsNull()); } TEST(NodeSpecTest, Ex6_11_MultiLineComments) { Node doc = Load(ex6_11); EXPECT_EQ(1, doc.size()); EXPECT_EQ("value", doc["key"].as<std::string>()); } TEST(NodeSpecTest, Ex6_12_SeparationSpacesII) { Node doc = Load(ex6_12); std::map<std::string, std::string> sammy; sammy["first"] = "Sammy"; sammy["last"] = "Sosa"; EXPECT_EQ(1, doc.size()); EXPECT_EQ(2, doc[sammy].size()); EXPECT_EQ(65, doc[sammy]["hr"].as<int>()); EXPECT_EQ("0.278", doc[sammy]["avg"].as<std::string>()); } TEST(NodeSpecTest, Ex6_13_ReservedDirectives) { Node doc = Load(ex6_13); EXPECT_EQ("foo", doc.as<std::string>()); } TEST(NodeSpecTest, Ex6_14_YAMLDirective) { Node doc = Load(ex6_14); EXPECT_EQ("foo", doc.as<std::string>()); } TEST(NodeSpecTest, Ex6_15_InvalidRepeatedYAMLDirective) { EXPECT_THROW_PARSER_EXCEPTION(Load(ex6_15), ErrorMsg::REPEATED_YAML_DIRECTIVE); } TEST(NodeSpecTest, Ex6_16_TagDirective) { Node doc = Load(ex6_16); EXPECT_EQ("tag:yaml.org,2002:str", doc.Tag()); EXPECT_EQ("foo", doc.as<std::string>()); } TEST(NodeSpecTest, Ex6_17_InvalidRepeatedTagDirective) { EXPECT_THROW_PARSER_EXCEPTION(Load(ex6_17), ErrorMsg::REPEATED_TAG_DIRECTIVE); } TEST(NodeSpecTest, Ex6_18_PrimaryTagHandle) { std::vector<Node> docs = LoadAll(ex6_18); EXPECT_EQ(2, docs.size()); { Node doc = docs[0]; EXPECT_EQ("!foo", doc.Tag()); EXPECT_EQ("bar", doc.as<std::string>()); } { Node doc = docs[1]; EXPECT_EQ("tag:example.com,2000:app/foo", doc.Tag()); EXPECT_EQ("bar", doc.as<std::string>()); } } TEST(NodeSpecTest, Ex6_19_SecondaryTagHandle) { Node doc = Load(ex6_19); EXPECT_EQ("tag:example.com,2000:app/int", doc.Tag()); EXPECT_EQ("1 - 3", doc.as<std::string>()); } TEST(NodeSpecTest, Ex6_20_TagHandles) { Node doc = Load(ex6_20); EXPECT_EQ("tag:example.com,2000:app/foo", doc.Tag()); EXPECT_EQ("bar", doc.as<std::string>()); } TEST(NodeSpecTest, Ex6_21_LocalTagPrefix) { std::vector<Node> docs = LoadAll(ex6_21); EXPECT_EQ(2, docs.size()); { Node doc = docs[0]; EXPECT_EQ("!my-light", doc.Tag()); EXPECT_EQ("fluorescent", doc.as<std::string>()); } { Node doc = docs[1]; EXPECT_EQ("!my-light", doc.Tag()); EXPECT_EQ("green", doc.as<std::string>()); } } TEST(NodeSpecTest, Ex6_22_GlobalTagPrefix) { Node doc = Load(ex6_22); EXPECT_EQ(1, doc.size()); EXPECT_EQ("tag:example.com,2000:app/foo", doc[0].Tag()); EXPECT_EQ("bar", doc[0].as<std::string>()); } TEST(NodeSpecTest, Ex6_23_NodeProperties) { Node doc = Load(ex6_23); EXPECT_EQ(2, doc.size()); for (const_iterator it = doc.begin(); it != doc.end(); ++it) { if (it->first.as<std::string>() == "foo") { EXPECT_EQ("tag:yaml.org,2002:str", it->first.Tag()); EXPECT_EQ("tag:yaml.org,2002:str", it->second.Tag()); EXPECT_EQ("bar", it->second.as<std::string>()); } else if (it->first.as<std::string>() == "baz") { EXPECT_EQ("foo", it->second.as<std::string>()); } else FAIL() << "unknown key"; } } TEST(NodeSpecTest, Ex6_24_VerbatimTags) { Node doc = Load(ex6_24); EXPECT_EQ(1, doc.size()); for (const_iterator it = doc.begin(); it != doc.end(); ++it) { EXPECT_EQ("tag:yaml.org,2002:str", it->first.Tag()); EXPECT_EQ("foo", it->first.as<std::string>()); EXPECT_EQ("!bar", it->second.Tag()); EXPECT_EQ("baz", it->second.as<std::string>()); } } TEST(NodeSpecTest, DISABLED_Ex6_25_InvalidVerbatimTags) { Node doc = Load(ex6_25); // TODO: check tags (but we probably will say these are valid, I think) FAIL() << "not implemented yet"; } TEST(NodeSpecTest, Ex6_26_TagShorthands) { Node doc = Load(ex6_26); EXPECT_EQ(3, doc.size()); EXPECT_EQ("!local", doc[0].Tag()); EXPECT_EQ("foo", doc[0].as<std::string>()); EXPECT_EQ("tag:yaml.org,2002:str", doc[1].Tag()); EXPECT_EQ("bar", doc[1].as<std::string>()); EXPECT_EQ("tag:example.com,2000:app/tag%21", doc[2].Tag()); EXPECT_EQ("baz", doc[2].as<std::string>()); } TEST(NodeSpecTest, Ex6_27a_InvalidTagShorthands) { EXPECT_THROW_PARSER_EXCEPTION(Load(ex6_27a), ErrorMsg::TAG_WITH_NO_SUFFIX); } // TODO: should we reject this one (since !h! is not declared)? TEST(NodeSpecTest, DISABLED_Ex6_27b_InvalidTagShorthands) { Load(ex6_27b); FAIL() << "not implemented yet"; } TEST(NodeSpecTest, Ex6_28_NonSpecificTags) { Node doc = Load(ex6_28); EXPECT_EQ(3, doc.size()); EXPECT_EQ("12", doc[0].as<std::string>()); // TODO: check tags. How? EXPECT_EQ(12, doc[1].as<int>()); EXPECT_EQ("12", doc[2].as<std::string>()); } TEST(NodeSpecTest, Ex6_29_NodeAnchors) { Node doc = Load(ex6_29); EXPECT_EQ(2, doc.size()); EXPECT_EQ("Value", doc["First occurrence"].as<std::string>()); EXPECT_EQ("Value", doc["Second occurrence"].as<std::string>()); } TEST(NodeSpecTest, Ex7_1_AliasNodes) { Node doc = Load(ex7_1); EXPECT_EQ(4, doc.size()); EXPECT_EQ("Foo", doc["First occurrence"].as<std::string>()); EXPECT_EQ("Foo", doc["Second occurrence"].as<std::string>()); EXPECT_EQ("Bar", doc["Override anchor"].as<std::string>()); EXPECT_EQ("Bar", doc["Reuse anchor"].as<std::string>()); } TEST(NodeSpecTest, Ex7_2_EmptyNodes) { Node doc = Load(ex7_2); EXPECT_EQ(2, doc.size()); for (const_iterator it = doc.begin(); it != doc.end(); ++it) { if (it->first.as<std::string>() == "foo") { EXPECT_EQ("tag:yaml.org,2002:str", it->second.Tag()); EXPECT_EQ("", it->second.as<std::string>()); } else if (it->first.as<std::string>() == "") { EXPECT_EQ("tag:yaml.org,2002:str", it->first.Tag()); EXPECT_EQ("bar", it->second.as<std::string>()); } else FAIL() << "unexpected key"; } } TEST(NodeSpecTest, Ex7_3_CompletelyEmptyNodes) { Node doc = Load(ex7_3); EXPECT_EQ(2, doc.size()); EXPECT_TRUE(doc["foo"].IsNull()); EXPECT_EQ("bar", doc[Null].as<std::string>()); } TEST(NodeSpecTest, Ex7_4_DoubleQuotedImplicitKeys) { Node doc = Load(ex7_4); EXPECT_EQ(1, doc.size()); EXPECT_EQ(1, doc["implicit block key"].size()); EXPECT_EQ(1, doc["implicit block key"][0].size()); EXPECT_EQ( "value", doc["implicit block key"][0]["implicit flow key"].as<std::string>()); } TEST(NodeSpecTest, Ex7_5_DoubleQuotedLineBreaks) { Node doc = Load(ex7_5); EXPECT_TRUE(doc.as<std::string>() == "folded to a space,\nto a line feed, or \t \tnon-content"); } TEST(NodeSpecTest, Ex7_6_DoubleQuotedLines) { Node doc = Load(ex7_6); EXPECT_TRUE(doc.as<std::string>() == " 1st non-empty\n2nd non-empty 3rd non-empty "); } TEST(NodeSpecTest, Ex7_7_SingleQuotedCharacters) { Node doc = Load(ex7_7); EXPECT_EQ("here's to \"quotes\"", doc.as<std::string>()); } TEST(NodeSpecTest, Ex7_8_SingleQuotedImplicitKeys) { Node doc = Load(ex7_8); EXPECT_EQ(1, doc.size()); EXPECT_EQ(1, doc["implicit block key"].size()); EXPECT_EQ(1, doc["implicit block key"][0].size()); EXPECT_EQ( "value", doc["implicit block key"][0]["implicit flow key"].as<std::string>()); } TEST(NodeSpecTest, Ex7_9_SingleQuotedLines) { Node doc = Load(ex7_9); EXPECT_TRUE(doc.as<std::string>() == " 1st non-empty\n2nd non-empty 3rd non-empty "); } TEST(NodeSpecTest, Ex7_10_PlainCharacters) { Node doc = Load(ex7_10); EXPECT_EQ(6, doc.size()); EXPECT_EQ("::vector", doc[0].as<std::string>()); EXPECT_EQ(": - ()", doc[1].as<std::string>()); EXPECT_EQ("Up, up, and away!", doc[2].as<std::string>()); EXPECT_EQ(-123, doc[3].as<int>()); EXPECT_EQ("http://example.com/foo#bar", doc[4].as<std::string>()); EXPECT_EQ(5, doc[5].size()); EXPECT_EQ("::vector", doc[5][0].as<std::string>()); EXPECT_EQ(": - ()", doc[5][1].as<std::string>()); EXPECT_EQ("Up, up, and away!", doc[5][2].as<std::string>()); EXPECT_EQ(-123, doc[5][3].as<int>()); EXPECT_EQ("http://example.com/foo#bar", doc[5][4].as<std::string>()); } TEST(NodeSpecTest, Ex7_11_PlainImplicitKeys) { Node doc = Load(ex7_11); EXPECT_EQ(1, doc.size()); EXPECT_EQ(1, doc["implicit block key"].size()); EXPECT_EQ(1, doc["implicit block key"][0].size()); EXPECT_EQ( "value", doc["implicit block key"][0]["implicit flow key"].as<std::string>()); } TEST(NodeSpecTest, Ex7_12_PlainLines) { Node doc = Load(ex7_12); EXPECT_TRUE(doc.as<std::string>() == "1st non-empty\n2nd non-empty 3rd non-empty"); } TEST(NodeSpecTest, Ex7_13_FlowSequence) { Node doc = Load(ex7_13); EXPECT_EQ(2, doc.size()); EXPECT_EQ(2, doc[0].size()); EXPECT_EQ("one", doc[0][0].as<std::string>()); EXPECT_EQ("two", doc[0][1].as<std::string>()); EXPECT_EQ(2, doc[1].size()); EXPECT_EQ("three", doc[1][0].as<std::string>()); EXPECT_EQ("four", doc[1][1].as<std::string>()); } TEST(NodeSpecTest, Ex7_14_FlowSequenceEntries) { Node doc = Load(ex7_14); EXPECT_EQ(5, doc.size()); EXPECT_EQ("double quoted", doc[0].as<std::string>()); EXPECT_EQ("single quoted", doc[1].as<std::string>()); EXPECT_EQ("plain text", doc[2].as<std::string>()); EXPECT_EQ(1, doc[3].size()); EXPECT_EQ("nested", doc[3][0].as<std::string>()); EXPECT_EQ(1, doc[4].size()); EXPECT_EQ("pair", doc[4]["single"].as<std::string>()); } TEST(NodeSpecTest, Ex7_15_FlowMappings) { Node doc = Load(ex7_15); EXPECT_EQ(2, doc.size()); EXPECT_EQ(2, doc[0].size()); EXPECT_EQ("two", doc[0]["one"].as<std::string>()); EXPECT_EQ("four", doc[0]["three"].as<std::string>()); EXPECT_EQ(2, doc[1].size()); EXPECT_EQ("six", doc[1]["five"].as<std::string>()); EXPECT_EQ("eight", doc[1]["seven"].as<std::string>()); } TEST(NodeSpecTest, Ex7_16_FlowMappingEntries) { Node doc = Load(ex7_16); EXPECT_EQ(3, doc.size()); EXPECT_EQ("entry", doc["explicit"].as<std::string>()); EXPECT_EQ("entry", doc["implicit"].as<std::string>()); EXPECT_TRUE(doc[Null].IsNull()); } TEST(NodeSpecTest, Ex7_17_FlowMappingSeparateValues) { Node doc = Load(ex7_17); EXPECT_EQ(4, doc.size()); EXPECT_EQ("separate", doc["unquoted"].as<std::string>()); EXPECT_TRUE(doc["http://foo.com"].IsNull()); EXPECT_TRUE(doc["omitted value"].IsNull()); EXPECT_EQ("omitted key", doc[Null].as<std::string>()); } TEST(NodeSpecTest, Ex7_18_FlowMappingAdjacentValues) { Node doc = Load(ex7_18); EXPECT_EQ(3, doc.size()); EXPECT_EQ("value", doc["adjacent"].as<std::string>()); EXPECT_EQ("value", doc["readable"].as<std::string>()); EXPECT_TRUE(doc["empty"].IsNull()); } TEST(NodeSpecTest, Ex7_19_SinglePairFlowMappings) { Node doc = Load(ex7_19); EXPECT_EQ(1, doc.size()); EXPECT_EQ(1, doc[0].size()); EXPECT_EQ("bar", doc[0]["foo"].as<std::string>()); } TEST(NodeSpecTest, Ex7_20_SinglePairExplicitEntry) { Node doc = Load(ex7_20); EXPECT_EQ(1, doc.size()); EXPECT_EQ(1, doc[0].size()); EXPECT_EQ("baz", doc[0]["foo bar"].as<std::string>()); } TEST(NodeSpecTest, Ex7_21_SinglePairImplicitEntries) { Node doc = Load(ex7_21); EXPECT_EQ(3, doc.size()); EXPECT_EQ(1, doc[0].size()); EXPECT_EQ(1, doc[0][0].size()); EXPECT_EQ("separate", doc[0][0]["YAML"].as<std::string>()); EXPECT_EQ(1, doc[1].size()); EXPECT_EQ(1, doc[1][0].size()); EXPECT_EQ("empty key entry", doc[1][0][Null].as<std::string>()); EXPECT_EQ(1, doc[2].size()); EXPECT_EQ(1, doc[2][0].size()); std::map<std::string, std::string> key; key["JSON"] = "like"; EXPECT_EQ("adjacent", doc[2][0][key].as<std::string>()); } TEST(NodeSpecTest, Ex7_22_InvalidImplicitKeys) { EXPECT_THROW_PARSER_EXCEPTION(Load(ex7_22), ErrorMsg::END_OF_SEQ_FLOW); } TEST(NodeSpecTest, Ex7_23_FlowContent) { Node doc = Load(ex7_23); EXPECT_EQ(5, doc.size()); EXPECT_EQ(2, doc[0].size()); EXPECT_EQ("a", doc[0][0].as<std::string>()); EXPECT_EQ("b", doc[0][1].as<std::string>()); EXPECT_EQ(1, doc[1].size()); EXPECT_EQ("b", doc[1]["a"].as<std::string>()); EXPECT_EQ("a", doc[2].as<std::string>()); EXPECT_EQ('b', doc[3].as<char>()); EXPECT_EQ("c", doc[4].as<std::string>()); } TEST(NodeSpecTest, Ex7_24_FlowNodes) { Node doc = Load(ex7_24); EXPECT_EQ(5, doc.size()); EXPECT_EQ("tag:yaml.org,2002:str", doc[0].Tag()); EXPECT_EQ("a", doc[0].as<std::string>()); EXPECT_EQ('b', doc[1].as<char>()); EXPECT_EQ("c", doc[2].as<std::string>()); EXPECT_EQ("c", doc[3].as<std::string>()); EXPECT_EQ("tag:yaml.org,2002:str", doc[4].Tag()); EXPECT_EQ("", doc[4].as<std::string>()); } TEST(NodeSpecTest, Ex8_1_BlockScalarHeader) { Node doc = Load(ex8_1); EXPECT_EQ(4, doc.size()); EXPECT_EQ("literal\n", doc[0].as<std::string>()); EXPECT_EQ(" folded\n", doc[1].as<std::string>()); EXPECT_EQ("keep\n\n", doc[2].as<std::string>()); EXPECT_EQ(" strip", doc[3].as<std::string>()); } TEST(NodeSpecTest, Ex8_2_BlockIndentationHeader) { Node doc = Load(ex8_2); EXPECT_EQ(4, doc.size()); EXPECT_EQ("detected\n", doc[0].as<std::string>()); EXPECT_EQ("\n\n# detected\n", doc[1].as<std::string>()); EXPECT_EQ(" explicit\n", doc[2].as<std::string>()); EXPECT_EQ("\t\ndetected\n", doc[3].as<std::string>()); } TEST(NodeSpecTest, Ex8_3a_InvalidBlockScalarIndentationIndicators) { EXPECT_THROW_PARSER_EXCEPTION(Load(ex8_3a), ErrorMsg::END_OF_SEQ); } TEST(NodeSpecTest, Ex8_3b_InvalidBlockScalarIndentationIndicators) { EXPECT_THROW_PARSER_EXCEPTION(Load(ex8_3b), ErrorMsg::END_OF_SEQ); } TEST(NodeSpecTest, Ex8_3c_InvalidBlockScalarIndentationIndicators) { EXPECT_THROW_PARSER_EXCEPTION(Load(ex8_3c), ErrorMsg::END_OF_SEQ); } TEST(NodeSpecTest, Ex8_4_ChompingFinalLineBreak) { Node doc = Load(ex8_4); EXPECT_EQ(3, doc.size()); EXPECT_EQ("text", doc["strip"].as<std::string>()); EXPECT_EQ("text\n", doc["clip"].as<std::string>()); EXPECT_EQ("text\n", doc["keep"].as<std::string>()); } TEST(NodeSpecTest, DISABLED_Ex8_5_ChompingTrailingLines) { Node doc = Load(ex8_5); EXPECT_EQ(3, doc.size()); EXPECT_EQ("# text", doc["strip"].as<std::string>()); EXPECT_EQ("# text\n", doc["clip"].as<std::string>()); // NOTE: I believe this is a bug in the YAML spec - // it should be "# text\n\n" EXPECT_EQ("# text\n", doc["keep"].as<std::string>()); } TEST(NodeSpecTest, Ex8_6_EmptyScalarChomping) { Node doc = Load(ex8_6); EXPECT_EQ(3, doc.size()); EXPECT_EQ("", doc["strip"].as<std::string>()); EXPECT_EQ("", doc["clip"].as<std::string>()); EXPECT_EQ("\n", doc["keep"].as<std::string>()); } TEST(NodeSpecTest, Ex8_7_LiteralScalar) { Node doc = Load(ex8_7); EXPECT_EQ("literal\n\ttext\n", doc.as<std::string>()); } TEST(NodeSpecTest, Ex8_8_LiteralContent) { Node doc = Load(ex8_8); EXPECT_EQ("\n\nliteral\n \n\ntext\n", doc.as<std::string>()); } TEST(NodeSpecTest, Ex8_9_FoldedScalar) { Node doc = Load(ex8_9); EXPECT_EQ("folded text\n", doc.as<std::string>()); } TEST(NodeSpecTest, Ex8_10_FoldedLines) { Node doc = Load(ex8_10); EXPECT_TRUE(doc.as<std::string>() == "\nfolded line\nnext line\n * bullet\n\n * list\n * " "lines\n\nlast line\n"); } TEST(NodeSpecTest, Ex8_11_MoreIndentedLines) { Node doc = Load(ex8_11); EXPECT_TRUE(doc.as<std::string>() == "\nfolded line\nnext line\n * bullet\n\n * list\n * " "lines\n\nlast line\n"); } TEST(NodeSpecTest, Ex8_12_EmptySeparationLines) { Node doc = Load(ex8_12); EXPECT_TRUE(doc.as<std::string>() == "\nfolded line\nnext line\n * bullet\n\n * list\n * " "lines\n\nlast line\n"); } TEST(NodeSpecTest, Ex8_13_FinalEmptyLines) { Node doc = Load(ex8_13); EXPECT_TRUE(doc.as<std::string>() == "\nfolded line\nnext line\n * bullet\n\n * list\n * " "lines\n\nlast line\n"); } TEST(NodeSpecTest, Ex8_14_BlockSequence) { Node doc = Load(ex8_14); EXPECT_EQ(1, doc.size()); EXPECT_EQ(2, doc["block sequence"].size()); EXPECT_EQ("one", doc["block sequence"][0].as<std::string>()); EXPECT_EQ(1, doc["block sequence"][1].size()); EXPECT_EQ("three", doc["block sequence"][1]["two"].as<std::string>()); } TEST(NodeSpecTest, Ex8_15_BlockSequenceEntryTypes) { Node doc = Load(ex8_15); EXPECT_EQ(4, doc.size()); EXPECT_TRUE(doc[0].IsNull()); EXPECT_EQ("block node\n", doc[1].as<std::string>()); EXPECT_EQ(2, doc[2].size()); EXPECT_EQ("one", doc[2][0].as<std::string>()); EXPECT_EQ("two", doc[2][1].as<std::string>()); EXPECT_EQ(1, doc[3].size()); EXPECT_EQ("two", doc[3]["one"].as<std::string>()); } TEST(NodeSpecTest, Ex8_16_BlockMappings) { Node doc = Load(ex8_16); EXPECT_EQ(1, doc.size()); EXPECT_EQ(1, doc["block mapping"].size()); EXPECT_EQ("value", doc["block mapping"]["key"].as<std::string>()); } TEST(NodeSpecTest, Ex8_17_ExplicitBlockMappingEntries) { Node doc = Load(ex8_17); EXPECT_EQ(2, doc.size()); EXPECT_TRUE(doc["explicit key"].IsNull()); EXPECT_EQ(2, doc["block key\n"].size()); EXPECT_EQ("one", doc["block key\n"][0].as<std::string>()); EXPECT_EQ("two", doc["block key\n"][1].as<std::string>()); } TEST(NodeSpecTest, Ex8_18_ImplicitBlockMappingEntries) { Node doc = Load(ex8_18); EXPECT_EQ(3, doc.size()); EXPECT_EQ("in-line value", doc["plain key"].as<std::string>()); EXPECT_TRUE(doc[Null].IsNull()); EXPECT_EQ(1, doc["quoted key"].size()); EXPECT_EQ("entry", doc["quoted key"][0].as<std::string>()); } TEST(NodeSpecTest, Ex8_19_CompactBlockMappings) { Node doc = Load(ex8_19); EXPECT_EQ(2, doc.size()); EXPECT_EQ(1, doc[0].size()); EXPECT_EQ("yellow", doc[0]["sun"].as<std::string>()); EXPECT_EQ(1, doc[1].size()); std::map<std::string, std::string> key; key["earth"] = "blue"; EXPECT_EQ(1, doc[1][key].size()); EXPECT_EQ("white", doc[1][key]["moon"].as<std::string>()); } TEST(NodeSpecTest, Ex8_20_BlockNodeTypes) { Node doc = Load(ex8_20); EXPECT_EQ(3, doc.size()); EXPECT_EQ("flow in block", doc[0].as<std::string>()); EXPECT_EQ("Block scalar\n", doc[1].as<std::string>()); EXPECT_EQ(1, doc[2].size()); EXPECT_EQ("bar", doc[2]["foo"].as<std::string>()); } TEST(NodeSpecTest, DISABLED_Ex8_21_BlockScalarNodes) { Node doc = Load(ex8_21); EXPECT_EQ(2, doc.size()); // NOTE: I believe this is a bug in the YAML spec - // it should be "value\n" EXPECT_EQ("value", doc["literal"].as<std::string>()); EXPECT_EQ("value", doc["folded"].as<std::string>()); EXPECT_EQ("!foo", doc["folded"].Tag()); } TEST(NodeSpecTest, Ex8_22_BlockCollectionNodes) { Node doc = Load(ex8_22); EXPECT_EQ(2, doc.size()); EXPECT_EQ(2, doc["sequence"].size()); EXPECT_EQ("entry", doc["sequence"][0].as<std::string>()); EXPECT_EQ(1, doc["sequence"][1].size()); EXPECT_EQ("nested", doc["sequence"][1][0].as<std::string>()); EXPECT_EQ(1, doc["mapping"].size()); EXPECT_EQ("bar", doc["mapping"]["foo"].as<std::string>()); } } }
35.328622
81
0.608447
xiaomingfun
c8e274f3f7831208c480b6d90d2d9b48d94ee1f2
8,387
cpp
C++
lib/Sema/IDETypeCheckingRequests.cpp
jackgmarch/swift
a53ab388bbbe86db37fd388201781f6a50f414c4
[ "Apache-2.0" ]
1
2021-06-22T18:53:18.000Z
2021-06-22T18:53:18.000Z
lib/Sema/IDETypeCheckingRequests.cpp
jackgmarch/swift
a53ab388bbbe86db37fd388201781f6a50f414c4
[ "Apache-2.0" ]
null
null
null
lib/Sema/IDETypeCheckingRequests.cpp
jackgmarch/swift
a53ab388bbbe86db37fd388201781f6a50f414c4
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/AST/ASTPrinter.h" #include "swift/AST/Decl.h" #include "swift/AST/NameLookup.h" #include "swift/Basic/SourceManager.h" #include "swift/Frontend/Frontend.h" #include "swift/Sema/ConstraintSystem.h" #include "swift/Sema/IDETypeCheckingRequests.h" #include "swift/Subsystems.h" #include "TypeChecker.h" using namespace swift; namespace swift { // Implement the IDE type zone. #define SWIFT_TYPEID_ZONE IDETypeChecking #define SWIFT_TYPEID_HEADER "swift/Sema/IDETypeCheckingRequestIDZone.def" #include "swift/Basic/ImplementTypeIDZone.h" #undef SWIFT_TYPEID_ZONE #undef SWIFT_TYPEID_HEADER } // Define request evaluation functions for each of the IDE type check requests. static AbstractRequestFunction *ideTypeCheckRequestFunctions[] = { #define SWIFT_REQUEST(Zone, Name, Sig, Caching, LocOptions) \ reinterpret_cast<AbstractRequestFunction *>(&Name::evaluateRequest), #include "swift/Sema/IDETypeCheckingRequestIDZone.def" #undef SWIFT_REQUEST }; void swift::registerIDETypeCheckRequestFunctions(Evaluator &evaluator) { evaluator.registerRequestFunctions(Zone::IDETypeChecking, ideTypeCheckRequestFunctions); } /// Consider the following example /// /// \code /// protocol FontStyle {} /// struct FontStyleOne: FontStyle {} /// extension FontStyle where Self == FontStyleOne { /// static var one: FontStyleOne { FontStyleOne() } /// } /// func foo<T: FontStyle>(x: T) {} /// /// func case1() { /// foo(x: .#^COMPLETE^#) // extension should be considered applied here /// } /// func case2<T: FontStyle>(x: T) { /// x.#^COMPLETE_2^# // extension should not be considered applied here /// } /// \endcode /// We want to consider the extension applied in the first case but not the /// second case. In the first case the constraint `T: FontStyle` from the /// definition of `foo` should be considered an 'at-least' constraint and any /// additional constraints on `T` (like `T == FonstStyleOne`) can be /// fulfilled by picking a more specialized version of `T`. /// However, in the second case, `T: FontStyle` should be considered an /// 'at-most' constraint and we can't make the assumption that `x` has a more /// specialized type. /// /// After type-checking we cannot easily differentiate the two cases. In both /// we have a unresolved dot completion on a primary archetype that /// conforms to `FontStyle`. /// /// To tell them apart, we apply the following heuristic: If the primary /// archetype refers to a generic parameter that is not visible in the current /// decl context (i.e. the current decl context is not a child context of the /// parameter's decl context), it is not the type of a variable visible /// in the current decl context. Hence, we must be in the first case and /// consider all extensions applied, otherwise we should only consider those /// extensions applied whose requirements are fulfilled. class ContainsSpecializableArchetype : public TypeWalker { const DeclContext *DC; bool Result = false; ContainsSpecializableArchetype(const DeclContext *DC) : DC(DC) {} Action walkToTypePre(Type T) override { if (auto *Archetype = T->getAs<ArchetypeType>()) { if (auto *GenericTypeParam = Archetype->mapTypeOutOfContext()->getAs<GenericTypeParamType>()) { if (auto GenericTypeParamDecl = GenericTypeParam->getDecl()) { bool ParamMaybeVisibleInCurrentContext = (DC == GenericTypeParamDecl->getDeclContext() || DC->isChildContextOf(GenericTypeParamDecl->getDeclContext())); if (!ParamMaybeVisibleInCurrentContext) { Result = true; return Action::Stop; } } } } return Action::Continue; } public: static bool check(const DeclContext *DC, Type T) { if (!T->hasArchetype()) { // Fast path, we don't have an archetype to check. return false; } ContainsSpecializableArchetype Checker(DC); T.walk(Checker); return Checker.Result; } }; static bool isExtensionAppliedInternal(const DeclContext *DC, Type BaseTy, const ExtensionDecl *ED) { // We can't do anything if the base type has unbound generic parameters. // We can't leak type variables into another constraint system. // For check on specializable archetype see comment on // ContainsSpecializableArchetype. if (BaseTy->hasTypeVariable() || BaseTy->hasUnboundGenericType() || BaseTy->hasUnresolvedType() || BaseTy->hasError() || ContainsSpecializableArchetype::check(DC, BaseTy)) return true; if (!ED->isConstrainedExtension()) return true; GenericSignature genericSig = ED->getGenericSignature(); auto *module = DC->getParentModule(); SubstitutionMap substMap = BaseTy->getContextSubstitutionMap( module, ED->getExtendedNominal()); return TypeChecker::checkGenericArguments( module, genericSig->getRequirements(), QuerySubstitutionMap{substMap}) == RequirementCheckResult::Success; } static bool isMemberDeclAppliedInternal(const DeclContext *DC, Type BaseTy, const ValueDecl *VD) { if (BaseTy->isExistentialType() && VD->isStatic()) return false; // We can't leak type variables into another constraint system. // We can't do anything if the base type has unbound generic parameters. if (BaseTy->hasTypeVariable() || BaseTy->hasUnboundGenericType()|| BaseTy->hasUnresolvedType() || BaseTy->hasError()) return true; const GenericContext *genericDecl = VD->getAsGenericContext(); if (!genericDecl) return true; GenericSignature genericSig = genericDecl->getGenericSignature(); if (!genericSig) return true; auto *module = DC->getParentModule(); SubstitutionMap substMap = BaseTy->getContextSubstitutionMap( module, VD->getDeclContext()); // Note: we treat substitution failure as success, to avoid tripping // up over generic parameters introduced by the declaration itself. return TypeChecker::checkGenericArguments( module, genericSig->getRequirements(), QuerySubstitutionMap{substMap}) != RequirementCheckResult::Failure; } bool IsDeclApplicableRequest::evaluate(Evaluator &evaluator, DeclApplicabilityOwner Owner) const { if (auto *VD = dyn_cast<ValueDecl>(Owner.ExtensionOrMember)) { return isMemberDeclAppliedInternal(Owner.DC, Owner.Ty, VD); } else if (auto *ED = dyn_cast<ExtensionDecl>(Owner.ExtensionOrMember)) { return isExtensionAppliedInternal(Owner.DC, Owner.Ty, ED); } else { llvm_unreachable("unhandled decl kind"); } } bool TypeRelationCheckRequest::evaluate(Evaluator &evaluator, TypeRelationCheckInput Owner) const { Optional<constraints::ConstraintKind> CKind; switch (Owner.Relation) { case TypeRelation::ConvertTo: CKind = constraints::ConstraintKind::Conversion; break; } assert(CKind.hasValue()); return TypeChecker::typesSatisfyConstraint(Owner.Pair.FirstTy, Owner.Pair.SecondTy, Owner.OpenArchetypes, *CKind, Owner.DC); } TypePair RootAndResultTypeOfKeypathDynamicMemberRequest::evaluate(Evaluator &evaluator, SubscriptDecl *subscript) const { if (!isValidKeyPathDynamicMemberLookup(subscript)) return TypePair(); const auto *param = subscript->getIndices()->get(0); auto keyPathType = param->getType()->getAs<BoundGenericType>(); if (!keyPathType) return TypePair(); auto genericArgs = keyPathType->getGenericArgs(); assert(!genericArgs.empty() && genericArgs.size() == 2 && "invalid keypath dynamic member"); return TypePair(genericArgs[0], genericArgs[1]); }
39.191589
80
0.682604
jackgmarch
c8e27d524998826bd8708344a34d876340fa916c
1,574
cpp
C++
Fase 3/src/cone.cpp
pinetreeaxe/CG-TP
d77eb45d998c91e0cb0d9468244b229f8c0325f9
[ "MIT" ]
1
2021-12-23T15:17:42.000Z
2021-12-23T15:17:42.000Z
Fase 3/src/cone.cpp
pinetreeaxe/CG-TP
d77eb45d998c91e0cb0d9468244b229f8c0325f9
[ "MIT" ]
null
null
null
Fase 3/src/cone.cpp
pinetreeaxe/CG-TP
d77eb45d998c91e0cb0d9468244b229f8c0325f9
[ "MIT" ]
null
null
null
#include "cone.hpp" #include "point.hpp" #define _USE_MATH_DEFINES #include "math.h" Cone::Cone(int argc, char** argv) { radius = std::stof(argv[0]); height = std::stof(argv[1]); slices = std::stoi(argv[2]); stacks = std::stoi(argv[2]); } std::vector<Point> Cone::draw() { Point center = Point(0, 0, 0); Point top = Point(0, height, 0); float step = 2 * M_PI / slices; std::vector<Point> points; for (int i = 0; i < slices; i++) { Point p1 = Point(SphericalPoint(step * i, 0, radius)); Point p2 = Point(SphericalPoint(step * (i+1), 0, radius)); points.push_back(p1); points.push_back(center); points.push_back(p2); Vector step1 = Vector(top.get_x() - p1.get_x(), top.get_y() - p1.get_y(), top.get_z() - p1.get_z()); step1.divide(stacks); Vector step2 = Vector(top.get_x() - p2.get_x(), top.get_y() - p2.get_y(), top.get_z() - p2.get_z()); step2.divide(stacks); for (int j = 0; j < stacks - 1;j++) { Point p3 = Point(p1.get_x(), p1.get_y(), p1.get_z()); p3.add_vector(step1); Point p4 = Point(p2.get_x(), p2.get_y(), p2.get_z()); p4.add_vector(step2); points.push_back(p1); points.push_back(p2); points.push_back(p3); points.push_back(p2); points.push_back(p4); points.push_back(p3); p1.set_x(p3.get_x()); p1.set_y(p3.get_y()); p1.set_z(p3.get_z()); p2.set_x(p4.get_x()); p2.set_y(p4.get_y()); p2.set_z(p4.get_z()); } points.push_back(p2); points.push_back(top); points.push_back(p1); } return points; }
23.848485
103
0.593393
pinetreeaxe
c8e6879fc286dfb63fe9bf69f359debfe2a49446
3,533
hpp
C++
src/D3D12Hook.hpp
MeatSafeMurderer/REFramework
e275d7eccccfcb70311863b3f822428bdd74ce95
[ "MIT" ]
1
2022-01-25T04:46:24.000Z
2022-01-25T04:46:24.000Z
src/D3D12Hook.hpp
drowhunter/REFramework
49ef476d13439110cc0ae565cc323cd615d9b327
[ "MIT" ]
null
null
null
src/D3D12Hook.hpp
drowhunter/REFramework
49ef476d13439110cc0ae565cc323cd615d9b327
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <functional> #pragma comment(lib, "d3d12.lib") #pragma comment(lib, "dxgi") #include <d3d12.h> #include <dxgi1_4.h> #include "utility/PointerHook.hpp" class D3D12Hook { public: typedef std::function<void(D3D12Hook&)> OnPresentFn; typedef std::function<void(D3D12Hook&)> OnResizeBuffersFn; typedef std::function<void(D3D12Hook&)> OnResizeTargetFn; typedef std::function<void(D3D12Hook&)> OnCreateSwapChainFn; D3D12Hook() = default; virtual ~D3D12Hook(); bool hook(); bool unhook(); bool is_hooked() { return m_hooked; } void on_present(OnPresentFn fn) { m_on_present = fn; } void on_post_present(OnPresentFn fn) { m_on_post_present = fn; } void on_resize_buffers(OnResizeBuffersFn fn) { m_on_resize_buffers = fn; } void on_resize_target(OnResizeTargetFn fn) { m_on_resize_target = fn; } /*void on_create_swap_chain(OnCreateSwapChainFn fn) { m_on_create_swap_chain = fn; }*/ ID3D12Device4* get_device() const { return m_device; } IDXGISwapChain3* get_swap_chain() const { return m_swap_chain; } auto get_swapchain_0() { return m_swapchain_0; } auto get_swapchain_1() { return m_swapchain_1; } ID3D12CommandQueue* get_command_queue() const { return m_command_queue; } UINT get_display_width() const { return m_display_width; } UINT get_display_height() const { return m_display_height; } UINT get_render_width() const { return m_render_width; } UINT get_render_height() const { return m_render_height; } bool is_inside_present() const { return m_inside_present; } bool is_proton_swapchain() const { return m_using_proton_swapchain; } protected: ID3D12Device4* m_device{ nullptr }; IDXGISwapChain3* m_swap_chain{ nullptr }; IDXGISwapChain3* m_swapchain_0{}; IDXGISwapChain3* m_swapchain_1{}; ID3D12CommandQueue* m_command_queue{ nullptr }; UINT m_display_width{ NULL }; UINT m_display_height{ NULL }; UINT m_render_width{ NULL }; UINT m_render_height{ NULL }; uint32_t m_command_queue_offset{}; uint32_t m_proton_swapchain_offset{}; bool m_using_proton_swapchain{ false }; bool m_hooked{ false }; bool m_inside_present{false}; std::unique_ptr<PointerHook> m_present_hook{}; std::unique_ptr<PointerHook> m_resize_buffers_hook{}; std::unique_ptr<PointerHook> m_resize_target_hook{}; //std::unique_ptr<FunctionHook> m_create_swap_chain_hook{}; OnPresentFn m_on_present{ nullptr }; OnPresentFn m_on_post_present{ nullptr }; OnResizeBuffersFn m_on_resize_buffers{ nullptr }; OnResizeTargetFn m_on_resize_target{ nullptr }; //OnCreateSwapChainFn m_on_create_swap_chain{ nullptr }; static HRESULT WINAPI present(IDXGISwapChain3* swap_chain, UINT sync_interval, UINT flags); static HRESULT WINAPI resize_buffers(IDXGISwapChain3* swap_chain, UINT buffer_count, UINT width, UINT height, DXGI_FORMAT new_format, UINT swap_chain_flags); static HRESULT WINAPI resize_target(IDXGISwapChain3* swap_chain, const DXGI_MODE_DESC* new_target_parameters); //static HRESULT WINAPI create_swap_chain(IDXGIFactory4* factory, IUnknown* device, HWND hwnd, const DXGI_SWAP_CHAIN_DESC* desc, const DXGI_SWAP_CHAIN_FULLSCREEN_DESC* p_fullscreen_desc, IDXGIOutput* p_restrict_to_output, IDXGISwapChain** swap_chain); };
28.039683
255
0.714407
MeatSafeMurderer
c8e7ce19a78060cd76425b101fd5387e4077a1a7
583
cpp
C++
Hacker Rank/C++/Introduction/Hacker rank Variable Sized Arrays.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
28
2017-11-08T11:52:11.000Z
2021-07-16T06:30:02.000Z
Hacker Rank/C++/Introduction/Hacker rank Variable Sized Arrays.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
null
null
null
Hacker Rank/C++/Introduction/Hacker rank Variable Sized Arrays.cpp
akash246/Competitive-Programming-Solutions
68db69ba8a771a433e5338bc4e837a02d3f89823
[ "MIT" ]
30
2017-09-01T09:14:27.000Z
2021-04-12T12:08:56.000Z
#include <iostream> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); const int sz= 1e5; int n, q, k, a, b; cin>>n>>q; int** seqSet = new int*[(const int)n]; for(int i= 0; i<n; i++){ cin>>k; int* seq = new int[(const int)k]; for(int j= 0; j<k; j++){ cin>>seq[j]; } seqSet[i]= seq; //delete[] b; } for(int i= 0; i<q; i++){ cin>>a>>b; cout<<seqSet[a][b]<<endl; } delete[] seqSet; return 0; }
15.756757
42
0.427101
akash246
c8ea11c4cda7e0a6fecbfb38344352a4489fdbd0
1,991
cpp
C++
Leetcode/Binary_Tree/leaf-similar-trees.cpp
susantabiswas/competitive_coding
49163ecdc81b68f5c1bd90988cc0dfac34ad5a31
[ "MIT" ]
2
2021-04-29T14:44:17.000Z
2021-10-01T17:33:22.000Z
Leetcode/Binary_Tree/leaf-similar-trees.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
null
null
null
Leetcode/Binary_Tree/leaf-similar-trees.cpp
adibyte95/competitive_coding
a6f084d71644606c21840875bad78d99f678a89d
[ "MIT" ]
1
2021-10-01T17:33:29.000Z
2021-10-01T17:33:29.000Z
/* https://leetcode.com/problems/leaf-similar-trees/submissions/ Idea is to find the order of leaf nodes of 1st tree and then do a preorder traversal of 2nd tree and check if the leaves of 2nd tree are also in the same order. */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: // Finds the leaves in sequential order void findLeaves(TreeNode *root, vector<int> &leaves) { if(root) { // if current is a leaf node if(!root->left && !root->right) { leaves.emplace_back(root->val); return; } findLeaves(root->left, leaves); findLeaves(root->right, leaves); } } // checks if the leaves of the current tree match the // given order of leaves bool compareLeaves(TreeNode *root, vector<int> &leaves, int &curr) { if(root) { // if leaf node if(!root->left && !root->right) { return curr < leaves.size() && root->val == leaves[curr++]; } return compareLeaves(root->left, leaves, curr) && compareLeaves(root->right, leaves, curr); } return true; } bool leafSimilar(TreeNode* root1, TreeNode* root2) { /// find the leaf nodes of tree 1 vector<int> leaves; findLeaves(root1, leaves); int curr = 0; // check if the leaves of tree 2 are the same as that of tree 1 return compareLeaves(root2, leaves, curr) && curr == leaves.size(); // if n_leaves_tree1 > n_leaves_tree2 } };
32.112903
93
0.547966
susantabiswas
c8ee4909f5212f6e145f82ecae66f5eac2b95071
2,667
cpp
C++
code/nes/mapper/10.cpp
oldGanon/neszett
7b42b042fe74e37e18f93718c3549feeea7d85e7
[ "MIT" ]
null
null
null
code/nes/mapper/10.cpp
oldGanon/neszett
7b42b042fe74e37e18f93718c3549feeea7d85e7
[ "MIT" ]
null
null
null
code/nes/mapper/10.cpp
oldGanon/neszett
7b42b042fe74e37e18f93718c3549feeea7d85e7
[ "MIT" ]
null
null
null
static u8 Mapper10_Read(cart *Cart, u16 Address) { switch (Address >> 12) { case 0: { u8 Value = Cart->Chr[Cart->Mapper9.ChrLatch[0]][Address & 0xFFF]; if (0x0FD8 <= Address && Address <= 0x0FDF) Cart->Mapper9.ChrLatch[0] = 0; if (0x0FE8 <= Address && Address <= 0x0FEF) Cart->Mapper9.ChrLatch[0] = 1; return Value; } break; case 1: { u8 Value = Cart->Chr[Cart->Mapper9.ChrLatch[1]][Address & 0xFFF]; if (0x1FD8 <= Address && Address <= 0x1FDF) Cart->Mapper9.ChrLatch[1] = 2; if (0x1FE8 <= Address && Address <= 0x1FEF) Cart->Mapper9.ChrLatch[1] = 3; return Value; } break; case 2: case 3: return Cart->Nametable[(Address >> 10) & 3][Address & 0x3FF]; case 4: case 5: break; case 6: case 7: if (Cart->Ram) { return Cart->Ram[(Address & 0x1FFF)]; } break; case 8: case 9: case 10: case 11: return Cart->Rom[0][Address & 0x3FFF]; case 12: case 13: case 14: case 15: return Cart->Rom[1][Address & 0x3FFF]; } return 0; // error } static void Mapper10_Write(cart *Cart, u16 Address, u8 Value) { switch (Address >> 12) { case 0: Cart->Chr[Cart->Mapper9.ChrLatch[0]][Address & 0xFFF] = Value; break; case 1: Cart->Chr[Cart->Mapper9.ChrLatch[1]][Address & 0xFFF] = Value; break; case 2: case 3: Cart->Nametable[(Address >> 10) & 3][Address & 0x3FF] = Value; break; case 6: case 7: if (Cart->Ram) { Cart->Ram[(Address & 0x1FFF)] = Value; } break; case 0xA: Cart->Rom[0] = Cart->PrgRom + (0x4000 * ((Value & 0xF) % Cart->PrgRomCount)); break; case 0xB: Cart->Chr[0] = Cart->ChrRom + (0x1000 * ((Value & 0x1F) % Cart->ChrRomCount)); break; case 0xC: Cart->Chr[1] = Cart->ChrRom + (0x1000 * ((Value & 0x1F) % Cart->ChrRomCount)); break; case 0xD: Cart->Chr[2] = Cart->ChrRom + (0x1000 * ((Value & 0x1F) % Cart->ChrRomCount)); break; case 0xE: Cart->Chr[3] = Cart->ChrRom + (0x1000 * ((Value & 0x1F) % Cart->ChrRomCount)); break; case 0xF: Cart_SetMirroring(Cart, (Value & 1) | 2); break; default: break; } } static void Mapper10_Init(cart *Cart) { Cart->ChrRomCount <<= 1; Cart->Read = Mapper10_Read; Cart->Write = Mapper10_Write; for (u8 i = 0; i < 4; ++i) Cart->Chr[i] = Cart->ChrRom + 0 * 0x1000; Cart->Ram = Cart->PrgRam; Cart->Rom[0] = Cart->PrgRom + (0x4000 * (Cart->PrgRomCount - 2)); Cart->Rom[1] = Cart->PrgRom + (0x4000 * (Cart->PrgRomCount - 1)); Cart->Mapper9.ChrLatch[0] = 0; Cart->Mapper9.ChrLatch[1] = 2; }
41.030769
103
0.56393
oldGanon
c8f10eca26b6cb3f6bdbcc15af563a8996e89d07
20,037
cc
C++
src/third_party/starboard/rdk/shared/drm/gst_decryptor_ocdm.cc
rmaddali991/rdk-cobalt
b2f08a80c136be75295338aeb71895d06bb6d374
[ "Apache-2.0" ]
1
2022-01-25T21:22:47.000Z
2022-01-25T21:22:47.000Z
src/third_party/starboard/rdk/shared/drm/gst_decryptor_ocdm.cc
rmaddali991/rdk-cobalt
b2f08a80c136be75295338aeb71895d06bb6d374
[ "Apache-2.0" ]
null
null
null
src/third_party/starboard/rdk/shared/drm/gst_decryptor_ocdm.cc
rmaddali991/rdk-cobalt
b2f08a80c136be75295338aeb71895d06bb6d374
[ "Apache-2.0" ]
1
2021-09-14T22:35:29.000Z
2021-09-14T22:35:29.000Z
// // Copyright 2020 Comcast Cable Communications Management, LLC // // 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. // // SPDX-License-Identifier: Apache-2.0 #include "third_party/starboard/rdk/shared/drm/gst_decryptor_ocdm.h" #if defined(HAS_OCDM) #include "third_party/starboard/rdk/shared/drm/drm_system_ocdm.h" #include "starboard/common/mutex.h" #include "starboard/common/condition_variable.h" #include <gst/gst.h> #include <gst/base/gstbasetransform.h> #include <opencdm/open_cdm.h> namespace third_party { namespace starboard { namespace rdk { namespace shared { namespace drm { namespace { G_BEGIN_DECLS #define COBALT_OCDM_DECRYPTOR_TYPE (cobalt_ocdm_decryptor_get_type()) #define COBALT_OCDM_DECRYPTOR(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), COBALT_OCDM_DECRYPTOR_TYPE, CobaltOcdmDecryptor)) #define COBALT_OCDM_DECRYPTOR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), COBALT_OCDM_DECRYPTOR_TYPE, CobaltOcdmDecryptorClass)) typedef struct _CobaltOcdmDecryptor CobaltOcdmDecryptor; typedef struct _CobaltOcdmDecryptorClass CobaltOcdmDecryptorClass; typedef struct _CobaltOcdmDecryptorPrivate CobaltOcdmDecryptorPrivate; GType cobalt_ocdm_decryptor_get_type(void); struct _CobaltOcdmDecryptor { GstBaseTransform parent; CobaltOcdmDecryptorPrivate *priv; }; struct _CobaltOcdmDecryptorClass { GstBaseTransformClass parentClass; }; G_END_DECLS static GstStaticPadTemplate sinkTemplate = GST_STATIC_PAD_TEMPLATE( "sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY); static GstStaticPadTemplate srcTemplate = GST_STATIC_PAD_TEMPLATE( "src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY); GST_DEBUG_CATEGORY(cobalt_ocdm_decryptor_debug_category); #define GST_CAT_DEFAULT cobalt_ocdm_decryptor_debug_category struct _CobaltOcdmDecryptorPrivate : public DrmSystemOcdm::Observer { _CobaltOcdmDecryptorPrivate() { #ifndef GST_DISABLE_GST_DEBUG if (gst_debug_category_get_threshold(GST_CAT_DEFAULT) >= GST_LEVEL_DEBUG) { decrypt_dur_.reserve( 300 ); } #endif } ~_CobaltOcdmDecryptorPrivate() { if (drm_system_) drm_system_->RemoveObserver(this); if (current_key_id_) { gst_buffer_unref(current_key_id_); current_key_id_ = nullptr; } if (cached_caps_) { gst_caps_unref(cached_caps_); cached_caps_ = nullptr; } } // DrmSystemOcdm::Observer void OnKeyReady(const uint8_t* key, size_t key_len) override { #ifndef GST_DISABLE_GST_DEBUG if (gst_debug_category_get_threshold(GST_CAT_DEFAULT) >= GST_LEVEL_DEBUG) { gchar *md5sum = g_compute_checksum_for_data(G_CHECKSUM_MD5, key, key_len); GST_DEBUG("key ready: %s", md5sum); g_free(md5sum); } #endif ::starboard::ScopedLock lock(mutex_); if (awaiting_key_info_) condition_.Signal(); } GstFlowReturn Decrypt( CobaltOcdmDecryptor* self, GstBuffer* buffer, GstBuffer* subsamples, uint32_t subsample_count, GstBuffer* iv, GstBuffer* key) { gint64 start = 0; #ifndef GST_DISABLE_GST_DEBUG const GstDebugLevel debug_level = gst_debug_category_get_threshold(GST_CAT_DEFAULT); if (debug_level >= GST_LEVEL_TRACE) { gchar *md5sum = 0; GstMapInfo map_info; if (gst_buffer_map(key, &map_info, GST_MAP_READ)) { md5sum = g_compute_checksum_for_data(G_CHECKSUM_MD5, map_info.data, map_info.size); gst_buffer_unmap(key, &map_info); } GST_TRACE_OBJECT(self, "buf=(%" GST_PTR_FORMAT "), " "subsample_count=%u, subsamples=(%p), iv=(%p), key=(%p : %s)", buffer, subsample_count, subsamples, iv, key, md5sum); g_free(md5sum); } #endif if ( !drm_system_ ) { GstContext* context = gst_element_get_context(GST_ELEMENT(self), "cobalt-drm-system"); if (context) { const GValue* value = gst_structure_get_value(gst_context_get_structure(context), "drm-system-instance"); DrmSystemOcdm* drm_system = reinterpret_cast<DrmSystemOcdm*>(value ? g_value_get_pointer(value) : nullptr); SetDrmSystem( drm_system ); } if (!drm_system_) { GST_ELEMENT_ERROR (self, STREAM, DECRYPT, ("No DRM System instance"), (NULL)); return GST_FLOW_ERROR; } } GstMapInfo map_info; if (FALSE == gst_buffer_map(key, &map_info, GST_MAP_READ)) { GST_ELEMENT_ERROR (self, STREAM, DECRYPT, ("Failed to map kid buffer"), (NULL)); return GST_FLOW_NOT_SUPPORTED; } else { if (!current_key_id_ || gst_buffer_memcmp(current_key_id_, 0, map_info.data, map_info.size) != 0) { if (debug_level >= GST_LEVEL_DEBUG) { gchar *md5sum = g_compute_checksum_for_data(G_CHECKSUM_MD5, map_info.data, map_info.size); GST_DEBUG_OBJECT(self, "Got buffer protected with key %s", md5sum); g_free(md5sum); } ::starboard::ScopedLock lock(mutex_); current_session_id_.clear(); if (current_key_id_) { gst_buffer_unref(current_key_id_); current_key_id_ = nullptr; } while(true) { if (is_flushing_ || is_active_ == false) break; current_session_id_ = drm_system_->SessionIdByKeyId(map_info.data, map_info.size); if (!current_session_id_.empty()) { current_key_id_ = gst_buffer_copy(key); break; } GST_DEBUG_OBJECT(self, "Session id is empty, waiting"); awaiting_key_info_ = &map_info; condition_.Wait(); awaiting_key_info_ = nullptr; } if (debug_level >= GST_LEVEL_DEBUG) { gchar *md5sum = g_compute_checksum_for_data(G_CHECKSUM_MD5, (const guchar*)current_session_id_.c_str(), current_session_id_.size()); GST_DEBUG_OBJECT(self, "Using session with id '%s'", md5sum); g_free(md5sum); } } gst_buffer_unmap(key, &map_info); } if ( current_session_id_.empty() ) { if ( is_flushing_ ) { GST_DEBUG_OBJECT(self, "flushing"); return GST_FLOW_FLUSHING; } if ( !is_active_ ) { GST_DEBUG_OBJECT(self, "inactive"); return GST_BASE_TRANSFORM_FLOW_DROPPED; } GST_ELEMENT_ERROR (self, STREAM, DECRYPT_NOKEY, ("No session found"), (NULL)); return GST_FLOW_NOT_SUPPORTED; } GstCaps *caps = nullptr; gst_caps_replace(&caps, cached_caps_); if ( !caps ) { GstPad* sink_pad = gst_element_get_static_pad(GST_ELEMENT(self), "sink"); caps = gst_pad_get_current_caps(sink_pad); gst_object_unref(sink_pad); GST_DEBUG_OBJECT(self, "using new caps for decrypt = %" GST_PTR_FORMAT, caps); SetCachedCaps( caps ); } #ifndef GST_DISABLE_GST_DEBUG if ( debug_level >= GST_LEVEL_DEBUG ) { start = g_get_monotonic_time(); } #endif int rc = drm_system_->Decrypt( current_session_id_, buffer, subsamples, subsample_count, iv, key, caps); if ( caps ) { gst_caps_unref(caps); caps = nullptr; } if ( rc != 0 ) { if ( rc == ERROR_INVALID_SESSION ) { GST_DEBUG_OBJECT(self, "Invalid session. Probably due to player shutdown."); return GST_BASE_TRANSFORM_FLOW_DROPPED; } GST_ELEMENT_ERROR (self, STREAM, DECRYPT, ("Decryption failed"), ("error code = %d", rc)); return GST_FLOW_ERROR; } if ( start ) { gint64 dur_ms = (g_get_monotonic_time() - start) / 1000; decrypt_dur_.push_back(dur_ms); total_time_ += dur_ms; total_size_ += gst_buffer_get_size(buffer); ++buf_count_; if ( buf_count_ == 300 ) { std::sort(decrypt_dur_.begin(), decrypt_dur_.end()); uint64_t median = decrypt_dur_[ decrypt_dur_.size() / 2 ]; uint64_t max_time = *decrypt_dur_.rbegin(); uint64_t total_time = total_time_; total_time_ = 0; uint64_t total_size = total_size_; total_size_ = 0; uint32_t buf_count = buf_count_; buf_count_ = 0; decrypt_dur_.resize(0); GST_DEBUG_OBJECT(self, "%s decrypt time: " "avg = %" G_GUINT64_FORMAT " ms, " "median = %" G_GUINT64_FORMAT " ms, " "max = %" G_GUINT64_FORMAT " ms, " "size = %" G_GUINT64_FORMAT " kb, " "buf count = %u", IsVideo() ? "video" : "audio", (total_time / buf_count), median, max_time, (total_size / 1024), buf_count); } } return GST_FLOW_OK; } void SetDrmSystem(DrmSystemOcdm* system) { if (drm_system_) drm_system_->RemoveObserver(this); drm_system_ = system; if (drm_system_) drm_system_->AddObserver(this); } void SetIsFlushing(bool is_flushing) { ::starboard::ScopedLock lock(mutex_); is_flushing_ = is_flushing; condition_.Signal(); } void SetActive(bool is_active) { ::starboard::ScopedLock lock(mutex_); is_active_ = is_active; condition_.Signal(); } void SetCachedCaps(GstCaps* caps) { gst_caps_replace(&cached_caps_, caps); if ( caps ) { const GstStructure *s; const gchar *media_type; s = gst_caps_get_structure (caps, 0); media_type = gst_structure_get_name (s); is_video_ = g_str_has_prefix(media_type, "video"); } } bool IsVideo() const { return is_video_; } private: ::starboard::Mutex mutex_; ::starboard::ConditionVariable condition_ { mutex_ }; GstCaps* cached_caps_ { nullptr }; GstMapInfo* awaiting_key_info_ { nullptr }; GstBuffer* current_key_id_ { nullptr }; std::string current_session_id_; DrmSystemOcdm* drm_system_ { nullptr }; bool is_flushing_ { false }; bool is_active_ { true }; bool is_video_ { false }; std::vector<uint64_t> decrypt_dur_; uint64_t total_time_ { 0 }; uint64_t total_size_ { 0 }; uint32_t buf_count_ { 0 }; }; #define cobalt_ocdm_decryptor_parent_class parent_class G_DEFINE_TYPE_WITH_PRIVATE(CobaltOcdmDecryptor, cobalt_ocdm_decryptor, GST_TYPE_BASE_TRANSFORM); static void cobalt_ocdm_decryptor_finalize(GObject*); static GstCaps* cobalt_ocdm_decryptor_transform_caps(GstBaseTransform*, GstPadDirection, GstCaps*, GstCaps*); static GstFlowReturn cobalt_ocdm_decryptor_transform_ip(GstBaseTransform* base, GstBuffer* buffer); static gboolean cobalt_ocdm_decryptor_sink_event(GstBaseTransform* base, GstEvent* event); static gboolean cobalt_ocdm_decryptor_stop(GstBaseTransform *base); static gboolean cobalt_ocdm_decryptor_start(GstBaseTransform *base); static void cobalt_ocdm_decryptor_set_context(GstElement* element, GstContext* context); static GstStateChangeReturn cobalt_ocdm_decryptor_change_state(GstElement* element, GstStateChange transition); static void cobalt_ocdm_decryptor_class_init(CobaltOcdmDecryptorClass* klass) { GST_DEBUG_CATEGORY_INIT( cobalt_ocdm_decryptor_debug_category, "cobaltocdm", 0, "OCDM Decryptor for Cobalt"); GObjectClass* gobject_class = G_OBJECT_CLASS(klass); gobject_class->finalize = GST_DEBUG_FUNCPTR(cobalt_ocdm_decryptor_finalize); GstElementClass* element_class = GST_ELEMENT_CLASS(klass); element_class->set_context = GST_DEBUG_FUNCPTR(cobalt_ocdm_decryptor_set_context); element_class->change_state = GST_DEBUG_FUNCPTR(cobalt_ocdm_decryptor_change_state); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&sinkTemplate)); gst_element_class_add_pad_template(element_class, gst_static_pad_template_get(&srcTemplate)); gst_element_class_set_static_metadata( element_class, "OCDM Decryptor.", GST_ELEMENT_FACTORY_KLASS_DECRYPTOR, "Decryptor element for Cobalt.", "Comcast"); GstBaseTransformClass* base_transform_class = GST_BASE_TRANSFORM_CLASS(klass); base_transform_class->transform_caps = GST_DEBUG_FUNCPTR(cobalt_ocdm_decryptor_transform_caps); base_transform_class->transform_ip = GST_DEBUG_FUNCPTR(cobalt_ocdm_decryptor_transform_ip); base_transform_class->transform_ip_on_passthrough = FALSE; base_transform_class->sink_event = GST_DEBUG_FUNCPTR(cobalt_ocdm_decryptor_sink_event); base_transform_class->start = GST_DEBUG_FUNCPTR(cobalt_ocdm_decryptor_start); base_transform_class->stop = GST_DEBUG_FUNCPTR(cobalt_ocdm_decryptor_stop); } static void cobalt_ocdm_decryptor_init(CobaltOcdmDecryptor* self) { CobaltOcdmDecryptorPrivate* priv = reinterpret_cast<CobaltOcdmDecryptorPrivate*>( cobalt_ocdm_decryptor_get_instance_private(self)); self->priv = new (priv) CobaltOcdmDecryptorPrivate(); GstBaseTransform* base = GST_BASE_TRANSFORM(self); gst_base_transform_set_in_place(base, TRUE); gst_base_transform_set_passthrough(base, FALSE); gst_base_transform_set_gap_aware(base, FALSE); } static void cobalt_ocdm_decryptor_finalize(GObject* object) { CobaltOcdmDecryptor* self = COBALT_OCDM_DECRYPTOR(object); CobaltOcdmDecryptorPrivate* priv = reinterpret_cast<CobaltOcdmDecryptorPrivate*>( cobalt_ocdm_decryptor_get_instance_private(self)); priv->~CobaltOcdmDecryptorPrivate(); GST_CALL_PARENT(G_OBJECT_CLASS, finalize, (object)); } static GstCaps* cobalt_ocdm_decryptor_transform_caps(GstBaseTransform* base, GstPadDirection direction, GstCaps* caps, GstCaps* filter) { if (direction == GST_PAD_UNKNOWN) return nullptr; CobaltOcdmDecryptor* self = COBALT_OCDM_DECRYPTOR(base); CobaltOcdmDecryptorPrivate* priv = reinterpret_cast<CobaltOcdmDecryptorPrivate*>( cobalt_ocdm_decryptor_get_instance_private(self)); GST_DEBUG_OBJECT(self, "Transform in direction: %s, caps %" GST_PTR_FORMAT ", filter %" GST_PTR_FORMAT, direction == GST_PAD_SINK ? "GST_PAD_SINK" : "GST_PAD_SRC", caps, filter); priv->SetCachedCaps( nullptr ); return GST_BASE_TRANSFORM_CLASS(parent_class)->transform_caps(base, direction, caps, filter); } static GstFlowReturn cobalt_ocdm_decryptor_transform_ip(GstBaseTransform* base, GstBuffer* buffer) { CobaltOcdmDecryptor* self = COBALT_OCDM_DECRYPTOR(base); CobaltOcdmDecryptorPrivate* priv = reinterpret_cast<CobaltOcdmDecryptorPrivate*>( cobalt_ocdm_decryptor_get_instance_private(self)); GST_TRACE_OBJECT(self, "Transform in place buf=(%" GST_PTR_FORMAT ")", buffer); GstProtectionMeta* protection_meta = reinterpret_cast<GstProtectionMeta*>(gst_buffer_get_protection_meta(buffer)); if (!protection_meta) { GST_TRACE_OBJECT(self, "Clear sample"); return GST_FLOW_OK; } GstFlowReturn ret = GST_FLOW_NOT_SUPPORTED; GstStructure* info = protection_meta->info; GstBuffer* subsamples = nullptr; GstBuffer* iv = nullptr; GstBuffer* key = nullptr; uint32_t subsample_count = 0u; uint32_t encryption_scheme = kSbDrmEncryptionSchemeAesCtr; const GValue* value = nullptr; if ( gst_structure_get_uint(info, "encryption_scheme", &encryption_scheme) ) { if (encryption_scheme != kSbDrmEncryptionSchemeAesCtr) { GST_ELEMENT_ERROR (self, STREAM, DECRYPT, ("Decryption failed"), ("Unsupported encryption scheme = %d", encryption_scheme)); goto exit; } } value = gst_structure_get_value(info, "kid"); if (!value) { GST_ELEMENT_ERROR (self, STREAM, DECRYPT_NOKEY, ("No key ID available for encrypted sample"), (NULL)); goto exit; } key = gst_value_get_buffer(value); value = gst_structure_get_value(info, "iv"); if (!value) { GST_ELEMENT_ERROR (self, STREAM, DECRYPT_NOKEY, ("Failed to get IV buffer"), (NULL)); goto exit; } iv = gst_value_get_buffer(value); if (!gst_structure_get_uint(info, "subsample_count", &subsample_count)) { GST_ELEMENT_ERROR (self, STREAM, DECRYPT, ("Failed to get subsamples_count"), (NULL)); goto exit; } if (subsample_count) { value = gst_structure_get_value(info, "subsamples"); if (!value) { GST_ELEMENT_ERROR (self, STREAM, DECRYPT, ("Failed to get subsamples buffer"), (NULL)); goto exit; } subsamples = gst_value_get_buffer(value); } ret = priv->Decrypt(self, buffer, subsamples, subsample_count, iv, key); GST_TRACE_OBJECT(self, "ret=%s", gst_flow_get_name(ret)); exit: gst_buffer_remove_meta(buffer, reinterpret_cast<GstMeta*>(protection_meta)); return ret; } static void cobalt_ocdm_decryptor_set_context(GstElement* element, GstContext* context) { CobaltOcdmDecryptor* self = COBALT_OCDM_DECRYPTOR(element); CobaltOcdmDecryptorPrivate* priv = reinterpret_cast<CobaltOcdmDecryptorPrivate*>( cobalt_ocdm_decryptor_get_instance_private(self)); if (gst_context_has_context_type(context, "cobalt-drm-system")) { const GValue* value = gst_structure_get_value(gst_context_get_structure(context), "drm-system-instance"); DrmSystemOcdm* drm_system = reinterpret_cast<DrmSystemOcdm*>(value ? g_value_get_pointer(value) : nullptr); priv->SetDrmSystem( drm_system ); GST_DEBUG_OBJECT(self, "got drm system %p", drm_system); return; } GST_ELEMENT_CLASS(parent_class)->set_context(element, context); } static GstStateChangeReturn cobalt_ocdm_decryptor_change_state(GstElement* element, GstStateChange transition) { CobaltOcdmDecryptor* self = COBALT_OCDM_DECRYPTOR(element); CobaltOcdmDecryptorPrivate* priv = reinterpret_cast<CobaltOcdmDecryptorPrivate*>( cobalt_ocdm_decryptor_get_instance_private(self)); switch (transition) { case GST_STATE_CHANGE_READY_TO_PAUSED: priv->SetActive(true); break; case GST_STATE_CHANGE_PAUSED_TO_READY: priv->SetActive(false); break; default: break; } GstStateChangeReturn result = GST_ELEMENT_CLASS(parent_class)->change_state(element, transition); return result; } static gboolean cobalt_ocdm_decryptor_sink_event(GstBaseTransform* base, GstEvent* event) { CobaltOcdmDecryptor* self = COBALT_OCDM_DECRYPTOR(base); CobaltOcdmDecryptorPrivate* priv = reinterpret_cast<CobaltOcdmDecryptorPrivate*>( cobalt_ocdm_decryptor_get_instance_private(self)); switch (GST_EVENT_TYPE(event)) { case GST_EVENT_FLUSH_START: { GST_DEBUG_OBJECT(self, "flushing"); priv->SetIsFlushing(true); break; } case GST_EVENT_FLUSH_STOP: { GST_DEBUG_OBJECT(self, "flushing done"); priv->SetIsFlushing(false); break; default: break; } } return GST_BASE_TRANSFORM_CLASS(parent_class)->sink_event(base, event); } static gboolean cobalt_ocdm_decryptor_stop(GstBaseTransform *base) { CobaltOcdmDecryptor* self = COBALT_OCDM_DECRYPTOR(base); CobaltOcdmDecryptorPrivate* priv = reinterpret_cast<CobaltOcdmDecryptorPrivate*>( cobalt_ocdm_decryptor_get_instance_private(self)); priv->SetActive(false); return TRUE; } static gboolean cobalt_ocdm_decryptor_start(GstBaseTransform *base) { CobaltOcdmDecryptor* self = COBALT_OCDM_DECRYPTOR(base); CobaltOcdmDecryptorPrivate* priv = reinterpret_cast<CobaltOcdmDecryptorPrivate*>( cobalt_ocdm_decryptor_get_instance_private(self)); priv->SetActive(true); return TRUE; } } // namespace GstElement *CreateDecryptorElement(const gchar* name) { return GST_ELEMENT ( g_object_new (COBALT_OCDM_DECRYPTOR_TYPE, name) ); } } // namespace drm } // namespace shared } // namespace rdk } // namespace starboard } // namespace third_party #else //defined(HAS_OCDM) namespace third_party { namespace starboard { namespace rdk { namespace shared { namespace drm { GstElement *CreateDecryptorElement(const gchar* name) { return nullptr; } } // namespace drm } // namespace shared } // namespace rdk } // namespace starboard } // namespace third_party #endif //defined(HAS_OCDM)
34.134583
142
0.726456
rmaddali991
c8f3d8243aca5d8a84ea9b1770949f69a20dbf1c
3,396
cpp
C++
KTL/KTL.Containers.ListNode.cpp
MeeSong/KTL
c556e44c57a402ce049a3f83270b40ccaca1fec6
[ "MIT" ]
105
2016-09-24T14:47:32.000Z
2022-03-28T15:15:31.000Z
KTL/KTL.Containers.ListNode.cpp
c3358/KTL
c556e44c57a402ce049a3f83270b40ccaca1fec6
[ "MIT" ]
2
2019-08-21T22:24:45.000Z
2021-07-28T11:28:59.000Z
KTL/KTL.Containers.ListNode.cpp
c3358/KTL
c556e44c57a402ce049a3f83270b40ccaca1fec6
[ "MIT" ]
46
2017-08-30T07:28:28.000Z
2022-02-04T14:42:57.000Z
#include "KTL.Containers.ListNode.h" #include "KTL.Type.Uitility.h" namespace ktl { inline namespace containers { /// STRUCT _List_node_base bool _List_node_base::empty() const NOEXCEPT$TYPE { return static_cast<bool>((m_next == this)); } void _List_node_base::swap( _List_node_base& aLeft, _List_node_base& aRight) NOEXCEPT$TYPE { if (!aLeft.empty()) { if (!aRight.empty()) { // Both aLeft and aRight are not empty. swap_adl(aLeft.m_next, aRight.m_next); swap_adl(aLeft.m_prev, aRight.m_prev); aLeft.m_next->m_prev = aLeft.m_prev->m_next = &aLeft; aRight.m_next->m_prev = aRight.m_prev->m_next = &aRight; } else { // aLeft is not empty, aRight is empty. aRight.m_next = aLeft.m_next; aRight.m_prev = aLeft.m_prev; aRight.m_next->m_prev = aRight.m_prev->m_next = &aRight; aLeft.m_next = aLeft.m_prev = &aLeft; } } else if (!aRight.empty()) { // aLeft is empty, aRight is not empty. aLeft.m_next = aRight.m_next; aLeft.m_prev = aRight.m_prev; aLeft.m_next->m_prev = aLeft.m_prev->m_next = &aLeft; aRight.m_next = aRight.m_prev = &aRight; } // Both aLeft and aRight are empty. } void _List_node_base::transfer( _List_node_base *const aFirst, _List_node_base *const aLast) NOEXCEPT$TYPE { if (aFirst && aLast && this != aLast && aFirst != aLast) { // Remove [first, last) from its old position. aLast->m_prev->m_next = this; aFirst->m_prev->m_next = aLast; this->m_prev->m_next = aFirst; // Splice [first, last) into its new position. _List_node_base *const vTemp = this->m_prev; this->m_prev = aLast->m_prev; aLast->m_prev = aFirst->m_prev; aFirst->m_prev = vTemp; } } void _List_node_base::reverse() NOEXCEPT$TYPE { _List_node_base * vTemp = this; do { swap_adl(vTemp->m_next, vTemp->m_prev); // Old next node is now prev vTemp = vTemp->m_prev; } while (vTemp != this); } void _List_node_base::hook(_List_node_base *const aPosition) NOEXCEPT$TYPE { this->m_next = aPosition; this->m_prev = aPosition->m_prev; aPosition->m_prev->m_next = this; aPosition->m_prev = this; } void _List_node_base::unhook() NOEXCEPT$TYPE { _List_node_base *const vNext = this->m_next; _List_node_base *const vPrev = this->m_prev; vPrev->m_next = vNext; vNext->m_prev = vPrev; } } }
30.872727
83
0.463486
MeeSong
c8f8f7d67b845678eac7969d423acde39d1e96ef
35,410
cpp
C++
src/llvm/lib/VMCore/DebugInfo.cpp
jeltz/rust-debian-package
07eaa3658867408248c555b1b3a593c012b4f931
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2015-02-04T20:57:19.000Z
2015-02-04T20:57:19.000Z
src/llvm/lib/VMCore/DebugInfo.cpp
jeltz/rust-debian-package
07eaa3658867408248c555b1b3a593c012b4f931
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
src/llvm/lib/VMCore/DebugInfo.cpp
jeltz/rust-debian-package
07eaa3658867408248c555b1b3a593c012b4f931
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
//===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the helper classes used to build and interpret debug // information in LLVM IR form. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Intrinsics.h" #include "llvm/IntrinsicInst.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace llvm::dwarf; //===----------------------------------------------------------------------===// // DIDescriptor //===----------------------------------------------------------------------===// DIDescriptor::DIDescriptor(const DIFile F) : DbgNode(F.DbgNode) { } DIDescriptor::DIDescriptor(const DISubprogram F) : DbgNode(F.DbgNode) { } DIDescriptor::DIDescriptor(const DILexicalBlockFile F) : DbgNode(F.DbgNode) { } DIDescriptor::DIDescriptor(const DILexicalBlock F) : DbgNode(F.DbgNode) { } DIDescriptor::DIDescriptor(const DIVariable F) : DbgNode(F.DbgNode) { } DIDescriptor::DIDescriptor(const DIType F) : DbgNode(F.DbgNode) { } StringRef DIDescriptor::getStringField(unsigned Elt) const { if (DbgNode == 0) return StringRef(); if (Elt < DbgNode->getNumOperands()) if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt))) return MDS->getString(); return StringRef(); } uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const { if (DbgNode == 0) return 0; if (Elt < DbgNode->getNumOperands()) if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt))) return CI->getZExtValue(); return 0; } DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const { if (DbgNode == 0) return DIDescriptor(); if (Elt < DbgNode->getNumOperands()) return DIDescriptor(dyn_cast_or_null<const MDNode>(DbgNode->getOperand(Elt))); return DIDescriptor(); } GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const { if (DbgNode == 0) return 0; if (Elt < DbgNode->getNumOperands()) return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt)); return 0; } Constant *DIDescriptor::getConstantField(unsigned Elt) const { if (DbgNode == 0) return 0; if (Elt < DbgNode->getNumOperands()) return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt)); return 0; } Function *DIDescriptor::getFunctionField(unsigned Elt) const { if (DbgNode == 0) return 0; if (Elt < DbgNode->getNumOperands()) return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt)); return 0; } unsigned DIVariable::getNumAddrElements() const { if (getVersion() <= LLVMDebugVersion8) return DbgNode->getNumOperands()-6; if (getVersion() == LLVMDebugVersion9) return DbgNode->getNumOperands()-7; return DbgNode->getNumOperands()-8; } /// getInlinedAt - If this variable is inlined then return inline location. MDNode *DIVariable::getInlinedAt() const { if (getVersion() <= LLVMDebugVersion9) return NULL; return dyn_cast_or_null<MDNode>(DbgNode->getOperand(7)); } //===----------------------------------------------------------------------===// // Predicates //===----------------------------------------------------------------------===// /// isBasicType - Return true if the specified tag is legal for /// DIBasicType. bool DIDescriptor::isBasicType() const { if (!DbgNode) return false; switch (getTag()) { case dwarf::DW_TAG_base_type: case dwarf::DW_TAG_unspecified_type: return true; default: return false; } } /// isDerivedType - Return true if the specified tag is legal for DIDerivedType. bool DIDescriptor::isDerivedType() const { if (!DbgNode) return false; switch (getTag()) { case dwarf::DW_TAG_typedef: case dwarf::DW_TAG_pointer_type: case dwarf::DW_TAG_reference_type: case dwarf::DW_TAG_rvalue_reference_type: case dwarf::DW_TAG_const_type: case dwarf::DW_TAG_volatile_type: case dwarf::DW_TAG_restrict_type: case dwarf::DW_TAG_member: case dwarf::DW_TAG_inheritance: case dwarf::DW_TAG_friend: return true; default: // CompositeTypes are currently modelled as DerivedTypes. return isCompositeType(); } } /// isCompositeType - Return true if the specified tag is legal for /// DICompositeType. bool DIDescriptor::isCompositeType() const { if (!DbgNode) return false; switch (getTag()) { case dwarf::DW_TAG_array_type: case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_union_type: case dwarf::DW_TAG_enumeration_type: case dwarf::DW_TAG_vector_type: case dwarf::DW_TAG_subroutine_type: case dwarf::DW_TAG_class_type: return true; default: return false; } } /// isVariable - Return true if the specified tag is legal for DIVariable. bool DIDescriptor::isVariable() const { if (!DbgNode) return false; switch (getTag()) { case dwarf::DW_TAG_auto_variable: case dwarf::DW_TAG_arg_variable: case dwarf::DW_TAG_return_variable: return true; default: return false; } } /// isType - Return true if the specified tag is legal for DIType. bool DIDescriptor::isType() const { return isBasicType() || isCompositeType() || isDerivedType(); } /// isSubprogram - Return true if the specified tag is legal for /// DISubprogram. bool DIDescriptor::isSubprogram() const { return DbgNode && getTag() == dwarf::DW_TAG_subprogram; } /// isGlobalVariable - Return true if the specified tag is legal for /// DIGlobalVariable. bool DIDescriptor::isGlobalVariable() const { return DbgNode && (getTag() == dwarf::DW_TAG_variable || getTag() == dwarf::DW_TAG_constant); } /// isGlobal - Return true if the specified tag is legal for DIGlobal. bool DIDescriptor::isGlobal() const { return isGlobalVariable(); } /// isUnspecifiedParmeter - Return true if the specified tag is /// DW_TAG_unspecified_parameters. bool DIDescriptor::isUnspecifiedParameter() const { return DbgNode && getTag() == dwarf::DW_TAG_unspecified_parameters; } /// isScope - Return true if the specified tag is one of the scope /// related tag. bool DIDescriptor::isScope() const { if (!DbgNode) return false; switch (getTag()) { case dwarf::DW_TAG_compile_unit: case dwarf::DW_TAG_lexical_block: case dwarf::DW_TAG_subprogram: case dwarf::DW_TAG_namespace: return true; default: break; } return false; } /// isTemplateTypeParameter - Return true if the specified tag is /// DW_TAG_template_type_parameter. bool DIDescriptor::isTemplateTypeParameter() const { return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter; } /// isTemplateValueParameter - Return true if the specified tag is /// DW_TAG_template_value_parameter. bool DIDescriptor::isTemplateValueParameter() const { return DbgNode && getTag() == dwarf::DW_TAG_template_value_parameter; } /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit. bool DIDescriptor::isCompileUnit() const { return DbgNode && getTag() == dwarf::DW_TAG_compile_unit; } /// isFile - Return true if the specified tag is DW_TAG_file_type. bool DIDescriptor::isFile() const { return DbgNode && getTag() == dwarf::DW_TAG_file_type; } /// isNameSpace - Return true if the specified tag is DW_TAG_namespace. bool DIDescriptor::isNameSpace() const { return DbgNode && getTag() == dwarf::DW_TAG_namespace; } /// isLexicalBlockFile - Return true if the specified descriptor is a /// lexical block with an extra file. bool DIDescriptor::isLexicalBlockFile() const { return DbgNode && getTag() == dwarf::DW_TAG_lexical_block && (DbgNode->getNumOperands() == 3); } /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block. bool DIDescriptor::isLexicalBlock() const { return DbgNode && getTag() == dwarf::DW_TAG_lexical_block && (DbgNode->getNumOperands() > 3); } /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type. bool DIDescriptor::isSubrange() const { return DbgNode && getTag() == dwarf::DW_TAG_subrange_type; } /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator. bool DIDescriptor::isEnumerator() const { return DbgNode && getTag() == dwarf::DW_TAG_enumerator; } /// isObjCProperty - Return true if the specified tag is DW_TAG bool DIDescriptor::isObjCProperty() const { return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property; } //===----------------------------------------------------------------------===// // Simple Descriptor Constructors and other Methods //===----------------------------------------------------------------------===// DIType::DIType(const MDNode *N) : DIScope(N) { if (!N) return; if (!isBasicType() && !isDerivedType() && !isCompositeType()) { DbgNode = 0; } } unsigned DIArray::getNumElements() const { if (!DbgNode) return 0; return DbgNode->getNumOperands(); } /// replaceAllUsesWith - Replace all uses of debug info referenced by /// this descriptor. void DIType::replaceAllUsesWith(DIDescriptor &D) { if (!DbgNode) return; // Since we use a TrackingVH for the node, its easy for clients to manufacture // legitimate situations where they want to replaceAllUsesWith() on something // which, due to uniquing, has merged with the source. We shield clients from // this detail by allowing a value to be replaced with replaceAllUsesWith() // itself. if (DbgNode != D) { MDNode *Node = const_cast<MDNode*>(DbgNode); const MDNode *DN = D; const Value *V = cast_or_null<Value>(DN); Node->replaceAllUsesWith(const_cast<Value*>(V)); MDNode::deleteTemporary(Node); } } /// replaceAllUsesWith - Replace all uses of debug info referenced by /// this descriptor. void DIType::replaceAllUsesWith(MDNode *D) { if (!DbgNode) return; // Since we use a TrackingVH for the node, its easy for clients to manufacture // legitimate situations where they want to replaceAllUsesWith() on something // which, due to uniquing, has merged with the source. We shield clients from // this detail by allowing a value to be replaced with replaceAllUsesWith() // itself. if (DbgNode != D) { MDNode *Node = const_cast<MDNode*>(DbgNode); const MDNode *DN = D; const Value *V = cast_or_null<Value>(DN); Node->replaceAllUsesWith(const_cast<Value*>(V)); MDNode::deleteTemporary(Node); } } /// isUnsignedDIType - Return true if type encoding is unsigned. bool DIType::isUnsignedDIType() { DIDerivedType DTy(DbgNode); if (DTy.Verify()) return DTy.getTypeDerivedFrom().isUnsignedDIType(); DIBasicType BTy(DbgNode); if (BTy.Verify()) { unsigned Encoding = BTy.getEncoding(); if (Encoding == dwarf::DW_ATE_unsigned || Encoding == dwarf::DW_ATE_unsigned_char) return true; } return false; } /// Verify - Verify that a compile unit is well formed. bool DICompileUnit::Verify() const { if (!DbgNode) return false; StringRef N = getFilename(); if (N.empty()) return false; // It is possible that directory and produce string is empty. return true; } /// Verify - Verify that an ObjC property is well formed. bool DIObjCProperty::Verify() const { if (!DbgNode) return false; unsigned Tag = getTag(); if (Tag != dwarf::DW_TAG_APPLE_property) return false; DIType Ty = getType(); if (!Ty.Verify()) return false; // Don't worry about the rest of the strings for now. return true; } /// Verify - Verify that a type descriptor is well formed. bool DIType::Verify() const { if (!DbgNode) return false; if (getContext() && !getContext().Verify()) return false; unsigned Tag = getTag(); if (!isBasicType() && Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type && Tag != dwarf::DW_TAG_reference_type && Tag != dwarf::DW_TAG_rvalue_reference_type && Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_vector_type && Tag != dwarf::DW_TAG_array_type && Tag != dwarf::DW_TAG_enumeration_type && Tag != dwarf::DW_TAG_subroutine_type && getFilename().empty()) return false; return true; } /// Verify - Verify that a basic type descriptor is well formed. bool DIBasicType::Verify() const { return isBasicType(); } /// Verify - Verify that a derived type descriptor is well formed. bool DIDerivedType::Verify() const { return isDerivedType(); } /// Verify - Verify that a composite type descriptor is well formed. bool DICompositeType::Verify() const { if (!DbgNode) return false; if (getContext() && !getContext().Verify()) return false; return true; } /// Verify - Verify that a subprogram descriptor is well formed. bool DISubprogram::Verify() const { if (!DbgNode) return false; if (getContext() && !getContext().Verify()) return false; DICompositeType Ty = getType(); if (!Ty.Verify()) return false; return true; } /// Verify - Verify that a global variable descriptor is well formed. bool DIGlobalVariable::Verify() const { if (!DbgNode) return false; if (getDisplayName().empty()) return false; if (getContext() && !getContext().Verify()) return false; DIType Ty = getType(); if (!Ty.Verify()) return false; if (!getGlobal() && !getConstant()) return false; return true; } /// Verify - Verify that a variable descriptor is well formed. bool DIVariable::Verify() const { if (!DbgNode) return false; if (getContext() && !getContext().Verify()) return false; DIType Ty = getType(); if (!Ty.Verify()) return false; return true; } /// Verify - Verify that a location descriptor is well formed. bool DILocation::Verify() const { if (!DbgNode) return false; return DbgNode->getNumOperands() == 4; } /// Verify - Verify that a namespace descriptor is well formed. bool DINameSpace::Verify() const { if (!DbgNode) return false; if (getName().empty()) return false; return true; } /// getOriginalTypeSize - If this type is derived from a base type then /// return base type size. uint64_t DIDerivedType::getOriginalTypeSize() const { unsigned Tag = getTag(); if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_restrict_type) return getSizeInBits(); DIType BaseType = getTypeDerivedFrom(); // If this type is not derived from any type then take conservative approach. if (!BaseType.isValid()) return getSizeInBits(); // If this is a derived type, go ahead and get the base type, unless it's a // reference then it's just the size of the field. Pointer types have no need // of this since they're a different type of qualification on the type. if (BaseType.getTag() == dwarf::DW_TAG_reference_type || BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type) return getSizeInBits(); if (BaseType.isDerivedType()) return DIDerivedType(BaseType).getOriginalTypeSize(); return BaseType.getSizeInBits(); } /// getObjCProperty - Return property node, if this ivar is associated with one. MDNode *DIDerivedType::getObjCProperty() const { if (getVersion() <= LLVMDebugVersion11 || DbgNode->getNumOperands() <= 10) return NULL; return dyn_cast_or_null<MDNode>(DbgNode->getOperand(10)); } /// isInlinedFnArgument - Return true if this variable provides debugging /// information for an inlined function arguments. bool DIVariable::isInlinedFnArgument(const Function *CurFn) { assert(CurFn && "Invalid function"); if (!getContext().isSubprogram()) return false; // This variable is not inlined function argument if its scope // does not describe current function. return !DISubprogram(getContext()).describes(CurFn); } /// describes - Return true if this subprogram provides debugging /// information for the function F. bool DISubprogram::describes(const Function *F) { assert(F && "Invalid function"); if (F == getFunction()) return true; StringRef Name = getLinkageName(); if (Name.empty()) Name = getName(); if (F->getName() == Name) return true; return false; } unsigned DISubprogram::isOptimized() const { assert (DbgNode && "Invalid subprogram descriptor!"); if (DbgNode->getNumOperands() == 16) return getUnsignedField(15); return 0; } MDNode *DISubprogram::getVariablesNodes() const { if (!DbgNode || DbgNode->getNumOperands() <= 19) return NULL; if (MDNode *Temp = dyn_cast_or_null<MDNode>(DbgNode->getOperand(19))) return dyn_cast_or_null<MDNode>(Temp->getOperand(0)); return NULL; } DIArray DISubprogram::getVariables() const { if (!DbgNode || DbgNode->getNumOperands() <= 19) return DIArray(); if (MDNode *T = dyn_cast_or_null<MDNode>(DbgNode->getOperand(19))) if (MDNode *A = dyn_cast_or_null<MDNode>(T->getOperand(0))) return DIArray(A); return DIArray(); } StringRef DIScope::getFilename() const { if (!DbgNode) return StringRef(); if (isLexicalBlockFile()) return DILexicalBlockFile(DbgNode).getFilename(); if (isLexicalBlock()) return DILexicalBlock(DbgNode).getFilename(); if (isSubprogram()) return DISubprogram(DbgNode).getFilename(); if (isCompileUnit()) return DICompileUnit(DbgNode).getFilename(); if (isNameSpace()) return DINameSpace(DbgNode).getFilename(); if (isType()) return DIType(DbgNode).getFilename(); if (isFile()) return DIFile(DbgNode).getFilename(); llvm_unreachable("Invalid DIScope!"); } StringRef DIScope::getDirectory() const { if (!DbgNode) return StringRef(); if (isLexicalBlockFile()) return DILexicalBlockFile(DbgNode).getDirectory(); if (isLexicalBlock()) return DILexicalBlock(DbgNode).getDirectory(); if (isSubprogram()) return DISubprogram(DbgNode).getDirectory(); if (isCompileUnit()) return DICompileUnit(DbgNode).getDirectory(); if (isNameSpace()) return DINameSpace(DbgNode).getDirectory(); if (isType()) return DIType(DbgNode).getDirectory(); if (isFile()) return DIFile(DbgNode).getDirectory(); llvm_unreachable("Invalid DIScope!"); } DIArray DICompileUnit::getEnumTypes() const { if (!DbgNode || DbgNode->getNumOperands() < 14) return DIArray(); if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(10))) if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0))) return DIArray(A); return DIArray(); } DIArray DICompileUnit::getRetainedTypes() const { if (!DbgNode || DbgNode->getNumOperands() < 14) return DIArray(); if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(11))) if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0))) return DIArray(A); return DIArray(); } DIArray DICompileUnit::getSubprograms() const { if (!DbgNode || DbgNode->getNumOperands() < 14) return DIArray(); if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(12))) if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0))) return DIArray(A); return DIArray(); } DIArray DICompileUnit::getGlobalVariables() const { if (!DbgNode || DbgNode->getNumOperands() < 14) return DIArray(); if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(13))) if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0))) return DIArray(A); return DIArray(); } /// fixupObjcLikeName - Replace contains special characters used /// in a typical Objective-C names with '.' in a given string. static void fixupObjcLikeName(StringRef Str, SmallVectorImpl<char> &Out) { bool isObjCLike = false; for (size_t i = 0, e = Str.size(); i < e; ++i) { char C = Str[i]; if (C == '[') isObjCLike = true; if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' || C == '+' || C == '(' || C == ')')) Out.push_back('.'); else Out.push_back(C); } } /// getFnSpecificMDNode - Return a NameMDNode, if available, that is /// suitable to hold function specific information. NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) { SmallString<32> Name = StringRef("llvm.dbg.lv."); StringRef FName = "fn"; if (Fn.getFunction()) FName = Fn.getFunction()->getName(); else FName = Fn.getName(); char One = '\1'; if (FName.startswith(StringRef(&One, 1))) FName = FName.substr(1); fixupObjcLikeName(FName, Name); return M.getNamedMetadata(Name.str()); } /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable /// to hold function specific information. NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) { SmallString<32> Name = StringRef("llvm.dbg.lv."); StringRef FName = "fn"; if (Fn.getFunction()) FName = Fn.getFunction()->getName(); else FName = Fn.getName(); char One = '\1'; if (FName.startswith(StringRef(&One, 1))) FName = FName.substr(1); fixupObjcLikeName(FName, Name); return M.getOrInsertNamedMetadata(Name.str()); } /// createInlinedVariable - Create a new inlined variable based on current /// variable. /// @param DV Current Variable. /// @param InlinedScope Location at current variable is inlined. DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope, LLVMContext &VMContext) { SmallVector<Value *, 16> Elts; // Insert inlined scope as 7th element. for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i) i == 7 ? Elts.push_back(InlinedScope) : Elts.push_back(DV->getOperand(i)); return DIVariable(MDNode::get(VMContext, Elts)); } /// cleanseInlinedVariable - Remove inlined scope from the variable. DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) { SmallVector<Value *, 16> Elts; // Insert inlined scope as 7th element. for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i) i == 7 ? Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext))): Elts.push_back(DV->getOperand(i)); return DIVariable(MDNode::get(VMContext, Elts)); } /// getDISubprogram - Find subprogram that is enclosing this scope. DISubprogram llvm::getDISubprogram(const MDNode *Scope) { DIDescriptor D(Scope); if (D.isSubprogram()) return DISubprogram(Scope); if (D.isLexicalBlockFile()) return getDISubprogram(DILexicalBlockFile(Scope).getContext()); if (D.isLexicalBlock()) return getDISubprogram(DILexicalBlock(Scope).getContext()); return DISubprogram(); } /// getDICompositeType - Find underlying composite type. DICompositeType llvm::getDICompositeType(DIType T) { if (T.isCompositeType()) return DICompositeType(T); if (T.isDerivedType()) return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom()); return DICompositeType(); } /// isSubprogramContext - Return true if Context is either a subprogram /// or another context nested inside a subprogram. bool llvm::isSubprogramContext(const MDNode *Context) { if (!Context) return false; DIDescriptor D(Context); if (D.isSubprogram()) return true; if (D.isType()) return isSubprogramContext(DIType(Context).getContext()); return false; } //===----------------------------------------------------------------------===// // DebugInfoFinder implementations. //===----------------------------------------------------------------------===// /// processModule - Process entire module and collect debug info. void DebugInfoFinder::processModule(Module &M) { if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) { for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) { DICompileUnit CU(CU_Nodes->getOperand(i)); addCompileUnit(CU); if (CU.getVersion() > LLVMDebugVersion10) { DIArray GVs = CU.getGlobalVariables(); for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) { DIGlobalVariable DIG(GVs.getElement(i)); if (addGlobalVariable(DIG)) processType(DIG.getType()); } DIArray SPs = CU.getSubprograms(); for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) processSubprogram(DISubprogram(SPs.getElement(i))); DIArray EnumTypes = CU.getEnumTypes(); for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) processType(DIType(EnumTypes.getElement(i))); DIArray RetainedTypes = CU.getRetainedTypes(); for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) processType(DIType(RetainedTypes.getElement(i))); return; } } } for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI) for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE; ++BI) { if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI)) processDeclare(DDI); DebugLoc Loc = BI->getDebugLoc(); if (Loc.isUnknown()) continue; LLVMContext &Ctx = BI->getContext(); DIDescriptor Scope(Loc.getScope(Ctx)); if (Scope.isCompileUnit()) addCompileUnit(DICompileUnit(Scope)); else if (Scope.isSubprogram()) processSubprogram(DISubprogram(Scope)); else if (Scope.isLexicalBlockFile()) { DILexicalBlockFile DBF = DILexicalBlockFile(Scope); processLexicalBlock(DILexicalBlock(DBF.getScope())); } else if (Scope.isLexicalBlock()) processLexicalBlock(DILexicalBlock(Scope)); if (MDNode *IA = Loc.getInlinedAt(Ctx)) processLocation(DILocation(IA)); } if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) { for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i))); if (addGlobalVariable(DIG)) { if (DIG.getVersion() <= LLVMDebugVersion10) addCompileUnit(DIG.getCompileUnit()); processType(DIG.getType()); } } } if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp")) for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) processSubprogram(DISubprogram(NMD->getOperand(i))); } /// processLocation - Process DILocation. void DebugInfoFinder::processLocation(DILocation Loc) { if (!Loc.Verify()) return; DIDescriptor S(Loc.getScope()); if (S.isCompileUnit()) addCompileUnit(DICompileUnit(S)); else if (S.isSubprogram()) processSubprogram(DISubprogram(S)); else if (S.isLexicalBlock()) processLexicalBlock(DILexicalBlock(S)); else if (S.isLexicalBlockFile()) { DILexicalBlockFile DBF = DILexicalBlockFile(S); processLexicalBlock(DILexicalBlock(DBF.getScope())); } processLocation(Loc.getOrigLocation()); } /// processType - Process DIType. void DebugInfoFinder::processType(DIType DT) { if (!addType(DT)) return; if (DT.getVersion() <= LLVMDebugVersion10) addCompileUnit(DT.getCompileUnit()); if (DT.isCompositeType()) { DICompositeType DCT(DT); processType(DCT.getTypeDerivedFrom()); DIArray DA = DCT.getTypeArray(); for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) { DIDescriptor D = DA.getElement(i); if (D.isType()) processType(DIType(D)); else if (D.isSubprogram()) processSubprogram(DISubprogram(D)); } } else if (DT.isDerivedType()) { DIDerivedType DDT(DT); processType(DDT.getTypeDerivedFrom()); } } /// processLexicalBlock void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) { DIScope Context = LB.getContext(); if (Context.isLexicalBlock()) return processLexicalBlock(DILexicalBlock(Context)); else if (Context.isLexicalBlockFile()) { DILexicalBlockFile DBF = DILexicalBlockFile(Context); return processLexicalBlock(DILexicalBlock(DBF.getScope())); } else return processSubprogram(DISubprogram(Context)); } /// processSubprogram - Process DISubprogram. void DebugInfoFinder::processSubprogram(DISubprogram SP) { if (!addSubprogram(SP)) return; if (SP.getVersion() <= LLVMDebugVersion10) addCompileUnit(SP.getCompileUnit()); processType(SP.getType()); } /// processDeclare - Process DbgDeclareInst. void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) { MDNode *N = dyn_cast<MDNode>(DDI->getVariable()); if (!N) return; DIDescriptor DV(N); if (!DV.isVariable()) return; if (!NodesSeen.insert(DV)) return; if (DIVariable(N).getVersion() <= LLVMDebugVersion10) addCompileUnit(DIVariable(N).getCompileUnit()); processType(DIVariable(N).getType()); } /// addType - Add type into Tys. bool DebugInfoFinder::addType(DIType DT) { if (!DT.isValid()) return false; if (!NodesSeen.insert(DT)) return false; TYs.push_back(DT); return true; } /// addCompileUnit - Add compile unit into CUs. bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) { if (!CU.Verify()) return false; if (!NodesSeen.insert(CU)) return false; CUs.push_back(CU); return true; } /// addGlobalVariable - Add global variable into GVs. bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) { if (!DIDescriptor(DIG).isGlobalVariable()) return false; if (!NodesSeen.insert(DIG)) return false; GVs.push_back(DIG); return true; } // addSubprogram - Add subprgoram into SPs. bool DebugInfoFinder::addSubprogram(DISubprogram SP) { if (!DIDescriptor(SP).isSubprogram()) return false; if (!NodesSeen.insert(SP)) return false; SPs.push_back(SP); return true; } //===----------------------------------------------------------------------===// // DIDescriptor: dump routines for all descriptors. //===----------------------------------------------------------------------===// /// dump - Print descriptor to dbgs() with a newline. void DIDescriptor::dump() const { print(dbgs()); dbgs() << '\n'; } /// print - Print descriptor. void DIDescriptor::print(raw_ostream &OS) const { if (!DbgNode) return; if (const char *Tag = dwarf::TagString(getTag())) OS << "[ " << Tag << " ]"; if (this->isSubrange()) { DISubrange(DbgNode).printInternal(OS); } else if (this->isCompileUnit()) { DICompileUnit(DbgNode).printInternal(OS); } else if (this->isFile()) { DIFile(DbgNode).printInternal(OS); } else if (this->isEnumerator()) { DIEnumerator(DbgNode).printInternal(OS); } else if (this->isBasicType()) { DIType(DbgNode).printInternal(OS); } else if (this->isDerivedType()) { DIDerivedType(DbgNode).printInternal(OS); } else if (this->isCompositeType()) { DICompositeType(DbgNode).printInternal(OS); } else if (this->isSubprogram()) { DISubprogram(DbgNode).printInternal(OS); } else if (this->isGlobalVariable()) { DIGlobalVariable(DbgNode).printInternal(OS); } else if (this->isVariable()) { DIVariable(DbgNode).printInternal(OS); } else if (this->isObjCProperty()) { DIObjCProperty(DbgNode).printInternal(OS); } else if (this->isScope()) { DIScope(DbgNode).printInternal(OS); } } void DISubrange::printInternal(raw_ostream &OS) const { OS << " [" << getLo() << ", " << getHi() << ']'; } void DIScope::printInternal(raw_ostream &OS) const { OS << " [" << getDirectory() << "/" << getFilename() << ']'; } void DICompileUnit::printInternal(raw_ostream &OS) const { DIScope::printInternal(OS); if (unsigned Lang = getLanguage()) OS << " [" << dwarf::LanguageString(Lang) << ']'; } void DIEnumerator::printInternal(raw_ostream &OS) const { OS << " [" << getName() << " :: " << getEnumValue() << ']'; } void DIType::printInternal(raw_ostream &OS) const { if (!DbgNode) return; StringRef Res = getName(); if (!Res.empty()) OS << " [" << Res << "]"; // TODO: Print context? OS << " [line " << getLineNumber() << ", size " << getSizeInBits() << ", align " << getAlignInBits() << ", offset " << getOffsetInBits(); if (isBasicType()) if (const char *Enc = dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding())) OS << ", enc " << Enc; OS << "]"; if (isPrivate()) OS << " [private]"; else if (isProtected()) OS << " [protected]"; if (isForwardDecl()) OS << " [fwd]"; } void DIDerivedType::printInternal(raw_ostream &OS) const { DIType::printInternal(OS); OS << " [from " << getTypeDerivedFrom().getName() << ']'; } void DICompositeType::printInternal(raw_ostream &OS) const { DIType::printInternal(OS); DIArray A = getTypeArray(); OS << " [" << A.getNumElements() << " elements]"; } void DISubprogram::printInternal(raw_ostream &OS) const { // TODO : Print context OS << " [line " << getLineNumber() << ']'; if (isLocalToUnit()) OS << " [local]"; if (isDefinition()) OS << " [def]"; if (getScopeLineNumber() != getLineNumber()) OS << " [scope " << getScopeLineNumber() << "]"; StringRef Res = getName(); if (!Res.empty()) OS << " [" << Res << ']'; } void DIGlobalVariable::printInternal(raw_ostream &OS) const { StringRef Res = getName(); if (!Res.empty()) OS << " [" << Res << ']'; OS << " [line " << getLineNumber() << ']'; // TODO : Print context if (isLocalToUnit()) OS << " [local]"; if (isDefinition()) OS << " [def]"; } void DIVariable::printInternal(raw_ostream &OS) const { StringRef Res = getName(); if (!Res.empty()) OS << " [" << Res << ']'; OS << " [line " << getLineNumber() << ']'; } void DIObjCProperty::printInternal(raw_ostream &OS) const { StringRef Name = getObjCPropertyName(); if (!Name.empty()) OS << " [" << Name << ']'; OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6) << ']'; } static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS, const LLVMContext &Ctx) { if (!DL.isUnknown()) { // Print source line info. DIScope Scope(DL.getScope(Ctx)); // Omit the directory, because it's likely to be long and uninteresting. if (Scope.Verify()) CommentOS << Scope.getFilename(); else CommentOS << "<unknown>"; CommentOS << ':' << DL.getLine(); if (DL.getCol() != 0) CommentOS << ':' << DL.getCol(); DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx)); if (!InlinedAtDL.isUnknown()) { CommentOS << " @[ "; printDebugLoc(InlinedAtDL, CommentOS, Ctx); CommentOS << " ]"; } } } void DIVariable::printExtendedName(raw_ostream &OS) const { const LLVMContext &Ctx = DbgNode->getContext(); StringRef Res = getName(); if (!Res.empty()) OS << Res << "," << getLineNumber(); if (MDNode *InlinedAt = getInlinedAt()) { DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt); if (!InlinedAtDL.isUnknown()) { OS << " @["; printDebugLoc(InlinedAtDL, OS, Ctx); OS << "]"; } } }
30.290847
82
0.65747
jeltz
c8f94857af570a7b0aaf2c4ef85bedcbb1321966
9,265
cc
C++
ecp5/config.cc
ZirconiumX/nextpnr
3c078f609029d363b1081e727de8a19162867b08
[ "ISC" ]
79
2019-09-26T12:46:28.000Z
2021-04-22T16:10:12.000Z
ecp5/config.cc
ZirconiumX/nextpnr
3c078f609029d363b1081e727de8a19162867b08
[ "ISC" ]
15
2019-12-24T11:25:28.000Z
2021-02-07T21:11:58.000Z
ecp5/config.cc
ZirconiumX/nextpnr
3c078f609029d363b1081e727de8a19162867b08
[ "ISC" ]
12
2019-12-27T16:22:47.000Z
2021-04-21T09:19:58.000Z
/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 David Shah <david@symbioticeda.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 "config.h" #include <boost/range/adaptor/reversed.hpp> #include <iomanip> #include "log.h" NEXTPNR_NAMESPACE_BEGIN #define fmt(x) (static_cast<const std::ostringstream &>(std::ostringstream() << x).str()) inline std::string to_string(const std::vector<bool> &bv) { std::ostringstream os; for (auto bit : boost::adaptors::reverse(bv)) os << (bit ? '1' : '0'); return os.str(); } inline std::istream &operator>>(std::istream &in, std::vector<bool> &bv) { bv.clear(); std::string s; in >> s; for (auto c : boost::adaptors::reverse(s)) { assert((c == '0') || (c == '1')); bv.push_back((c == '1')); } return in; } struct ConfigBit { int frame; int bit; bool inv; }; static ConfigBit cbit_from_str(const std::string &s) { size_t idx = 0; ConfigBit b; if (s[idx] == '!') { b.inv = true; ++idx; } else { b.inv = false; } NPNR_ASSERT(s[idx] == 'F'); ++idx; size_t b_pos = s.find('B'); NPNR_ASSERT(b_pos != std::string::npos); b.frame = stoi(s.substr(idx, b_pos - idx)); b.bit = stoi(s.substr(b_pos + 1)); return b; } inline std::string to_string(ConfigBit b) { std::ostringstream ss; if (b.inv) ss << "!"; ss << "F" << b.frame; ss << "B" << b.bit; return ss.str(); } // Skip whitespace, optionally including newlines inline void skip_blank(std::istream &in, bool nl = false) { int c = in.peek(); while (in && (((c == ' ') || (c == '\t')) || (nl && ((c == '\n') || (c == '\r'))))) { in.get(); c = in.peek(); } } // Return true if end of line (or file) inline bool skip_check_eol(std::istream &in) { skip_blank(in, false); if (!in) return false; int c = in.peek(); // Comments count as end of line if (c == '#') { in.get(); c = in.peek(); while (in && c != EOF && c != '\n') { in.get(); c = in.peek(); } return true; } return (c == EOF || c == '\n'); } // Skip past blank lines and comments inline void skip(std::istream &in) { skip_blank(in, true); while (in && (in.peek() == '#')) { // Skip comment line skip_check_eol(in); skip_blank(in, true); } } // Return true if at the end of a record (or file) inline bool skip_check_eor(std::istream &in) { skip(in); int c = in.peek(); return (c == EOF || c == '.'); } // Return true if at the end of file inline bool skip_check_eof(std::istream &in) { skip(in); int c = in.peek(); return (c == EOF); } std::ostream &operator<<(std::ostream &out, const ConfigArc &arc) { out << "arc: " << arc.sink << " " << arc.source << std::endl; return out; } std::istream &operator>>(std::istream &in, ConfigArc &arc) { in >> arc.sink; in >> arc.source; return in; } std::ostream &operator<<(std::ostream &out, const ConfigWord &cw) { out << "word: " << cw.name << " " << to_string(cw.value) << std::endl; return out; } std::istream &operator>>(std::istream &in, ConfigWord &cw) { in >> cw.name; in >> cw.value; return in; } std::ostream &operator<<(std::ostream &out, const ConfigEnum &cw) { out << "enum: " << cw.name << " " << cw.value << std::endl; return out; } std::istream &operator>>(std::istream &in, ConfigEnum &ce) { in >> ce.name; in >> ce.value; return in; } std::ostream &operator<<(std::ostream &out, const ConfigUnknown &cu) { out << "unknown: " << to_string(ConfigBit{cu.frame, cu.bit, false}) << std::endl; return out; } std::istream &operator>>(std::istream &in, ConfigUnknown &cu) { std::string s; in >> s; ConfigBit c = cbit_from_str(s); cu.frame = c.frame; cu.bit = c.bit; assert(!c.inv); return in; } std::ostream &operator<<(std::ostream &out, const TileConfig &tc) { for (const auto &arc : tc.carcs) out << arc; for (const auto &cword : tc.cwords) out << cword; for (const auto &cenum : tc.cenums) out << cenum; for (const auto &cunk : tc.cunknowns) out << cunk; return out; } std::istream &operator>>(std::istream &in, TileConfig &tc) { tc.carcs.clear(); tc.cwords.clear(); tc.cenums.clear(); while (!skip_check_eor(in)) { std::string type; in >> type; if (type == "arc:") { ConfigArc a; in >> a; tc.carcs.push_back(a); } else if (type == "word:") { ConfigWord w; in >> w; tc.cwords.push_back(w); } else if (type == "enum:") { ConfigEnum e; in >> e; tc.cenums.push_back(e); } else if (type == "unknown:") { ConfigUnknown u; in >> u; tc.cunknowns.push_back(u); } else { NPNR_ASSERT_FALSE_STR("unexpected token " + type + " while reading config text"); } } return in; } void TileConfig::add_arc(const std::string &sink, const std::string &source) { carcs.push_back({sink, source}); } void TileConfig::add_word(const std::string &name, const std::vector<bool> &value) { cwords.push_back({name, value}); } void TileConfig::add_enum(const std::string &name, const std::string &value) { cenums.push_back({name, value}); } void TileConfig::add_unknown(int frame, int bit) { cunknowns.push_back({frame, bit}); } std::string TileConfig::to_string() const { std::stringstream ss; ss << *this; return ss.str(); } TileConfig TileConfig::from_string(const std::string &str) { std::stringstream ss(str); TileConfig tc; ss >> tc; return tc; } bool TileConfig::empty() const { return carcs.empty() && cwords.empty() && cenums.empty() && cunknowns.empty(); } std::ostream &operator<<(std::ostream &out, const ChipConfig &cc) { out << ".device " << cc.chip_name << std::endl << std::endl; for (const auto &meta : cc.metadata) out << ".comment " << meta << std::endl; out << std::endl; for (const auto &tile : cc.tiles) { if (!tile.second.empty()) { out << ".tile " << tile.first << std::endl; out << tile.second; out << std::endl; } } for (const auto &bram : cc.bram_data) { out << ".bram_init " << bram.first << std::endl; std::ios_base::fmtflags f(out.flags()); for (size_t i = 0; i < bram.second.size(); i++) { out << std::setw(3) << std::setfill('0') << std::hex << bram.second.at(i); if (i % 8 == 7) out << std::endl; else out << " "; } out.flags(f); out << std::endl; } for (const auto &tg : cc.tilegroups) { out << ".tile_group"; for (const auto &tile : tg.tiles) { out << " " << tile; } out << std::endl; out << tg.config; out << std::endl; } return out; } std::istream &operator>>(std::istream &in, ChipConfig &cc) { while (!skip_check_eof(in)) { std::string verb; in >> verb; if (verb == ".device") { in >> cc.chip_name; } else if (verb == ".comment") { std::string line; getline(in, line); cc.metadata.push_back(line); } else if (verb == ".tile") { std::string tilename; in >> tilename; TileConfig tc; in >> tc; cc.tiles[tilename] = tc; } else if (verb == ".tile_group") { TileGroup tg; std::string line; getline(in, line); std::stringstream ss2(line); std::string tile; while (ss2) { ss2 >> tile; tg.tiles.push_back(tile); } in >> tg.config; cc.tilegroups.push_back(tg); } else if (verb == ".bram_init") { uint16_t bram; in >> bram; std::ios_base::fmtflags f(in.flags()); while (!skip_check_eor(in)) { uint16_t value; in >> std::hex >> value; cc.bram_data[bram].push_back(value); } in.flags(f); } else { log_error("unrecognised config entry %s\n", verb.c_str()); } } return in; } NEXTPNR_NAMESPACE_END
26.396011
119
0.538586
ZirconiumX
c8fa382a0dd07bbd6e34d683b502db485518fb7f
642
cpp
C++
test/std/numerics/rand/rand.device/entropy.pass.cpp
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
test/std/numerics/rand/rand.device/entropy.pass.cpp
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
test/std/numerics/rand/rand.device/entropy.pass.cpp
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <random> // class random_device; // double entropy() const; #include <random.hxx> #include <cassert.hxx> #include "test_macros.h" int main(int, char**) { std::random_device r; double e = r.entropy(); ((void)e); // Prevent unused warning return 0; }
22.928571
80
0.507788
K-Wu
c8fafe4555eef67cad25aaa687a6298e30a5d0d6
19,604
cpp
C++
oldies/bofiocmdchannel.cpp
onbings/bofstd
366ff7f7d8871d5fa5785d5690d90506a7714ecc
[ "MIT" ]
null
null
null
oldies/bofiocmdchannel.cpp
onbings/bofstd
366ff7f7d8871d5fa5785d5690d90506a7714ecc
[ "MIT" ]
1
2021-03-20T14:46:54.000Z
2021-03-20T14:47:10.000Z
oldies/bofiocmdchannel.cpp
onbings/bofstd
366ff7f7d8871d5fa5785d5690d90506a7714ecc
[ "MIT" ]
null
null
null
/* * Copyright (c) 2013-2023, Evs Broadcast Equipment All rights reserved. * * Author: Bernard HARMEL: b.harmel@evs.com * Web: www.evs.com * Revision: 1.0 * * Rem: Nothing * * History: * * V 1.00 Dec 19 2017 BHA : Initial release */ #include <bofstd/bofiocmdchannel.h> #include <bofstd/ibofioconnection.h> #include <bofstd/bofstring.h> #include <bofstd/bofstringformatter.h> #include <regex> BEGIN_BOF_NAMESPACE() const uint32_t DATA_FRAGMENT_SIZE = 0x400000; BofIoCmdChannel::BofIoCmdChannel(const IBOF_IO_CONNECTION_PARAM &_rIBofIoConnectionParam_X, BofIoConnectionManager *_pIoConnectionManager) : IBofIoConnection(_rIBofIoConnectionParam_X, _pIoConnectionManager), mpIoConnectionManager(_pIoConnectionManager), mpIoDataChannel(nullptr), mConnectTimeoutInMs_U32(1000), mIoCmdTimeoutInMs_U32(3000), mIoDataTimeoutInMs_U32(7000), mpBofStringCircularBuffer(nullptr), mConnectedAddress_S(""), mListenForConnection_B(false) { BOF_STRING_CIRCULAR_BUFFER_PARAM BofStringCircularBufferParam_X; BOF_ASSERT(mpIoConnectionManager != nullptr); BOF_CIRCULAR_BUFFER_PARAM BofCircularBufferParam_X; IBOF_IO_CONNECTION_PARAM DataIBofIoConnectionParam_X = _rIBofIoConnectionParam_X; DataIBofIoConnectionParam_X.Name_S = DataIBofIoConnectionParam_X.Name_S + "_Data"; mDataConnectToAddress_X.Reset(); mErrorCode_E = BOFERR_NOT_ENOUGH_RESOURCE; mpIoDataChannel = new BofIoDataChannel(*this, DataIBofIoConnectionParam_X, _pIoConnectionManager); BOF_ASSERT(mpIoDataChannel != nullptr); if (mpIoDataChannel) { mErrorCode_E = mpIoDataChannel->LastErrorCode(); if (mErrorCode_E == BOFERR_NO_ERROR) { mErrorCode_E = BOFERR_NOT_ENOUGH_RESOURCE; BofStringCircularBufferParam_X.Reset(); BofStringCircularBufferParam_X.MultiThreadAware_B = true; BofStringCircularBufferParam_X.BufferSizeInByte_U32 = 0x2000; BofStringCircularBufferParam_X.Overwrite_B = false; BofStringCircularBufferParam_X.pData_c = nullptr; BofStringCircularBufferParam_X.Blocking_B = true; mpBofStringCircularBuffer = new BofStringCircularBuffer(BofStringCircularBufferParam_X); if (mpBofStringCircularBuffer != nullptr) { mErrorCode_E = mpBofStringCircularBuffer->LastErrorCode(); } } } } BofIoCmdChannel::~BofIoCmdChannel() { Disconnect(DEFAULT_CMD_DATA_TIMEOUT); BOF_SAFE_DELETE(mpIoDataChannel); BOF_SAFE_DELETE(mpBofStringCircularBuffer); //Done in ~IBofIoConnection MarkConnectionAsDeleted(); } std::string &BofIoCmdChannel::ConnectedAddress() { return mConnectedAddress_S; } const BOF_SOCKET_ADDRESS &BofIoCmdChannel::DataConnectToAddress(bool &_rListenForConnection_B) { _rListenForConnection_B = mListenForConnection_B; return mDataConnectToAddress_X; } uint32_t BofIoCmdChannel::ConnectTimeoutInMs() { return mConnectTimeoutInMs_U32; } uint32_t BofIoCmdChannel::IoCmdTimeoutInMs() { return mIoCmdTimeoutInMs_U32; } uint32_t BofIoCmdChannel::IoDataTimeoutInMs() { return mIoDataTimeoutInMs_U32; } BOFERR BofIoCmdChannel::Connect(const BOF_IO_CHANNEL_PARAM &_rBofIoChannelParam_X, std::string &_rWelcomeMsg_S) { BOFERR Rts_E; uint32_t Start_U32; int32_t RemainingTimeout_S32; _rWelcomeMsg_S = ""; RemainingTimeout_S32 = _rBofIoChannelParam_X.ConnectTimeoutInMs_U32 + 1000; Start_U32 = Bof_GetMsTickCount(); Rts_E = IoConnectionManager()->Connect(this, _rBofIoChannelParam_X); if (Rts_E == BOFERR_NO_ERROR) { Rts_E = BOFERR_TIMEOUT; RemainingTimeout_S32 -= Bof_ElapsedMsTime(Start_U32); if (RemainingTimeout_S32 > 0) { Start_U32 = Bof_GetMsTickCount(); Rts_E = WaitForConnect(RemainingTimeout_S32); if (Rts_E == BOFERR_NO_ERROR) { Rts_E = BOFERR_TIMEOUT; RemainingTimeout_S32 -= Bof_ElapsedMsTime(Start_U32); if (RemainingTimeout_S32 > 0) { Rts_E = WaitForEndOfCommand(RemainingTimeout_S32, _rWelcomeMsg_S); } } } if (Rts_E == BOFERR_NO_ERROR) { mConnectedAddress_S = _rBofIoChannelParam_X.Address_S; } else { IoConnectionManager()->PushDisconnect("IoCmdChannel::Connect", UvConnection(), true); } } return Rts_E; } BOFERR BofIoCmdChannel::Disconnect(uint32_t _TimeoutInMs_U32) { BOFERR Rts_E; Rts_E = CloseDataChannel(_TimeoutInMs_U32); BOF_ASSERT(Rts_E == BOFERR_NO_ERROR); Rts_E = IoConnectionManager()->PushDisconnect("IoCmdChannel::Disconnect", UvConnection(), false); if (Rts_E == BOFERR_NO_ERROR) { mConnectedAddress_S = ""; } return Rts_E; } BOFERR BofIoCmdChannel::Login(uint32_t _TimeoutInMs_U32, const std::string &_rUser_S, const std::string &_rPassword_S) { BOFERR Rts_E; uint32_t ReplyCode_U32; std::string Reply_S; Rts_E = SendIoCmdAndWaitForReply(_TimeoutInMs_U32, Bof_Sprintf("USER %s\r\n", _rUser_S.c_str()), 331, Reply_S, ReplyCode_U32); if (Rts_E == BOFERR_NO_ERROR) { Rts_E = SendIoCmdAndWaitForReply(_TimeoutInMs_U32, Bof_Sprintf("PASS %s\r\n", _rPassword_S.c_str()), 230, Reply_S, ReplyCode_U32); if (Rts_E == BOFERR_NO_ERROR) { Rts_E = SendIoCmdAndWaitForReply(_TimeoutInMs_U32, "TYPE I\r\n", 200, Reply_S, ReplyCode_U32); } } return Rts_E; } BOFERR BofIoCmdChannel::SendIoCmd(uint32_t _TimeoutInMs_U32, const std::string &_rCmd_S) { BOFERR Rts_E = IsConnected() ? BOFERR_NO_ERROR : BOFERR_NOT_OPENED; if (Rts_E == BOFERR_NO_ERROR) { Rts_E = WriteData(_TimeoutInMs_U32, _rCmd_S, nullptr, true, false, false); } return Rts_E; } BOFERR BofIoCmdChannel::WaitForIoCmdReply(uint32_t _TimeoutInMs_U32, uint32_t _ExpectedReplyCode_U32, std::string &_rReply_S, uint32_t &_rReplyCode_U32) { //After QUIT cmd IsConnected is false BOFERR Rts_E = IsConnected() ? BOFERR_NO_ERROR : BOFERR_NOT_OPENED; BOFERR Rts_E = BOFERR_NO_ERROR; _rReplyCode_U32 = 0; _rReply_S = ""; if (Rts_E == BOFERR_NO_ERROR) { Rts_E = WaitForEndOfCommand(_TimeoutInMs_U32, _rReply_S); if (Rts_E == BOFERR_NO_ERROR) { _rReplyCode_U32 = BofIoCmdChannel::S_ReplyCodeFromString(_rReply_S); if (_rReply_S.size() >= 4) { _rReply_S = _rReply_S.substr(4); if (_rReplyCode_U32 != _ExpectedReplyCode_U32) { Rts_E = BOFERR_INVALID_VALUE; } } else { Rts_E = BOFERR_INVALID_ANSWER; } } } return Rts_E; } BOFERR BofIoCmdChannel::SendIoCmdAndWaitForReply(uint32_t _TimeoutInMs_U32, const std::string &_rCmd_S, uint32_t _ExpectedReplyCode_U32, std::string &_rReply_S, uint32_t &_rReplyCode_U32) { BOFERR Rts_E = IsConnected() ? BOFERR_NO_ERROR : BOFERR_NOT_OPENED; uint32_t Start_U32; int32_t RemainingTimeout_S32; _rReplyCode_U32 = 0; _rReply_S = ""; if (Rts_E == BOFERR_NO_ERROR) { RemainingTimeout_S32 = _TimeoutInMs_U32; Start_U32 = Bof_GetMsTickCount(); Rts_E = WriteData(_TimeoutInMs_U32, _rCmd_S, nullptr, true, false, false); if (Rts_E == BOFERR_NO_ERROR) { Rts_E = BOFERR_TIMEOUT; RemainingTimeout_S32 -= Bof_ElapsedMsTime(Start_U32); if (RemainingTimeout_S32 > 0) { Rts_E = WaitForIoCmdReply(RemainingTimeout_S32, _ExpectedReplyCode_U32, _rReply_S, _rReplyCode_U32); } } } return Rts_E; } BOFERR BofIoCmdChannel::SendIoCmdToCreateDataChannel(uint32_t _TimeoutInMs_U32, uint16_t _ActivePort_U16, const BOF_BUFFER &_rNotifyBuffer_X) { BOFERR Rts_E = BOFERR_RUNNING; uint32_t ReplyCode_U32; std::string Reply_S; BOF_IO_CHANNEL_PARAM IoChannelParam_X; IBOF_IO_CONNECTION_PARAM IBofIoConnectionParam_X; uint32_t Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32, PortHigh_U32, PortLow_U32; uint16_t Port_U16; BOF_ASSERT(mpIoConnectionManager != nullptr); BOF_ASSERT(mpIoDataChannel != nullptr); if (_ActivePort_U16) { mListenForConnection_B = false; mDataConnectToAddress_X = LocalAddress(); mDataConnectToAddress_X.Set(mDataConnectToAddress_X.IpV6_B, _ActivePort_U16); BOF_U32IPADDR_TO_U8IPADDR(mDataConnectToAddress_X.IpV4Address_X.sin_addr.s_addr, Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32); Port_U16 = _ActivePort_U16; PortHigh_U32 = static_cast<uint8_t>(Port_U16 >> 8); PortLow_U32 = static_cast<uint8_t>(Port_U16); Rts_E = SendIoCmdAndWaitForReply(_TimeoutInMs_U32, Bof_Sprintf("PORT %d,%d,%d,%d,%d,%d\r\n", Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32, PortHigh_U32, PortLow_U32), 200, Reply_S, ReplyCode_U32); if (Rts_E == BOFERR_NO_ERROR) { } } else { Rts_E = SendIoCmdAndWaitForReply(_TimeoutInMs_U32, Bof_Sprintf("PASV\r\n"), 227, Reply_S, ReplyCode_U32); if (Rts_E == BOFERR_NO_ERROR) { static std::regex S_RegExPasv("^.*?(\\d+),(\\d+),(\\d+),(\\d+),(\\d+),(\\d+).*$"); std::cmatch PasvMatch; Rts_E = BOFERR_INVALID_ANSWER; /* *Online regex builder/test: https://regex101.com/ If [the regex search is] successful, it is not empty and contains a series of sub_match objects: the first sub_match element corresponds to the entire match, and, if the regex expression contained sub-expressions to be matched (i.e., parentheses-delimited groups), their corresponding sub-matches are stored as successive sub_match elements in the match_results object. whatever whatever something abc something abc by default, regexes are greedy, meaning it will match as much as possible. Therefore /^.*abc/ would match "whatever whatever something abc something ". Adding the non-greedy quantifier ? makes the regex only match "whatever whatever something ". */ //Match means all the string-> use ^ for begin and $ for end if ((std::regex_match(Reply_S.c_str(), PasvMatch, S_RegExPasv)) && (PasvMatch.size() == 1 + 6)) { Rts_E = BOFERR_NO_ERROR; Ip1_U32 = static_cast<uint32_t>(std::stoi(PasvMatch[1].str())); Ip2_U32 = static_cast<uint32_t>(std::stoi(PasvMatch[2].str())); Ip3_U32 = static_cast<uint32_t>(std::stoi(PasvMatch[3].str())); Ip4_U32 = static_cast<uint32_t>(std::stoi(PasvMatch[4].str())); PortHigh_U32 = static_cast<uint8_t>(std::stoi(PasvMatch[5].str())); PortLow_U32 = static_cast<uint8_t>(std::stoi(PasvMatch[6].str())); Port_U16 = static_cast<uint16_t>((PortHigh_U32 << 8) + PortLow_U32); mListenForConnection_B = true; mDataConnectToAddress_X.Set(false, BOF_SOCK_TYPE::BOF_SOCK_TCP, BOF_PROTOCOL_TYPE::BOF_PROTOCOL_TCP, Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32, Port_U16); } } } if (Rts_E == BOFERR_NO_ERROR) { //Make this on next io cmd 'list/stor/retr) Rts_E = mpIoDataChannel->OpenDataChannel(_TimeoutInMs_U32, mListenForConnection_B, mDataConnectToAddress_X, 0x100000, 0x100000); if (Rts_E == BOFERR_NO_ERROR) { } } return Rts_E; } BOFERR BofIoCmdChannel::OpenDataChannel(uint32_t _TimeoutInMs_U32, bool _ListenForConnection_B, BOF_SOCKET_ADDRESS &_rConnectToAddress_X, uint32_t _RcvBufferSize_U32, uint32_t _SndBufferSize_U32) { BOFERR Rts_E = BOFERR_NOT_RUNNING; BOF_ASSERT(mpIoDataChannel != nullptr); Rts_E = mpIoDataChannel->OpenDataChannel(_TimeoutInMs_U32, _ListenForConnection_B, _rConnectToAddress_X, _RcvBufferSize_U32, _SndBufferSize_U32); return Rts_E; } BOFERR BofIoCmdChannel::CloseDataChannel(uint32_t _TimeoutInMs_U32) { BOFERR Rts_E = BOFERR_NOT_RUNNING; BOF_ASSERT(mpIoDataChannel != nullptr); Rts_E = mpIoDataChannel->CloseDataChannel(_TimeoutInMs_U32); return Rts_E; } uint32_t BofIoCmdChannel::S_ReplyCodeFromString(const std::string &_rReply_S) { uint32_t Rts_U32 = 0; if (_rReply_S.size() >= 4) { try { Rts_U32 = std::stoi(_rReply_S.substr(0, 3)); } catch (const std::exception &) { // e.what() Rts_U32 = 0; } } return Rts_U32; } BOFERR BofIoCmdChannel::WaitForEndOfCommand(uint32_t _TimeoutInMs_U32, std::string &_rReply_S) { BOFERR Rts_E; uint32_t Nb_U32; char pData_c[0x1000]; Nb_U32 = sizeof(pData_c); Rts_E = mpBofStringCircularBuffer->PopString(&Nb_U32, pData_c, _TimeoutInMs_U32); if (Rts_E == BOFERR_NO_ERROR) { BOF_ASSERT(Nb_U32 >= 4); //226 \r\n has been remove in push op _rReply_S = std::string(pData_c, pData_c + Nb_U32); } return Rts_E; } /* BOFERR BofIoCmdChannel::WaitForEndOfTransfert(uint32_t _TimeoutInMs_U32, std::string &_rReply_S) { BOFERR Rts_E; // BOF_ASSERT(mRemainingIoSize_S64 != 0); _rReply_S = ""; Rts_E = WaitForEndOfIo(_TimeoutInMs_U32); if (Rts_E == BOFERR_NO_ERROR) { } return Rts_E; } */ BOFERR BofIoCmdChannel::V_DataRead(uint32_t _Nb_U32, uint8_t *_pBuffer_U8) { BOFERR Rts_E = BOFERR_NO_ERROR; uint32_t Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32, PortHigh_U32, PortLow_U32; uint16_t Port_U16; //https://regex101.com/ //^.*?(\d+),(\d+),(\d+),(\d+),(\d+),(\d+).*$ //Port command successful (12,34,56,78,90,13). static std::regex S_RegExPasvPort("^.*?(\\d+),(\\d+),(\\d+),(\\d+),(\\d+),(\\d+).*$"); std::cmatch PasvPortMatch; BOF_IO_CHANNEL_PARAM IoChannelParam_X; IBOF_IO_CONNECTION_PARAM IBofIoConnectionParam_X; BOF_IO_DELEGATE_CMD IoDelegateCmd_X; BOF_ASSERT(_Nb_U32 >= 2); BOF_ASSERT(_pBuffer_U8[_Nb_U32 - 2] == '\r'); BOF_ASSERT(_pBuffer_U8[_Nb_U32 - 1] == '\n'); std::string Cmd_S(_pBuffer_U8, _pBuffer_U8 + _Nb_U32 - 2); std::string Reply_S; //We can stay here for low time as we are in the libuv callback context //ReplyCode_U32 = IoCmdChannel::S_ReplyCodeFromString(Cmd_S); //if (ReplyCode_U32==0) //It is a command if (ServerSession()) { std::vector<std::string> CmdArgCollection = Bof_StringSplit(Cmd_S, " "); if (CmdArgCollection[0] == "USER") { Reply_S = Bof_Sprintf("331 User name okay, need password.\r\n"); } else if (CmdArgCollection[0] == "PASS") { Reply_S = Bof_Sprintf("230 User logged in, proceed.\r\n"); } else if (CmdArgCollection[0] == "TYPE") { Reply_S = Bof_Sprintf("200 Type set to \"%s\"\r\n", CmdArgCollection[1].c_str()); } else if (CmdArgCollection[0] == "CWD") { Reply_S = Bof_Sprintf("200 Change to '%s'\n", CmdArgCollection[1].c_str()); } else if (CmdArgCollection[0] == "PWD") { Reply_S = Bof_Sprintf("257 Remote directory now \"%s\"\r\n", "/tmp"); } else if (CmdArgCollection[0] == "PORT") { Rts_E = BOFERR_INVALID_ANSWER; if ((std::regex_match(CmdArgCollection[1].c_str(), PasvPortMatch, S_RegExPasvPort)) && (PasvPortMatch.size() == 1 + 6)) { Rts_E = BOFERR_NO_ERROR; Ip1_U32 = static_cast<uint32_t>(std::stoi(PasvPortMatch[1].str())); Ip2_U32 = static_cast<uint32_t>(std::stoi(PasvPortMatch[2].str())); Ip3_U32 = static_cast<uint32_t>(std::stoi(PasvPortMatch[3].str())); Ip4_U32 = static_cast<uint32_t>(std::stoi(PasvPortMatch[4].str())); PortHigh_U32 = static_cast<uint8_t>(std::stoi(PasvPortMatch[5].str())); PortLow_U32 = static_cast<uint8_t>(std::stoi(PasvPortMatch[6].str())); Port_U16 = static_cast<uint16_t>((PortHigh_U32 << 8) + PortLow_U32); mListenForConnection_B = true; mDataConnectToAddress_X.Set(false, BOF_SOCK_TYPE::BOF_SOCK_TCP, BOF_PROTOCOL_TYPE::BOF_PROTOCOL_TCP, Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32, Port_U16); Reply_S = Bof_Sprintf("200 Port command successful (%d: %d.%d.%d.%d).\r\n", Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32, PortHigh_U32, PortLow_U32); BOF_ASSERT(mpIoDataChannel != nullptr); IoDelegateCmd_X.IoCmd_E = BOF_IO_CMD::IO_CMD_OPEN; IoDelegateCmd_X.ListenForConnection_B = mListenForConnection_B; Rts_E = mpIoDataChannel->PushIoDelegateCmd(IoDataTimeoutInMs(), IoDelegateCmd_X); BOF_ASSERT(Rts_E == BOFERR_NO_ERROR); } } else if (CmdArgCollection[0] == "PASV") { Rts_E = BOFERR_NO_ERROR; Port_U16 = static_cast<uint16_t>(Bof_Random(false, 49100, 49200)); PortHigh_U32 = static_cast<uint8_t>(Port_U16 >> 8); PortLow_U32 = static_cast<uint8_t>(Port_U16); mListenForConnection_B = false; mDataConnectToAddress_X = LocalAddress(); mDataConnectToAddress_X.Set(mDataConnectToAddress_X.IpV6_B, Port_U16); BOF_U32IPADDR_TO_U8IPADDR(mDataConnectToAddress_X.IpV4Address_X.sin_addr.s_addr, Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32); mDataConnectToAddress_X.Set(false, BOF_SOCK_TYPE::BOF_SOCK_TCP, BOF_PROTOCOL_TYPE::BOF_PROTOCOL_TCP, Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32, Port_U16); Reply_S = Bof_Sprintf("227 Entering Passive Mode (%d,%d,%d,%d,%d,%d).\r\n", Ip1_U32, Ip2_U32, Ip3_U32, Ip4_U32, PortHigh_U32, PortLow_U32); BOF_ASSERT(mpIoDataChannel != nullptr); IoDelegateCmd_X.IoCmd_E = BOF_IO_CMD::IO_CMD_OPEN; IoDelegateCmd_X.ListenForConnection_B = mListenForConnection_B; Rts_E = mpIoDataChannel->PushIoDelegateCmd(IoDataTimeoutInMs(), IoDelegateCmd_X); BOF_ASSERT(Rts_E == BOFERR_NO_ERROR); } else if (CmdArgCollection[0] == "QUIT") { BOF_ASSERT(mpIoDataChannel != nullptr); IoDelegateCmd_X.IoCmd_E = BOF_IO_CMD::IO_CMD_CLOSE; Rts_E = mpIoDataChannel->PushIoDelegateCmd(IoDataTimeoutInMs(), IoDelegateCmd_X); BOF_ASSERT(Rts_E == BOFERR_NO_ERROR); } else if (CmdArgCollection[0] == "ABOR") { BOF_ASSERT(mpIoDataChannel != nullptr); IoDelegateCmd_X.IoCmd_E = BOF_IO_CMD::IO_CMD_ABORT; Rts_E = mpIoDataChannel->PushIoDelegateCmd(IoDataTimeoutInMs(), IoDelegateCmd_X); BOF_ASSERT(Rts_E == BOFERR_NO_ERROR); } else if (CmdArgCollection[0] == "LIST") { BOF_ASSERT(mpIoDataChannel != nullptr); IoDelegateCmd_X.IoCmd_E = BOF_IO_CMD::IO_CMD_LIST; Rts_E = mpIoDataChannel->PushIoDelegateCmd(IoDataTimeoutInMs(), IoDelegateCmd_X); BOF_ASSERT(Rts_E == BOFERR_NO_ERROR); } else if (CmdArgCollection[0] == "STOR") { BOF_ASSERT(mpIoDataChannel != nullptr); IoDelegateCmd_X.IoCmd_E = BOF_IO_CMD::IO_CMD_STOR; Rts_E = mpIoDataChannel->PushIoDelegateCmd(IoDataTimeoutInMs(), IoDelegateCmd_X); BOF_ASSERT(Rts_E == BOFERR_NO_ERROR); } else if (CmdArgCollection[0] == "RETR") { BOF_ASSERT(mpIoDataChannel != nullptr); IoDelegateCmd_X.IoCmd_E = BOF_IO_CMD::IO_CMD_RETR; Rts_E = mpIoDataChannel->PushIoDelegateCmd(IoDataTimeoutInMs(), IoDelegateCmd_X); BOF_ASSERT(Rts_E == BOFERR_NO_ERROR); } if (Reply_S != "") { Rts_E = WriteData(IoCmdTimeoutInMs(), Reply_S, nullptr, true, false, true); if (Rts_E == BOFERR_NO_ERROR) { } } } else { BOF_ASSERT(_Nb_U32 >= 6); //226 \r\n BOF_ASSERT(_pBuffer_U8[_Nb_U32 - 2] == '\r'); BOF_ASSERT(_pBuffer_U8[_Nb_U32 - 1] == '\n'); Rts_E = mpBofStringCircularBuffer->PushBinary(_Nb_U32 - 2, reinterpret_cast<const char *>(_pBuffer_U8), IoCmdTimeoutInMs()); } return Rts_E; } BOFERR BofIoCmdChannel::V_DataWritten(BOFERR _Sts_E, void *_pUserArg) { //LOGGER_INFORMATION(DBG_INIT, 0, "V_DataWritten Sts %s UserArg %p",Bof_ErrorCode(_Sts_E), _pUserArg); return BOFERR_NO_ERROR; } BOFERR BofIoCmdChannel::V_RemoteIoClosed() { // LOGGER_INFORMATION(DBG_INIT, 0, "V_RemoteIoClosed"); return BOFERR_NO_ERROR; } BOFERR BofIoCmdChannel::V_Connected() { //printf("V_Connected %s\n",Name().c_str()); BOFERR Rts_E; Rts_E = ServerSession() ? WriteData(IoCmdTimeoutInMs(), "220 EVS FTP Server (v) 09.08 (mc) 1606 (d) 26/05/64 (a) B.Harmel [B: 2/8 MB L:127.0.0.1:xxxx R:127.0.0.1:yyyy]\r\n", nullptr, true, false, true) : BOFERR_NO_ERROR; return Rts_E; } BOFERR BofIoCmdChannel::V_ConnectFailed(BOFERR _Sts_E) { // LOGGER_INFORMATION(DBG_INIT, 0, "V_ConnectFailed Sts %s", Bof_ErrorCode(_Sts_E)); return BOFERR_NO_ERROR; } BOFERR BofIoCmdChannel::V_Disconnected() { BOFERR Rts_E; Rts_E = Disconnect(DEFAULT_CMD_DATA_TIMEOUT); return Rts_E; } END_BOF_NAMESPACE()
34.636042
197
0.721536
onbings
c8fb9d106e32da5effdfa87891c19660c076a8a1
25,312
cpp
C++
llvm/lib/Transforms/Scalar/ADCE.cpp
kubamracek/llvm-project
f7ff1869cdd487d4baaf009380901e5469d8344d
[ "Apache-2.0" ]
null
null
null
llvm/lib/Transforms/Scalar/ADCE.cpp
kubamracek/llvm-project
f7ff1869cdd487d4baaf009380901e5469d8344d
[ "Apache-2.0" ]
null
null
null
llvm/lib/Transforms/Scalar/ADCE.cpp
kubamracek/llvm-project
f7ff1869cdd487d4baaf009380901e5469d8344d
[ "Apache-2.0" ]
null
null
null
//===- ADCE.cpp - Code to perform dead code elimination -------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the Aggressive Dead Code Elimination pass. This pass // optimistically assumes that all instructions are dead until proven otherwise, // allowing it to eliminate dead computations that other DCE passes do not // catch, particularly involving loop computations. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/ADCE.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/GraphTraits.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/DomTreeUpdater.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/IteratedDominanceFrontier.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/PassManager.h" #include "llvm/IR/Use.h" #include "llvm/IR/Value.h" #include "llvm/InitializePasses.h" #include "llvm/Pass.h" #include "llvm/ProfileData/InstrProf.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Scalar.h" #include <cassert> #include <cstddef> #include <utility> using namespace llvm; #define DEBUG_TYPE "adce" STATISTIC(NumRemoved, "Number of instructions removed"); STATISTIC(NumBranchesRemoved, "Number of branch instructions removed"); // This is a temporary option until we change the interface to this pass based // on optimization level. static cl::opt<bool> RemoveControlFlowFlag("adce-remove-control-flow", cl::init(true), cl::Hidden); // This option enables removing of may-be-infinite loops which have no other // effect. static cl::opt<bool> RemoveLoops("adce-remove-loops", cl::init(false), cl::Hidden); namespace { /// Information about Instructions struct InstInfoType { /// True if the associated instruction is live. bool Live = false; /// Quick access to information for block containing associated Instruction. struct BlockInfoType *Block = nullptr; }; /// Information about basic blocks relevant to dead code elimination. struct BlockInfoType { /// True when this block contains a live instructions. bool Live = false; /// True when this block ends in an unconditional branch. bool UnconditionalBranch = false; /// True when this block is known to have live PHI nodes. bool HasLivePhiNodes = false; /// Control dependence sources need to be live for this block. bool CFLive = false; /// Quick access to the LiveInfo for the terminator, /// holds the value &InstInfo[Terminator] InstInfoType *TerminatorLiveInfo = nullptr; /// Corresponding BasicBlock. BasicBlock *BB = nullptr; /// Cache of BB->getTerminator(). Instruction *Terminator = nullptr; /// Post-order numbering of reverse control flow graph. unsigned PostOrder; bool terminatorIsLive() const { return TerminatorLiveInfo->Live; } }; class AggressiveDeadCodeElimination { Function &F; // ADCE does not use DominatorTree per se, but it updates it to preserve the // analysis. DominatorTree *DT; PostDominatorTree &PDT; /// Mapping of blocks to associated information, an element in BlockInfoVec. /// Use MapVector to get deterministic iteration order. MapVector<BasicBlock *, BlockInfoType> BlockInfo; bool isLive(BasicBlock *BB) { return BlockInfo[BB].Live; } /// Mapping of instructions to associated information. DenseMap<Instruction *, InstInfoType> InstInfo; bool isLive(Instruction *I) { return InstInfo[I].Live; } /// Instructions known to be live where we need to mark /// reaching definitions as live. SmallVector<Instruction *, 128> Worklist; /// Debug info scopes around a live instruction. SmallPtrSet<const Metadata *, 32> AliveScopes; /// Set of blocks with not known to have live terminators. SmallSetVector<BasicBlock *, 16> BlocksWithDeadTerminators; /// The set of blocks which we have determined whose control /// dependence sources must be live and which have not had /// those dependences analyzed. SmallPtrSet<BasicBlock *, 16> NewLiveBlocks; /// Set up auxiliary data structures for Instructions and BasicBlocks and /// initialize the Worklist to the set of must-be-live Instruscions. void initialize(); /// Return true for operations which are always treated as live. bool isAlwaysLive(Instruction &I); /// Return true for instrumentation instructions for value profiling. bool isInstrumentsConstant(Instruction &I); /// Propagate liveness to reaching definitions. void markLiveInstructions(); /// Mark an instruction as live. void markLive(Instruction *I); /// Mark a block as live. void markLive(BlockInfoType &BB); void markLive(BasicBlock *BB) { markLive(BlockInfo[BB]); } /// Mark terminators of control predecessors of a PHI node live. void markPhiLive(PHINode *PN); /// Record the Debug Scopes which surround live debug information. void collectLiveScopes(const DILocalScope &LS); void collectLiveScopes(const DILocation &DL); /// Analyze dead branches to find those whose branches are the sources /// of control dependences impacting a live block. Those branches are /// marked live. void markLiveBranchesFromControlDependences(); /// Remove instructions not marked live, return if any instruction was /// removed. bool removeDeadInstructions(); /// Identify connected sections of the control flow graph which have /// dead terminators and rewrite the control flow graph to remove them. bool updateDeadRegions(); /// Set the BlockInfo::PostOrder field based on a post-order /// numbering of the reverse control flow graph. void computeReversePostOrder(); /// Make the terminator of this block an unconditional branch to \p Target. void makeUnconditional(BasicBlock *BB, BasicBlock *Target); public: AggressiveDeadCodeElimination(Function &F, DominatorTree *DT, PostDominatorTree &PDT) : F(F), DT(DT), PDT(PDT) {} bool performDeadCodeElimination(); }; } // end anonymous namespace bool AggressiveDeadCodeElimination::performDeadCodeElimination() { initialize(); markLiveInstructions(); return removeDeadInstructions(); } static bool isUnconditionalBranch(Instruction *Term) { auto *BR = dyn_cast<BranchInst>(Term); return BR && BR->isUnconditional(); } void AggressiveDeadCodeElimination::initialize() { auto NumBlocks = F.size(); // We will have an entry in the map for each block so we grow the // structure to twice that size to keep the load factor low in the hash table. BlockInfo.reserve(NumBlocks); size_t NumInsts = 0; // Iterate over blocks and initialize BlockInfoVec entries, count // instructions to size the InstInfo hash table. for (auto &BB : F) { NumInsts += BB.size(); auto &Info = BlockInfo[&BB]; Info.BB = &BB; Info.Terminator = BB.getTerminator(); Info.UnconditionalBranch = isUnconditionalBranch(Info.Terminator); } // Initialize instruction map and set pointers to block info. InstInfo.reserve(NumInsts); for (auto &BBInfo : BlockInfo) for (Instruction &I : *BBInfo.second.BB) InstInfo[&I].Block = &BBInfo.second; // Since BlockInfoVec holds pointers into InstInfo and vice-versa, we may not // add any more elements to either after this point. for (auto &BBInfo : BlockInfo) BBInfo.second.TerminatorLiveInfo = &InstInfo[BBInfo.second.Terminator]; // Collect the set of "root" instructions that are known live. for (Instruction &I : instructions(F)) if (isAlwaysLive(I)) markLive(&I); if (!RemoveControlFlowFlag) return; if (!RemoveLoops) { // This stores state for the depth-first iterator. In addition // to recording which nodes have been visited we also record whether // a node is currently on the "stack" of active ancestors of the current // node. using StatusMap = DenseMap<BasicBlock *, bool>; class DFState : public StatusMap { public: std::pair<StatusMap::iterator, bool> insert(BasicBlock *BB) { return StatusMap::insert(std::make_pair(BB, true)); } // Invoked after we have visited all children of a node. void completed(BasicBlock *BB) { (*this)[BB] = false; } // Return true if \p BB is currently on the active stack // of ancestors. bool onStack(BasicBlock *BB) { auto Iter = find(BB); return Iter != end() && Iter->second; } } State; State.reserve(F.size()); // Iterate over blocks in depth-first pre-order and // treat all edges to a block already seen as loop back edges // and mark the branch live it if there is a back edge. for (auto *BB: depth_first_ext(&F.getEntryBlock(), State)) { Instruction *Term = BB->getTerminator(); if (isLive(Term)) continue; for (auto *Succ : successors(BB)) if (State.onStack(Succ)) { // back edge.... markLive(Term); break; } } } // Mark blocks live if there is no path from the block to a // return of the function. // We do this by seeing which of the postdomtree root children exit the // program, and for all others, mark the subtree live. for (auto &PDTChild : children<DomTreeNode *>(PDT.getRootNode())) { auto *BB = PDTChild->getBlock(); auto &Info = BlockInfo[BB]; // Real function return if (isa<ReturnInst>(Info.Terminator)) { LLVM_DEBUG(dbgs() << "post-dom root child is a return: " << BB->getName() << '\n';); continue; } // This child is something else, like an infinite loop. for (auto DFNode : depth_first(PDTChild)) markLive(BlockInfo[DFNode->getBlock()].Terminator); } // Treat the entry block as always live auto *BB = &F.getEntryBlock(); auto &EntryInfo = BlockInfo[BB]; EntryInfo.Live = true; if (EntryInfo.UnconditionalBranch) markLive(EntryInfo.Terminator); // Build initial collection of blocks with dead terminators for (auto &BBInfo : BlockInfo) if (!BBInfo.second.terminatorIsLive()) BlocksWithDeadTerminators.insert(BBInfo.second.BB); } bool AggressiveDeadCodeElimination::isAlwaysLive(Instruction &I) { // TODO -- use llvm::isInstructionTriviallyDead if (I.isEHPad() || I.mayHaveSideEffects() || !I.willReturn()) { // Skip any value profile instrumentation calls if they are // instrumenting constants. if (isInstrumentsConstant(I)) return false; return true; } if (!I.isTerminator()) return false; if (RemoveControlFlowFlag && (isa<BranchInst>(I) || isa<SwitchInst>(I))) return false; return true; } // Check if this instruction is a runtime call for value profiling and // if it's instrumenting a constant. bool AggressiveDeadCodeElimination::isInstrumentsConstant(Instruction &I) { // TODO -- move this test into llvm::isInstructionTriviallyDead if (CallInst *CI = dyn_cast<CallInst>(&I)) if (Function *Callee = CI->getCalledFunction()) if (Callee->getName().equals(getInstrProfValueProfFuncName())) if (isa<Constant>(CI->getArgOperand(0))) return true; return false; } void AggressiveDeadCodeElimination::markLiveInstructions() { // Propagate liveness backwards to operands. do { // Worklist holds newly discovered live instructions // where we need to mark the inputs as live. while (!Worklist.empty()) { Instruction *LiveInst = Worklist.pop_back_val(); LLVM_DEBUG(dbgs() << "work live: "; LiveInst->dump();); for (Use &OI : LiveInst->operands()) if (Instruction *Inst = dyn_cast<Instruction>(OI)) markLive(Inst); if (auto *PN = dyn_cast<PHINode>(LiveInst)) markPhiLive(PN); } // After data flow liveness has been identified, examine which branch // decisions are required to determine live instructions are executed. markLiveBranchesFromControlDependences(); } while (!Worklist.empty()); } void AggressiveDeadCodeElimination::markLive(Instruction *I) { auto &Info = InstInfo[I]; if (Info.Live) return; LLVM_DEBUG(dbgs() << "mark live: "; I->dump()); Info.Live = true; Worklist.push_back(I); // Collect the live debug info scopes attached to this instruction. if (const DILocation *DL = I->getDebugLoc()) collectLiveScopes(*DL); // Mark the containing block live auto &BBInfo = *Info.Block; if (BBInfo.Terminator == I) { BlocksWithDeadTerminators.remove(BBInfo.BB); // For live terminators, mark destination blocks // live to preserve this control flow edges. if (!BBInfo.UnconditionalBranch) for (auto *BB : successors(I->getParent())) markLive(BB); } markLive(BBInfo); } void AggressiveDeadCodeElimination::markLive(BlockInfoType &BBInfo) { if (BBInfo.Live) return; LLVM_DEBUG(dbgs() << "mark block live: " << BBInfo.BB->getName() << '\n'); BBInfo.Live = true; if (!BBInfo.CFLive) { BBInfo.CFLive = true; NewLiveBlocks.insert(BBInfo.BB); } // Mark unconditional branches at the end of live // blocks as live since there is no work to do for them later if (BBInfo.UnconditionalBranch) markLive(BBInfo.Terminator); } void AggressiveDeadCodeElimination::collectLiveScopes(const DILocalScope &LS) { if (!AliveScopes.insert(&LS).second) return; if (isa<DISubprogram>(LS)) return; // Tail-recurse through the scope chain. collectLiveScopes(cast<DILocalScope>(*LS.getScope())); } void AggressiveDeadCodeElimination::collectLiveScopes(const DILocation &DL) { // Even though DILocations are not scopes, shove them into AliveScopes so we // don't revisit them. if (!AliveScopes.insert(&DL).second) return; // Collect live scopes from the scope chain. collectLiveScopes(*DL.getScope()); // Tail-recurse through the inlined-at chain. if (const DILocation *IA = DL.getInlinedAt()) collectLiveScopes(*IA); } void AggressiveDeadCodeElimination::markPhiLive(PHINode *PN) { auto &Info = BlockInfo[PN->getParent()]; // Only need to check this once per block. if (Info.HasLivePhiNodes) return; Info.HasLivePhiNodes = true; // If a predecessor block is not live, mark it as control-flow live // which will trigger marking live branches upon which // that block is control dependent. for (auto *PredBB : predecessors(Info.BB)) { auto &Info = BlockInfo[PredBB]; if (!Info.CFLive) { Info.CFLive = true; NewLiveBlocks.insert(PredBB); } } } void AggressiveDeadCodeElimination::markLiveBranchesFromControlDependences() { if (BlocksWithDeadTerminators.empty()) return; LLVM_DEBUG({ dbgs() << "new live blocks:\n"; for (auto *BB : NewLiveBlocks) dbgs() << "\t" << BB->getName() << '\n'; dbgs() << "dead terminator blocks:\n"; for (auto *BB : BlocksWithDeadTerminators) dbgs() << "\t" << BB->getName() << '\n'; }); // The dominance frontier of a live block X in the reverse // control graph is the set of blocks upon which X is control // dependent. The following sequence computes the set of blocks // which currently have dead terminators that are control // dependence sources of a block which is in NewLiveBlocks. const SmallPtrSet<BasicBlock *, 16> BWDT{ BlocksWithDeadTerminators.begin(), BlocksWithDeadTerminators.end() }; SmallVector<BasicBlock *, 32> IDFBlocks; ReverseIDFCalculator IDFs(PDT); IDFs.setDefiningBlocks(NewLiveBlocks); IDFs.setLiveInBlocks(BWDT); IDFs.calculate(IDFBlocks); NewLiveBlocks.clear(); // Dead terminators which control live blocks are now marked live. for (auto *BB : IDFBlocks) { LLVM_DEBUG(dbgs() << "live control in: " << BB->getName() << '\n'); markLive(BB->getTerminator()); } } //===----------------------------------------------------------------------===// // // Routines to update the CFG and SSA information before removing dead code. // //===----------------------------------------------------------------------===// bool AggressiveDeadCodeElimination::removeDeadInstructions() { // Updates control and dataflow around dead blocks bool RegionsUpdated = updateDeadRegions(); LLVM_DEBUG({ for (Instruction &I : instructions(F)) { // Check if the instruction is alive. if (isLive(&I)) continue; if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I)) { // Check if the scope of this variable location is alive. if (AliveScopes.count(DII->getDebugLoc()->getScope())) continue; // If intrinsic is pointing at a live SSA value, there may be an // earlier optimization bug: if we know the location of the variable, // why isn't the scope of the location alive? if (Value *V = DII->getVariableLocationOp(0)) if (Instruction *II = dyn_cast<Instruction>(V)) if (isLive(II)) dbgs() << "Dropping debug info for " << *DII << "\n"; } } }); // The inverse of the live set is the dead set. These are those instructions // that have no side effects and do not influence the control flow or return // value of the function, and may therefore be deleted safely. // NOTE: We reuse the Worklist vector here for memory efficiency. for (Instruction &I : instructions(F)) { // Check if the instruction is alive. if (isLive(&I)) continue; if (auto *DII = dyn_cast<DbgInfoIntrinsic>(&I)) { // Check if the scope of this variable location is alive. if (AliveScopes.count(DII->getDebugLoc()->getScope())) continue; // Fallthrough and drop the intrinsic. } // Prepare to delete. Worklist.push_back(&I); I.dropAllReferences(); } for (Instruction *&I : Worklist) { ++NumRemoved; I->eraseFromParent(); } return !Worklist.empty() || RegionsUpdated; } // A dead region is the set of dead blocks with a common live post-dominator. bool AggressiveDeadCodeElimination::updateDeadRegions() { LLVM_DEBUG({ dbgs() << "final dead terminator blocks: " << '\n'; for (auto *BB : BlocksWithDeadTerminators) dbgs() << '\t' << BB->getName() << (BlockInfo[BB].Live ? " LIVE\n" : "\n"); }); // Don't compute the post ordering unless we needed it. bool HavePostOrder = false; bool Changed = false; for (auto *BB : BlocksWithDeadTerminators) { auto &Info = BlockInfo[BB]; if (Info.UnconditionalBranch) { InstInfo[Info.Terminator].Live = true; continue; } if (!HavePostOrder) { computeReversePostOrder(); HavePostOrder = true; } // Add an unconditional branch to the successor closest to the // end of the function which insures a path to the exit for each // live edge. BlockInfoType *PreferredSucc = nullptr; for (auto *Succ : successors(BB)) { auto *Info = &BlockInfo[Succ]; if (!PreferredSucc || PreferredSucc->PostOrder < Info->PostOrder) PreferredSucc = Info; } assert((PreferredSucc && PreferredSucc->PostOrder > 0) && "Failed to find safe successor for dead branch"); // Collect removed successors to update the (Post)DominatorTrees. SmallPtrSet<BasicBlock *, 4> RemovedSuccessors; bool First = true; for (auto *Succ : successors(BB)) { if (!First || Succ != PreferredSucc->BB) { Succ->removePredecessor(BB); RemovedSuccessors.insert(Succ); } else First = false; } makeUnconditional(BB, PreferredSucc->BB); // Inform the dominators about the deleted CFG edges. SmallVector<DominatorTree::UpdateType, 4> DeletedEdges; for (auto *Succ : RemovedSuccessors) { // It might have happened that the same successor appeared multiple times // and the CFG edge wasn't really removed. if (Succ != PreferredSucc->BB) { LLVM_DEBUG(dbgs() << "ADCE: (Post)DomTree edge enqueued for deletion" << BB->getName() << " -> " << Succ->getName() << "\n"); DeletedEdges.push_back({DominatorTree::Delete, BB, Succ}); } } DomTreeUpdater(DT, &PDT, DomTreeUpdater::UpdateStrategy::Eager) .applyUpdates(DeletedEdges); NumBranchesRemoved += 1; Changed = true; } return Changed; } // reverse top-sort order void AggressiveDeadCodeElimination::computeReversePostOrder() { // This provides a post-order numbering of the reverse control flow graph // Note that it is incomplete in the presence of infinite loops but we don't // need numbers blocks which don't reach the end of the functions since // all branches in those blocks are forced live. // For each block without successors, extend the DFS from the block // backward through the graph SmallPtrSet<BasicBlock*, 16> Visited; unsigned PostOrder = 0; for (auto &BB : F) { if (!succ_empty(&BB)) continue; for (BasicBlock *Block : inverse_post_order_ext(&BB,Visited)) BlockInfo[Block].PostOrder = PostOrder++; } } void AggressiveDeadCodeElimination::makeUnconditional(BasicBlock *BB, BasicBlock *Target) { Instruction *PredTerm = BB->getTerminator(); // Collect the live debug info scopes attached to this instruction. if (const DILocation *DL = PredTerm->getDebugLoc()) collectLiveScopes(*DL); // Just mark live an existing unconditional branch if (isUnconditionalBranch(PredTerm)) { PredTerm->setSuccessor(0, Target); InstInfo[PredTerm].Live = true; return; } LLVM_DEBUG(dbgs() << "making unconditional " << BB->getName() << '\n'); NumBranchesRemoved += 1; IRBuilder<> Builder(PredTerm); auto *NewTerm = Builder.CreateBr(Target); InstInfo[NewTerm].Live = true; if (const DILocation *DL = PredTerm->getDebugLoc()) NewTerm->setDebugLoc(DL); InstInfo.erase(PredTerm); PredTerm->eraseFromParent(); } //===----------------------------------------------------------------------===// // // Pass Manager integration code // //===----------------------------------------------------------------------===// PreservedAnalyses ADCEPass::run(Function &F, FunctionAnalysisManager &FAM) { // ADCE does not need DominatorTree, but require DominatorTree here // to update analysis if it is already available. auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F); auto &PDT = FAM.getResult<PostDominatorTreeAnalysis>(F); if (!AggressiveDeadCodeElimination(F, DT, PDT).performDeadCodeElimination()) return PreservedAnalyses::all(); PreservedAnalyses PA; // TODO: We could track if we have actually done CFG changes. if (!RemoveControlFlowFlag) PA.preserveSet<CFGAnalyses>(); else { PA.preserve<DominatorTreeAnalysis>(); PA.preserve<PostDominatorTreeAnalysis>(); } PA.preserve<GlobalsAA>(); return PA; } namespace { struct ADCELegacyPass : public FunctionPass { static char ID; // Pass identification, replacement for typeid ADCELegacyPass() : FunctionPass(ID) { initializeADCELegacyPassPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function &F) override { if (skipFunction(F)) return false; // ADCE does not need DominatorTree, but require DominatorTree here // to update analysis if it is already available. auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); return AggressiveDeadCodeElimination(F, DT, PDT) .performDeadCodeElimination(); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<PostDominatorTreeWrapperPass>(); if (!RemoveControlFlowFlag) AU.setPreservesCFG(); else { AU.addPreserved<DominatorTreeWrapperPass>(); AU.addPreserved<PostDominatorTreeWrapperPass>(); } AU.addPreserved<GlobalsAAWrapperPass>(); } }; } // end anonymous namespace char ADCELegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(ADCELegacyPass, "adce", "Aggressive Dead Code Elimination", false, false) INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) INITIALIZE_PASS_END(ADCELegacyPass, "adce", "Aggressive Dead Code Elimination", false, false) FunctionPass *llvm::createAggressiveDCEPass() { return new ADCELegacyPass(); }
33.839572
80
0.677386
kubamracek
c8fcc68062ea917c59d83c05200d57317d1e76e6
8,857
cpp
C++
dep/reactphysics3d/src/memory/PoolAllocator.cpp
harperkdavis/hkedengine
4dbb9c5106aa8eaaf4369232f8036a05ce55ab3f
[ "MIT" ]
1
2022-02-14T11:54:13.000Z
2022-02-14T11:54:13.000Z
dep/reactphysics3d/src/memory/PoolAllocator.cpp
harperkdavis/hkedengine
4dbb9c5106aa8eaaf4369232f8036a05ce55ab3f
[ "MIT" ]
null
null
null
dep/reactphysics3d/src/memory/PoolAllocator.cpp
harperkdavis/hkedengine
4dbb9c5106aa8eaaf4369232f8036a05ce55ab3f
[ "MIT" ]
null
null
null
/******************************************************************************** * ReactPhysics3D physics library, http://www.reactphysics3d.com * * Copyright (c) 2010-2022 Daniel Chappuis * ********************************************************************************* * * * 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. * * * ********************************************************************************/ // Libraries #include <reactphysics3d/memory/PoolAllocator.h> #include <reactphysics3d/memory/MemoryManager.h> #include <cstdlib> #include <cassert> using namespace reactphysics3d; // Initialization of static variables bool PoolAllocator::isMapSizeToHeadIndexInitialized = false; size_t PoolAllocator::mUnitSizes[NB_HEAPS]; int PoolAllocator::mMapSizeToHeapIndex[MAX_UNIT_SIZE + 1]; // Constructor PoolAllocator::PoolAllocator(MemoryAllocator& baseAllocator) : mBaseAllocator(baseAllocator) { // Allocate some memory to manage the blocks mNbAllocatedMemoryBlocks = 64; mNbCurrentMemoryBlocks = 0; const size_t sizeToAllocate = mNbAllocatedMemoryBlocks * sizeof(MemoryBlock); mMemoryBlocks = static_cast<MemoryBlock*>(baseAllocator.allocate(sizeToAllocate)); memset(mMemoryBlocks, 0, sizeToAllocate); memset(mFreeMemoryUnits, 0, sizeof(mFreeMemoryUnits)); #ifndef NDEBUG mNbTimesAllocateMethodCalled = 0; #endif // If the mMapSizeToHeapIndex has not been initialized yet if (!isMapSizeToHeadIndexInitialized) { // Initialize the array that contains the sizes of the memory units that will // be allocated in each different heap for (uint i=0; i < NB_HEAPS; i++) { mUnitSizes[i] = (i+1) * 8; } // Initialize the lookup table that maps the size to allocated to the // corresponding heap we will use for the allocation uint j = 0; mMapSizeToHeapIndex[0] = -1; // This element should not be used for (uint i=1; i <= MAX_UNIT_SIZE; i++) { if (i <= mUnitSizes[j]) { mMapSizeToHeapIndex[i] = j; } else { j++; mMapSizeToHeapIndex[i] = j; } } isMapSizeToHeadIndexInitialized = true; } } // Destructor PoolAllocator::~PoolAllocator() { // Release the memory allocated for each block for (uint i=0; i<mNbCurrentMemoryBlocks; i++) { mBaseAllocator.release(mMemoryBlocks[i].memoryUnits, BLOCK_SIZE); } mBaseAllocator.release(mMemoryBlocks, mNbAllocatedMemoryBlocks * sizeof(MemoryBlock)); #ifndef NDEBUG // Check that the allocate() and release() methods have been called the same // number of times to avoid memory leaks. assert(mNbTimesAllocateMethodCalled == 0); #endif } // Allocate memory of a given size (in bytes) and return a pointer to the // allocated memory. void* PoolAllocator::allocate(size_t size) { // Lock the method with a mutex std::lock_guard<std::mutex> lock(mMutex); assert(size > 0); // We cannot allocate zero bytes if (size == 0) return nullptr; #ifndef NDEBUG mNbTimesAllocateMethodCalled++; #endif // If we need to allocate more than the maximum memory unit size if (size > MAX_UNIT_SIZE) { // Allocate memory using default allocation return mBaseAllocator.allocate(size); } // Get the index of the heap that will take care of the allocation request int indexHeap = mMapSizeToHeapIndex[size]; assert(indexHeap >= 0 && indexHeap < NB_HEAPS); // If there still are free memory units in the corresponding heap if (mFreeMemoryUnits[indexHeap] != nullptr) { // Return a pointer to the memory unit MemoryUnit* unit = mFreeMemoryUnits[indexHeap]; mFreeMemoryUnits[indexHeap] = unit->nextUnit; return unit; } else { // If there is no more free memory units in the corresponding heap // If we need to allocate more memory to contains the blocks if (mNbCurrentMemoryBlocks == mNbAllocatedMemoryBlocks) { // Allocate more memory to contain the blocks MemoryBlock* currentMemoryBlocks = mMemoryBlocks; mNbAllocatedMemoryBlocks += 64; mMemoryBlocks = static_cast<MemoryBlock*>(mBaseAllocator.allocate(mNbAllocatedMemoryBlocks * sizeof(MemoryBlock))); memcpy(mMemoryBlocks, currentMemoryBlocks, mNbCurrentMemoryBlocks * sizeof(MemoryBlock)); memset(mMemoryBlocks + mNbCurrentMemoryBlocks, 0, 64 * sizeof(MemoryBlock)); mBaseAllocator.release(currentMemoryBlocks, mNbCurrentMemoryBlocks * sizeof(MemoryBlock)); } // Allocate a new memory blocks for the corresponding heap and divide it in many // memory units MemoryBlock* newBlock = mMemoryBlocks + mNbCurrentMemoryBlocks; newBlock->memoryUnits = static_cast<MemoryUnit*>(mBaseAllocator.allocate(BLOCK_SIZE)); assert(newBlock->memoryUnits != nullptr); size_t unitSize = mUnitSizes[indexHeap]; size_t nbUnits = BLOCK_SIZE / unitSize; assert(nbUnits * unitSize <= BLOCK_SIZE); void* memoryUnitsStart = static_cast<void*>(newBlock->memoryUnits); char* memoryUnitsStartChar = static_cast<char*>(memoryUnitsStart); for (size_t i=0; i < nbUnits - 1; i++) { void* unitPointer = static_cast<void*>(memoryUnitsStartChar + unitSize * i); void* nextUnitPointer = static_cast<void*>(memoryUnitsStartChar + unitSize * (i+1)); MemoryUnit* unit = static_cast<MemoryUnit*>(unitPointer); MemoryUnit* nextUnit = static_cast<MemoryUnit*>(nextUnitPointer); unit->nextUnit = nextUnit; } void* lastUnitPointer = static_cast<void*>(memoryUnitsStartChar + unitSize*(nbUnits-1)); MemoryUnit* lastUnit = static_cast<MemoryUnit*>(lastUnitPointer); lastUnit->nextUnit = nullptr; // Add the new allocated block into the list of free memory units in the heap mFreeMemoryUnits[indexHeap] = newBlock->memoryUnits->nextUnit; mNbCurrentMemoryBlocks++; // Return the pointer to the first memory unit of the new allocated block return newBlock->memoryUnits; } } // Release previously allocated memory. void PoolAllocator::release(void* pointer, size_t size) { // Lock the method with a mutex std::lock_guard<std::mutex> lock(mMutex); assert(size > 0); // Cannot release a 0-byte allocated memory if (size == 0) return; #ifndef NDEBUG mNbTimesAllocateMethodCalled--; #endif // If the size is larger than the maximum memory unit size if (size > MAX_UNIT_SIZE) { // Release the memory using the default deallocation mBaseAllocator.release(pointer, size); return; } // Get the index of the heap that has handled the corresponding allocation request int indexHeap = mMapSizeToHeapIndex[size]; assert(indexHeap >= 0 && indexHeap < NB_HEAPS); // Insert the released memory unit into the list of free memory units of the // corresponding heap MemoryUnit* releasedUnit = static_cast<MemoryUnit*>(pointer); releasedUnit->nextUnit = mFreeMemoryUnits[indexHeap]; mFreeMemoryUnits[indexHeap] = releasedUnit; }
41.976303
127
0.612736
harperkdavis
74027ddd1b2091464bc1bc21541c4b122b58a31d
582
cpp
C++
src/vulkan/vulkan_functions/VulkanFunctions.cpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
null
null
null
src/vulkan/vulkan_functions/VulkanFunctions.cpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
null
null
null
src/vulkan/vulkan_functions/VulkanFunctions.cpp
jabronicus/P-Engine
7786c2f97d19bd2913b706f6afe5087a392b1a3c
[ "MIT" ]
1
2021-08-24T05:43:01.000Z
2021-08-24T05:43:01.000Z
#include "../../../include/vulkan/vulkan_functions/VulkanFunctions.hpp" // exported #define EXPORTED_VULKAN_FUNCTION( name ) PFN_##name name; // global #define GLOBAL_LEVEL_VULKAN_FUNCTION( name ) PFN_##name name; // instance #define INSTANCE_LEVEL_VULKAN_FUNCTION( name ) PFN_##name name; // device #define DEVICE_LEVEL_VULKAN_FUNCTION( name ) PFN_##name name; // include the inline file #include "../../../include/vulkan/vulkan_functions/VulkanFunctionsList.inl"
34.235294
171
0.61512
jabronicus
7403b37150f26fdd72dde0b2077ee3a6d3adbd70
664
cpp
C++
1.Arrays/Arrays_Smallest_and_Largest_number.cpp
suraj0803/DSA
6ea21e452d7662e2351ee2a7b0415722e1bbf094
[ "MIT" ]
null
null
null
1.Arrays/Arrays_Smallest_and_Largest_number.cpp
suraj0803/DSA
6ea21e452d7662e2351ee2a7b0415722e1bbf094
[ "MIT" ]
null
null
null
1.Arrays/Arrays_Smallest_and_Largest_number.cpp
suraj0803/DSA
6ea21e452d7662e2351ee2a7b0415722e1bbf094
[ "MIT" ]
null
null
null
#include<iostream> #include<climits> // INT_MAX and INT_MIN for max and min of integer size using namespace std; int main() { int n; cin>>n; int arr[1000]; for(int i=0; i<n; i++){ cin >> arr[i]; } // Algorithm to find largest and smallest number int largest = INT_MIN; int smallest = INT_MAX; for(int i=0; i<n; i++){ if(arr[i]>largest){ largest = arr[i]; } if(arr[i]<smallest){ smallest = arr[i]; } } cout<<"Largest element is : "<<largest<<endl; cout<<"Smallest element is :"<<smallest<<endl; return 0; }
18.971429
73
0.50753
suraj0803
7403f7c10bfb5d18c2065976f01b86e1b4a978cd
990
hpp
C++
programs/rodeos/streamer_plugin.hpp
forfreeday/eos
11d35f0f934402321853119d36caeb7022813743
[ "Apache-2.0", "MIT" ]
13,162
2017-05-29T22:08:27.000Z
2022-03-29T19:25:05.000Z
programs/rodeos/streamer_plugin.hpp
forfreeday/eos
11d35f0f934402321853119d36caeb7022813743
[ "Apache-2.0", "MIT" ]
6,450
2017-05-30T14:41:50.000Z
2022-03-30T11:30:04.000Z
programs/rodeos/streamer_plugin.hpp
forfreeday/eos
11d35f0f934402321853119d36caeb7022813743
[ "Apache-2.0", "MIT" ]
4,491
2017-05-29T22:08:32.000Z
2022-03-29T07:09:52.000Z
// copyright defined in LICENSE.txt #pragma once #include <appbase/application.hpp> #include <eosio/abi.hpp> #include "cloner_plugin.hpp" namespace b1 { struct stream_wrapper_v0 { eosio::name route; std::vector<char> data; }; EOSIO_REFLECT(stream_wrapper_v0, route, data); using stream_wrapper = std::variant<stream_wrapper_v0>; class streamer_plugin : public appbase::plugin<streamer_plugin> { public: APPBASE_PLUGIN_REQUIRES((cloner_plugin)) streamer_plugin(); virtual ~streamer_plugin(); virtual void set_program_options(appbase::options_description& cli, appbase::options_description& cfg) override; void plugin_initialize(const appbase::variables_map& options); void plugin_startup(); void plugin_shutdown(); void stream_data(const char* data, uint64_t data_size); private: std::shared_ptr<struct streamer_plugin_impl> my; void publish_to_streams(const stream_wrapper_v0& sw); }; } // namespace b1
25.384615
115
0.733333
forfreeday
7407582567ad68a0eaa36b269fb1a5f0678c4b99
3,149
hpp
C++
src/math/vector4.hpp
JustSlavic/gl2
1b4752d3273a1e401c970e18ae7151bba004a4ec
[ "MIT" ]
null
null
null
src/math/vector4.hpp
JustSlavic/gl2
1b4752d3273a1e401c970e18ae7151bba004a4ec
[ "MIT" ]
2
2021-05-29T20:34:50.000Z
2021-05-29T20:39:25.000Z
src/math/vector4.hpp
JustSlavic/gl2
1b4752d3273a1e401c970e18ae7151bba004a4ec
[ "MIT" ]
null
null
null
#pragma once #include <defines.h> #include "float.hpp" #include "color.hpp" #include "vector2.hpp" #include "vector3.hpp" namespace math { struct vector4 { union { struct { f32 x, y, z, w; }; struct { f32 u, v, s, t; }; struct { f32 r, g, b, a; }; struct { f32 _1, _2, _3, _4; }; struct { vector2 xy, zw; }; struct { vector2 uv, st; }; struct { vector3 xyz; f32 dummy_w; }; struct { color24 rgb; f32 dummy_a; }; color32 rgba; }; inline static vector4 make () { return { 0.f, 0.f, 0.f, 0.f }; } inline static vector4 make (f32 value) { return { value, value, value, value }; } inline static vector4 make (f32 x, f32 y, f32 z, f32 w) { return { x, y, z, w }; } inline static vector4 make (f32 x, f32 y, vector2 v2) { return { x, y, v2.x, v2.y }; } inline static vector4 make (vector2 v1, f32 z, f32 w) { return { v1.x, v1.y, z, w }; } inline static vector4 make (f32 x, vector2 v1, f32 w) { return { x, v1.x, v1.y, w }; } inline static vector4 make (vector2 v1, vector2 v2) { return { v1.x, v1.y, v2.x, v2.y }; } inline static vector4 make (f32 x, vector3 v3) { return { x, v3.x, v3.y, v3.z }; } inline static vector4 make (vector3 v3, f32 w) { return { v3.x, v3.y, v3.z, w }; } inline vector4& operator += (const vector4& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } inline vector4& operator -= (const vector4& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; } inline vector4& operator *= (f32 c) { x *= c; y *= c; z *= c; w *= c; return *this; } }; inline f32 dot (const vector4& a, const vector4& b) { return a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w; } inline bool equal (const vector4& a, const vector4& b) { return math::equal(a.x, b.x) && math::equal(a.y, b.y) && math::equal(a.z, b.z) && math::equal(a.w, b.w); } inline vector4 operator - (const vector4& a) { return { -a.x, -a.y, -a.z, -a.w }; } inline vector4 operator + (const vector4& a, const vector4& b) { return { a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w }; } inline vector4 operator - (const vector4& a, const vector4& b) { return { a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w }; } inline vector4 operator * (const vector4& a, f32 c) { return { c * a.x, c * a.y, c * a.z, c * a.w }; } inline vector4 operator * (f32 c, const vector4& a) { return { c * a.x, c * a.y, c * a.z, c * a.w }; } inline vector4 operator / (const vector4& v, f32 c) { return { v.x / c, v.y / c, v.z / c, v.w / c }; } inline bool operator == (const vector4& a, const vector4& b) { return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w); } inline bool operator != (const vector4& a, const vector4& b) { return !(a == b); } inline vector4 lerp (const vector4& a, const vector4& b, f32 t) { return { lerp(a.x, b.x, t), lerp(a.y, b.y, t), lerp(a.z, b.z, t), lerp(a.w, b.w, t) }; } } // math
28.369369
108
0.527151
JustSlavic
7409d06c4f5e0cc9922a60db8e17e474817f1e6c
314
cpp
C++
source/mess/engine/World.cpp
nsubiron/mess-engine
278580cca2b48ca7700a3c92525d34b5a72a545a
[ "MIT" ]
1
2017-11-03T11:42:29.000Z
2017-11-03T11:42:29.000Z
source/mess/engine/World.cpp
nsubiron/mess-engine
278580cca2b48ca7700a3c92525d34b5a72a545a
[ "MIT" ]
null
null
null
source/mess/engine/World.cpp
nsubiron/mess-engine
278580cca2b48ca7700a3c92525d34b5a72a545a
[ "MIT" ]
null
null
null
#include "mess/engine/World.h" #include "mess/engine/Actor.h" namespace mess { namespace engine { void World::visit(Actor &actor) { _actors.push_back(actor.WeakFromThis()); } void World::visit(Tickable &tickable) { _tick.RegisterTickable(tickable); } } // namespace engine } // namespace mess
17.444444
44
0.694268
nsubiron
7409d466cc0ab9fa0594b61a31865bca122d4097
968
cpp
C++
test/test_iostream_unix2dos.cpp
blindij/boostkata
5a0509c0413bddac54af94d2c00f9cb24b172279
[ "MIT" ]
null
null
null
test/test_iostream_unix2dos.cpp
blindij/boostkata
5a0509c0413bddac54af94d2c00f9cb24b172279
[ "MIT" ]
null
null
null
test/test_iostream_unix2dos.cpp
blindij/boostkata
5a0509c0413bddac54af94d2c00f9cb24b172279
[ "MIT" ]
null
null
null
// File: test_iostream_unix2dos.cpp // // Test the unix2dos output filter. Are we adding a CR? #include "catch2/catch.hpp" #include "iostreams/example/container_device.hpp" #include "iostreams/example/unix2dos_filter.hpp" #include <boost/iostreams/invert.hpp> //? #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/device/back_inserter.hpp> using namespace std; namespace io = boost::iostreams; namespace ex = boost::iostreams::example; TEST_CASE("Use unix2dos output_filter","[iostream][unix2dos]"){ typedef ex::container_sink<string> string_sink; string result; io::filtering_ostream out; out.push(ex::unix2dos_output_filter()); out.push(back_inserter(result)); out << "Hello World!\n"; // The length of the s tring is 13 characters out.flush(); REQUIRE( result == "Hello World!\r\n"); SECTION("Check that the length of the string is 14 characters"){ REQUIRE( result.length() == 14); } }
33.37931
74
0.715909
blindij
740ac443d38129867d52892912dd9cc348d048f0
2,196
cpp
C++
GameServer/DescManager.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/DescManager.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/DescManager.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
1
2022-01-17T09:34:39.000Z
2022-01-17T09:34:39.000Z
#include <boost/lambda/lambda.hpp> #include "stdhdrs.h" #include "Server.h" #include "DescManager.h" static DescManager local_instance; DescManager* DescManager::instance() { return &local_instance; } bool DescManager::insert( CDescriptor* desc ) { if (this->getDescByUserIndex(desc->m_index)) { LOG_ERROR("duplication data : userIndex[%d] userId[%s]", desc->m_index, (const char *)desc->m_idname); return false; } desc_info info; info.m_userIndex = desc->m_index; info.m_id = desc->m_idname; info.m_desc = desc; map_.insert(info); return true; } bool DescManager::erase( CDescriptor* desc ) { map_t::index<Key_User_Index>::type& p = map_.get<Key_User_Index>(); map_t::index<Key_User_Index>::type::iterator it = p.find(desc->m_index); if (it == p.end()) { LOG_ERROR("not found data : userIndex[%d] userId[%s]", desc->m_index, (const char *)desc->m_idname); return false; } p.erase(it); return true; } CDescriptor* DescManager::getDescByUserIndex( int userIndex ) { map_t::index<Key_User_Index>::type& p = map_.get<Key_User_Index>(); map_t::index<Key_User_Index>::type::iterator it = p.find(userIndex); return (it != p.end()) ? (*it).m_desc : NULL; } CDescriptor* DescManager::getDescById(const char* id) { std::string tid(id); return this->getDescById(tid); } CDescriptor* DescManager::getDescById( std::string id ) { map_t::index<Key_Id>::type& p = map_.get<Key_Id>(); map_t::index<Key_Id>::type::iterator it = p.find(id); return (it != p.end()) ? (*it).m_desc : NULL; } void DescManager::changeUserIndex( int oldUserIndex, int newUserIndex ) { map_t::index<Key_User_Index>::type& p = map_.get<Key_User_Index>(); map_t::index<Key_User_Index>::type::iterator it = p.find(oldUserIndex); if (it == p.end()) return; p.modify_key(it, boost::lambda::_1 = newUserIndex); } void DescManager::saveAllBeforServerDown() { LOG_INFO(">> saving all user data because server down <<"); map_t::index<Key_User_Index>::type& p = map_.get<Key_User_Index>(); map_t::index<Key_User_Index>::type::iterator it = p.begin(); map_t::index<Key_User_Index>::type::iterator endit = p.end(); for (; it != endit; ++it) { gserver->CloseSocket((*it).m_desc); } }
24.674157
104
0.6949
openlastchaos
740af1fee90ebfe3670b3c618d784dc3be93fa2c
641
hpp
C++
entity_component_system/src/Component.hpp
JacobNeal/gl-projects
4ea40797fde28602b9f787f0ec8005dcd164e054
[ "MIT" ]
null
null
null
entity_component_system/src/Component.hpp
JacobNeal/gl-projects
4ea40797fde28602b9f787f0ec8005dcd164e054
[ "MIT" ]
null
null
null
entity_component_system/src/Component.hpp
JacobNeal/gl-projects
4ea40797fde28602b9f787f0ec8005dcd164e054
[ "MIT" ]
null
null
null
#ifndef COMPONENT_HPP #define COMPONENT_HPP #include <sstream> #include "Types.hpp" class Component { public: Component(const ComponentType & type); virtual ~Component(); ComponentType getType(); friend std::stringstream & operator >>(std::stringstream & stream, Component & comp) { comp.read(stream); return stream; } virtual void read(std::stringstream & stream) = 0; protected: /**************************************** * Data members ****************************************/ ComponentType m_type; }; #endif
20.03125
92
0.50546
JacobNeal
740b29bc9728ce58dd7518e6392c254b80b8b450
1,621
cpp
C++
QSynthesis/Frontend/Tabs/Tuning/Scrolls/NoneScrollArea.cpp
SineStriker/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
3
2021-12-08T05:30:52.000Z
2021-12-18T10:46:49.000Z
QSynthesis/Frontend/Tabs/Tuning/Scrolls/NoneScrollArea.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
QSynthesis/Frontend/Tabs/Tuning/Scrolls/NoneScrollArea.cpp
QSynthesis/QSynthesis-Old
7b96f2d1292a4a57de6e1c50d4df2a57bfe2bc5d
[ "MIT" ]
null
null
null
#include "NoneScrollArea.h" NoneScrollArea::NoneScrollArea(QWidget *parent) : MoreWidget(parent) { m_widget = nullptr; } NoneScrollArea::~NoneScrollArea() { } void NoneScrollArea::setWidget(QWidget *widget) { m_widget = widget; widget->move(0, 0); } QWidget *NoneScrollArea::widget() { return m_widget; } void NoneScrollArea::setPercentageX(double value) { if (!m_widget || m_widget->width() <= this->width()) { return; } double toX = (value / 100.0) * (this->width() - m_widget->width()); m_widget->move(toX, m_widget->y()); } void NoneScrollArea::setPercentageY(double value) { if (!m_widget || m_widget->height() <= this->height()) { return; } double toY = (value / 100.0) * (this->height() - m_widget->height()); m_widget->move(m_widget->x(), toY); } double NoneScrollArea::percentageX() { if (!m_widget || m_widget->width() <= this->width()) { return 0; } return m_widget->x() / (this->width() - m_widget->width()) * 100.0; } double NoneScrollArea::percentageY() { if (!m_widget || m_widget->height() <= this->height()) { return 0; } return m_widget->y() / (this->height() - m_widget->height()) * 100.0; } void NoneScrollArea::setValueX(int value) { m_widget->move(-value, m_widget->y()); } int NoneScrollArea::valueX() const { return -m_widget->x(); } void NoneScrollArea::setValueY(int value) { m_widget->move(m_widget->x(), -value); } int NoneScrollArea::valueY() const { return -m_widget->y(); } void NoneScrollArea::resizeEvent(QResizeEvent *event) { emit resized(event); }
23.838235
73
0.628624
SineStriker
740cfc162e84e9a83e8dde940adaccf867a49069
3,386
cpp
C++
test/UnitTests/Tests/JsonParsingTests.cpp
jasonsandlin/PlayFabCoreCSdk
ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19
[ "Apache-2.0" ]
1
2021-11-19T00:33:51.000Z
2021-11-19T00:33:51.000Z
test/UnitTests/Tests/JsonParsingTests.cpp
jasonsandlin/PlayFabCoreCSdk
ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19
[ "Apache-2.0" ]
7
2021-03-27T01:12:25.000Z
2021-08-13T22:05:59.000Z
test/UnitTests/Tests/JsonParsingTests.cpp
jasonsandlin/PlayFabCoreCSdk
ecf51e9a7a90e579efed595bd1d76ec8f3a1ae19
[ "Apache-2.0" ]
3
2021-12-04T20:43:04.000Z
2022-01-03T21:16:32.000Z
#include "pch.h" #include "EnumTraits.h" #include "JsonUtils.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace PlayFab { enum class PFEnum { Value1, Value2 }; template<> struct EnumRange<PFEnum> { static constexpr PFEnum maxValue = PFEnum::Value2; }; template<> struct EnumRange<PFCountryCode> { static constexpr PFCountryCode maxValue = PFCountryCode::ZW; }; namespace UnitTests { constexpr char jsonString[] = R"( { "EnumValue":"Value2", "ArrayValue":["0","1","2","3","4","5"], "SubObjectValue": { "CountryCode":"IN" } } )"; TEST_CLASS(JsonParsingTests) { public: TEST_METHOD(BasicJsonParsing) { struct SubObjectModel : public InputModel, OutputModel<SubObjectModel> { using ModelType = SubObjectModel; PFCountryCode CountryCode; void FromJson(const JsonValue& input) { JsonUtils::ObjectGetMember(input, "CountryCode", CountryCode); } size_t RequiredBufferSize() const { // unused return 0; } Result<SubObjectModel const*> Copy(ModelBuffer&) const { // unused return E_NOTIMPL; } JsonValue ToJson() const { return ToJson(*this); } static JsonValue ToJson(const SubObjectModel& model) { JsonValue output{ rapidjson::kObjectType }; JsonUtils::ObjectAddMember(output, "CountryCode", model.CountryCode); return output; } }; struct ObjectModel : public InputModel, OutputModel<ObjectModel> { using ModelType = ObjectModel; PFEnum EnumValue; CStringVector ArrayValue; SubObjectModel SubObjectValue; void FromJson(const JsonValue& input) { JsonUtils::ObjectGetMember(input, "EnumValue", EnumValue); JsonUtils::ObjectGetMember(input, "ArrayValue", ArrayValue); JsonUtils::ObjectGetMember(input, "SubObjectValue", SubObjectValue); } size_t RequiredBufferSize() const { // unused return 0; } Result<ObjectModel const*> Copy(ModelBuffer&) const { // unused return E_NOTIMPL; } JsonValue ToJson() const { JsonValue output{ rapidjson::kObjectType }; JsonUtils::ObjectAddMember(output, "EnumValue", EnumValue); JsonUtils::ObjectAddMemberArray(output, "ArrayValue", ArrayValue.data(), static_cast<uint32_t>(ArrayValue.size())); JsonUtils::ObjectAddMember<SubObjectModel>(output, "SubObjectValue", &SubObjectValue); return output; } }; JsonDocument inputJson; inputJson.Parse(jsonString); ObjectModel model; model.FromJson(inputJson); JsonValue outputJson{ model.ToJson() }; Assert::IsTrue(inputJson == outputJson); } }; } // UnitTests } // PlayFab
27.306452
132
0.538098
jasonsandlin
740dc15c90f5de0a79342999b0c43395c5c67300
57,836
cpp
C++
docker/tensorflow-lite-micro-rtos-fvp/sw/ethos-u/samples/person_detection/person_male_man_men.cpp
junpuf/Tool-Solutions
9879f48fb43028a0fd9fa070b2f8f852697384c8
[ "Apache-2.0" ]
1
2021-07-03T23:50:31.000Z
2021-07-03T23:50:31.000Z
docker/tensorflow-lite-micro-rtos-fvp/sw/ethos-u/samples/person_detection/person_male_man_men.cpp
junpuf/Tool-Solutions
9879f48fb43028a0fd9fa070b2f8f852697384c8
[ "Apache-2.0" ]
null
null
null
docker/tensorflow-lite-micro-rtos-fvp/sw/ethos-u/samples/person_detection/person_male_man_men.cpp
junpuf/Tool-Solutions
9879f48fb43028a0fd9fa070b2f8f852697384c8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Arm Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the License); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ //--------------------------------------------- // This file was autogenerated by the script // convert_image_to_cpp.sh // Do not edit //--------------------------------------------- #include "images.hpp" const unsigned char person_male_man_men[] __attribute__((section("input_data_sec"), aligned(4))) = { 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xed, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xea, 0xeb, 0xea, 0xea, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xe9, 0xea, 0xe9, 0xe9, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xe9, 0xe9, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xed, 0xed, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xeb, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xeb, 0xeb, 0xeb, 0xea, 0xeb, 0xeb, 0xea, 0xea, 0xea, 0xeb, 0xeb, 0xea, 0xea, 0xea, 0xea, 0xea, 0xea, 0xeb, 0xea, 0xea, 0xea, 0xea, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xed, 0xed, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xea, 0xea, 0xea, 0xea, 0xea, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xea, 0xeb, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xed, 0xed, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xea, 0xeb, 0xeb, 0xeb, 0xea, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xec, 0xec, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xea, 0xea, 0xeb, 0xeb, 0xea, 0xeb, 0xeb, 0xea, 0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xeb, 0xea, 0xec, 0xec, 0xeb, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xeb, 0xeb, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xed, 0xed, 0xef, 0xf2, 0xee, 0xe6, 0xe0, 0xe6, 0xee, 0xf1, 0xee, 0xee, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xed, 0xf0, 0xf2, 0xe5, 0xd1, 0xca, 0xcf, 0xd6, 0xda, 0xe2, 0xc5, 0xde, 0xe8, 0xee, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xeb, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xeb, 0xec, 0xec, 0xec, 0xed, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xf0, 0xf3, 0xe5, 0xc5, 0xba, 0xa0, 0x5e, 0x6d, 0xb4, 0xb0, 0x83, 0x9e, 0xc1, 0xc2, 0xba, 0xf7, 0xee, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xec, 0xec, 0xeb, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xec, 0xe4, 0xce, 0xc6, 0xd5, 0xbc, 0x88, 0x40, 0x27, 0x38, 0x2c, 0x44, 0x7c, 0x66, 0x69, 0x6c, 0xb9, 0xe6, 0xed, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xe6, 0xe1, 0xd3, 0xbe, 0xc6, 0x94, 0x61, 0x33, 0x20, 0x1a, 0x1c, 0x21, 0x24, 0x20, 0x1f, 0x25, 0x35, 0x63, 0xb3, 0xf1, 0xeb, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xee, 0xeb, 0xe9, 0xe8, 0xd5, 0xdf, 0x9a, 0x47, 0x32, 0x21, 0x26, 0x23, 0x29, 0x26, 0x21, 0x17, 0x0e, 0x1e, 0x24, 0x36, 0x61, 0xda, 0xee, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xef, 0xec, 0xec, 0xf1, 0xe6, 0xda, 0x96, 0x46, 0x29, 0x26, 0x2b, 0x2b, 0x2a, 0x21, 0x21, 0x20, 0x1a, 0x0f, 0x15, 0x18, 0x21, 0x19, 0x79, 0xf5, 0xea, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xee, 0xf1, 0xf6, 0xd0, 0x96, 0x67, 0x34, 0x24, 0x22, 0x20, 0x21, 0x2a, 0x2c, 0x24, 0x1a, 0x20, 0x20, 0x16, 0x19, 0x18, 0x18, 0x18, 0x27, 0xac, 0xf0, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf2, 0xf2, 0xf0, 0xe4, 0x8d, 0x44, 0x38, 0x28, 0x1e, 0x17, 0x15, 0x1d, 0x1c, 0x19, 0x1e, 0x31, 0x2f, 0x1c, 0x21, 0x1f, 0x1a, 0x17, 0x13, 0x16, 0x1b, 0x34, 0xad, 0xf5, 0xeb, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf3, 0xeb, 0xd4, 0xc7, 0x63, 0x28, 0x3c, 0x3c, 0x1c, 0x13, 0x0f, 0x19, 0x1a, 0x17, 0x17, 0x11, 0x1e, 0x2f, 0x2a, 0x19, 0x18, 0x21, 0x17, 0x12, 0x12, 0x19, 0x25, 0x56, 0xe3, 0xf0, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf0, 0xee, 0xf2, 0xe3, 0xcd, 0xe1, 0x92, 0x31, 0x33, 0x35, 0x19, 0x12, 0x0f, 0x19, 0x1c, 0x16, 0x1a, 0x16, 0x17, 0x1b, 0x1f, 0x1d, 0x1e, 0x1c, 0x1b, 0x16, 0x14, 0x11, 0x15, 0x24, 0x32, 0xaf, 0xf5, 0xec, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xe5, 0xf1, 0xe2, 0xf7, 0xd5, 0x66, 0x2d, 0x3a, 0x29, 0x13, 0x10, 0x14, 0x1f, 0x18, 0x1d, 0x15, 0x19, 0x14, 0x0c, 0x11, 0x1b, 0x18, 0x1e, 0x23, 0x1c, 0x1a, 0x15, 0x1a, 0x29, 0x2d, 0x82, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf3, 0xe4, 0xcb, 0xdb, 0xd7, 0x5f, 0x2c, 0x30, 0x32, 0x17, 0x12, 0x0f, 0x20, 0x1e, 0x1f, 0x16, 0x18, 0x1f, 0x1e, 0x1a, 0x13, 0x16, 0x1c, 0x1f, 0x23, 0x26, 0x27, 0x16, 0x20, 0x28, 0x27, 0x61, 0xd2, 0xf2, 0xec, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf2, 0xe6, 0xcd, 0x67, 0x42, 0x37, 0x40, 0x2e, 0x15, 0x10, 0x14, 0x23, 0x1e, 0x1f, 0x11, 0x1a, 0x18, 0x1e, 0x21, 0x20, 0x23, 0x23, 0x2f, 0x3d, 0x2d, 0x25, 0x1c, 0x22, 0x21, 0x24, 0x35, 0x9c, 0xf0, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xef, 0xf6, 0xe7, 0x76, 0x87, 0x44, 0x46, 0x22, 0x14, 0x12, 0x1b, 0x20, 0x20, 0x16, 0x13, 0x14, 0x12, 0x20, 0x1d, 0x1c, 0x34, 0x41, 0x4f, 0x40, 0x33, 0x3b, 0x20, 0x23, 0x1b, 0x1e, 0x1a, 0x57, 0xcb, 0xf2, 0xec, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xef, 0xfa, 0xba, 0x97, 0xae, 0x61, 0x49, 0x1d, 0x14, 0x10, 0x1f, 0x1b, 0x18, 0x10, 0x12, 0x10, 0x12, 0x1b, 0x22, 0x2b, 0x5c, 0x77, 0x60, 0x43, 0x5c, 0x40, 0x29, 0x11, 0x19, 0x14, 0x1b, 0x32, 0xaf, 0xf5, 0xec, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xef, 0xef, 0xef, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xef, 0xf8, 0xb3, 0xbf, 0x9f, 0x64, 0x44, 0x1c, 0x15, 0x12, 0x20, 0x14, 0x17, 0x10, 0x0f, 0x12, 0x12, 0x19, 0x24, 0x49, 0x82, 0x82, 0x58, 0x60, 0x53, 0x6c, 0x34, 0x18, 0x17, 0x13, 0x29, 0x2f, 0x9e, 0xf6, 0xec, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xb0, 0xd9, 0xa3, 0x80, 0x39, 0x1e, 0x11, 0x1a, 0x20, 0x12, 0x14, 0x0e, 0x13, 0x17, 0x1b, 0x19, 0x2e, 0x6a, 0x8c, 0x64, 0x4f, 0x5d, 0x85, 0x77, 0x2a, 0x3a, 0x1a, 0x1b, 0x25, 0x2e, 0x69, 0xf0, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf0, 0xf2, 0xea, 0xc5, 0xe9, 0xab, 0x77, 0x31, 0x1e, 0x14, 0x23, 0x16, 0x17, 0x1f, 0x24, 0x25, 0x27, 0x24, 0x1d, 0x40, 0x61, 0x57, 0x4d, 0x6a, 0x8f, 0x95, 0x64, 0x43, 0x4f, 0x19, 0x16, 0x2a, 0x23, 0x48, 0xda, 0xf2, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf0, 0xe6, 0xed, 0xb5, 0x54, 0x2f, 0x1f, 0x1a, 0x25, 0x17, 0x1c, 0x27, 0x2f, 0x33, 0x2e, 0x21, 0x35, 0x4b, 0x58, 0x61, 0x81, 0x98, 0x97, 0x8f, 0x4c, 0x5b, 0x4c, 0x19, 0x21, 0x2d, 0x1c, 0x31, 0xbc, 0xf6, 0xec, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xe7, 0xed, 0xb6, 0x55, 0x32, 0x26, 0x21, 0x23, 0x19, 0x1e, 0x1d, 0x15, 0x19, 0x2d, 0x42, 0x49, 0x65, 0x7d, 0x8a, 0x8e, 0x92, 0x94, 0x7f, 0x51, 0x78, 0x49, 0x20, 0x1c, 0x32, 0x26, 0x33, 0xb4, 0xf7, 0xeb, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xed, 0xf1, 0xbd, 0x5b, 0x36, 0x31, 0x21, 0x24, 0x1f, 0x2d, 0x3c, 0x3e, 0x4b, 0x5c, 0x62, 0x6b, 0x82, 0x83, 0x8d, 0x95, 0x92, 0x9a, 0x6e, 0x6a, 0x8d, 0x3f, 0x1f, 0x22, 0x38, 0x1c, 0x58, 0xe1, 0xf0, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf0, 0xda, 0x61, 0x33, 0x37, 0x20, 0x28, 0x24, 0x3b, 0x57, 0x56, 0x62, 0x78, 0x80, 0x88, 0x87, 0x84, 0x8a, 0x92, 0x9a, 0x85, 0x5f, 0xa0, 0x81, 0x39, 0x1d, 0x37, 0x3f, 0x4a, 0xb8, 0xf1, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf1, 0xf1, 0xee, 0xf0, 0x7a, 0x2f, 0x40, 0x26, 0x28, 0x2f, 0x4f, 0x69, 0x5d, 0x66, 0x7e, 0x8d, 0x8a, 0x89, 0x8a, 0x8c, 0x8f, 0x88, 0x73, 0x96, 0xa8, 0x7b, 0x40, 0x28, 0x44, 0x3b, 0x46, 0xc5, 0xef, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xee, 0xf8, 0xab, 0x2b, 0x44, 0x2f, 0x25, 0x37, 0x40, 0x41, 0x3a, 0x37, 0x5e, 0x7e, 0x83, 0x8b, 0x86, 0x88, 0x6f, 0x71, 0x94, 0x9e, 0xa4, 0x7f, 0x53, 0x35, 0x4b, 0x46, 0x59, 0xd8, 0xef, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xef, 0xf7, 0xcf, 0x39, 0x39, 0x3e, 0x32, 0x2e, 0x27, 0x36, 0x34, 0x21, 0x30, 0x66, 0x76, 0x83, 0x78, 0x5e, 0x3a, 0x30, 0x59, 0x66, 0x8d, 0x8a, 0x54, 0x40, 0x4d, 0x56, 0xa4, 0xf3, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf2, 0xec, 0x66, 0x41, 0x36, 0x3d, 0x41, 0x40, 0x40, 0x2c, 0x21, 0x1e, 0x42, 0x5e, 0x70, 0x61, 0x47, 0x30, 0x27, 0x43, 0x61, 0x6a, 0x73, 0x5a, 0x4a, 0x4c, 0x5e, 0xcb, 0xf0, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xef, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xef, 0xf6, 0xac, 0x67, 0x2a, 0x44, 0x47, 0x33, 0x35, 0x2f, 0x34, 0x23, 0x30, 0x5b, 0x89, 0x73, 0x4f, 0x38, 0x1a, 0x21, 0x4b, 0x80, 0x80, 0x68, 0x4f, 0x42, 0x70, 0xee, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xef, 0xf6, 0xd1, 0x8f, 0x2e, 0x4e, 0x53, 0x53, 0x5f, 0x60, 0x54, 0x4d, 0x47, 0x64, 0x8f, 0x8f, 0x6a, 0x4c, 0x49, 0x59, 0x5b, 0x58, 0x7e, 0x71, 0x49, 0x39, 0x94, 0xf7, 0xed, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xef, 0xb3, 0x30, 0x55, 0x62, 0x71, 0x6e, 0x65, 0x6a, 0x60, 0x55, 0x6d, 0x89, 0x98, 0x85, 0x6d, 0x60, 0x6a, 0x85, 0x86, 0x77, 0x72, 0x33, 0x39, 0xa9, 0xf0, 0xee, 0xef, 0xef, 0xef, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf7, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xef, 0xf9, 0xc9, 0x39, 0x5f, 0x60, 0x73, 0x7b, 0x78, 0x7b, 0x60, 0x59, 0x6b, 0x87, 0x9b, 0x94, 0x81, 0x83, 0x79, 0x81, 0x97, 0x9c, 0x9b, 0x3f, 0x5a, 0xb3, 0xed, 0xef, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf0, 0xf4, 0xe0, 0x56, 0x62, 0x61, 0x70, 0x7c, 0x81, 0x79, 0x53, 0x58, 0x70, 0x83, 0x91, 0x97, 0x8e, 0x84, 0x84, 0x8c, 0x9e, 0xac, 0xa8, 0x5e, 0x69, 0xa8, 0xf3, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf0, 0xf0, 0xf3, 0x8a, 0x5d, 0x60, 0x71, 0x7e, 0x80, 0x66, 0x47, 0x61, 0x76, 0x84, 0x91, 0x80, 0x88, 0x8d, 0x89, 0x96, 0xa3, 0xae, 0xac, 0x84, 0x7b, 0xb4, 0xf6, 0xed, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xef, 0xfa, 0xa2, 0x5a, 0x5e, 0x6d, 0x79, 0x77, 0x47, 0x49, 0x5e, 0x78, 0x8d, 0x98, 0x8e, 0x69, 0x86, 0x89, 0x99, 0xa5, 0xa8, 0xb1, 0x91, 0x8d, 0xd4, 0xf4, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xef, 0xf6, 0xd1, 0x64, 0x5a, 0x66, 0x73, 0x69, 0x42, 0x3f, 0x3e, 0x64, 0x7f, 0x70, 0x7a, 0x65, 0x69, 0x83, 0x91, 0xa3, 0xa8, 0xac, 0x9b, 0xb4, 0xe7, 0xf0, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf0, 0xf2, 0xed, 0x70, 0x55, 0x61, 0x70, 0x5f, 0x4b, 0x44, 0x3a, 0x4a, 0x69, 0x75, 0x71, 0x6f, 0x53, 0x78, 0x88, 0x9a, 0xa7, 0xab, 0x9c, 0xd5, 0xf3, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf0, 0xf2, 0xed, 0x74, 0x52, 0x63, 0x6f, 0x5b, 0x4f, 0x55, 0x50, 0x54, 0x6c, 0x83, 0x80, 0x70, 0x51, 0x6a, 0x8a, 0x95, 0xa1, 0xae, 0xd0, 0xf2, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf0, 0xf0, 0xf5, 0x80, 0x51, 0x67, 0x6e, 0x5d, 0x56, 0x5b, 0x5d, 0x6a, 0x7a, 0x88, 0x9a, 0x89, 0x5e, 0x60, 0x92, 0x96, 0x9b, 0xc7, 0xf7, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xef, 0xfa, 0x95, 0x50, 0x6a, 0x6f, 0x65, 0x49, 0x3a, 0x40, 0x48, 0x5a, 0x59, 0x5e, 0x79, 0x6c, 0x61, 0x96, 0x98, 0x99, 0xd2, 0xf3, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xee, 0xfb, 0xb4, 0x4e, 0x68, 0x72, 0x64, 0x28, 0x56, 0x68, 0x7a, 0x9a, 0x92, 0x74, 0x3c, 0x6f, 0x67, 0x94, 0x9a, 0xa1, 0xde, 0xf3, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xee, 0xef, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf6, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf0, 0xf6, 0xd8, 0x5a, 0x61, 0x76, 0x5e, 0x0e, 0x3d, 0x5a, 0x79, 0x99, 0x87, 0x7e, 0x34, 0x55, 0x72, 0x94, 0x99, 0xa9, 0xeb, 0xf1, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf0, 0xf0, 0xf2, 0x78, 0x59, 0x75, 0x61, 0x16, 0x10, 0x1b, 0x25, 0x2a, 0x30, 0x25, 0x09, 0x54, 0x79, 0x95, 0x98, 0xbb, 0xf3, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xee, 0xfb, 0xa3, 0x53, 0x73, 0x64, 0x23, 0x28, 0x34, 0x3d, 0x42, 0x53, 0x38, 0x22, 0x69, 0x7f, 0x9a, 0x99, 0xd0, 0xf5, 0xee, 0xf0, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf7, 0xf7, 0xf7, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xef, 0xf8, 0xca, 0x56, 0x6b, 0x68, 0x33, 0x33, 0x44, 0x4f, 0x58, 0x6e, 0x49, 0x44, 0x72, 0x84, 0x9c, 0x9c, 0xd7, 0xf4, 0xef, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf2, 0xf1, 0xf1, 0xef, 0xf7, 0xd2, 0x57, 0x64, 0x63, 0x4a, 0x2e, 0x49, 0x56, 0x5e, 0x71, 0x40, 0x65, 0x76, 0x8d, 0x9a, 0x9e, 0xdb, 0xf3, 0xef, 0xf0, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xf1, 0xee, 0xf7, 0xc4, 0x53, 0x61, 0x5c, 0x5b, 0x4b, 0x34, 0x49, 0x51, 0x3f, 0x30, 0x89, 0x7b, 0x94, 0x9a, 0xa3, 0xdb, 0xf3, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xef, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf1, 0xf1, 0xef, 0xf2, 0xff, 0xb6, 0x4f, 0x5d, 0x5b, 0x50, 0x6e, 0x37, 0x2b, 0x2a, 0x24, 0x5f, 0x92, 0x84, 0x99, 0x98, 0xa5, 0xd9, 0xf3, 0xef, 0xf0, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf0, 0xf7, 0xe2, 0xb9, 0x81, 0x53, 0x5a, 0x5a, 0x4d, 0x55, 0x64, 0x64, 0x55, 0x51, 0x86, 0x8f, 0x8e, 0x98, 0x9a, 0xa7, 0xce, 0xf5, 0xef, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf2, 0xf0, 0xf0, 0xf4, 0xf7, 0xc4, 0x74, 0x54, 0x68, 0x52, 0x58, 0x5d, 0x4f, 0x4b, 0x50, 0x60, 0x5c, 0x6b, 0x93, 0x8a, 0x96, 0x94, 0x9c, 0xab, 0xb7, 0xd3, 0xf1, 0xf4, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf1, 0xf0, 0xf1, 0xf6, 0xf6, 0xdf, 0xa2, 0x77, 0x5b, 0x5a, 0x66, 0x50, 0x52, 0x65, 0x52, 0x4f, 0x4f, 0x4c, 0x58, 0x78, 0x8a, 0x88, 0x97, 0x8b, 0x9b, 0xa9, 0xb7, 0xaf, 0xb4, 0xd8, 0xf4, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf2, 0xf2, 0xf1, 0xf2, 0xf7, 0xf4, 0xda, 0xb0, 0x84, 0x75, 0x7d, 0x55, 0x59, 0x5f, 0x52, 0x4a, 0x65, 0x62, 0x52, 0x4d, 0x4f, 0x5f, 0x79, 0x80, 0x94, 0x8c, 0x86, 0x9b, 0xa9, 0xb5, 0xb3, 0xab, 0x91, 0xcd, 0xf0, 0xef, 0xee, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf2, 0xf1, 0xf4, 0xf8, 0xef, 0xd2, 0xab, 0x8d, 0x83, 0x7b, 0x81, 0x7d, 0x57, 0x59, 0x5c, 0x53, 0x45, 0x57, 0x73, 0x67, 0x64, 0x65, 0x71, 0x81, 0x8a, 0x96, 0x7f, 0x8d, 0x9b, 0xa9, 0xb2, 0xb5, 0xb4, 0xa1, 0xb0, 0xdc, 0xed, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf2, 0xf3, 0xf7, 0xea, 0xc8, 0xa6, 0x91, 0x8e, 0x8f, 0x88, 0x80, 0x83, 0x81, 0x5c, 0x5a, 0x5c, 0x55, 0x49, 0x49, 0x6b, 0x72, 0x76, 0x7c, 0x89, 0x8a, 0x8e, 0x85, 0x7d, 0x8d, 0x9f, 0xab, 0xb2, 0xb5, 0xb5, 0xa9, 0xb6, 0xd2, 0xd4, 0xec, 0xf1, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf1, 0xf6, 0xf1, 0xc5, 0xa3, 0x97, 0x98, 0x99, 0x96, 0x93, 0x8b, 0x86, 0x86, 0x88, 0x63, 0x59, 0x5c, 0x59, 0x50, 0x44, 0x50, 0x68, 0x70, 0x71, 0x7b, 0x83, 0x87, 0x7c, 0x7d, 0x8e, 0xa0, 0xab, 0xb1, 0xb4, 0xb7, 0xa7, 0xb6, 0xd3, 0xcb, 0xd3, 0xe6, 0xf1, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf6, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf2, 0xf1, 0xf8, 0xe6, 0xaf, 0x9b, 0xa1, 0xa3, 0x9f, 0x9d, 0x9b, 0x96, 0x91, 0x8b, 0x8a, 0x8f, 0x6d, 0x59, 0x5b, 0x57, 0x54, 0x4c, 0x47, 0x50, 0x58, 0x5b, 0x63, 0x76, 0x81, 0x7a, 0x82, 0x91, 0xa1, 0xaa, 0xae, 0xb5, 0xb8, 0xa1, 0xbc, 0xd1, 0xcd, 0xc5, 0xcd, 0xdf, 0xf1, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf5, 0xf8, 0xdb, 0xa7, 0xa1, 0xa7, 0xa6, 0xa5, 0xa2, 0xa0, 0x9f, 0x9a, 0x94, 0x8f, 0x8c, 0x93, 0x77, 0x5a, 0x5e, 0x59, 0x59, 0x53, 0x52, 0x4d, 0x4c, 0x52, 0x5b, 0x6f, 0x7b, 0x79, 0x84, 0x93, 0xa2, 0xaa, 0xae, 0xb4, 0xb6, 0x9a, 0xc2, 0xcc, 0xce, 0xba, 0xc5, 0xca, 0xd9, 0xef, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf5, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf2, 0xf5, 0xeb, 0xc4, 0xa1, 0xa3, 0xa9, 0xa9, 0xaa, 0xa9, 0xa4, 0xa6, 0xa4, 0x9e, 0x98, 0x94, 0x90, 0x96, 0x84, 0x5d, 0x61, 0x5f, 0x5c, 0x59, 0x58, 0x59, 0x56, 0x57, 0x5f, 0x6e, 0x74, 0x77, 0x83, 0x95, 0xa0, 0xa9, 0xac, 0xb2, 0xaf, 0x95, 0xc8, 0xc7, 0xcd, 0xb8, 0xba, 0xc8, 0xc7, 0xd3, 0xeb, 0xf2, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf5, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf2, 0xf7, 0xe3, 0xa6, 0x9d, 0xa4, 0xa9, 0xab, 0xac, 0xae, 0xaa, 0xa8, 0xac, 0xa5, 0xa1, 0x9b, 0x98, 0x94, 0x97, 0x93, 0x65, 0x5f, 0x60, 0x5f, 0x5d, 0x5e, 0x60, 0x60, 0x5d, 0x61, 0x6c, 0x71, 0x79, 0x89, 0x96, 0x9f, 0xa7, 0xa9, 0xb2, 0xa3, 0x99, 0xcf, 0xc4, 0xc9, 0xbc, 0xb6, 0xc2, 0xca, 0xc4, 0xcc, 0xe3, 0xf0, 0xef, 0xee, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf5, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf6, 0xec, 0xad, 0xa1, 0xa5, 0xa8, 0xaa, 0xad, 0xad, 0xb1, 0xaa, 0xb0, 0xae, 0xa8, 0xa5, 0x9f, 0x9e, 0x97, 0x99, 0x9f, 0x71, 0x5a, 0x61, 0x62, 0x61, 0x63, 0x67, 0x69, 0x67, 0x69, 0x70, 0x76, 0x7f, 0x8f, 0x98, 0xa3, 0xa5, 0xa7, 0xaf, 0x92, 0xab, 0xce, 0xc6, 0xc3, 0xbc, 0xb4, 0xba, 0xc6, 0xc8, 0xc4, 0xc5, 0xda, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xad, 0x9a, 0xa9, 0xa7, 0xaa, 0xab, 0xaf, 0xb1, 0xb0, 0xac, 0xb4, 0xad, 0xad, 0xa9, 0xa3, 0xa2, 0x99, 0x9d, 0xa6, 0x88, 0x59, 0x63, 0x65, 0x64, 0x66, 0x6d, 0x6f, 0x6b, 0x6f, 0x74, 0x7a, 0x86, 0x95, 0x97, 0xa6, 0xa9, 0xa6, 0x9e, 0x8e, 0xbc, 0xc9, 0xca, 0xbd, 0xbb, 0xb6, 0xb6, 0xc1, 0xca, 0xc7, 0xc3, 0xc7, 0xd9, 0xef, 0xef, 0xee, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf5, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf2, 0xf9, 0xbf, 0x91, 0x9e, 0xac, 0xaa, 0xac, 0xab, 0xb0, 0xb3, 0xaf, 0xb1, 0xb6, 0xae, 0xae, 0xac, 0xa8, 0xa6, 0x9e, 0xa0, 0xa7, 0xa0, 0x67, 0x66, 0x6b, 0x68, 0x6a, 0x72, 0x77, 0x74, 0x75, 0x78, 0x7d, 0x8f, 0x99, 0x98, 0xa6, 0xaf, 0x9f, 0x91, 0x9a, 0xc5, 0xc7, 0xcb, 0xb9, 0xbb, 0xb7, 0xb4, 0xc0, 0xc7, 0xc9, 0xc0, 0xc5, 0xca, 0xdd, 0xf0, 0xef, 0xee, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf5, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf2, 0xf8, 0xda, 0x91, 0x99, 0x9b, 0xad, 0xac, 0xac, 0xad, 0xb2, 0xb4, 0xb0, 0xb6, 0xb7, 0xaf, 0xae, 0xab, 0xa9, 0xa7, 0xa3, 0xa3, 0xa6, 0xad, 0x81, 0x69, 0x73, 0x6f, 0x6d, 0x7a, 0x80, 0x7e, 0x7b, 0x7c, 0x7f, 0x95, 0x9b, 0x99, 0xa7, 0xa8, 0x99, 0x8f, 0xb3, 0xc4, 0xc9, 0xc8, 0xb8, 0xbb, 0xba, 0xb6, 0xbf, 0xc2, 0xcb, 0xbf, 0xc2, 0xc9, 0xcf, 0xdf, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf2, 0xa4, 0x8e, 0x9a, 0x99, 0xad, 0xae, 0xab, 0xaf, 0xb4, 0xb3, 0xb2, 0xb8, 0xb7, 0xb1, 0xad, 0xac, 0xaa, 0xa7, 0xa7, 0xa9, 0xa5, 0xb0, 0xa2, 0x73, 0x78, 0x74, 0x73, 0x7d, 0x82, 0x7f, 0x7c, 0x7f, 0x87, 0x9c, 0xa0, 0x9f, 0xa6, 0x9c, 0x8e, 0x9a, 0xc5, 0xc0, 0xca, 0xc7, 0xb9, 0xbc, 0xbd, 0xb8, 0xbb, 0xbe, 0xcd, 0xbf, 0xc3, 0xc7, 0xce, 0xd1, 0xe1, 0xf0, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf2, 0xf9, 0xca, 0x8d, 0x91, 0x9b, 0x99, 0xa8, 0xb2, 0xa9, 0xb2, 0xb3, 0xb3, 0xb4, 0xb9, 0xb6, 0xb1, 0xae, 0xad, 0xa8, 0xa8, 0xa9, 0xae, 0xa5, 0xad, 0xb5, 0x90, 0x78, 0x7f, 0x7d, 0x7c, 0x80, 0x7b, 0x7e, 0x7f, 0x8c, 0x9e, 0xa2, 0xa1, 0x9e, 0x98, 0x92, 0xb7, 0xc6, 0xc0, 0xc9, 0xc7, 0xba, 0xbc, 0xbd, 0xb8, 0xba, 0xba, 0xcc, 0xc2, 0xc1, 0xc5, 0xcc, 0xd0, 0xd0, 0xde, 0xf0, 0xee, 0xef, 0xf0, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf2, 0xf5, 0xe9, 0xa1, 0x8d, 0x93, 0x9b, 0x9b, 0xa2, 0xb5, 0xa9, 0xb5, 0xb3, 0xb2, 0xb6, 0xba, 0xb6, 0xb1, 0xaf, 0xad, 0xa8, 0xaa, 0xac, 0xae, 0xa6, 0xab, 0xb6, 0xae, 0x83, 0x81, 0x86, 0x87, 0x87, 0x84, 0x84, 0x83, 0x8c, 0x9c, 0xa1, 0x9b, 0x98, 0x93, 0xa8, 0xc4, 0xc6, 0xbd, 0xc9, 0xc6, 0xbb, 0xbd, 0xbd, 0xb8, 0xbd, 0xb6, 0xca, 0xc7, 0xbe, 0xc3, 0xc9, 0xcd, 0xd1, 0xd6, 0xec, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf1, 0xf7, 0xbe, 0x96, 0x8c, 0x97, 0x9c, 0x9c, 0x9a, 0xb5, 0xaa, 0xb6, 0xb0, 0xb0, 0xb7, 0xb9, 0xb5, 0xb1, 0xaf, 0xae, 0xa9, 0xac, 0xb0, 0xb0, 0xa9, 0xa9, 0xb6, 0xb5, 0xa5, 0x81, 0x87, 0x8d, 0x91, 0x91, 0x89, 0x85, 0x8b, 0x95, 0x9b, 0x99, 0x95, 0x9d, 0xc0, 0xc2, 0xc8, 0xb9, 0xc8, 0xc4, 0xbb, 0xbe, 0xbc, 0xb7, 0xbe, 0xb4, 0xc6, 0xca, 0xbc, 0xc6, 0xc8, 0xca, 0xd0, 0xd7, 0xe5, 0xf0, 0xee, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf2, 0xf6, 0xe1, 0xa2, 0x97, 0x8a, 0x98, 0x9f, 0x9d, 0x97, 0xae, 0xad, 0xb7, 0xae, 0xaf, 0xb9, 0xb9, 0xb7, 0xb2, 0xb0, 0xad, 0xa9, 0xae, 0xb0, 0xb2, 0xad, 0xa9, 0xb5, 0xb6, 0xb6, 0xa3, 0x89, 0x8e, 0x92, 0x95, 0x8d, 0x85, 0x88, 0x8f, 0x97, 0x97, 0x9b, 0xbc, 0xc1, 0xc3, 0xc5, 0xb9, 0xc5, 0xc1, 0xbc, 0xbd, 0xba, 0xb8, 0xbf, 0xb2, 0xc2, 0xca, 0xbd, 0xc7, 0xc7, 0xc6, 0xd5, 0xd6, 0xda, 0xee, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf2, 0xf6, 0xbe, 0x9f, 0x91, 0x8e, 0x98, 0xa4, 0x9d, 0x99, 0xa5, 0xb0, 0xb8, 0xad, 0xae, 0xbb, 0xb8, 0xb7, 0xb2, 0xb1, 0xab, 0xaa, 0xb0, 0xb2, 0xb2, 0xb0, 0xab, 0xb3, 0xb3, 0xb7, 0xb7, 0xac, 0x98, 0x92, 0x93, 0x8f, 0x86, 0x85, 0x8b, 0x91, 0xa2, 0xbc, 0xc2, 0xbf, 0xc4, 0xc2, 0xb9, 0xc2, 0xbf, 0xbd, 0xbe, 0xb9, 0xb8, 0xbf, 0xb3, 0xbe, 0xcb, 0xbd, 0xc5, 0xc1, 0xc8, 0xd8, 0xd2, 0xd6, 0xe5, 0xf0, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf1, 0xf4, 0xf4, 0xf4, 0xf4, 0xf3, 0xf3, 0xf2, 0xf7, 0xde, 0xa9, 0xa4, 0x8d, 0x91, 0x99, 0xa0, 0x9f, 0x9b, 0x99, 0xb3, 0xb9, 0xac, 0xad, 0xbc, 0xb6, 0xb5, 0xb2, 0xb0, 0xab, 0xab, 0xb1, 0xb3, 0xb3, 0xb0, 0xaa, 0xb6, 0xb2, 0xb3, 0xb9, 0xb7, 0xb7, 0xa9, 0xa0, 0x9a, 0x93, 0x93, 0x9d, 0xb0, 0xc0, 0xc0, 0xc0, 0xbc, 0xc5, 0xbf, 0xb9, 0xbe, 0xbe, 0xbd, 0xbc, 0xb7, 0xba, 0xbd, 0xb6, 0xb8, 0xcb, 0xbf, 0xc2, 0xbb, 0xd0, 0xd3, 0xd0, 0xd6, 0xdc, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf0, 0xf1, 0xf1, 0xf1, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf3, 0xf2, 0xf7, 0xc0, 0xa6, 0xa3, 0x8c, 0x94, 0x9f, 0x99, 0xa1, 0x9f, 0x8d, 0xb4, 0xbb, 0xab, 0xae, 0xbc, 0xb5, 0xb5, 0xb2, 0xb1, 0xab, 0xab, 0xb3, 0xb4, 0xb4, 0xb2, 0xab, 0xb5, 0xb5, 0xad, 0xb7, 0xb8, 0xba, 0xbd, 0xb9, 0xb6, 0xb6, 0xbb, 0xc0, 0xc1, 0xc0, 0xbf, 0xbc, 0xba, 0xc7, 0xbd, 0xb9, 0xba, 0xbc, 0xbc, 0xbc, 0xb7, 0xbb, 0xbb, 0xb9, 0xb4, 0xcc, 0xc0, 0xbb, 0xc0, 0xd4, 0xcc, 0xcf, 0xd5, 0xd8, 0xe8, 0xf0, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf0, 0xf1, 0xf1, 0xf1, 0xf4, 0xf4, 0xf3, 0xf3, 0xf3, 0xf2, 0xf4, 0xeb, 0xaa, 0xa7, 0xa0, 0x8c, 0x98, 0xa3, 0x97, 0x9e, 0xa3, 0x84, 0xb0, 0xbe, 0xa8, 0xaf, 0xbc, 0xb3, 0xb4, 0xb0, 0xb0, 0xaa, 0xad, 0xb3, 0xb4, 0xb3, 0xb5, 0xac, 0xb4, 0xb7, 0xac, 0xaf, 0xb4, 0xb9, 0xba, 0xb9, 0xba, 0xbc, 0xbe, 0xbe, 0xbd, 0xbe, 0xba, 0xba, 0xbc, 0xc4, 0xba, 0xb9, 0xba, 0xbb, 0xbd, 0xbd, 0xb7, 0xbb, 0xbb, 0xbb, 0xb1, 0xcc, 0xc0, 0xb8, 0xc9, 0xcf, 0xcb, 0xce, 0xd0, 0xd7, 0xdf, 0xf0, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf3, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf7, 0xce, 0xa9, 0xa4, 0x9f, 0x8e, 0x9b, 0xa4, 0x9c, 0x99, 0xa7, 0x82, 0xab, 0xbf, 0xa3, 0xb0, 0xba, 0xb1, 0xb4, 0xaf, 0xb1, 0xa8, 0xad, 0xb1, 0xb4, 0xb2, 0xb4, 0xad, 0xb2, 0xb9, 0xb0, 0xac, 0xb2, 0xb4, 0xb7, 0xb0, 0xb3, 0xb9, 0xbc, 0xbb, 0xba, 0xbb, 0xb9, 0xb7, 0xbe, 0xc0, 0xba, 0xb9, 0xba, 0xbc, 0xbd, 0xbe, 0xb7, 0xbc, 0xb9, 0xbb, 0xae, 0xc6, 0xbf, 0xbc, 0xcf, 0xc9, 0xc9, 0xcf, 0xca, 0xd7, 0xd8, 0xec, 0xef, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf3, 0xf2, 0xf2, 0xf2, 0xf1, 0xf2, 0xf2, 0xac, 0xad, 0x9f, 0xa1, 0x91, 0x9f, 0xa2, 0x9e, 0x9b, 0xa1, 0x86, 0xa6, 0xbe, 0x9e, 0xb2, 0xbb, 0xb1, 0xb3, 0xaf, 0xb2, 0xa7, 0xb0, 0xb3, 0xb5, 0xb3, 0xb3, 0xad, 0xb0, 0xb9, 0xb2, 0xac, 0xaf, 0xb4, 0xb8, 0xb6, 0xae, 0xb5, 0xb9, 0xb9, 0xba, 0xb9, 0xba, 0xb6, 0xc0, 0xbd, 0xbb, 0xbb, 0xbc, 0xbc, 0xbd, 0xbe, 0xb8, 0xbd, 0xba, 0xbc, 0xad, 0xc3, 0xbc, 0xc3, 0xca, 0xc8, 0xc7, 0xce, 0xc4, 0xd5, 0xd5, 0xe5, 0xf0, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf2, 0xf2, 0xf2, 0xf2, 0xf1, 0xf6, 0xdc, 0x9f, 0xb1, 0x9c, 0xa2, 0x93, 0xa3, 0xa0, 0x9c, 0xa2, 0x9b, 0x85, 0xa7, 0xbf, 0x9a, 0xb4, 0xb8, 0xaf, 0xb0, 0xb0, 0xb3, 0xa7, 0xb2, 0xb2, 0xb5, 0xb3, 0xb4, 0xb0, 0xae, 0xb8, 0xb3, 0xaf, 0xac, 0xb1, 0xb5, 0xb8, 0xb3, 0xb2, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xb6, 0xc1, 0xbb, 0xba, 0xba, 0xbb, 0xbb, 0xbc, 0xbe, 0xb8, 0xbd, 0xba, 0xbb, 0xac, 0xbf, 0xbe, 0xc7, 0xc6, 0xc6, 0xc8, 0xcf, 0xc0, 0xd3, 0xd6, 0xdd, 0xf0, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf2, 0xf2, 0xf2, 0xf2, 0xf0, 0xf7, 0xba, 0x9f, 0xb3, 0x99, 0x9d, 0x99, 0xa3, 0xa1, 0x99, 0xa5, 0x9c, 0x81, 0xa9, 0xbd, 0x97, 0xb6, 0xb5, 0xaf, 0xad, 0xb2, 0xb2, 0xa7, 0xb4, 0xb4, 0xb4, 0xb3, 0xb3, 0xb2, 0xae, 0xb9, 0xb4, 0xb2, 0xad, 0xaf, 0xb4, 0xb6, 0xb5, 0xb3, 0xb6, 0xb8, 0xb8, 0xb8, 0xb5, 0xb8, 0xc0, 0xba, 0xba, 0xb9, 0xbb, 0xbc, 0xbc, 0xbe, 0xb9, 0xbc, 0xbc, 0xb9, 0xaa, 0xbd, 0xc2, 0xc6, 0xc4, 0xc2, 0xca, 0xce, 0xbc, 0xd0, 0xd8, 0xd6, 0xec, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf2, 0xf1, 0xf1, 0xf0, 0xf3, 0xe7, 0xa3, 0xa4, 0xb2, 0x9a, 0x99, 0x9a, 0xa5, 0xa1, 0x96, 0xa6, 0x9d, 0x82, 0xac, 0xba, 0x94, 0xb8, 0xb2, 0xad, 0xad, 0xb2, 0xaf, 0xa7, 0xb3, 0xb4, 0xb5, 0xb3, 0xb5, 0xb3, 0xab, 0xb9, 0xb4, 0xb3, 0xaf, 0xad, 0xb2, 0xb6, 0xb5, 0xb6, 0xb6, 0xb8, 0xb9, 0xb7, 0xb4, 0xbb, 0xbf, 0xba, 0xba, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xb9, 0xbc, 0xbc, 0xb9, 0xa8, 0xbd, 0xc6, 0xc2, 0xc5, 0xc0, 0xca, 0xcc, 0xbb, 0xcd, 0xd9, 0xd3, 0xe6, 0xf0, 0xee, 0xef, 0xef, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xef, 0xf7, 0xc5, 0xa0, 0xa7, 0xb4, 0x99, 0x9d, 0x93, 0xab, 0xa1, 0x93, 0xa4, 0x9a, 0x80, 0xaf, 0xb3, 0x91, 0xb9, 0xaf, 0xab, 0xad, 0xb2, 0xad, 0xa9, 0xb4, 0xb3, 0xb2, 0xb2, 0xb4, 0xb3, 0xaa, 0xb7, 0xb4, 0xb3, 0xb2, 0xad, 0xae, 0xb4, 0xb5, 0xb6, 0xb6, 0xb7, 0xb8, 0xb6, 0xb4, 0xbe, 0xbe, 0xba, 0xba, 0xba, 0xba, 0xba, 0xbb, 0xbb, 0xb9, 0xbd, 0xbc, 0xba, 0xa8, 0xbe, 0xc8, 0xbd, 0xc5, 0xbe, 0xcb, 0xc8, 0xb9, 0xcc, 0xda, 0xd3, 0xde, 0xf0, 0xee, 0xef, 0xef, 0xee, 0xef, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf1, 0xf2, 0xb2, 0xa4, 0xa8, 0xb6, 0x97, 0xa2, 0x93, 0xa6, 0xad, 0x90, 0xa0, 0x9a, 0x80, 0xb2, 0xac, 0x90, 0xb9, 0xab, 0xa7, 0xac, 0xb2, 0xab, 0xab, 0xb5, 0xb2, 0xb2, 0xb3, 0xb5, 0xb4, 0xab, 0xb5, 0xb5, 0xb3, 0xb3, 0xae, 0xaa, 0xb2, 0xb6, 0xb7, 0xb6, 0xb6, 0xb7, 0xb5, 0xb5, 0xbf, 0xbd, 0xb8, 0xb9, 0xb9, 0xbb, 0xbb, 0xbb, 0xbc, 0xba, 0xbd, 0xbd, 0xba, 0xa6, 0xbf, 0xc7, 0xbd, 0xc3, 0xbd, 0xc9, 0xc3, 0xb9, 0xcb, 0xdb, 0xd4, 0xd7, 0xed, 0xee, 0xee, 0xef, 0xef, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf0, 0xf5, 0xda, 0xa9, 0xac, 0xa5, 0xb9, 0x9a, 0xa0, 0x9e, 0x99, 0xaf, 0x98, 0x99, 0x9b, 0x7d, 0xb2, 0xa5, 0x8d, 0xba, 0xa8, 0xa4, 0xac, 0xb1, 0xa9, 0xac, 0xb3, 0xb2, 0xb1, 0xb4, 0xb5, 0xb5, 0xac, 0xb5, 0xb8, 0xb3, 0xb5, 0xb3, 0xa9, 0xb0, 0xb6, 0xb6, 0xb5, 0xb5, 0xb7, 0xb4, 0xb5, 0xc0, 0xbc, 0xb7, 0xb9, 0xb9, 0xba, 0xba, 0xb9, 0xbc, 0xb9, 0xbc, 0xbd, 0xb9, 0xa6, 0xbe, 0xc2, 0xbe, 0xbf, 0xbf, 0xc5, 0xbe, 0xb8, 0xcb, 0xd9, 0xd7, 0xd4, 0xe7, 0xef, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xef, 0xf7, 0xc2, 0xa0, 0xb6, 0xaa, 0xb9, 0xa0, 0x9a, 0xa6, 0x9a, 0xa1, 0xa3, 0x8f, 0x9c, 0x77, 0xaf, 0x9b, 0x8b, 0xb9, 0xa6, 0xa1, 0xa9, 0xb0, 0xa7, 0xb0, 0xb2, 0xb1, 0xb1, 0xb3, 0xb4, 0xb6, 0xae, 0xb2, 0xb7, 0xb3, 0xb5, 0xb7, 0xab, 0xad, 0xb7, 0xb6, 0xb5, 0xb5, 0xb6, 0xb3, 0xb6, 0xc1, 0xbb, 0xb8, 0xba, 0xba, 0xbc, 0xba, 0xb9, 0xbc, 0xb9, 0xbc, 0xbd, 0xb9, 0xa5, 0xbf, 0xc0, 0xbe, 0xbc, 0xbd, 0xbe, 0xbb, 0xb7, 0xca, 0xd7, 0xd8, 0xd3, 0xdf, 0xef, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf0, 0xf4, 0xbd, 0x96, 0xaf, 0xb3, 0xbc, 0xa8, 0x90, 0xad, 0x9c, 0xa2, 0xa0, 0x92, 0x92, 0x79, 0xac, 0x91, 0x8b, 0xb7, 0xa4, 0x9c, 0xa8, 0xae, 0xa6, 0xb1, 0xb2, 0xb0, 0xb1, 0xb3, 0xb5, 0xb5, 0xaf, 0xb1, 0xb8, 0xb3, 0xb5, 0xb8, 0xab, 0xaa, 0xb6, 0xb7, 0xb5, 0xb5, 0xb6, 0xb3, 0xb8, 0xc1, 0xb9, 0xb8, 0xba, 0xb9, 0xbc, 0xbd, 0xb9, 0xbc, 0xb9, 0xba, 0xbc, 0xb8, 0xa5, 0xbe, 0xbc, 0xbf, 0xb9, 0xb8, 0xba, 0xb9, 0xb8, 0xc5, 0xd6, 0xd9, 0xd4, 0xda, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf1, 0xf0, 0xf0, 0xf0, 0xed, 0xcc, 0xb3, 0xb1, 0xc2, 0xb4, 0x8d, 0xab, 0xa1, 0xa7, 0x9c, 0x99, 0x8b, 0x76, 0xa8, 0x88, 0x8d, 0xb6, 0xa2, 0x97, 0xa7, 0xaa, 0xa8, 0xb0, 0xb0, 0xb0, 0xb2, 0xb2, 0xb3, 0xb4, 0xb1, 0xaf, 0xb8, 0xb3, 0xb3, 0xb6, 0xac, 0xa6, 0xb4, 0xb6, 0xb4, 0xb4, 0xb5, 0xb2, 0xba, 0xc0, 0xb8, 0xb9, 0xbc, 0xb9, 0xbd, 0xc0, 0xbd, 0xbb, 0xba, 0xbd, 0xbc, 0xb7, 0xa6, 0xbd, 0xb8, 0xbc, 0xb3, 0xb7, 0xb7, 0xb8, 0xb8, 0xc4, 0xd5, 0xd8, 0xd5, 0xd8, 0xe8, 0xef, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf6, 0xe7, 0xb7, 0xc0, 0xbd, 0x9d, 0x9d, 0xaf, 0xa4, 0xa3, 0x95, 0x8d, 0x6e, 0xa7, 0x86, 0x8d, 0xb2, 0xa0, 0x98, 0xa8, 0xa7, 0xaa, 0xb2, 0xaf, 0xaf, 0xb1, 0xb1, 0xb3, 0xb3, 0xb1, 0xaf, 0xb8, 0xb3, 0xb4, 0xb5, 0xaf, 0xa2, 0xb3, 0xb5, 0xb3, 0xb2, 0xb5, 0xb2, 0xbb, 0xbe, 0xb6, 0xb9, 0xbb, 0xbb, 0xbd, 0xc0, 0xbf, 0xb9, 0xba, 0xc3, 0xba, 0xb6, 0xa7, 0xbf, 0xb5, 0xb5, 0xb1, 0xb5, 0xb3, 0xb9, 0xb8, 0xc4, 0xd1, 0xd7, 0xd5, 0xd7, 0xe2, 0xef, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xef, 0xef, 0xef, 0xed, 0xf2, 0xde, 0xbd, 0xbd, 0xb0, 0x94, 0xab, 0xa7, 0xa6, 0x96, 0x8e, 0x6d, 0xa5, 0x84, 0x8b, 0xae, 0x9a, 0x96, 0xa6, 0xa4, 0xac, 0xb0, 0xae, 0xae, 0xb0, 0xb1, 0xb2, 0xb3, 0xb2, 0xaf, 0xb7, 0xb5, 0xb5, 0xb5, 0xb2, 0xa0, 0xad, 0xb6, 0xb2, 0xb3, 0xb4, 0xb2, 0xba, 0xbc, 0xb8, 0xbb, 0xbb, 0xbb, 0xbc, 0xc1, 0xbf, 0xb9, 0xb9, 0xcd, 0xbc, 0xb3, 0xa9, 0xbd, 0xae, 0xb0, 0xb0, 0xae, 0xb4, 0xb9, 0xb9, 0xc0, 0xcf, 0xd5, 0xd4, 0xd6, 0xdb, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xf0, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xf1, 0xdb, 0xc1, 0xb4, 0xa7, 0x9e, 0xac, 0xa7, 0x9e, 0x8b, 0x69, 0x9c, 0x7c, 0x8c, 0xac, 0x99, 0x93, 0xa3, 0xa4, 0xac, 0xaf, 0xae, 0xaf, 0xb0, 0xb1, 0xb0, 0xb2, 0xb3, 0xb0, 0xb6, 0xb4, 0xb4, 0xb3, 0xb3, 0xa2, 0xa6, 0xb6, 0xb2, 0xb2, 0xb2, 0xb2, 0xba, 0xba, 0xb7, 0xba, 0xba, 0xba, 0xbb, 0xbf, 0xbd, 0xb9, 0xb7, 0xcd, 0xc9, 0xb1, 0xae, 0xb4, 0xa6, 0xad, 0xad, 0xac, 0xb4, 0xb7, 0xb7, 0xbe, 0xca, 0xd3, 0xd4, 0xd7, 0xd8, 0xe9, 0xef, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xef, 0xef, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xef, 0x9f, 0xaa, 0xa7, 0xa4, 0xab, 0xac, 0xa1, 0x8c, 0x66, 0x92, 0x76, 0x8d, 0xa8, 0x96, 0x93, 0x9f, 0xa2, 0xac, 0xad, 0xad, 0xaf, 0xb0, 0xb0, 0xb1, 0xb2, 0xb3, 0xb0, 0xb5, 0xb4, 0xb2, 0xb3, 0xb0, 0xa4, 0xa2, 0xb4, 0xb2, 0xb2, 0xb1, 0xb2, 0xbb, 0xb8, 0xb7, 0xba, 0xb8, 0xba, 0xbc, 0xbc, 0xbd, 0xb6, 0xba, 0xc1, 0xcb, 0xbc, 0xb3, 0xa2, 0xa5, 0xab, 0xa9, 0xae, 0xb5, 0xb3, 0xb7, 0xbd, 0xc1, 0xcf, 0xd4, 0xd3, 0xd4, 0xe0, 0xef, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xef, 0xe9, 0x6b, 0x7b, 0xac, 0xa5, 0xac, 0xb1, 0xaa, 0x8b, 0x63, 0x8c, 0x74, 0x8b, 0xa5, 0x92, 0x93, 0x9b, 0xa0, 0xac, 0xac, 0xad, 0xae, 0xb0, 0xb0, 0xb0, 0xb1, 0xb3, 0xb1, 0xb3, 0xb5, 0xb3, 0xb4, 0xaf, 0xa4, 0xa0, 0xb0, 0xb1, 0xb0, 0xaf, 0xb2, 0xb7, 0xb7, 0xba, 0xba, 0xb9, 0xba, 0xbc, 0xbb, 0xbf, 0xb4, 0xba, 0xbd, 0xb9, 0xca, 0xa9, 0x92, 0xa7, 0xa8, 0xa8, 0xb2, 0xb1, 0xb2, 0xb6, 0xba, 0xbf, 0xce, 0xd6, 0xd2, 0xd2, 0xdb, 0xec, 0xee, 0xed, 0xee, 0xee, 0xee, 0xee, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xed, 0xf2, 0xdd, 0x62, 0x4e, 0x82, 0xb2, 0xad, 0xb0, 0xb6, 0x99, 0x5f, 0x83, 0x73, 0x89, 0xa3, 0x91, 0x92, 0x97, 0x9e, 0xa8, 0xaa, 0xac, 0xad, 0xaf, 0xae, 0xb0, 0xb2, 0xb1, 0xb1, 0xb3, 0xb6, 0xb4, 0xb2, 0xae, 0xa5, 0x9f, 0xae, 0xb1, 0xb0, 0xaf, 0xb3, 0xb6, 0xb6, 0xb9, 0xb9, 0xb9, 0xbc, 0xbc, 0xb8, 0xbf, 0xb6, 0xb9, 0xbf, 0xaf, 0xc7, 0x9d, 0x91, 0xa6, 0xa4, 0xab, 0xaf, 0xac, 0xb2, 0xb5, 0xba, 0xc3, 0xcf, 0xd6, 0xd0, 0xd3, 0xdb, 0xe8, 0xee, 0xed, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xee, 0xec, 0xf4, 0xca, 0x57, 0x56, 0x4f, 0x7e, 0xb3, 0xb4, 0xb4, 0xab, 0x68, 0x78, 0x72, 0x87, 0x9f, 0x90, 0x8e, 0x93, 0x9e, 0xa5, 0xa7, 0xaa, 0xac, 0xad, 0xad, 0xae, 0xb0, 0xb1, 0xb0, 0xb1, 0xb4, 0xb4, 0xaf, 0xab, 0xa4, 0x9e, 0xac, 0xaf, 0xae, 0xae, 0xb3, 0xb5, 0xb5, 0xb7, 0xba, 0xb9, 0xbd, 0xbb, 0xb8, 0xbf, 0xb5, 0xb9, 0xbf, 0xb1, 0xb2, 0x90, 0x95, 0xa2, 0xa6, 0xaf, 0xaa, 0xae, 0xb2, 0xb6, 0xbd, 0xc7, 0xcd, 0xd2, 0xd0, 0xd5, 0xd9, 0xe2, 0xee, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xee, 0xed, 0xed, 0xed, 0xeb, 0xf6, 0xb5, 0x4e, 0x58, 0x56, 0x4e, 0x70, 0xae, 0xb7, 0xaf, 0x74, 0x72, 0x73, 0x85, 0x9b, 0x91, 0x8d, 0x91, 0x9f, 0xa5, 0xa5, 0xa8, 0xaa, 0xad, 0xad, 0xac, 0xad, 0xaf, 0xb0, 0xb0, 0xb3, 0xb4, 0xaf, 0xa9, 0xa2, 0x9a, 0xa8, 0xae, 0xad, 0xad, 0xb2, 0xb4, 0xb4, 0xb6, 0xb9, 0xbc, 0xbb, 0xbb, 0xb9, 0xc0, 0xb3, 0xb8, 0xbe, 0xad, 0x9f, 0x89, 0x99, 0x9f, 0xaa, 0xaa, 0xa8, 0xaf, 0xb4, 0xb8, 0xbd, 0xc5, 0xcc, 0xd0, 0xd3, 0xd2, 0xd5, 0xe2, 0xee, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed, 0xed }; unsigned int person_male_man_men_len = 9216;
72.47619
100
0.649146
junpuf
740f45d8b87e808b1b2af5c587fd356d4ad772f0
7,903
cpp
C++
editor/editor_path.cpp
LinuxUserGD/godot-opengl-4
6776f665672b86f0566681460a559f4ec25ccc8b
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
15
2020-12-20T19:24:59.000Z
2022-03-25T19:41:12.000Z
editor/editor_path.cpp
LinuxUserGD/godot-opengl-4
6776f665672b86f0566681460a559f4ec25ccc8b
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
2
2021-12-10T04:07:19.000Z
2021-12-27T20:00:03.000Z
editor/editor_path.cpp
LinuxUserGD/godot-opengl-4
6776f665672b86f0566681460a559f4ec25ccc8b
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
1
2022-01-16T14:18:33.000Z
2022-01-16T14:18:33.000Z
/*************************************************************************/ /* editor_path.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "editor_path.h" #include "editor_node.h" #include "editor_scale.h" void EditorPath::_add_children_to_popup(Object *p_obj, int p_depth) { if (p_depth > 8) { return; } List<PropertyInfo> pinfo; p_obj->get_property_list(&pinfo); for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_EDITOR)) { continue; } if (E->get().hint != PROPERTY_HINT_RESOURCE_TYPE) { continue; } Variant value = p_obj->get(E->get().name); if (value.get_type() != Variant::OBJECT) { continue; } Object *obj = value; if (!obj) { continue; } Ref<Texture> icon = EditorNode::get_singleton()->get_object_icon(obj); String proper_name = ""; Vector<String> name_parts = E->get().name.split("/"); for (int i = 0; i < name_parts.size(); i++) { if (i > 0) { proper_name += " > "; } proper_name += name_parts[i].capitalize(); } int index = sub_objects_menu->get_item_count(); sub_objects_menu->add_icon_item(icon, proper_name, objects.size()); sub_objects_menu->set_item_h_offset(index, p_depth * 10 * EDSCALE); objects.push_back(obj->get_instance_id()); _add_children_to_popup(obj, p_depth + 1); } } void EditorPath::_show_popup() { sub_objects_menu->clear(); Size2 size = get_size(); Point2 gp = get_global_position(); gp.y += size.y; sub_objects_menu->set_position(gp); sub_objects_menu->set_size(Size2(size.width, 1)); sub_objects_menu->set_parent_rect(Rect2(Point2(gp - sub_objects_menu->get_position()), size)); sub_objects_menu->popup(); } void EditorPath::_about_to_show() { Object *obj = ObjectDB::get_instance(history->get_path_object(history->get_path_size() - 1)); if (!obj) { return; } objects.clear(); _add_children_to_popup(obj); if (sub_objects_menu->get_item_count() == 0) { sub_objects_menu->add_item(TTR("No sub-resources found.")); sub_objects_menu->set_item_disabled(0, true); } } void EditorPath::update_path() { for (int i = 0; i < history->get_path_size(); i++) { Object *obj = ObjectDB::get_instance(history->get_path_object(i)); if (!obj) { continue; } Ref<Texture> icon = EditorNode::get_singleton()->get_object_icon(obj); if (icon.is_valid()) { current_object_icon->set_texture(icon); } if (i == history->get_path_size() - 1) { String name; if (Object::cast_to<Resource>(obj)) { Resource *r = Object::cast_to<Resource>(obj); if (r->get_path().is_resource_file()) { name = r->get_path().get_file(); } else { name = r->get_name(); } if (name == "") { name = r->get_class(); } } else if (obj->is_class("ScriptEditorDebuggerInspectedObject")) { name = obj->call("get_title"); } else if (Object::cast_to<Node>(obj)) { name = Object::cast_to<Node>(obj)->get_name(); } else if (Object::cast_to<Resource>(obj) && Object::cast_to<Resource>(obj)->get_name() != "") { name = Object::cast_to<Resource>(obj)->get_name(); } else { name = obj->get_class(); } current_object_label->set_text(" " + name); // An extra space so the text is not too close of the icon. set_tooltip(obj->get_class()); } } } void EditorPath::clear_path() { set_disabled(true); set_tooltip(""); current_object_label->set_text(""); current_object_icon->set_texture(nullptr); sub_objects_icon->set_visible(false); } void EditorPath::enable_path() { set_disabled(false); sub_objects_icon->set_visible(true); } void EditorPath::_id_pressed(int p_idx) { ERR_FAIL_INDEX(p_idx, objects.size()); Object *obj = ObjectDB::get_instance(objects[p_idx]); if (!obj) { return; } EditorNode::get_singleton()->push_item(obj); } void EditorPath::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: case NOTIFICATION_THEME_CHANGED: { update_path(); // Button overrides Control's method, so we have to improvise. sub_objects_icon->set_texture(sub_objects_icon->get_icon("select_arrow", "Tree")); current_object_label->add_font_override("font", get_font("main", "EditorFonts")); } break; case NOTIFICATION_READY: { connect("pressed", this, "_show_popup"); } break; } } void EditorPath::_bind_methods() { ClassDB::bind_method("_show_popup", &EditorPath::_show_popup); ClassDB::bind_method("_about_to_show", &EditorPath::_about_to_show); ClassDB::bind_method("_id_pressed", &EditorPath::_id_pressed); } EditorPath::EditorPath(EditorHistory *p_history) { history = p_history; MarginContainer *main_mc = memnew(MarginContainer); main_mc->set_anchors_and_margins_preset(PRESET_WIDE); main_mc->add_constant_override("margin_left", 4 * EDSCALE); main_mc->add_constant_override("margin_right", 6 * EDSCALE); main_mc->set_mouse_filter(MOUSE_FILTER_PASS); add_child(main_mc); HBoxContainer *main_hb = memnew(HBoxContainer); main_mc->add_child(main_hb); current_object_icon = memnew(TextureRect); current_object_icon->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); main_hb->add_child(current_object_icon); current_object_label = memnew(Label); current_object_label->set_clip_text(true); current_object_label->set_align(Label::ALIGN_LEFT); current_object_label->set_h_size_flags(SIZE_EXPAND_FILL); main_hb->add_child(current_object_label); sub_objects_icon = memnew(TextureRect); sub_objects_icon->set_visible(false); sub_objects_icon->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED); main_hb->add_child(sub_objects_icon); sub_objects_menu = memnew(PopupMenu); add_child(sub_objects_menu); sub_objects_menu->connect("about_to_show", this, "_about_to_show"); sub_objects_menu->connect("id_pressed", this, "_id_pressed"); set_tooltip(TTR("Open a list of sub-resources.")); }
33.773504
106
0.634316
LinuxUserGD
7414de68795bdb3bb140493f55051e00808a2b1b
2,263
cpp
C++
tests/chaining.cpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
null
null
null
tests/chaining.cpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
1
2021-07-24T16:29:11.000Z
2021-07-26T20:00:17.000Z
tests/chaining.cpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
null
null
null
/** * Copyright 2021 Robert MacGregor * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <memory> #include "gtest/gtest.h" #include <tribalscript/interpreter.hpp> #include <tribalscript/storedvalue.hpp> #include <tribalscript/libraries/libraries.hpp> #include <tribalscript/executionstate.hpp> TEST(InterpreterTest, Chaining) { TribalScript::Interpreter interpreter; TribalScript::registerAllLibraries(&interpreter); TribalScript::ExecutionState state = TribalScript::ExecutionState(&interpreter); interpreter.execute("cases/chaining.cs", &state); // Check results TribalScript::StoredValue* rootResult = interpreter.getGlobal("result::root"); ASSERT_TRUE(rootResult); ASSERT_EQ(rootResult->toInteger(), 0); TribalScript::StoredValue* aResult = interpreter.getGlobal("result::a"); ASSERT_TRUE(aResult); ASSERT_EQ(aResult->toInteger(), 1); TribalScript::StoredValue* bResult = interpreter.getGlobal("result::b"); ASSERT_TRUE(bResult); ASSERT_EQ(bResult->toInteger(), 2); TribalScript::StoredValue* cResult = interpreter.getGlobal("result::c"); ASSERT_TRUE(cResult); ASSERT_EQ(cResult->toInteger(), 3); } int main() { testing::InitGoogleTest(); return RUN_ALL_TESTS(); }
38.355932
207
0.756518
Ragora
7415d6e5762cdf57c9daf6b7476576d47fb058b9
1,997
cpp
C++
src/kernel/Memory/Paging/PageTableManager.cpp
platinumTypeC/Mapple-os
9e7c0d78d94c8bf43cb349a7bdba335c3dd1ea75
[ "MIT" ]
5
2022-02-02T05:59:53.000Z
2022-03-20T06:01:19.000Z
src/kernel/Memory/Paging/PageTableManager.cpp
platinumTypeC/Mapple-os
9e7c0d78d94c8bf43cb349a7bdba335c3dd1ea75
[ "MIT" ]
1
2022-02-18T17:45:40.000Z
2022-02-20T09:03:48.000Z
src/kernel/Memory/Paging/PageTableManager.cpp
platinumTypeC/Mapple-os
9e7c0d78d94c8bf43cb349a7bdba335c3dd1ea75
[ "MIT" ]
null
null
null
#include <mapple/Gui.h> #include <mapple/Memory.h> #include <mapple/cstr.h> PageTableManager::PageTableManager(PageTable* PML4Address){ this->PML4 = PML4Address; } void PageTableManager::MapMemory(void* virtualMemory, void* physicalMemory){ PageMapIndexer indexer = PageMapIndexer((uint64_t)virtualMemory); PageDirectoryEntry PDE; PDE = PML4->entries[indexer.PDP_i]; PageTable* PDP; if (!PDE.GetFlag(PT_Flag::Present)){ PDP = (PageTable*)GlobalAllocator->RequestPage(); Memset(PDP, 0, 0x1000); PDE.SetAddress((uint64_t)PDP >> 12); PDE.SetFlag(PT_Flag::Present, true); PDE.SetFlag(PT_Flag::ReadWrite, true); PML4->entries[indexer.PDP_i] = PDE; } else { PDP = (PageTable*)((uint64_t)PDE.GetAddress() << 12); } PDE = PDP->entries[indexer.PD_i]; PageTable* PD; if (!PDE.GetFlag(PT_Flag::Present)){ PD = (PageTable*)GlobalAllocator->RequestPage(); Memset(PD, 0, 0x1000); PDE.SetAddress((uint64_t)PD >> 12); PDE.SetFlag(PT_Flag::Present, true); PDE.SetFlag(PT_Flag::ReadWrite, true); PDP->entries[indexer.PD_i] = PDE; } else { PD = (PageTable*)((uint64_t)PDE.GetAddress() << 12); } PDE = PD->entries[indexer.PT_i]; PageTable* PT; if (!PDE.GetFlag(PT_Flag::Present)){ PT = (PageTable*)GlobalAllocator->RequestPage(); Memset(PT, 0, 0x1000); PDE.SetAddress((uint64_t)PT >> 12); PDE.SetFlag(PT_Flag::Present, true); PDE.SetFlag(PT_Flag::ReadWrite, true); PD->entries[indexer.PT_i] = PDE; } else { PT = (PageTable*)((uint64_t)PDE.GetAddress() << 12); } PDE = PT->entries[indexer.P_i]; PDE.SetAddress((uint64_t)physicalMemory >> 12); PDE.SetFlag(PT_Flag::Present, true); PDE.SetFlag(PT_Flag::ReadWrite, true); PT->entries[indexer.P_i] = PDE; }
30.257576
77
0.594392
platinumTypeC
7416f0b7db9a21dff4702a7d15e880e20fc6fee9
2,560
hpp
C++
src/nuclear/src/include/nuclear_bits/dsl/store/TypeCallbackStore.hpp
Bidski/NUClearNet.js
cbca598a4a930de48e05653a58f69fe1652c8793
[ "MIT" ]
null
null
null
src/nuclear/src/include/nuclear_bits/dsl/store/TypeCallbackStore.hpp
Bidski/NUClearNet.js
cbca598a4a930de48e05653a58f69fe1652c8793
[ "MIT" ]
null
null
null
src/nuclear/src/include/nuclear_bits/dsl/store/TypeCallbackStore.hpp
Bidski/NUClearNet.js
cbca598a4a930de48e05653a58f69fe1652c8793
[ "MIT" ]
null
null
null
/* * Copyright (C) 2013 Trent Houliston <trent@houliston.me>, Jake Woods <jake.f.woods@gmail.com> * 2014-2017 Trent Houliston <trent@houliston.me> * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NUCLEAR_DSL_STORE_TYPECALLBACKSTORE_HPP #define NUCLEAR_DSL_STORE_TYPECALLBACKSTORE_HPP #include <memory> #include "nuclear_bits/threading/Reaction.hpp" #include "nuclear_bits/util/TypeList.hpp" namespace NUClear { namespace dsl { namespace store { /** * @biref The main callback store for reactions that are executed when a paticular type is emitted. * * @details This store is the main location that callbacks that are executed on type are stored. * This method of storing is how the system realises compile time message dispatch. By storing each * differnt type of message user in its own location the system knows exactly which reactions to * execuing without having to do an expensive lookup. This reduces the latency and computational * power invovled in spawning a new reaction when a type is emitted. * * @tparam TriggeringType the type that when emitted will start this function */ template <typename TriggeringType> using TypeCallbackStore = util::TypeList<TriggeringType, TriggeringType, std::shared_ptr<threading::Reaction>>; } // namespace store } // namespace dsl } // namespace NUClear #endif // NUCLEAR_DSL_STORE_TYPECALLBACKSTORE_HPP
51.2
120
0.730078
Bidski
74177f6a2e1ceb221424b49344903edbfbe958b5
564
hpp
C++
include/xvega/grammar/marks/mark_square.hpp
domoritz/xvega
3754dee3e7e38e79282ba267cd86c3885807a4cd
[ "BSD-3-Clause" ]
34
2020-08-14T14:32:51.000Z
2022-02-16T23:20:02.000Z
include/xvega/grammar/marks/mark_square.hpp
domoritz/xvega
3754dee3e7e38e79282ba267cd86c3885807a4cd
[ "BSD-3-Clause" ]
19
2020-08-20T20:04:39.000Z
2022-02-28T14:34:37.000Z
include/xvega/grammar/marks/mark_square.hpp
domoritz/xvega
3754dee3e7e38e79282ba267cd86c3885807a4cd
[ "BSD-3-Clause" ]
7
2020-08-14T14:18:17.000Z
2022-02-01T10:59:24.000Z
// Copyright (c) 2020, QuantStack and XVega Contributors // // Distributed under the terms of the BSD 3-Clause License. // // The full license is in the file LICENSE, distributed with this software. #ifndef XVEGA_MARK_SQUARE_HPP #define XVEGA_MARK_SQUARE_HPP #include "../marks.hpp" namespace xv { struct mark_square : public mark<mark_square> { // Square Mark Properties XPROPERTY(xtl::xoptional<double>, mark_square, size); XVEGA_API mark_square(); }; XVEGA_API void to_json(nl::json&, const mark_square&); } #endif
21.692308
75
0.702128
domoritz
741a53ce885c52b501afbaf75eeca7d58746da0c
2,438
cpp
C++
src/engine/core/src/graphics/render_target/render_surface.cpp
mjopenglsdl/halley
68b4bd0845569fa2bafaa72bef3926795f0a6d9b
[ "Apache-2.0" ]
null
null
null
src/engine/core/src/graphics/render_target/render_surface.cpp
mjopenglsdl/halley
68b4bd0845569fa2bafaa72bef3926795f0a6d9b
[ "Apache-2.0" ]
null
null
null
src/engine/core/src/graphics/render_target/render_surface.cpp
mjopenglsdl/halley
68b4bd0845569fa2bafaa72bef3926795f0a6d9b
[ "Apache-2.0" ]
null
null
null
#include "graphics/render_target/render_surface.h" #include "graphics/render_target/render_target_texture.h" #include "graphics/texture.h" #include "graphics/texture_descriptor.h" #include "graphics/material/material.h" #include "graphics/material/material_definition.h" #include "api/video_api.h" #include "graphics/sprite/sprite.h" #include "resources/resources.h" using namespace Halley; RenderSurface::RenderSurface(VideoAPI& video, Resources& resources, const String& materialName, RenderSurfaceOptions options) : video(video) , options(options) { material = std::make_shared<Material>(resources.get<MaterialDefinition>(materialName)); } void RenderSurface::setSize(Vector2i size) { if (size != curRenderSize && size.x > 0 && size.y > 0) { curRenderSize = size; const auto textureSize = Vector2i(nextPowerOf2(size.x), nextPowerOf2(size.y)); if (textureSize != curTextureSize) { curTextureSize = textureSize; std::shared_ptr<Texture> colourTarget = video.createTexture(textureSize); if (!options.name.isEmpty()) { colourTarget->setAssetId(options.name + "_colour0_v" + toString(version)); } auto colourDesc = TextureDescriptor(textureSize, TextureFormat::RGBA); colourDesc.isRenderTarget = true; colourDesc.useFiltering = options.useFiltering; colourTarget->load(std::move(colourDesc)); material->set("tex0", colourTarget); renderTarget = video.createTextureRenderTarget(); renderTarget->setTarget(0, colourTarget); if (options.createDepthStencil) { std::shared_ptr<Texture> depthTarget = video.createTexture(textureSize); if (!options.name.isEmpty()) { depthTarget->setAssetId(options.name + "_depth_v" + toString(version)); } auto depthDesc = TextureDescriptor(textureSize, TextureFormat::DEPTH); depthDesc.isDepthStencil = true; depthTarget->load(std::move(depthDesc)); renderTarget->setDepthTexture(depthTarget); } version++; } renderTarget->setViewPort(Rect4i(Vector2i(), size)); } } bool RenderSurface::isReady() const { return static_cast<bool>(renderTarget); } Sprite RenderSurface::getSurfaceSprite() const { const auto& tex = renderTarget->getTexture(0); return Sprite() .setMaterial(material, false) .setSize(Vector2f(curRenderSize)) .setTexRect(Rect4f(Vector2f(), Vector2f(curRenderSize) / Vector2f(tex->getSize()))); } TextureRenderTarget& RenderSurface::getRenderTarget() const { return *renderTarget; }
31.25641
125
0.747334
mjopenglsdl
741ad11e8c51e6a8065d8247365c4a94e9432777
1,143
hpp
C++
include/universal/functions/factorial.hpp
hypercubestart/universal
a183ae390b5178299a5cbda7b830b7a6cbf332e2
[ "MIT" ]
null
null
null
include/universal/functions/factorial.hpp
hypercubestart/universal
a183ae390b5178299a5cbda7b830b7a6cbf332e2
[ "MIT" ]
null
null
null
include/universal/functions/factorial.hpp
hypercubestart/universal
a183ae390b5178299a5cbda7b830b7a6cbf332e2
[ "MIT" ]
null
null
null
#pragma once // factorial.hpp: definition of recursive and iterative factorial functions // // Copyright (C) 2017-2020 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. namespace sw { namespace function { // these factorials can take a Real type and thus could have a very funky behavior // TODO: do we ceil that incoming argument or test on integer properties? // factorial implemented using recursion. Should yield reasonable results even for Real types // as left-to-right evaluation starts with the smallest values first. template<typename Scalar> Scalar factorial(const Scalar& n) { assert(n >= Scalar(0)); Scalar n_minus_one = n - Scalar(1);// the boost types don't accept factorial(n - 1), so this is the work-around return (n == Scalar(0) || n == Scalar(1)) ? Scalar(1) : factorial(n_minus_one) * n; } // factorial through iteration template<typename Scalar> Scalar factoriali(const Scalar& n) { Scalar v = Scalar(1); for (Scalar i = Scalar(2); i <= n; ++i) { v *= i; } return v; } } // namespace function } // namespace sw
31.75
112
0.72091
hypercubestart
741e2dabfc8520e68da5e6a563fba1de5b5c38c5
5,337
hpp
C++
examples/pico_audio/synth.hpp
Idirianuk/pimoroni-pico
c6ebed06a55f08d546a1d2d7f28f449efb703c3d
[ "MIT" ]
425
2021-01-21T10:20:27.000Z
2022-03-30T13:07:35.000Z
examples/pico_audio/synth.hpp
Idirianuk/pimoroni-pico
c6ebed06a55f08d546a1d2d7f28f449efb703c3d
[ "MIT" ]
220
2021-01-22T11:27:57.000Z
2022-03-31T23:07:58.000Z
examples/pico_audio/synth.hpp
Idirianuk/pimoroni-pico
c6ebed06a55f08d546a1d2d7f28f449efb703c3d
[ "MIT" ]
174
2021-01-22T22:41:00.000Z
2022-03-28T13:09:32.000Z
#pragma once #include <cstdint> namespace synth { // The duration a note is played is determined by the amount of attack, // decay, and release, combined with the length of the note as defined by // the user. // // - Attack: number of milliseconds it takes for a note to hit full volume // - Decay: number of milliseconds it takes for a note to settle to sustain volume // - Sustain: percentage of full volume that the note sustains at (duration implied by other factors) // - Release: number of milliseconds it takes for a note to reduce to zero volume after it has ended // // Attack (750ms) - Decay (500ms) -------- Sustain ----- Release (250ms) // // + + + + // | | | | // | | | | // | | | | // v v v v // 0ms 1000ms 2000ms 3000ms 4000ms // // | XXXX | | | | // | X X|XX | | | // | X | XXX | | | // | X | XXXXXXXXXXXXXX|XXXXXXXXXXXXXXXXXXX| | // | X | | |X | // | X | | |X | // | X | | | X | // | X | | | X | // | X | | | X | // | X | | | X | // | X | | | X | // | X | | | X | // | X + + + | + + + | + + + | + + + | + // | X | | | | | | | | | | | | | | | | | // |X | | | | | | | | | | | | | | | | | // +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+---> #define CHANNEL_COUNT 8 constexpr float pi = 3.14159265358979323846f; const uint32_t sample_rate = 44100; extern uint16_t volume; enum Waveform { NOISE = 128, SQUARE = 64, SAW = 32, TRIANGLE = 16, SINE = 8, WAVE = 1 }; enum class ADSRPhase : uint8_t { ATTACK, DECAY, SUSTAIN, RELEASE, OFF }; struct AudioChannel { uint8_t waveforms = 0; // bitmask for enabled waveforms (see AudioWaveform enum for values) uint16_t frequency = 660; // frequency of the voice (Hz) uint16_t volume = 0xffff; // channel volume (default 50%) uint16_t attack_ms = 2; // attack period uint16_t decay_ms = 6; // decay period uint16_t sustain = 0xffff; // sustain volume uint16_t release_ms = 1; // release period uint16_t pulse_width = 0x7fff; // duty cycle of square wave (default 50%) int16_t noise = 0; // current noise value uint32_t waveform_offset = 0; // voice offset (Q8) int32_t filter_last_sample = 0; bool filter_enable = false; uint16_t filter_cutoff_frequency = 0; uint32_t adsr_frame = 0; // number of frames into the current ADSR phase uint32_t adsr_end_frame = 0; // frame target at which the ADSR changes to the next phase uint32_t adsr = 0; int32_t adsr_step = 0; ADSRPhase adsr_phase = ADSRPhase::OFF; uint8_t wave_buf_pos = 0; // int16_t wave_buffer[64]; // buffer for arbitrary waveforms. small as it's filled by user callback void *user_data = nullptr; void (*wave_buffer_callback)(AudioChannel &channel); void trigger_attack() { adsr_frame = 0; adsr_phase = ADSRPhase::ATTACK; adsr_end_frame = (attack_ms * sample_rate) / 1000; adsr_step = (int32_t(0xffffff) - int32_t(adsr)) / int32_t(adsr_end_frame); } void trigger_decay() { adsr_frame = 0; adsr_phase = ADSRPhase::DECAY; adsr_end_frame = (decay_ms * sample_rate) / 1000; adsr_step = (int32_t(sustain << 8) - int32_t(adsr)) / int32_t(adsr_end_frame); } void trigger_sustain() { adsr_frame = 0; adsr_phase = ADSRPhase::SUSTAIN; adsr_end_frame = 0; adsr_step = 0; } void trigger_release() { adsr_frame = 0; adsr_phase = ADSRPhase::RELEASE; adsr_end_frame = (release_ms * sample_rate) / 1000; adsr_step = (int32_t(0) - int32_t(adsr)) / int32_t(adsr_end_frame); } void off() { adsr_frame = 0; adsr_phase = ADSRPhase::OFF; adsr_step = 0; } }; extern AudioChannel channels[CHANNEL_COUNT]; int16_t get_audio_frame(); bool is_audio_playing(); }
40.12782
110
0.426082
Idirianuk
741fd13df719175f10895e5d4cb640137c493fee
3,457
cc
C++
TutorialMaterials/P04_PhysicsLists/source/src/Geometry.cc
hmdyt/Geant4Tutorial
cf6dea24a983a80b1994f3ca82fab5e7bb27f03c
[ "MIT" ]
2
2020-07-08T12:54:10.000Z
2021-07-21T02:37:02.000Z
2017.11/P04_PhysicsLists/source/src/Geometry.cc
koichi-murakami/g4tutorial
32ab20ef072c07c14d893f52712cf02a3dcc5e83
[ "BSD-2-Clause" ]
null
null
null
2017.11/P04_PhysicsLists/source/src/Geometry.cc
koichi-murakami/g4tutorial
32ab20ef072c07c14d893f52712cf02a3dcc5e83
[ "BSD-2-Clause" ]
1
2019-12-27T06:48:15.000Z
2019-12-27T06:48:15.000Z
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Geometry.cc //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #include "Geometry.hh" #include "G4Box.hh" #include "G4Tubs.hh" #include "G4LogicalVolume.hh" #include "G4PVPlacement.hh" #include "G4VPhysicalVolume.hh" #include "G4ThreeVector.hh" #include "G4RotationMatrix.hh" #include "G4Transform3D.hh" #include "G4NistManager.hh" #include "G4VisAttributes.hh" #include "G4SystemOfUnits.hh" //------------------------------------------------------------------------------ Geometry::Geometry() {} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ Geometry::~Geometry() {} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ G4VPhysicalVolume* Geometry::Construct() //------------------------------------------------------------------------------ { return ConstructDetector(); } //------------------------------------------------------------------------------ G4VPhysicalVolume* Geometry::ConstructDetector() //------------------------------------------------------------------------------ { // Get pointer to 'Material Manager' G4NistManager* materi_Man = G4NistManager::Instance(); // Define 'World Volume' // Define the shape of solid G4double leng_X_World = 2.0*m; // X-full-length of world G4double leng_Y_World = 2.0*m; // Y-full-length of world G4double leng_Z_World = 2.0*m; // Z-full-length of world G4Box* solid_World = new G4Box("Solid_World", leng_X_World/2.0, leng_Y_World/2.0, leng_Z_World/2.0); // Define logical volume G4Material* materi_World = materi_Man->FindOrBuildMaterial("G4_AIR"); G4LogicalVolume* logVol_World = new G4LogicalVolume(solid_World, materi_World, "LogVol_World"); logVol_World->SetVisAttributes (G4VisAttributes::Invisible); // Placement of logical volume G4int copyNum_World = 0; // Set ID number of world G4PVPlacement* physVol_World = new G4PVPlacement(G4Transform3D(), "PhysVol_World", logVol_World, 0, false, copyNum_World); // Define 'BGO Detector' // Define the shape of solid G4double radius_BGO = 2.5*cm; G4double leng_Z_BGO = 2.5*cm; G4Tubs* solid_BGO = new G4Tubs("Solid_BGO", 0., radius_BGO, leng_Z_BGO/2.0, 0., 360.*deg); // Define logical volume G4Material* materi_BGO = materi_Man->FindOrBuildMaterial("G4_BGO"); G4LogicalVolume* logVol_BGO = new G4LogicalVolume( solid_BGO, materi_BGO, "LogVol_BGO", 0, 0, 0 ); // Placement of logical volume G4double pos_X_LogV = 0.0*cm; // X-location LogV G4double pos_Y_LogV = 0.0*cm; // Y-location LogV G4double pos_Z_LogV = 0.0*cm; // Z-location LogV G4ThreeVector threeVect_LogV = G4ThreeVector(pos_X_LogV, pos_Y_LogV, pos_Z_LogV); G4RotationMatrix rotMtrx_LogV = G4RotationMatrix(); G4Transform3D trans3D_LogV = G4Transform3D(rotMtrx_LogV, threeVect_LogV); G4int copyNum_LogV = 1000; // Set ID number of LogV new G4PVPlacement(trans3D_LogV, "PhysVol_BGO", logVol_BGO, physVol_World, false, copyNum_LogV); // Return the physical world return physVol_World; }
40.670588
94
0.530518
hmdyt
74240a0ec00217c3d4a7f59edf3abd47eb91065b
2,781
cpp
C++
core/fpdfdoc/cpvt_fontmap.cpp
WarGloom/pdfium
e9a79aa2ef7d63aa8e1b2716d25725cf280f199f
[ "Apache-2.0" ]
7
2018-05-17T22:53:33.000Z
2022-02-05T15:51:41.000Z
core/fpdfdoc/cpvt_fontmap.cpp
WarGloom/pdfium
e9a79aa2ef7d63aa8e1b2716d25725cf280f199f
[ "Apache-2.0" ]
null
null
null
core/fpdfdoc/cpvt_fontmap.cpp
WarGloom/pdfium
e9a79aa2ef7d63aa8e1b2716d25725cf280f199f
[ "Apache-2.0" ]
3
2018-05-17T22:53:42.000Z
2022-01-18T05:53:34.000Z
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "core/fpdfdoc/cpvt_fontmap.h" #include <utility> #include "core/fpdfapi/font/cpdf_font.h" #include "core/fpdfapi/parser/cpdf_dictionary.h" #include "core/fpdfapi/parser/cpdf_document.h" #include "core/fpdfapi/parser/cpdf_reference.h" #include "core/fpdfapi/parser/fpdf_parser_utility.h" #include "core/fpdfdoc/cpdf_interactiveform.h" #include "core/fxcrt/fx_codepage.h" #include "third_party/base/check.h" #include "third_party/base/notreached.h" CPVT_FontMap::CPVT_FontMap(CPDF_Document* pDoc, CPDF_Dictionary* pResDict, const RetainPtr<CPDF_Font>& pDefFont, const ByteString& sDefFontAlias) : m_pDocument(pDoc), m_pResDict(pResDict), m_pDefFont(pDefFont), m_sDefFontAlias(sDefFontAlias) {} CPVT_FontMap::~CPVT_FontMap() = default; void CPVT_FontMap::SetupAnnotSysPDFFont() { if (!m_pDocument || !m_pResDict) return; RetainPtr<CPDF_Font> pPDFFont = CPDF_InteractiveForm::AddNativeInteractiveFormFont(m_pDocument.Get(), &m_sSysFontAlias); if (!pPDFFont) return; CPDF_Dictionary* pFontList = m_pResDict->GetDictFor("Font"); if (ValidateFontResourceDict(pFontList) && !pFontList->KeyExist(m_sSysFontAlias)) { pFontList->SetNewFor<CPDF_Reference>(m_sSysFontAlias, m_pDocument.Get(), pPDFFont->GetFontDict()->GetObjNum()); } m_pSysFont = std::move(pPDFFont); } RetainPtr<CPDF_Font> CPVT_FontMap::GetPDFFont(int32_t nFontIndex) { switch (nFontIndex) { case 0: return m_pDefFont; case 1: if (!m_pSysFont) SetupAnnotSysPDFFont(); return m_pSysFont; default: return nullptr; } } ByteString CPVT_FontMap::GetPDFFontAlias(int32_t nFontIndex) { switch (nFontIndex) { case 0: return m_sDefFontAlias; case 1: if (!m_pSysFont) SetupAnnotSysPDFFont(); return m_sSysFontAlias; default: return ByteString(); } } int32_t CPVT_FontMap::GetWordFontIndex(uint16_t word, FX_Charset charset, int32_t nFontIndex) { NOTREACHED(); return 0; } int32_t CPVT_FontMap::CharCodeFromUnicode(int32_t nFontIndex, uint16_t word) { NOTREACHED(); return 0; } FX_Charset CPVT_FontMap::CharSetFromUnicode(uint16_t word, FX_Charset nOldCharset) { NOTREACHED(); return FX_Charset::kANSI; }
29.585106
80
0.656598
WarGloom
742495068bce0587eb8b8525ea66ad704270e149
15,373
cc
C++
test/extensions/filters/http/wasm/wasm_filter_test.cc
kyessenov/envoy-wasm
1025deebb9d330501738b882da48a4152e3ab2e0
[ "Apache-2.0" ]
null
null
null
test/extensions/filters/http/wasm/wasm_filter_test.cc
kyessenov/envoy-wasm
1025deebb9d330501738b882da48a4152e3ab2e0
[ "Apache-2.0" ]
null
null
null
test/extensions/filters/http/wasm/wasm_filter_test.cc
kyessenov/envoy-wasm
1025deebb9d330501738b882da48a4152e3ab2e0
[ "Apache-2.0" ]
1
2019-10-05T18:14:00.000Z
2019-10-05T18:14:00.000Z
#include <stdio.h> #include "common/buffer/buffer_impl.h" #include "common/http/message_impl.h" #include "common/stats/isolated_store_impl.h" #include "common/stream_info/stream_info_impl.h" #include "extensions/common/wasm/wasm.h" #include "extensions/filters/http/wasm/wasm_filter.h" #include "test/mocks/grpc/mocks.h" #include "test/mocks/http/mocks.h" #include "test/mocks/network/mocks.h" #include "test/mocks/server/mocks.h" #include "test/mocks/ssl/mocks.h" #include "test/mocks/stream_info/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/printers.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::_; using testing::AtLeast; using testing::Eq; using testing::InSequence; using testing::Invoke; using testing::Return; using testing::ReturnPointee; using testing::ReturnRef; MATCHER_P(MapEq, rhs, "") { const Envoy::ProtobufWkt::Struct& obj = arg; EXPECT_TRUE(rhs.size() > 0); for (auto const& entry : rhs) { EXPECT_EQ(obj.fields().at(entry.first).string_value(), entry.second); } return true; } namespace Envoy { namespace Extensions { namespace HttpFilters { namespace Wasm { class TestFilter : public Envoy::Extensions::Common::Wasm::Context { public: TestFilter(Wasm* wasm) : Envoy::Extensions::Common::Wasm::Context(wasm) {} MOCK_METHOD2(scriptLog, void(spdlog::level::level_enum level, absl::string_view message)); }; class WasmHttpFilterTest : public testing::TestWithParam<std::string> { public: WasmHttpFilterTest() {} ~WasmHttpFilterTest() {} void setupConfig(const std::string& code) { envoy::config::filter::http::wasm::v2::Wasm proto_config; proto_config.mutable_vm_config()->set_vm(absl::StrCat("envoy.wasm.vm.", GetParam())); proto_config.mutable_vm_config()->mutable_code()->set_inline_bytes(code); Api::ApiPtr api = Api::createApiForTest(stats_store_); scope_ = Stats::ScopeSharedPtr(stats_store_.createScope("wasm.")); wasm_ = Extensions::Common::Wasm::createWasm(proto_config.id(), proto_config.vm_config(), cluster_manager_, dispatcher_, *api, *scope_, local_info_); } void setupNullConfig(const std::string& name) { envoy::config::filter::http::wasm::v2::Wasm proto_config; proto_config.mutable_vm_config()->set_vm("envoy.wasm.vm.null"); proto_config.mutable_vm_config()->mutable_code()->set_inline_bytes(name); Api::ApiPtr api = Api::createApiForTest(stats_store_); scope_ = Stats::ScopeSharedPtr(stats_store_.createScope("wasm.")); wasm_ = Extensions::Common::Wasm::createWasm(proto_config.id(), proto_config.vm_config(), cluster_manager_, dispatcher_, *api, *scope_, local_info_); } void setupFilter() { filter_ = std::make_shared<TestFilter>(wasm_.get()); filter_->setDecoderFilterCallbacks(decoder_callbacks_); filter_->setEncoderFilterCallbacks(encoder_callbacks_); wasm_->setGeneralContext( std::static_pointer_cast<Envoy::Extensions::Common::Wasm::Context>(filter_)); } Stats::IsolatedStoreImpl stats_store_; Stats::ScopeSharedPtr scope_; NiceMock<ThreadLocal::MockInstance> tls_; NiceMock<Event::MockDispatcher> dispatcher_; Upstream::MockClusterManager cluster_manager_; std::shared_ptr<Wasm> wasm_; std::shared_ptr<TestFilter> filter_; NiceMock<Envoy::Ssl::MockConnectionInfo> ssl_; NiceMock<Envoy::Network::MockConnection> connection_; NiceMock<Http::MockStreamDecoderFilterCallbacks> decoder_callbacks_; NiceMock<Http::MockStreamEncoderFilterCallbacks> encoder_callbacks_; NiceMock<Envoy::StreamInfo::MockStreamInfo> request_stream_info_; NiceMock<LocalInfo::MockLocalInfo> local_info_; }; INSTANTIATE_TEST_SUITE_P(Runtimes, WasmHttpFilterTest, testing::Values("wavm", "v8")); // Bad code in initial config. TEST_P(WasmHttpFilterTest, BadCode) { EXPECT_THROW_WITH_MESSAGE(setupConfig("bad code"), Common::Wasm::WasmException, "Failed to initialize WASM code from <inline>"); } // Script touching headers only, request that is headers only. TEST_P(WasmHttpFilterTest, HeadersOnlyRequestHeadersOnly) { setupConfig(TestEnvironment::readFileToStringForTest(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/filters/http/wasm/test_data/headers_cpp.wasm"))); setupFilter(); EXPECT_CALL(*filter_, scriptLog(spdlog::level::debug, Eq(absl::string_view("onRequestHeaders 1")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::info, Eq(absl::string_view("header path /")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::warn, Eq(absl::string_view("onDone 1")))); wasm_->start(); Http::TestHeaderMapImpl request_headers{{":path", "/"}, {"server", "envoy"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true)); EXPECT_THAT(request_headers.get_("newheader"), Eq("newheadervalue")); EXPECT_THAT(request_headers.get_("server"), Eq("envoy-wasm")); filter_->onDestroy(); } // Script touching headers only, request that is headers only. TEST_P(WasmHttpFilterTest, HeadersOnlyRequestHeadersAndBody) { setupConfig(TestEnvironment::readFileToStringForTest(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/filters/http/wasm/test_data/headers_cpp.wasm"))); setupFilter(); EXPECT_CALL(*filter_, scriptLog(spdlog::level::debug, Eq(absl::string_view("onRequestHeaders 1")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::info, Eq(absl::string_view("header path /")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::err, Eq(absl::string_view("onRequestBody hello")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::warn, Eq(absl::string_view("onDone 1")))); wasm_->start(); Http::TestHeaderMapImpl request_headers{{":path", "/"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true)); Buffer::OwnedImpl data("hello"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(data, true)); filter_->onDestroy(); } // Script testing AccessLog::Instance::log. TEST_P(WasmHttpFilterTest, AccessLog) { setupConfig(TestEnvironment::readFileToStringForTest(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/filters/http/wasm/test_data/headers_cpp.wasm"))); setupFilter(); EXPECT_CALL(*filter_, scriptLog(spdlog::level::debug, Eq(absl::string_view("onRequestHeaders 1")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::info, Eq(absl::string_view("header path /")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::err, Eq(absl::string_view("onRequestBody hello")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::warn, Eq(absl::string_view("onLog 1 /")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::warn, Eq(absl::string_view("onDone 1")))); wasm_->start(); Http::TestHeaderMapImpl request_headers{{":path", "/"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true)); Buffer::OwnedImpl data("hello"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(data, true)); filter_->onDestroy(); StreamInfo::MockStreamInfo log_stream_info; filter_->log(&request_headers, nullptr, nullptr, log_stream_info); } TEST_P(WasmHttpFilterTest, AsyncCall) { setupConfig(TestEnvironment::readFileToStringForTest(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/filters/http/wasm/test_data/async_call_cpp.wasm"))); setupFilter(); wasm_->start(); Http::TestHeaderMapImpl request_headers{{":path", "/"}}; Http::MockAsyncClientRequest request(&cluster_manager_.async_client_); Http::AsyncClient::Callbacks* callbacks = nullptr; EXPECT_CALL(cluster_manager_, get("cluster")); EXPECT_CALL(cluster_manager_, httpAsyncClientForCluster("cluster")); EXPECT_CALL(cluster_manager_.async_client_, send_(_, _, _)) .WillOnce( Invoke([&](Http::MessagePtr& message, Http::AsyncClient::Callbacks& cb, const Http::AsyncClient::RequestOptions&) -> Http::AsyncClient::Request* { EXPECT_EQ((Http::TestHeaderMapImpl{{":method", "POST"}, {":path", "/"}, {":authority", "foo"}, {"content-length", "11"}}), message->headers()); EXPECT_EQ((Http::TestHeaderMapImpl{{"trail", "cow"}}), *message->trailers()); callbacks = &cb; return &request; })); EXPECT_CALL(*filter_, scriptLog(spdlog::level::debug, Eq("response"))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::info, Eq(":status -> 200"))); EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers, false)); Http::MessagePtr response_message(new Http::ResponseMessageImpl( Http::HeaderMapPtr{new Http::TestHeaderMapImpl{{":status", "200"}}})); response_message->body().reset(new Buffer::OwnedImpl("response")); EXPECT_NE(callbacks, nullptr); if (callbacks) { callbacks->onSuccess(std::move(response_message)); } } TEST_P(WasmHttpFilterTest, GrpcCall) { setupConfig(TestEnvironment::readFileToStringForTest(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/filters/http/wasm/test_data/grpc_call_cpp.wasm"))); setupFilter(); wasm_->start(); Grpc::MockAsyncRequest request; Grpc::RawAsyncRequestCallbacks* callbacks = nullptr; Grpc::MockAsyncClientManager client_manager; auto client_factory = std::make_unique<Grpc::MockAsyncClientFactory>(); auto async_client = std::make_unique<Grpc::MockAsyncClient>(); Tracing::Span* parent_span{}; EXPECT_CALL(*async_client, sendRaw_(_, _, _, _, _, _)) .WillOnce(Invoke( [&](absl::string_view service_full_name, absl::string_view method_name, Buffer::Instance& message, Grpc::RawAsyncRequestCallbacks& cb, Tracing::Span& span, const absl::optional<std::chrono::milliseconds>& timeout) -> Grpc::AsyncRequest* { EXPECT_EQ(service_full_name, "service"); EXPECT_EQ(method_name, "method"); ProtobufWkt::Value value; EXPECT_TRUE( value.ParseFromArray(message.linearize(message.length()), message.length())); EXPECT_EQ(value.string_value(), "request"); callbacks = &cb; parent_span = &span; EXPECT_EQ(timeout->count(), 1000); return &request; })); EXPECT_CALL(*client_factory, create).WillOnce(Invoke([&]() -> Grpc::AsyncClientPtr { return std::move(async_client); })); EXPECT_CALL(cluster_manager_, grpcAsyncClientManager()) .WillOnce(Invoke([&]() -> Grpc::AsyncClientManager& { return client_manager; })); EXPECT_CALL(client_manager, factoryForGrpcService(_, _, _)) .WillOnce( Invoke([&](const envoy::api::v2::core::GrpcService&, Stats::Scope&, bool) -> Grpc::AsyncClientFactoryPtr { return std::move(client_factory); })); EXPECT_CALL(*filter_, scriptLog(spdlog::level::debug, Eq("response"))); Http::TestHeaderMapImpl request_headers{{":path", "/"}}; EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers, false)); ProtobufWkt::Value value; value.set_string_value("response"); std::string response_string; EXPECT_TRUE(value.SerializeToString(&response_string)); auto response = std::make_unique<Buffer::OwnedImpl>(response_string); EXPECT_NE(callbacks, nullptr); NiceMock<Tracing::MockSpan> span; if (callbacks) { callbacks->onSuccessRaw(std::move(response), span); } } TEST_P(WasmHttpFilterTest, Metadata) { setupConfig(TestEnvironment::readFileToStringForTest(TestEnvironment::substitute( "{{ test_rundir }}/test/extensions/filters/http/wasm/test_data/metadata_cpp.wasm"))); setupFilter(); envoy::api::v2::core::Node node_data; ProtobufWkt::Value node_val; node_val.set_string_value("wasm_node_get_value"); (*node_data.mutable_metadata()->mutable_fields())["wasm_node_get_key"] = node_val; EXPECT_CALL(local_info_, node()).WillOnce(ReturnRef(node_data)); EXPECT_CALL(*filter_, scriptLog(spdlog::level::debug, Eq(absl::string_view("onRequestHeaders 1 wasm_request_get_value")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::info, Eq(absl::string_view("header path /")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::err, Eq(absl::string_view("onRequestBody wasm_node_get_value")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::warn, Eq(absl::string_view("onLog 1 /")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::warn, Eq(absl::string_view("onDone 1")))); EXPECT_CALL( *filter_, scriptLog(spdlog::level::trace, Eq(absl::string_view("Struct wasm_request_get_value wasm_request_get_value")))); request_stream_info_.metadata_.mutable_filter_metadata()->insert( Protobuf::MapPair<std::string, ProtobufWkt::Struct>( HttpFilters::HttpFilterNames::get().Wasm, MessageUtil::keyValueStruct("wasm_request_get_key", "wasm_request_get_value"))); EXPECT_CALL(decoder_callbacks_, streamInfo()).WillRepeatedly(ReturnRef(request_stream_info_)); std::string serialized_value; ProtobufWkt::Value value; value.set_string_value("wasm_request_set_value"); EXPECT_TRUE(value.SerializeToString(&serialized_value)); EXPECT_CALL(request_stream_info_, setDynamicMetadata(HttpFilters::HttpFilterNames::get().Wasm, MapEq(std::map<std::string, std::string>{ {"wasm_request_set_key", serialized_value}}))); wasm_->start(); Http::TestHeaderMapImpl request_headers{{":path", "/"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true)); Buffer::OwnedImpl data("hello"); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(data, true)); filter_->onDestroy(); StreamInfo::MockStreamInfo log_stream_info; filter_->log(&request_headers, nullptr, nullptr, log_stream_info); } // Null VM Plugin, headers only. TEST_F(WasmHttpFilterTest, NullVmPluginRequestHeadersOnly) { setupNullConfig("null_vm_plugin"); setupFilter(); EXPECT_CALL(*filter_, scriptLog(spdlog::level::debug, Eq(absl::string_view("onRequestHeaders 1")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::info, Eq(absl::string_view("header path /")))); EXPECT_CALL(*filter_, scriptLog(spdlog::level::warn, Eq(absl::string_view("onDone 1")))); wasm_->start(); Http::TestHeaderMapImpl request_headers{{":path", "/"}, {"server", "envoy"}}; EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, true)); EXPECT_THAT(request_headers.get_("newheader"), Eq("newheadervalue")); EXPECT_THAT(request_headers.get_("server"), Eq("envoy-wasm")); filter_->onDestroy(); } } // namespace Wasm } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
46.165165
98
0.70162
kyessenov
7424c1e3d027bc287e177274399a1e46e3993e35
33,880
cpp
C++
opencv110/highgui/src/unsupport/cvcap_dc1394.cpp
hjhsggy/opencv
9b8cc736623c61667df81a48f93b665fa8a4c88d
[ "BSD-3-Clause" ]
106
2015-01-15T10:13:18.000Z
2021-11-10T01:39:07.000Z
otherlibs/highgui/cvcap_dc1394.cpp
anoopmenon/opencv-perl
b52785caee9f8967a4f2ead9c7b436056ffa830c
[ "BSD-3-Clause" ]
5
2015-02-05T17:43:12.000Z
2017-01-04T08:34:39.000Z
otherlibs/highgui/cvcap_dc1394.cpp
anoopmenon/opencv-perl
b52785caee9f8967a4f2ead9c7b436056ffa830c
[ "BSD-3-Clause" ]
24
2015-04-29T01:30:37.000Z
2020-07-24T15:50:05.000Z
/* This is the contributed code: Firewire and video4linux camera support for highgui 2003-03-12 Magnus Lundin lundin@mlu.mine.nu THIS EXEPERIMENTAL CODE Tested on 2.4.19 with 1394, video1394, v4l, dc1394 and raw1394 support This set of files adds support for firevre and usb cameras. First it tries to install a firewire camera, if that fails it tries a v4l/USB camera It has been tested with the motempl sample program INSTALLATION Install OpenCV Install v4l Install dc1394 raw1394 - coriander should work with your camera Backup highgui folder Copy new files cd into highgui folder make clean (cvcap.cpp must be rebuilt) make make install The build is controlled by the following entries in the highgui Makefile: libhighgui_la_LIBADD = -L/usr/X11R6/lib -lXm -lMrm -lUil -lpng -ljpeg -lz -ltiff -lavcodec -lraw1394 -ldc1394_control DEFS = -DHAVE_CONFIG_H -DHAVE_DC1394 HAVE_CAMV4L Now it should be possible to use highgui camera functions, works for me. THINGS TO DO Better ways to select 1394 or v4l camera Better support for videosize Format7 Comments and changes welcome /Magnus 2005-10-19 Roman Stanchak rstanchak@yahoo.com Support added for setting MODE and other DC1394 properties. Also added CONVERT_RGB flag which indicates whether or not color conversion is performed in cvRetrieveFrame. The default for CONVERT_RGB=1 for backward compatibility. Tested with 2.6.12 with libdc1394-1.0.0, libraw1394-0.10.1 using a Point Grey Flea */ /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "_highgui.h" #if !defined WIN32 && defined HAVE_DC1394 #include <unistd.h> #include <stdint.h> #include <libraw1394/raw1394.h> #include <libdc1394/dc1394_control.h> #ifdef NDEBUG #define CV_WARN(message) #else #define CV_WARN(message) fprintf(stderr, "warning: %s (%s:%d)\n", message, __FILE__, __LINE__) #endif #define CV_DC1394_CALL(expr) \ if((expr)<0){ \ OPENCV_ERROR(CV_StsInternal, "", "libdc1394 function call returned < 0"); \ } #define DELAY 50000 // bpp for 16-bits cameras... this value works for PtGrey DragonFly... #define MONO16_BPP 8 /* should be in pixelformat */ static void uyv2bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels); static void uyvy2bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels); static void uyyvyy2bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels); static void y2bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels); static void y162bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels, int bits); static void rgb482bgr(const unsigned char *src8, unsigned char *dest, unsigned long long int NumPixels, int bits); static char * videodev[4]={ "/dev/video1394/0", "/dev/video1394/1", "/dev/video1394/2", "/dev/video1394/3" }; typedef struct CvCaptureCAM_DC1394 { raw1394handle_t handle; nodeid_t camera_node; dc1394_cameracapture* camera; int format; int mode; int color_mode; int frame_rate; char * device_name; IplImage frame; int convert; int buffer_is_writeable; // indicates whether frame.imageData is allocated by OpenCV or DC1394 } CvCaptureCAM_DC1394; static void icvCloseCAM_DC1394( CvCaptureCAM_DC1394* capture ); static int icvGrabFrameCAM_DC1394( CvCaptureCAM_DC1394* capture ); static IplImage* icvRetrieveFrameCAM_DC1394( CvCaptureCAM_DC1394* capture ); static double icvGetPropertyCAM_DC1394( CvCaptureCAM_DC1394* capture, int property_id ); static int icvSetPropertyCAM_DC1394( CvCaptureCAM_DC1394* capture, int property_id, double value ); // utility functions static int icvFormatSupportedCAM_DC1394(int format, quadlet_t formats); static int icvModeSupportedCAM_DC1394(int format, int mode, quadlet_t modes); static int icvColorMode( int mode ); static unsigned int icvGetBestFrameRate( CvCaptureCAM_DC1394 * capture, int format, int mode); static int icvResizeFrame(CvCaptureCAM_DC1394 * capture); /*********************** Implementations ***************************************/ #define MAX_PORTS 3 #define MAX_CAMERAS 8 #define NUM_BUFFERS 8 struct raw1394_portinfo ports[MAX_PORTS]; static raw1394handle_t handles[MAX_PORTS]; static int camCount[MAX_PORTS]; static int numPorts = -1; static int numCameras = 0; static nodeid_t *camera_nodes; struct camnode {dc1394_cameracapture cam;int portnum;} cameras[MAX_CAMERAS]; static const int preferred_modes[] = { // uncomment the following line to test a particular mode: //FORMAT_VGA_NONCOMPRESSED, MODE_640x480_MONO16, 0, FORMAT_SVGA_NONCOMPRESSED_2, MODE_1600x1200_RGB, MODE_1600x1200_YUV422, MODE_1280x960_RGB, MODE_1280x960_YUV422, MODE_1600x1200_MONO, MODE_1280x960_MONO, MODE_1600x1200_MONO16, MODE_1280x960_MONO16, FORMAT_SVGA_NONCOMPRESSED_1, MODE_1024x768_RGB, MODE_1024x768_YUV422, MODE_800x600_RGB, MODE_800x600_YUV422, MODE_1024x768_MONO, MODE_800x600_MONO, MODE_1024x768_MONO16, MODE_800x600_MONO16, FORMAT_VGA_NONCOMPRESSED, MODE_640x480_RGB, MODE_640x480_YUV422, MODE_640x480_YUV411, MODE_320x240_YUV422, MODE_160x120_YUV444, MODE_640x480_MONO, MODE_640x480_MONO16, FORMAT_SCALABLE_IMAGE_SIZE, MODE_FORMAT7_0, MODE_FORMAT7_1, MODE_FORMAT7_2, MODE_FORMAT7_3, MODE_FORMAT7_4, MODE_FORMAT7_5, MODE_FORMAT7_6, MODE_FORMAT7_7, 0 }; void icvInitCapture_DC1394(){ int p; raw1394handle_t raw_handle = raw1394_new_handle(); if( raw_handle == 0 ) { numPorts = 0; return; } numPorts = raw1394_get_port_info(raw_handle, ports, MAX_PORTS); raw1394_destroy_handle(raw_handle); for (p = 0; p < numPorts; p++) { handles[p] = dc1394_create_handle(p); if (handles[p]==NULL) { numPorts=-1; return; /*ERROR_CLEANUP_EXIT*/ } /* get the camera nodes and describe them as we find them */ camera_nodes = dc1394_get_camera_nodes(handles[p], &camCount[p], 0); for (int i=0;i<camCount[p];i++) { cameras[numCameras].cam.node = camera_nodes[i]; cameras[numCameras].portnum = p; dc1394_stop_iso_transmission(handles[p], camera_nodes[i]); numCameras++; } } }; static CvCaptureCAM_DC1394 * icvCaptureFromCAM_DC1394 (int index) { quadlet_t modes[8], formats; int i; if (numPorts<0) icvInitCapture_DC1394(); if (numPorts==0) return 0; /* No i1394 ports found */ if (numCameras<1) return 0; if (index>=numCameras) return 0; if (index<0) return 0; CvCaptureCAM_DC1394 * pcap = (CvCaptureCAM_DC1394*)cvAlloc(sizeof(*pcap)); /* Select a port and camera */ pcap->device_name = videodev[cameras[index].portnum]; pcap->handle = handles[cameras[index].portnum]; pcap->camera = &cameras[index].cam; // get supported formats if (dc1394_query_supported_formats(pcap->handle, pcap->camera->node, &formats)<0) { fprintf(stderr,"%s:%d: Could not query supported formats\n",__FILE__,__LINE__); formats=0x0; } for (i=0; i < NUM_FORMATS; i++) { modes[i]=0; if (icvFormatSupportedCAM_DC1394(i+FORMAT_MIN, formats)){ if (dc1394_query_supported_modes(pcap->handle, pcap->camera->node, i+FORMAT_MIN, &modes[i])<0) { fprintf(stderr,"%s:%d: Could not query Format%d modes\n",__FILE__,__LINE__,i); } } } pcap->format = 0; pcap->mode = 0; pcap->color_mode = 0; pcap->frame_rate = 0; int format_idx = -1; // scan the list of preferred modes, and find a supported one for(i=0; (pcap->mode == 0) && (preferred_modes[i] != 0); i++) { if((preferred_modes[i] >= FORMAT_MIN) && (preferred_modes[i] <= FORMAT_MAX)) { pcap->format = preferred_modes[i]; format_idx = preferred_modes[i] - FORMAT_MIN; continue; } assert(format_idx != -1); if ( ! icvFormatSupportedCAM_DC1394(pcap->format, formats) ) continue; if ( icvModeSupportedCAM_DC1394(pcap->format, preferred_modes[i], modes[format_idx]) ){ pcap->mode = preferred_modes[i]; } } if (pcap->mode == 0) { fprintf(stderr,"%s:%d: Could not find a supported mode for this camera\n",__FILE__,__LINE__); goto ERROR; } pcap->color_mode = icvColorMode( pcap->mode ); if( pcap->color_mode == -1){ fprintf(stderr,"%s:%d: ERROR: BPP is Unsupported!!\n",__FILE__,__LINE__); goto ERROR; } // set frame rate to optimal value given format and mode pcap->frame_rate = icvGetBestFrameRate(pcap, pcap->format, pcap->mode); if (pcap->format!=FORMAT_SCALABLE_IMAGE_SIZE) { // everything except Format 7 if (dc1394_dma_setup_capture(pcap->handle, pcap->camera->node, index+1 /*channel*/, pcap->format, pcap->mode, SPEED_400, pcap->frame_rate, NUM_BUFFERS, #ifdef HAVE_DC1394_095 0 /*do_extra_buffering*/, #endif 1 /*DROP_FRAMES*/, pcap->device_name, pcap->camera) != DC1394_SUCCESS) { fprintf(stderr,"%s:%d: Failed to setup DMA capture with VIDEO1394\n",__FILE__,__LINE__); goto ERROR; } } else { if(dc1394_dma_setup_format7_capture(pcap->handle,pcap->camera->node,index+1 /*channel*/, pcap->mode, SPEED_400, QUERY_FROM_CAMERA, (unsigned int)QUERY_FROM_CAMERA, (unsigned int)QUERY_FROM_CAMERA, (unsigned int)QUERY_FROM_CAMERA, (unsigned int)QUERY_FROM_CAMERA, NUM_BUFFERS, #ifdef HAVE_DC1394_095 0 /*do_extra_buffering*/, #endif 1 /*DROP_FRAMES*/, pcap->device_name, pcap->camera) != DC1394_SUCCESS) { fprintf(stderr,"%s:%d: Failed to setup DMA capture with VIDEO1394\n",__FILE__,__LINE__); goto ERROR; } } if (dc1394_start_iso_transmission(pcap->handle, pcap->camera->node)!=DC1394_SUCCESS) { fprintf(stderr,"%s:%d: Could not start ISO transmission\n",__FILE__,__LINE__); goto ERROR; } usleep(DELAY); dc1394bool_t status; if (dc1394_get_iso_status(pcap->handle, pcap->camera->node, &status)!=DC1394_SUCCESS) { fprintf(stderr,"%s:%d: Could get ISO status",__FILE__,__LINE__); goto ERROR; } if (status==DC1394_FALSE) { fprintf(stderr,"%s:%d: ISO transmission refuses to start",__FILE__,__LINE__); goto ERROR; } // convert camera image to RGB by default pcap->convert=1; // no image data allocated yet pcap->buffer_is_writeable = 0; memset(&(pcap->frame), 0, sizeof(IplImage)); icvResizeFrame( pcap ); return pcap; ERROR: return 0; }; static void icvCloseCAM_DC1394( CvCaptureCAM_DC1394* capture ){ dc1394_stop_iso_transmission(capture->handle, capture->camera->node); dc1394_dma_unlisten (capture->handle, capture->camera); /* Deallocate space for RGBA data */ if(capture->convert){ cvFree(&capture->frame.imageData); } } static int icvGrabFrameCAM_DC1394( CvCaptureCAM_DC1394* capture ){ // TODO: should this function wait until the next frame is available or return // immediately ? float waiting = 0; do{ int result = dc1394_dma_single_capture_poll(capture->camera); if(result==DC1394_SUCCESS){ return 1; } else if(result==DC1394_NO_FRAME){ usleep(1000000/120); //sleep for at least a 1/2 of the frame rate waiting += 1.0/120.0; } else{ printf("dc1394_dma_single_capture_poll failed\n"); return 0; } } while(waiting<2); printf("dc1394_dma_single_capture_poll timed out\n"); return 0; } static IplImage* icvRetrieveFrameCAM_DC1394( CvCaptureCAM_DC1394* capture ){ if(capture->camera->capture_buffer ) { if(capture->convert){ /* Convert to RGBA */ unsigned char * src = (unsigned char *)capture->camera->capture_buffer; unsigned char * dst = (unsigned char *)capture->frame.imageData; switch (capture->color_mode) { case COLOR_FORMAT7_RGB8: //printf("icvRetrieveFrame convert RGB to BGR\n"); /* Convert RGB to BGR */ for (int i=0;i<capture->frame.imageSize;i+=6) { dst[i] = src[i+2]; dst[i+1] = src[i+1]; dst[i+2] = src[i]; dst[i+3] = src[i+5]; dst[i+4] = src[i+4]; dst[i+5] = src[i+3]; } break; case COLOR_FORMAT7_YUV422: //printf("icvRetrieveFrame convert YUV422 to BGR %d\n"); uyvy2bgr(src, dst, capture->camera->frame_width * capture->camera->frame_height); break; case COLOR_FORMAT7_MONO8: //printf("icvRetrieveFrame convert MONO8 to BGR %d\n"); y2bgr(src, dst, capture->camera->frame_width * capture->camera->frame_height); break; case COLOR_FORMAT7_YUV411: //printf("icvRetrieveFrame convert YUV411 to BGR %d\n"); uyyvyy2bgr(src, dst, capture->camera->frame_width * capture->camera->frame_height); break; case COLOR_FORMAT7_YUV444: //printf("icvRetrieveFrame convert YUV444 to BGR %d\n"); uyv2bgr(src, dst, capture->camera->frame_width * capture->camera->frame_height); break; case COLOR_FORMAT7_MONO16: //printf("icvRetrieveFrame convert MONO16 to BGR %d\n"); y162bgr(src, dst, capture->camera->frame_width * capture->camera->frame_height, MONO16_BPP); break; case COLOR_FORMAT7_RGB16: //printf("icvRetrieveFrame convert RGB16 to BGR %d\n"); rgb482bgr(src, dst, capture->camera->frame_width * capture->camera->frame_height, MONO16_BPP); break; default: fprintf(stderr,"%s:%d: Unsupported color mode %d\n",__FILE__,__LINE__,capture->color_mode); return 0; } /* switch (capture->mode) */ } else{ // return raw data capture->frame.imageData = (char *) capture->camera->capture_buffer; capture->frame.imageDataOrigin = (char *) capture->camera->capture_buffer; } // TODO: if convert=0, we are not actually done with the buffer // but this seems to work anyway. dc1394_dma_done_with_buffer(capture->camera); return &capture->frame; } return 0; }; static double icvGetPropertyCAM_DC1394( CvCaptureCAM_DC1394* capture, int property_id ){ int index=-1; switch ( property_id ) { case CV_CAP_PROP_CONVERT_RGB: return capture->convert; case CV_CAP_PROP_MODE: return capture->mode; case CV_CAP_PROP_FORMAT: return capture->format; case CV_CAP_PROP_FPS: CV_DC1394_CALL(dc1394_get_video_framerate(capture->handle, capture->camera->node, (unsigned int *) &capture->camera->frame_rate)); switch(capture->camera->frame_rate) { case FRAMERATE_1_875: return 1.875; case FRAMERATE_3_75: return 3.75; case FRAMERATE_7_5: return 7.5; case FRAMERATE_15: return 15.; case FRAMERATE_30: return 30.; case FRAMERATE_60: return 60; #if NUM_FRAMERATES > 6 case FRAMERATE_120: return 120; #endif #if NUM_FRAMERATES > 7 case FRAMERATE_240: return 240; #endif } default: index = property_id; // did they pass in a LIBDC1394 feature flag? break; } if(index>=FEATURE_MIN && index<=FEATURE_MAX){ dc1394bool_t has_feature; CV_DC1394_CALL( dc1394_is_feature_present(capture->handle, capture->camera->node, index, &has_feature)); if(!has_feature){ CV_WARN("Feature is not supported by this camera"); } else{ unsigned int value; dc1394_get_feature_value(capture->handle, capture->camera->node, index, &value); return (double) value; } } return 0; }; // resize capture->frame appropriately depending on camera and capture settings static int icvResizeFrame(CvCaptureCAM_DC1394 * capture){ if(capture->convert){ // resize if sizes are different, formats are different // or conversion option has changed if(capture->camera->frame_width != capture->frame.width || capture->camera->frame_height != capture->frame.height || capture->frame.depth != 8 || capture->frame.nChannels != 3 || capture->frame.imageData == NULL || capture->buffer_is_writeable == 0) { if(capture->frame.imageData && capture->buffer_is_writeable){ cvReleaseData( &(capture->frame)); } cvInitImageHeader( &capture->frame, cvSize( capture->camera->frame_width, capture->camera->frame_height ), IPL_DEPTH_8U, 3, IPL_ORIGIN_TL, 4 ); cvCreateData( &(capture->frame) ); capture->buffer_is_writeable = 1; } } else { // free image data if allocated by opencv if(capture->buffer_is_writeable){ cvReleaseData(&(capture->frame)); } // figure out number of channels and bpp int bpp = 8; int nch = 3; int width = capture->camera->frame_width; int height = capture->camera->frame_height; double code = CV_FOURCC('B','G','R',0); switch(capture->color_mode){ case COLOR_FORMAT7_YUV422: nch = 2; code = CV_FOURCC('Y','4','2','2'); break; case COLOR_FORMAT7_MONO8: code = CV_FOURCC('Y',0,0,0); nch = 1; break; case COLOR_FORMAT7_YUV411: code = CV_FOURCC('Y','4','1','1'); width *= 2; nch = 3; //yy[u/v] break; case COLOR_FORMAT7_YUV444: code = CV_FOURCC('Y','U','V',0); nch = 3; break; case COLOR_FORMAT7_MONO16: code = CV_FOURCC('Y',0,0,0); bpp = IPL_DEPTH_16S; nch = 1; break; case COLOR_FORMAT7_RGB16: bpp = IPL_DEPTH_16S; nch = 3; break; default: break; } // reset image header cvInitImageHeader( &capture->frame,cvSize( width, height ), bpp, nch, IPL_ORIGIN_TL, 4 ); //assert(capture->frame.imageSize == capture->camera->quadlets_per_frame*4); capture->buffer_is_writeable = 0; } return 1; } // Toggle setting about whether or not RGB color conversion is to be performed // Allocates/Initializes capture->frame appropriately int icvSetConvertRGB(CvCaptureCAM_DC1394 * capture, int convert){ if(convert==capture->convert){ // no action necessary return 1; } capture->convert = convert; return icvResizeFrame( capture ); } // given desired format, mode, and modes bitmask from camera, determine if format and mode are supported static int icvFormatSupportedCAM_DC1394(int format, quadlet_t formats){ // formats is a bitmask whose higher order bits indicate whether format is supported int shift = 31 - (format - FORMAT_MIN); int mask = 1 << shift; return (formats & mask) != 0; } // analyze modes bitmask from camera to determine if desired format and mode are supported static int icvModeSupportedCAM_DC1394(int format, int mode, quadlet_t modes){ // modes is a bitmask whose higher order bits indicate whether mode is supported int format_idx = format - FORMAT_MIN; int mode_format_min = MODE_FORMAT0_MIN + 32*format_idx; int shift = 31 - (mode - mode_format_min); int mask = 0x1 << shift; return (modes & mask) != 0; } // Setup camera to use given dc1394 mode static int icvSetModeCAM_DC1394( CvCaptureCAM_DC1394 * capture, int mode ){ quadlet_t modes, formats; //printf("<icvSetModeCAM_DC1394>\n"); // figure out corrent format for this mode int format = (mode - MODE_FORMAT0_MIN) / 32 + FORMAT_MIN; // get supported formats if (dc1394_query_supported_formats(capture->handle, capture->camera->node, &formats)<0) { fprintf(stderr,"%s:%d: Could not query supported formats\n",__FILE__,__LINE__); return 0; } // is format for requested mode supported ? if(icvFormatSupportedCAM_DC1394(format, formats)==0){ return 0; } // get supported modes for requested format if (dc1394_query_supported_modes(capture->handle, capture->camera->node, format, &modes)<0){ fprintf(stderr,"%s:%d: Could not query supported modes for format %d\n",__FILE__,__LINE__, capture->format); return 0; } // is requested mode supported ? if(! icvModeSupportedCAM_DC1394(format, mode, modes) ){ return 0; } int color_mode = icvColorMode( mode ); if(color_mode == -1){ return 0; } int frame_rate = icvGetBestFrameRate(capture, format, mode); dc1394_dma_unlisten(capture->handle, capture->camera); if (dc1394_dma_setup_capture(capture->handle, capture->camera->node, capture->camera->channel /*channel*/, format, mode, SPEED_400, frame_rate, NUM_BUFFERS, #ifdef HAVE_DC1394_095 0 /*do_extra_buffering*/, #endif 1 /*DROP_FRAMES*/, capture->device_name, capture->camera) != DC1394_SUCCESS) { fprintf(stderr,"%s:%d: Failed to setup DMA capture with VIDEO1394\n",__FILE__,__LINE__); return 0; } dc1394_start_iso_transmission(capture->handle, capture->camera->node); capture->frame_rate = frame_rate; capture->format = format; capture->mode = mode; capture->color_mode = color_mode; // now fix image size to match new mode icvResizeFrame( capture ); return 1; } // query camera for supported frame rates and select fastest for given format and mode static unsigned int icvGetBestFrameRate( CvCaptureCAM_DC1394 * capture, int format, int mode ){ quadlet_t framerates; if (dc1394_query_supported_framerates(capture->handle, capture->camera->node, format, mode, &framerates)!=DC1394_SUCCESS) { fprintf(stderr,"%s:%d: Could not query supported framerates\n",__FILE__,__LINE__); framerates = 0; } for (int f=FRAMERATE_MAX; f>=FRAMERATE_MIN; f--) { if (framerates & (0x1<< (31-(f-FRAMERATE_MIN)))) { return f; } } return 0; } static int icvSetFrameRateCAM_DC1394( CvCaptureCAM_DC1394 * capture, double value ){ unsigned int fps=15; if(capture->format == FORMAT_SCALABLE_IMAGE_SIZE) return 0; /* format 7 has no fixed framerates */ if (value==-1){ fps=icvGetBestFrameRate( capture, capture->format, capture->mode ); } else if (value==1.875) fps=FRAMERATE_1_875; else if (value==3.75) fps=FRAMERATE_3_75; else if (value==7.5) fps=FRAMERATE_7_5; else if (value==15) fps=FRAMERATE_15; else if (value==30) fps=FRAMERATE_30; else if (value==60) fps=FRAMERATE_60; #if NUM_FRAMERATES > 6 else if (value==120) fps=FRAMERATE_120; #endif #if NUM_FRAMERATES > 7 else if (value==240) fps=FRAMERATE_240; #endif dc1394_set_video_framerate(capture->handle, capture->camera->node,fps); dc1394_get_video_framerate(capture->handle, capture->camera->node, (unsigned int *) &capture->camera->frame_rate); return fps==(unsigned int) capture->camera->frame_rate; } // for given mode return color format static int icvColorMode( int mode ){ switch(mode) { case MODE_160x120_YUV444: return COLOR_FORMAT7_YUV444; case MODE_320x240_YUV422: case MODE_640x480_YUV422: case MODE_800x600_YUV422: case MODE_1024x768_YUV422: case MODE_1280x960_YUV422: case MODE_1600x1200_YUV422: return COLOR_FORMAT7_YUV422; case MODE_640x480_YUV411: return COLOR_FORMAT7_YUV411; case MODE_640x480_RGB: case MODE_800x600_RGB: case MODE_1024x768_RGB: case MODE_1280x960_RGB: case MODE_1600x1200_RGB: return COLOR_FORMAT7_RGB8; case MODE_640x480_MONO: case MODE_800x600_MONO: case MODE_1024x768_MONO: case MODE_1280x960_MONO: case MODE_1600x1200_MONO: return COLOR_FORMAT7_MONO8; case MODE_640x480_MONO16: case MODE_800x600_MONO16: case MODE_1024x768_MONO16: case MODE_1280x960_MONO16: case MODE_1600x1200_MONO16: return COLOR_FORMAT7_MONO16; case MODE_FORMAT7_0: case MODE_FORMAT7_1: case MODE_FORMAT7_2: case MODE_FORMAT7_3: case MODE_FORMAT7_4: case MODE_FORMAT7_5: case MODE_FORMAT7_6: case MODE_FORMAT7_7: fprintf(stderr,"%s:%d: Format7 not yet supported\n",__FILE__,__LINE__); default: break; } return -1; } // function to set camera properties using dc1394 feature enum // val == -1 indicates to set this property to 'auto' static int icvSetFeatureCAM_DC1394( CvCaptureCAM_DC1394* capture, int feature_id, int val){ dc1394bool_t isOn = DC1394_FALSE; dc1394bool_t hasAutoCapability = DC1394_FALSE; dc1394bool_t isAutoOn = DC1394_FALSE; unsigned int nval; unsigned int minval,maxval; // Turn the feature on if it is OFF if( dc1394_is_feature_on(capture->handle, capture->camera->node, feature_id, &isOn) == DC1394_FAILURE ) { return 0; } if( isOn == DC1394_FALSE ) { // try to turn it on. if( dc1394_feature_on_off(capture->handle, capture->camera->node, feature_id, 1) == DC1394_FAILURE ) { fprintf(stderr, "error turning feature %d on!\n", feature_id); return 0; } } // Check if the feature supports auto mode dc1394_has_auto_mode(capture->handle, capture->camera->node, feature_id, &hasAutoCapability); if( hasAutoCapability ) { // now check if the auto is on. if( dc1394_is_feature_auto(capture->handle, capture->camera->node, feature_id, &isAutoOn ) == DC1394_FAILURE ) { fprintf(stderr, "error determining if feature %d has auto on!\n", index); return 0; } } // Caller requested auto mode, but cannot support it else if(val==-1){ fprintf(stderr, "feature %d does not support auto mode\n", feature_id); return 0; } if(val==-1){ // if the auto mode isn't enabled, enable it if( isAutoOn == DC1394_FALSE ) { if(dc1394_auto_on_off(capture->handle, capture->camera->node, feature_id, 1) == DC1394_FAILURE ) { fprintf(stderr, "error turning feature %d auto ON!\n", feature_id); return 0; } } return 1; } // ELSE turn OFF auto and adjust feature manually if( isAutoOn == DC1394_TRUE ) { if(dc1394_auto_on_off(capture->handle, capture->camera->node, feature_id, 0) == DC1394_FAILURE ) { fprintf(stderr, "error turning feature %d auto OFF!\n", feature_id); return 0; } } // Clamp val to within feature range CV_DC1394_CALL( dc1394_get_min_value(capture->handle, capture->camera->node, feature_id, &minval)); CV_DC1394_CALL( dc1394_get_max_value(capture->handle, capture->camera->node, feature_id, &maxval)); val = MIN(maxval, MAX(val, minval)); if (dc1394_set_feature_value(capture->handle, capture->camera->node, feature_id, val) == DC1394_FAILURE){ fprintf(stderr, "error setting feature value\n"); return 0; } if (dc1394_get_feature_value(capture->handle, capture->camera->node, feature_id, &nval) == DC1394_FAILURE){ fprintf(stderr, "error setting feature value\n"); return 0; } return nval==(unsigned int)val; } // cvSetCaptureProperty callback function implementation static int icvSetPropertyCAM_DC1394( CvCaptureCAM_DC1394* capture, int property_id, double value ){ int index=-1; switch ( property_id ) { case CV_CAP_PROP_CONVERT_RGB: return icvSetConvertRGB( capture, value != 0 ); case CV_CAP_PROP_MODE: return icvSetModeCAM_DC1394( capture, (int) value ); case CV_CAP_PROP_FPS: return icvSetFrameRateCAM_DC1394( capture, value ); case CV_CAP_PROP_BRIGHTNESS: index = FEATURE_BRIGHTNESS; break; case CV_CAP_PROP_CONTRAST: index = FEATURE_GAMMA; break; case CV_CAP_PROP_SATURATION: index = FEATURE_SATURATION; break; case CV_CAP_PROP_HUE: index = FEATURE_HUE; break; case CV_CAP_PROP_GAIN: index = FEATURE_GAIN; break; default: index = property_id; // did they pass in a LIBDC1394 feature flag? break; } if(index>=FEATURE_MIN && index<=FEATURE_MAX){ return icvSetFeatureCAM_DC1394(capture, index, (int) value); } return 0; }; /********************************************************************** * * CONVERSION FUNCTIONS TO RGB 24bpp * **********************************************************************/ /* color conversion functions from Bart Nabbe. *//* corrected by Damien: bad coeficients in YUV2RGB */ #define YUV2RGB(y, u, v, r, g, b)\ r = y + ((v*1436) >> 10);\ g = y - ((u*352 + v*731) >> 10);\ b = y + ((u*1814) >> 10);\ r = r < 0 ? 0 : r;\ g = g < 0 ? 0 : g;\ b = b < 0 ? 0 : b;\ r = r > 255 ? 255 : r;\ g = g > 255 ? 255 : g;\ b = b > 255 ? 255 : b static void uyv2bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels) { register int i = NumPixels + (NumPixels << 1) - 1; register int j = NumPixels + (NumPixels << 1) - 1; register int y, u, v; register int r, g, b; while (i > 0) { v = src[i--] - 128; y = src[i--]; u = src[i--] - 128; YUV2RGB(y, u, v, r, g, b); dest[j--] = r; dest[j--] = g; dest[j--] = b; } } static void uyvy2bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels) { register int i = (NumPixels << 1) - 1; register int j = NumPixels + (NumPixels << 1) - 1; register int y0, y1, u, v; register int r, g, b; while (i > 0) { y1 = src[i--]; v = src[i--] - 128; y0 = src[i--]; u = src[i--] - 128; YUV2RGB(y1, u, v, r, g, b); dest[j--] = r; dest[j--] = g; dest[j--] = b; YUV2RGB(y0, u, v, r, g, b); dest[j--] = r; dest[j--] = g; dest[j--] = b; } } static void uyyvyy2bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels) { register int i = NumPixels + (NumPixels >> 1) - 1; register int j = NumPixels + (NumPixels << 1) - 1; register int y0, y1, y2, y3, u, v; register int r, g, b; while (i > 0) { y3 = src[i--]; y2 = src[i--]; v = src[i--] - 128; y1 = src[i--]; y0 = src[i--]; u = src[i--] - 128; YUV2RGB(y3, u, v, r, g, b); dest[j--] = r; dest[j--] = g; dest[j--] = b; YUV2RGB(y2, u, v, r, g, b); dest[j--] = r; dest[j--] = g; dest[j--] = b; YUV2RGB(y1, u, v, r, g, b); dest[j--] = r; dest[j--] = g; dest[j--] = b; YUV2RGB(y0, u, v, r, g, b); dest[j--] = r; dest[j--] = g; dest[j--] = b; } } static void y2bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels) { register int i = NumPixels - 1; register int j = NumPixels + (NumPixels << 1) - 1; register int y; while (i > 0) { y = src[i--]; dest[j--] = y; dest[j--] = y; dest[j--] = y; } } static void y162bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels, int bits) { register int i = (NumPixels << 1) - 1; register int j = NumPixels + (NumPixels << 1) - 1; register int y; while (i > 0) { y = src[i--]; y = (y + (src[i--] << 8)) >> (bits - 8); dest[j--] = y; dest[j--] = y; dest[j--] = y; } } // this one was in coriander but didn't take bits into account static void rgb482bgr(const unsigned char *src, unsigned char *dest, unsigned long long int NumPixels, int bits) { register int i = (NumPixels << 1) - 1; register int j = NumPixels + (NumPixels << 1) - 1; register int y; while (i > 0) { y = src[i--]; dest[j-2] = (y + (src[i--] << 8)) >> (bits - 8); j--; y = src[i--]; dest[j] = (y + (src[i--] << 8)) >> (bits - 8); j--; y = src[i--]; dest[j+2] = (y + (src[i--] << 8)) >> (bits - 8); j--; } } class CvCaptureCAM_DC1394_CPP : public CvCapture { public: CvCaptureCAM_DC1394_CPP() { captureDC1394 = 0; } virtual ~CvCaptureCAM_DC1394_CPP() { close(); } virtual bool open( int index ); virtual void close(); virtual double getProperty(int); virtual bool setProperty(int, double); virtual bool grabFrame(); virtual IplImage* retrieveFrame(); protected: CvCaptureCAM_DC1394* captureDC1394; }; bool CvCaptureCAM_DC1394_CPP::open( int index ) { close(); captureDC1394 = icvCaptureFromCAM_DC1394(index); return captureDC1394 != 0; } void CvCaptureCAM_DC1394_CPP::close() { if( captureDC1394 ) { icvCloseCAM_DC1394( captureDC1394 ); cvFree( &captureDC1394 ); } } bool CvCaptureCAM_DC1394_CPP::grabFrame() { return captureDC1394 ? icvGrabFrameCAM_DC1394( captureDC1394 ) != 0 : false; } IplImage* CvCaptureCAM_DC1394_CPP::retrieveFrame() { return captureDC1394 ? (IplImage*)icvRetrieveFrameCAM_DC1394( captureDC1394 ) : 0; } double CvCaptureCAM_DC1394_CPP::getProperty( int propId ) { return captureDC1394 ? icvGetPropertyCAM_DC1394( captureDC1394, propId ) : 0; } bool CvCaptureCAM_DC1394_CPP::setProperty( int propId, double value ) { return captureDC1394 ? icvSetPropertyCAM_DC1394( captureDC1394, propId, value ) != 0 : false; } CvCapture* cvCreateCameraCapture_DC1394( int index ) { CvCaptureCAM_DC1394_CPP* capture = new CvCaptureCAM_DC1394_CPP; if( capture->open( index )) return capture; delete capture; return 0; } #endif
30.223015
118
0.687279
hjhsggy
7425ac5695dbac58fedbbdff11fc626f324b89a1
14,273
cpp
C++
app/tests/model/Test_Board.cpp
HenrikThoroe/SWC-2021
8e7eee25e3a6fda7e863591b05fa161d8a2ebc78
[ "BSD-2-Clause", "MIT" ]
null
null
null
app/tests/model/Test_Board.cpp
HenrikThoroe/SWC-2021
8e7eee25e3a6fda7e863591b05fa161d8a2ebc78
[ "BSD-2-Clause", "MIT" ]
null
null
null
app/tests/model/Test_Board.cpp
HenrikThoroe/SWC-2021
8e7eee25e3a6fda7e863591b05fa161d8a2ebc78
[ "BSD-2-Clause", "MIT" ]
null
null
null
#include "catch.hpp" #include "Board.hpp" using namespace Model; using namespace Util; TEST_CASE("Test Board", "[model]") { auto board = Board(); auto piece1 = DeployedPiece(0, Position(0,0), Rotation::ZERO, PieceColor::BLUE); auto piece2 = DeployedPiece(18, Position(10,12), Rotation::ZERO_FLIPPED, PieceColor::YELLOW); auto piece3 = DeployedPiece(0, Position(19,0), Rotation::ZERO, PieceColor::BLUE); board.dropPiece(piece1); board.dropPiece(piece2); board.dropPiece(piece3); SECTION("Can Force Drop Positions") { auto board2 = Board(); board2.makeDropPosition(Position(0, 0), PieceColor::RED); board2.makeDropPosition(Position(10, 11), PieceColor::BLUE); REQUIRE(board2.canDrop(PieceColor::RED, 0, 0)); REQUIRE(board2.canDrop(PieceColor::BLUE, 10, 11)); } SECTION("Can Drop Pieces") { REQUIRE(board.at(0 , 0) == PieceColor::BLUE); REQUIRE(board.at(19, 0) == PieceColor::BLUE); REQUIRE(board.at(10, 12) == PieceColor::YELLOW); REQUIRE(board.at(10, 13) == PieceColor::YELLOW); REQUIRE(board.at(10, 14) == PieceColor::YELLOW); REQUIRE(board.at(10, 15) == PieceColor::YELLOW); REQUIRE(board.at(11, 13) == PieceColor::YELLOW); } SECTION("Has Valid Drop Positions") { auto dropPositionsBlue = board.getDropPositions(PieceColor::BLUE); auto dropPositionsYellow = board.getDropPositions(PieceColor::YELLOW); REQUIRE_THROWS(board.getDropPositions(PieceColor::NONE)); REQUIRE(board.canDrop(PieceColor::BLUE, 1, 1)); REQUIRE_FALSE(board.canDrop(PieceColor::BLUE, 1, 0)); REQUIRE(board.canDrop(PieceColor::BLUE, 18, 1)); REQUIRE(board.canDrop(PieceColor::YELLOW, 9, 11)); REQUIRE(board.canDrop(PieceColor::YELLOW, 11, 11)); REQUIRE(board.canDrop(PieceColor::YELLOW, 9, 16)); REQUIRE(board.canDrop(PieceColor::YELLOW, 11, 16)); REQUIRE(board.canDrop(PieceColor::YELLOW, 12, 12)); REQUIRE(board.canDrop(PieceColor::YELLOW, 12, 14)); REQUIRE(dropPositionsBlue.size() == 2); REQUIRE(dropPositionsYellow.size() == 6); } board.removePiece(piece1); board.removePiece(piece2); board.removePiece(piece3); SECTION("Can Remove Piece") { REQUIRE(board.at(0 , 0) == PieceColor::NONE); REQUIRE(board.at(19, 0) == PieceColor::NONE); REQUIRE(board.at(10, 12) == PieceColor::NONE); REQUIRE(board.at(10, 13) == PieceColor::NONE); REQUIRE(board.at(10, 14) == PieceColor::NONE); REQUIRE(board.at(10, 15) == PieceColor::NONE); REQUIRE(board.at(11, 13) == PieceColor::NONE); } SECTION("Has Valid Drop Positions After Removing") { auto dropPositionsBlue = board.getDropPositions(PieceColor::BLUE); auto dropPositionsYellow = board.getDropPositions(PieceColor::YELLOW); REQUIRE_FALSE(board.canDrop(PieceColor::BLUE, 1, 1)); REQUIRE_FALSE(board.canDrop(PieceColor::BLUE, 1, 0)); REQUIRE_FALSE(board.canDrop(PieceColor::BLUE, 18, 1)); REQUIRE_FALSE(board.canDrop(PieceColor::YELLOW, 9, 11)); REQUIRE_FALSE(board.canDrop(PieceColor::YELLOW, 11, 11)); REQUIRE_FALSE(board.canDrop(PieceColor::YELLOW, 9, 16)); REQUIRE_FALSE(board.canDrop(PieceColor::YELLOW, 11, 16)); REQUIRE_FALSE(board.canDrop(PieceColor::YELLOW, 12, 12)); REQUIRE_FALSE(board.canDrop(PieceColor::YELLOW, 12, 14)); REQUIRE(dropPositionsBlue.size() == 0); REQUIRE(dropPositionsYellow.size() == 0); } SECTION("Can Create Statistics") { const std::array<Model::DeployedPiece, 54> midGameMoves = { DeployedPiece(11, Position(19, 19), static_cast<Rotation>(7), PieceColor::BLUE), DeployedPiece(11, Position(0, 0), static_cast<Rotation>(0), PieceColor::YELLOW), DeployedPiece(11, Position(19, 0), static_cast<Rotation>(1), PieceColor::RED), DeployedPiece(11, Position(0, 16), static_cast<Rotation>(0), PieceColor::GREEN), DeployedPiece(20, Position(14, 14), static_cast<Rotation>(1), PieceColor::BLUE), DeployedPiece(18, Position(2, 4), static_cast<Rotation>(3), PieceColor::YELLOW), DeployedPiece(20, Position(15, 2), static_cast<Rotation>(5), PieceColor::RED), DeployedPiece(18, Position(4, 15), static_cast<Rotation>(1), PieceColor::GREEN), DeployedPiece(17, Position(11, 11), static_cast<Rotation>(5), PieceColor::BLUE), DeployedPiece(15, Position(8, 6), static_cast<Rotation>(4), PieceColor::YELLOW), DeployedPiece(17, Position(13, 6), static_cast<Rotation>(1), PieceColor::RED), DeployedPiece(15, Position(7, 13), static_cast<Rotation>(2), PieceColor::GREEN), DeployedPiece(14, Position(8, 8), static_cast<Rotation>(0), PieceColor::BLUE), DeployedPiece(14, Position(9, 7), static_cast<Rotation>(0), PieceColor::YELLOW), DeployedPiece(19, Position(10, 4), static_cast<Rotation>(1), PieceColor::RED), DeployedPiece(12, Position(7, 9), static_cast<Rotation>(0), PieceColor::GREEN), DeployedPiece(19, Position(12, 14), static_cast<Rotation>(1), PieceColor::BLUE), DeployedPiece(10, Position(12, 10), static_cast<Rotation>(0), PieceColor::YELLOW), DeployedPiece(14, Position(5, 2), static_cast<Rotation>(0), PieceColor::RED), DeployedPiece(10, Position(8, 16), static_cast<Rotation>(3), PieceColor::GREEN), DeployedPiece(18, Position(19, 14), static_cast<Rotation>(7), PieceColor::BLUE), DeployedPiece(16, Position(14, 8), static_cast<Rotation>(0), PieceColor::YELLOW), DeployedPiece(18, Position(16, 4), static_cast<Rotation>(3), PieceColor::RED), DeployedPiece(9, Position(14, 17), static_cast<Rotation>(3), PieceColor::GREEN), DeployedPiece(13, Position(12, 18), static_cast<Rotation>(5), PieceColor::BLUE), DeployedPiece(13, Position(18, 6), static_cast<Rotation>(1), PieceColor::YELLOW), DeployedPiece(15, Position(3, 6), static_cast<Rotation>(0), PieceColor::RED), DeployedPiece(14, Position(4, 9), static_cast<Rotation>(3), PieceColor::GREEN), DeployedPiece(5, Position(10, 13), static_cast<Rotation>(7), PieceColor::BLUE), DeployedPiece(17, Position(1, 6), static_cast<Rotation>(0), PieceColor::YELLOW), DeployedPiece(12, Position(2, 5), static_cast<Rotation>(1), PieceColor::RED), DeployedPiece(16, Position(1, 12), static_cast<Rotation>(0), PieceColor::GREEN), DeployedPiece(15, Position(6, 16), static_cast<Rotation>(7), PieceColor::BLUE), DeployedPiece(20, Position(14, 13), static_cast<Rotation>(0), PieceColor::YELLOW), DeployedPiece(13, Position(1, 10), static_cast<Rotation>(2), PieceColor::RED), DeployedPiece(13, Position(7, 17), static_cast<Rotation>(1), PieceColor::GREEN), DeployedPiece(7, Position(4, 16), static_cast<Rotation>(1), PieceColor::BLUE), DeployedPiece(12, Position(2, 2), static_cast<Rotation>(3), PieceColor::YELLOW), DeployedPiece(7, Position(12, 9), static_cast<Rotation>(0), PieceColor::RED), DeployedPiece(20, Position(2, 18), static_cast<Rotation>(6), PieceColor::GREEN), DeployedPiece(9, Position(4, 10), static_cast<Rotation>(0), PieceColor::BLUE), DeployedPiece(9, Position(19, 8), static_cast<Rotation>(0), PieceColor::YELLOW), DeployedPiece(10, Position(15, 10), static_cast<Rotation>(0), PieceColor::RED), DeployedPiece(5, Position(11, 19), static_cast<Rotation>(7), PieceColor::GREEN), DeployedPiece(2, Position(2, 16), static_cast<Rotation>(1), PieceColor::BLUE), DeployedPiece(5, Position(13, 14), static_cast<Rotation>(0), PieceColor::YELLOW), DeployedPiece(16, Position(8, 2), static_cast<Rotation>(0), PieceColor::RED), DeployedPiece(2, Position(14, 19), static_cast<Rotation>(3), PieceColor::GREEN), DeployedPiece(0, Position(17, 16), static_cast<Rotation>(0), PieceColor::BLUE), DeployedPiece(8, Position(12, 13), static_cast<Rotation>(4), PieceColor::YELLOW), DeployedPiece(5, Position(12, 0), static_cast<Rotation>(5), PieceColor::RED), DeployedPiece(17, Position(16, 16), static_cast<Rotation>(7), PieceColor::GREEN), DeployedPiece(1, Position(19, 16), static_cast<Rotation>(1), PieceColor::BLUE), DeployedPiece(2, Position(9, 12), static_cast<Rotation>(3), PieceColor::YELLOW) }; for (const DeployedPiece& move : midGameMoves) { board.dropPiece(move); } const std::array<BoardStatistics, 4>& stats = board.getStatistics(); //* Correct colors are assigned REQUIRE(stats[0].color == PieceColor::RED); REQUIRE(stats[1].color == PieceColor::BLUE); REQUIRE(stats[2].color == PieceColor::GREEN); REQUIRE(stats[3].color == PieceColor::YELLOW); //* Each color has valid pull factors REQUIRE(stats[0].pullFactor[0] == 14); REQUIRE(stats[0].pullFactor[1] == 19); REQUIRE(stats[0].pullFactor[2] == 11); REQUIRE(stats[0].pullFactor[3] == 10); REQUIRE(stats[1].pullFactor[0] == 11); REQUIRE(stats[1].pullFactor[1] == 9); REQUIRE(stats[1].pullFactor[2] == 19); REQUIRE(stats[1].pullFactor[3] == 17); REQUIRE(stats[2].pullFactor[0] == 12); REQUIRE(stats[2].pullFactor[1] == 8); REQUIRE(stats[2].pullFactor[2] == 18); REQUIRE(stats[2].pullFactor[3] == 19); REQUIRE(stats[3].pullFactor[0] == 19); REQUIRE(stats[3].pullFactor[1] == 13); REQUIRE(stats[3].pullFactor[2] == 14); REQUIRE(stats[3].pullFactor[3] == 10); //* Correct amount of free and blocked corners REQUIRE(stats[0].freeCorners == 20); REQUIRE(stats[1].freeCorners == 4); REQUIRE(stats[2].freeCorners == 12); REQUIRE(stats[3].freeCorners == 11); REQUIRE(stats[0].friendlyBlockedCorners == 0); REQUIRE(stats[1].friendlyBlockedCorners == 0); REQUIRE(stats[2].friendlyBlockedCorners == 3); REQUIRE(stats[3].friendlyBlockedCorners == 5); REQUIRE(stats[0].opponentBlockedCorners == 17); REQUIRE(stats[1].opponentBlockedCorners == 32); REQUIRE(stats[2].opponentBlockedCorners == 22); REQUIRE(stats[3].opponentBlockedCorners == 25); //* Correct amount of shared edges //? Unused until performance is fixed //// REQUIRE(stats[0].sharedEdges == 33); //// REQUIRE(stats[1].sharedEdges == 80); //// REQUIRE(stats[2].sharedEdges == 55); //// REQUIRE(stats[3].sharedEdges == 72); //// REQUIRE(stats[0].friendlySharedEdges == stats[1].friendlySharedEdges); //// REQUIRE(stats[2].friendlySharedEdges == stats[3].friendlySharedEdges); //// REQUIRE(stats[0].friendlySharedEdges == 0); //// REQUIRE(stats[1].friendlySharedEdges == 0); //// REQUIRE(stats[2].friendlySharedEdges == 7); //// REQUIRE(stats[3].friendlySharedEdges == 7); //// REQUIRE(stats[0].opponentSharedEdges == 33); //// REQUIRE(stats[1].opponentSharedEdges == 80); //// REQUIRE(stats[2].opponentSharedEdges == 48); //// REQUIRE(stats[3].opponentSharedEdges == 65); //* Correct amount of drop positions REQUIRE(stats[0].dropPositions == 15); REQUIRE(stats[1].dropPositions == 3); REQUIRE(stats[2].dropPositions == 7); REQUIRE(stats[3].dropPositions == 8); REQUIRE(stats[0].ratedDropPositions[0] == 2); REQUIRE(stats[0].ratedDropPositions[1] == 0); REQUIRE(stats[0].ratedDropPositions[2] == 0); REQUIRE(stats[0].ratedDropPositions[3] == 1); REQUIRE(stats[0].ratedDropPositions[4] == 4); REQUIRE(stats[0].ratedDropPositions[5] == 1); REQUIRE(stats[0].ratedDropPositions[6] == 3); REQUIRE(stats[0].ratedDropPositions[7] == 4); REQUIRE(stats[1].ratedDropPositions[0] == 0); REQUIRE(stats[1].ratedDropPositions[1] == 0); REQUIRE(stats[1].ratedDropPositions[2] == 2); REQUIRE(stats[1].ratedDropPositions[3] == 0); REQUIRE(stats[1].ratedDropPositions[4] == 1); REQUIRE(stats[1].ratedDropPositions[5] == 0); REQUIRE(stats[1].ratedDropPositions[6] == 0); REQUIRE(stats[1].ratedDropPositions[7] == 0); REQUIRE(stats[2].ratedDropPositions[0] == 0); REQUIRE(stats[2].ratedDropPositions[1] == 0); REQUIRE(stats[2].ratedDropPositions[2] == 3); REQUIRE(stats[2].ratedDropPositions[3] == 0); REQUIRE(stats[2].ratedDropPositions[4] == 4); REQUIRE(stats[2].ratedDropPositions[5] == 0); REQUIRE(stats[2].ratedDropPositions[6] == 0); REQUIRE(stats[2].ratedDropPositions[7] == 0); REQUIRE(stats[3].ratedDropPositions[0] == 0); REQUIRE(stats[3].ratedDropPositions[1] == 2); REQUIRE(stats[3].ratedDropPositions[2] == 2); REQUIRE(stats[3].ratedDropPositions[3] == 1); REQUIRE(stats[3].ratedDropPositions[4] == 2); REQUIRE(stats[3].ratedDropPositions[5] == 0); REQUIRE(stats[3].ratedDropPositions[6] == 1); REQUIRE(stats[3].ratedDropPositions[7] == 0); //* Can reset all values for (int i = 0; i < 0; ++i) { BoardStatistics& stat = const_cast<BoardStatistics&>(stats[i]); stat.reset(); for (int p = 0; p < 4; ++p) { REQUIRE(stat.pullFactor[p] == 0); } REQUIRE(stat.freeCorners == 0); REQUIRE(stat.friendlyBlockedCorners == 0); REQUIRE(stat.opponentBlockedCorners == 0); REQUIRE(stat.sharedEdges == 0); REQUIRE(stat.friendlySharedEdges == 0); REQUIRE(stat.opponentSharedEdges == 0); REQUIRE(stat.dropPositions == 0); for (int d = 0; d < 8; ++d) { REQUIRE(stat.ratedDropPositions[d] == 0); } } } }
49.731707
97
0.623065
HenrikThoroe
7426f6c3d700eb572342ff0b0bd8c7237479ff33
2,134
cc
C++
src/ppl/nn/oputils/onnx/reshape_concat.cc
aboluock/ppl.nn
47c786bee382cc0d779f1393bfeaa40b6ff73654
[ "Apache-2.0" ]
1
2021-08-23T04:59:26.000Z
2021-08-23T04:59:26.000Z
src/ppl/nn/oputils/onnx/reshape_concat.cc
aboluock/ppl.nn
47c786bee382cc0d779f1393bfeaa40b6ff73654
[ "Apache-2.0" ]
1
2022-03-07T15:35:35.000Z
2022-03-07T15:35:35.000Z
src/ppl/nn/oputils/onnx/reshape_concat.cc
aboluock/ppl.nn
47c786bee382cc0d779f1393bfeaa40b6ff73654
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "ppl/nn/oputils/onnx/reshape_concat.h" #include "ppl/nn/runtime/tensor_impl.h" using namespace ppl::common; using namespace ppl::nn::common; namespace ppl { namespace nn { namespace oputils { RetCode ReshapeConcat(InputOutputInfo* info, const void* arg) { auto param = (const ConcatParam*)arg; const TensorShape& in_shape0 = info->GetInput<TensorImpl>(0)->GetShape(); uint32_t fixed_axis = param->axis >= 0 ? param->axis : param->axis + info->GetInput<TensorImpl>(0)->GetShape().GetDimCount(); std::vector<int64_t> output_dim(in_shape0.GetDimCount()); for (uint32_t i = 0; i < in_shape0.GetDimCount(); ++i) { if (i == fixed_axis) { output_dim[i] = 0; for (uint32_t j = 0; j < info->GetInputCount(); ++j) { output_dim[i] += info->GetInput<TensorImpl>(j)->GetShape().GetDim(i); } } else { for (uint32_t j = 1; j < info->GetInputCount(); ++j) { if (info->GetInput<TensorImpl>(j)->GetShape().GetDim(i) != in_shape0.GetDim(i)) { return RC_INVALID_VALUE; } } output_dim[i] = in_shape0.GetDim(i); } } info->GetOutput<TensorImpl>(0)->GetShape().Reshape(output_dim); return RC_SUCCESS; } }}} // namespace ppl::nn::oputils
39.518519
111
0.656045
aboluock
742a144c4d3cb4a53069ab3f2154af1b83e59521
24,096
cxx
C++
PWGCF/Correlations/JCORRAN/Base/AliJEfficiencyScanner.cxx
ilyafokin/AliPhysics
7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4
[ "BSD-3-Clause" ]
1
2020-07-18T17:36:58.000Z
2020-07-18T17:36:58.000Z
PWGCF/Correlations/JCORRAN/Base/AliJEfficiencyScanner.cxx
ilyafokin/AliPhysics
7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4
[ "BSD-3-Clause" ]
1
2017-03-14T15:11:43.000Z
2017-03-14T15:53:09.000Z
PWGCF/Correlations/JCORRAN/Base/AliJEfficiencyScanner.cxx
ilyafokin/AliPhysics
7a0021a9d7ad4f0a9e52e0a13f9d3ca3b74c63d4
[ "BSD-3-Clause" ]
1
2022-01-24T11:11:09.000Z
2022-01-24T11:11:09.000Z
// //#include <Riostream.h> // #include <TChain.h> // #include <TVectorT.h> // #include <TVector3.h> // #include <TFile.h> // #include <TH1.h> // #include <TObjArray.h> // #include <TObjString.h> // #include <TFormula.h> // #include <TString.h> // #include <TRefArray.h> // #include <TNtuple.h> // #include <TArrayF.h> #include <TClonesArray.h> #include <TH1D.h> #include <TH2D.h> #include "AliJEfficiencyScanner.h" #include "AliJTrack.h" #include "AliJMCTrack.h" #include "AliJPhoton.h" #include "AliJEventHeader.h" #include "AliJRunHeader.h" #include <TFile.h> #include <TRandom.h> ClassImp(AliJEfficiencyScanner); //______________________________________________________________________________ AliJEfficiencyScanner::AliJEfficiencyScanner() : TNamed(), fMBTriggMask(0), fisIsolated(kFALSE), fisRelative(kTRUE), fisolParam(0.1), fisolCone(0.4), fTrackList(0), fMCTrackList(0x0), fEventHeader(0x0), fRunHeader(0x0), fhVertexZMC(0x0), fhVertexZTrigg(0x0), fhVertexZTriggVtx(0x0), fhVZRawMC(0x0), fhVZRecMC(0x0), fhVZRecAccMC(0x0), fh2VtxCent(0x0), fhL0Input(0x0), fhTriggerAlice(0x0), fhZVtxMCAll(0x0), fhZVtxMCTrigg(0x0), fhZVtxMCTriggVtx(0x0), fhZVtxRecAll(0x0), fhZVtxRecTrigg(0x0), fhZVtxRecTriggVtx(0x0), fVtxReFunc(0x0), fVtxMCFunc(0x0), fVtxRatioFunc(0x0), fVtxRatioMax(1) { //Default constructor for( int ivtx=0;ivtx<kNVtxBin;ivtx++ ){ for( int icent=0;icent<kNCentBin;icent++ ){ fhChargedPtMCTriggVtx[ivtx][icent] = 0x0; for( int ifilter=0;ifilter<AliJTrackCut::kJNTrackCuts;ifilter++ ){ for( int ipri=0;ipri<kNPrimaryStatus;ipri++ ){ for( int itt=0;itt<kNTrackType;itt++ ){ fhChargedPtMCRecoCentVtx[ivtx][icent][ifilter][ipri][itt] = 0x0; } } } } } for(int i=0; i<AliJTrackCut::kJNTrackCuts; i++){ fh2MultGenRawPrimary[i] = 0x0; fh2MultGenRawAll[i] = 0x0; } } //______________________________________________________________________________ AliJEfficiencyScanner::AliJEfficiencyScanner(const char *name): TNamed(name,name), fMBTriggMask(0), fisIsolated(kFALSE), fisRelative(kTRUE), fisolParam(0.1), fisolCone(0.4), fTrackList(0), fMCTrackList(0x0), fEventHeader(0x0), fRunHeader(0x0), fhVertexZMC(0x0), fhVertexZTrigg(0x0), fhVertexZTriggVtx(0x0), fhVZRawMC(0x0), fhVZRecMC(0x0), fhVZRecAccMC(0x0), fh2VtxCent(0x0), fhL0Input(0x0), fhTriggerAlice(0x0), fhZVtxMCAll(0x0), fhZVtxMCTrigg(0x0), fhZVtxMCTriggVtx(0x0), fhZVtxRecAll(0x0), fhZVtxRecTrigg(0x0), fhZVtxRecTriggVtx(0x0), fVtxReFunc(0x0), fVtxMCFunc(0x0), fVtxRatioFunc(0x0), fVtxRatioMax(1) { // Constructor for( int ivtx=0;ivtx<kNVtxBin;ivtx++ ){ for( int icent=0;icent<kNCentBin;icent++ ){ fhChargedPtMCTriggVtx[ivtx][icent] = 0x0; for( int ifilter=0;ifilter<AliJTrackCut::kJNTrackCuts;ifilter++ ){ for( int ipri=0;ipri<kNPrimaryStatus;ipri++ ){ for( int itt=0;itt<kNTrackType;itt++ ){ fhChargedPtMCRecoCentVtx[ivtx][icent][ifilter][ipri][itt] = 0x0; } } } } } for(int i=0; i<AliJTrackCut::kJNTrackCuts; i++){ fh2MultGenRawPrimary[i] = 0x0; fh2MultGenRawAll[i] = 0x0; } } //____________________________________________________________________________ AliJEfficiencyScanner::AliJEfficiencyScanner(const AliJEfficiencyScanner& ap) : TNamed(ap.GetName(), ap.GetTitle()), fMBTriggMask(ap.fMBTriggMask), fisIsolated(ap.fisIsolated), fisRelative(ap.fisRelative), fisolParam(ap.fisolParam), fisolCone(ap.fisolCone), fTrackList(ap.fTrackList), fMCTrackList(ap.fMCTrackList), fEventHeader( ap.fEventHeader ), fRunHeader(ap.fRunHeader), fhVertexZMC(ap.fhVertexZMC), fhVertexZTrigg(ap.fhVertexZTrigg), fhVertexZTriggVtx(ap.fhVertexZTriggVtx), fhVZRawMC(ap.fhVZRawMC), fhVZRecMC(ap.fhVZRecMC), fhVZRecAccMC(ap.fhVZRecAccMC), fh2VtxCent(ap.fh2VtxCent), fhL0Input(ap.fhL0Input), fhTriggerAlice(ap.fhTriggerAlice), fhZVtxMCAll(ap.fhZVtxMCAll), fhZVtxMCTrigg(ap.fhZVtxMCTrigg), fhZVtxMCTriggVtx(ap.fhZVtxMCTriggVtx), fhZVtxRecAll(ap.fhZVtxRecAll), fhZVtxRecTrigg(ap.fhZVtxRecTrigg), fhZVtxRecTriggVtx(ap.fhZVtxRecTriggVtx), fVtxReFunc(ap.fVtxReFunc), fVtxMCFunc(ap.fVtxMCFunc), fVtxRatioFunc(ap.fVtxRatioFunc), fVtxRatioMax(ap.fVtxRatioMax) { // cpy ctor for( int ivtx=0;ivtx<kNVtxBin;ivtx++ ){ for( int icent=0;icent<kNCentBin;icent++ ){ fhChargedPtMCTriggVtx[ivtx][icent] = ap.fhChargedPtMCTriggVtx[ivtx][icent]; for( int ifilter=0;ifilter<AliJTrackCut::kJNTrackCuts;ifilter++ ){ for( int ipri=0;ipri<kNPrimaryStatus;ipri++ ){ for( int itt=0;itt<kNTrackType;itt++ ){ fhChargedPtMCRecoCentVtx[ivtx][icent][ifilter][ipri][itt] = ap.fhChargedPtMCRecoCentVtx[ivtx][icent][ifilter][ipri][itt]; } } } } } for(int i=0; i<AliJTrackCut::kJNTrackCuts; i++){ fh2MultGenRawPrimary[i] = ap.fh2MultGenRawPrimary[i]; fh2MultGenRawAll[i] = ap.fh2MultGenRawAll[i]; } } //_____________________________________________________________________________ AliJEfficiencyScanner& AliJEfficiencyScanner::operator = (const AliJEfficiencyScanner& ap) { // assignment operator this->~AliJEfficiencyScanner(); new(this) AliJEfficiencyScanner(ap); return *this; } //______________________________________________________________________________ AliJEfficiencyScanner::~AliJEfficiencyScanner() { // destructor } //________________________________________________________________________ void AliJEfficiencyScanner::UserCreateOutputObjects() { //=== create the jcorran outputs objects cout<<"DEBUG Start AliJEfficiencyScanner::UserCreateOutputObjects() "<<"\t"<<gDirectory<<endl; double ptbin[300] = {0}; double pt = 0; int i = 0; for( i=0;i<300;i++ ){ ptbin[i] = pt; if( pt > 50 ) break; if( pt < 3 ) pt+= 0.05; else if( pt < 5 ) pt+= 0.1; else if( pt < 10 ) pt+= 1; else pt+= 1; } cout<<"n Ptbin = "<<i<<endl; int nPtBin = i-1; fh2VtxCent = new TH2D("h2VtxCent","h2VtxCent",100,0,10,110,0,110 ); fh2VtxCent->SetDirectory(gDirectory); int nVtxBin = kNVtxBin; int nCentBin = kNCentBin; if( fRunHeader->IsPP() ) nCentBin = 1; TString name =""; for( int ivtx=0;ivtx<nVtxBin;ivtx++ ){ for( int icent=0;icent<nCentBin;icent++ ){ fhChargedPtMC[ivtx][icent] = AddTH1D( Form("hChargedPtMC%02d%02d",ivtx,icent), new TH1D("","", nPtBin, ptbin) ); fhChargedPtMCTriggVtx[ivtx][icent]=AddTH1D( Form("hChargedPtMCTriggVtx%02d%02d", ivtx, icent ), new TH1D("", "", nPtBin, ptbin) ); fhChargedPtMCTrigg[ivtx][icent]=AddTH1D( Form("hChargedPtMCTrigg%02d%02d", ivtx, icent ), new TH1D("", "", nPtBin, ptbin) ); //for any MC track filled with MC pt in triggered event name = Form("h2DChargedPtTrigg%02d%02d",ivtx,icent); fh2DChargedPtTrigg[ivtx][icent]=AddTH2D(name, new TH2D(name,name, nPtBin, ptbin, 20, -0.8, 0.8)); //for any MC track filled with MC pt in triggered event with rec vertex name = Form("h2DChargedPtTriggVtx%02d%02d",ivtx,icent); fh2DChargedPtTriggVtx[ivtx][icent]=AddTH2D(name, new TH2D(name,name, nPtBin, ptbin, 20, -0.8, 0.8)); } } fhTriggerAlice = AddTH1D("hTriggerAlice",new TH1D("","",32,0,32)); fhL0Input = AddTH1D("hL0Input",new TH1D("","",32,0,32)); // DCA bin double dcaBin[1000]; double dbin=-50-1; int ndbin = 0; dcaBin[0] = dbin; double tol = 1e-5; while(dbin < 50-1){ if( fabs(dbin) < 2-tol ) dbin+=0.01; else if( fabs(dbin) < 5-tol ) dbin+= 0.05; else if( fabs(dbin) <= 10-tol ) dbin+= 0.1; else dbin += 1; if( fabs(dbin) < tol ) dbin=0; dcaBin[ndbin++] = dbin; } for( int ivtx=0;ivtx<nVtxBin;ivtx++ ){ for( int icent=0;icent<nCentBin;icent++ ){ for( int ifilter=0;ifilter<AliJTrackCut::kJNTrackCuts;ifilter++ ){ name = Form("h2DChargedPtAll%02d%02d%02d",ivtx,icent,ifilter); fh2DChargedPtAll[ivtx][icent][ifilter]=AddTH2D(name, new TH2D(name,name, nPtBin, ptbin, 20, -0.8, 0.8)); name = Form("h2DChargedPtRec%02d%02d%02d",ivtx,icent,ifilter); fh2DChargedPtRec[ivtx][icent][ifilter]=AddTH2D(name, new TH2D(name,name, nPtBin, ptbin, 20, -0.8, 0.8)); for( int ipri=0;ipri<kNPrimaryStatus;ipri++ ){ for( int itt=0;itt<kNTrackType;itt++ ){ name = Form("hChargedPtMCRecoCentVtx%02d%02d%02d%02d%02d", ivtx, icent, ifilter, ipri, itt ); fhChargedPtMCRecoCentVtx[ivtx][icent][ifilter][ipri][itt]=AddTH1D(name, new TH1D( name, name, nPtBin, ptbin)); } } name = Form("hDCA2VertexXY%02d%02d%02d", ivtx, icent, ifilter ); fhDCA2VertexXY[ivtx][icent][ifilter] = AddTH1D(name, new TH1D("","",ndbin-1, dcaBin )); name = Form("hDCA2VertexZ%02d%02d%02d", ivtx, icent, ifilter ); fhDCA2VertexZ[ivtx][icent][ifilter] = AddTH1D( name, new TH1D("","",ndbin-1, dcaBin )); } } } // TH2D * fh2MultGenRawPrimary[AliJTrackCut::kJNTrackCuts]; // TH2D * fh2MultGenRawAll[AliJTrackCut::kJNTrackCuts]; // TH1D * fhDCA2VertexXY[kNVtxBin][kNCentBin][AliJTrackCut::kJNTrackCuts]; for( int ifilter=0;ifilter<AliJTrackCut::kJNTrackCuts;ifilter++ ){ name = Form("h2MultGenRawPrimary%02d", ifilter); fh2MultGenRawPrimary[ifilter] = AddTH2D( name, new TH2D(name, name, 100,0,100,100,0,100 )); name = Form("h2MultGenRawAll%02d", ifilter); fh2MultGenRawAll[ifilter] = AddTH2D( name, new TH2D(name, name, 100,0,100,100,0,100 )); } double binsVertexMult[] = {0,1,2,3,4,5,10000}; int NbinsVertexMult = sizeof(binsVertexMult)/sizeof(double)-1; double binsVertexZ[] = {-10,-6,-3,-2,-1.5,-1,-0.5,0,0.5,1,1.5,2,3,6,10}; int NbinsVertexZ = sizeof(binsVertexZ)/sizeof(double)-1; fhVertexZMC = AddTH2D("hVertexZMC",new TH2D("hVertexZMC","hVertexZMC", NbinsVertexMult, binsVertexMult, NbinsVertexZ, binsVertexZ)); fhVertexZTrigg = AddTH2D("hVertexZTrigg",new TH2D("hVertexZTrigg","hVertexZTrigg", NbinsVertexMult, binsVertexMult, NbinsVertexZ, binsVertexZ)); fhVertexZTriggVtx = AddTH2D("hVertexZTriggVtx",new TH2D("hVertexZTriggVtx","hVertexZTriggVtx", NbinsVertexMult, binsVertexMult, NbinsVertexZ, binsVertexZ)); fhVZRawMC = AddTH1D("hVtxZMC", new TH1D("hVtxZMC","VertexZ in MC ",200,-50,50)); fhVZRecMC = AddTH1D("hVtxZRec", new TH1D("hVtxZRec","VertexZ Rec in MC",200,-50,50)); fhVZRecAccMC = AddTH1D("hVtxZRecAcc", new TH1D("hVtxZRecAcc","VertexZ Rec in MC and acc",200,-50,50)); int NvtxBins = 400; double vtxedge = 50; fhZVtxMCAll = AddTH1D("hZVtxMCAll", new TH1D("hZVtxMCAll","VetrexZ in MC for all event",NvtxBins, -vtxedge, vtxedge )); fhZVtxMCTrigg = AddTH1D("hZVtxMCTrigg", new TH1D("hZVtxMCTrigg","VetrexZ in MC for triggered event",NvtxBins, -vtxedge, vtxedge )); fhZVtxMCTriggVtx = AddTH1D("hZVtxMCTriggVtx", new TH1D("hZVtxMCTriggVtx","VetrexZ in MC for triggered and vtx reconstructed event",NvtxBins, -vtxedge, vtxedge )); fhZVtxRecAll = AddTH1D("hZVtxRecAll", new TH1D("hZVtxRecAll","VetrexZ in Rec for all event",NvtxBins, -vtxedge, vtxedge )); fhZVtxRecTrigg = AddTH1D("hZVtxRecTrigg", new TH1D("hZVtxRecTrigg","VetrexZ in Rec for triggered event",NvtxBins, -vtxedge, vtxedge )); fhZVtxRecTriggVtx = AddTH1D("hZVtxRecTriggVtx", new TH1D("hZVtxRecTriggVtx","VetrexZ in Rec for triggered and vtx reconstructed event",NvtxBins, -vtxedge, vtxedge )); double v0 = -20; double v1 = 20; fVtxReFunc = new TF1("VtxReFunc", "gaus",v0,v1); fVtxReFunc->SetParameters(1 , -7.14076e-01, 6.27110 ); fVtxMCFunc = new TF1("VtxMCFunc", "gaus",v0,v1); fVtxMCFunc->SetParameters(1, -4.53674e-01, 5.27088e+00 ); fVtxRatioFunc = new TF1("VtxRatioFunc", "VtxReFunc/VtxMCFunc",v0,v1); fVtxRatioMax = fVtxRatioFunc->GetMaximum(); //cout << "Add(fAliJRunHeader) in UserCreateObject() ======= " << endl; cout<<"DEBUG END AliJEfficiencyScanner::UserCreateOutputObjects() "<<endl; } //______________________________________________________________________________ void AliJEfficiencyScanner::UserExec(Option_t *option) { // Main loop // Called for each event JUNUSED(option); double zVtxCut = 10; double etaCut = 0.8; double nCentBin = 20; AliJEventHeader * eventHeader = GetJEventHeader(); //== TRIGGER( MB ) TODO is this? Bool_t triggeredEventMB = eventHeader->GetTriggerMaskJCorran() & fMBTriggMask; // 1:kMB 8:kINT7 //TODO UInt_t trigAlice = eventHeader->GetTriggerMaskAlice(); /* cout<<"Trigger"<<endl; for( int i=0;i<32 ;i++ ) cout<<Form("%02d",i)<<" "; cout<<endl; for( int i=0;i<32 ;i++ ) cout<<(eventHeader->GetTriggerMaskJCorran()&(1<<i)?1:0)<<" "; cout<<endl; for( int i=0;i<32 ;i++ ) cout<<(eventHeader->GetTriggerMaskAlice()&(1<<i)?1:0)<<" "; cout<<endl; */ /* bool isMB1 = trigAlice & (1UL<<0); bool isMBBG1 = trigAlice & (1UL<<3); bool isGFO = trigAlice & (1UL<<14); bool isMBBG3 = trigAlice & (1UL<<1); bool isV0A = trigAlice & (1UL<<10); bool isV0C = trigAlice & (1UL<11); */ // L0Input UInt_t l0Input = eventHeader->GetL0TriggerInputs(); /* bool isL0V0A = l0Input & (1UL<<9); bool isL0V0C = l0Input & (1UL<<10); bool isL0V0AND = l0Input & (1UL<<4); bool isL0V0OR = l0Input & (1UL<<1); bool isL0V0BeamGas = l0Input & (1UL<<2); bool isL0SMB = l0Input & (1UL<<3); bool isL0T0X = l0Input & (1UL<<0); */ for( UInt_t i=0;i<32;i++ ){ if( l0Input & 1UL<<i ) fhL0Input->Fill(i); if( trigAlice & 1UL<<i ) fhTriggerAlice->Fill(i); /* if( isL0V0A != isV0A ) cout<<"J_WARN 0 : L0:V0A != Class:V0A "<<isL0V0A<<"\t"<<isV0A<<endl; if( isL0V0C != isV0C ) cout<<"J_WARN 1 : L0:V0C != Class:V0C "<<isL0V0C<<"\t"<<isV0C<<endl; if( isL0SMB != isGFO ) cout<<"J_WARN 2 : L0:SMB != Class:GFO "<<isL0SMB<<"\t"<<isGFO<<endl; if( isL0V0OR != isMBBG1 ) cout<<"J_WARN 3 : L0:V0OR != Class:MBBG1 "<<isL0V0OR<<"\t"<<isMBBG1<<endl; if( (isL0V0A||isL0V0C) != isMBBG1 ) cout<<"J_WARN 4 : L0:V0A|V0C != Class:MBBG1 "<<(isL0V0A||isL0V0C)<<"\t"<<isMBBG1<<endl; if( ( isL0T0X || isL0V0OR || isL0SMB && !isL0V0BeamGas ) != isMB1 ) cout<<"J_WARN 5 : L0:MB1 != Class:MB1 "<<isMB1<<endl; if( (isL0V0OR || isL0SMB && !isL0V0BeamGas ) != (( isMBBG1 || isGFO ) && isMB1 )) cout<<"J_WARN 6 : L0:MB != Class:MB "<<(isL0V0OR || isL0SMB && !isL0V0BeamGas)<<"\t"<<((isMBBG1 || isGFO ) && isMB1)<<endl; if( (isL0V0OR || isL0SMB ) != (( isMBBG1 || isGFO ) )) cout<<"J_WARN 6 : L0:MB != Class:MB "<<(isL0V0OR || isL0SMB && !isL0V0BeamGas)<<"\t"<<((isMBBG1 || isGFO ) && isMB1)<<endl; */ } //* FOR TEST */ //Bool_t triggeredEventMB = ( isMBBG1 || isGFO ) && isMB1; //Bool_t triggeredEventMB = isMB1; //Bool_t triggeredEventMB = ( isMBBG1 || isGFO ); // //== REAL MB with L0 INput //triggeredEventMB = ( (isL0V0OR || isL0SMB) ); //== CENTRALITY double centrality = eventHeader->GetCentrality(); int iCent = int( centrality/(100./nCentBin)); if( iCent< 0 || iCent>20 ) return; //if( centrality < 0 || centrality > 100 ) return; if( fRunHeader->IsPP() ) {iCent = 0; centrality=0;} //== Vertex //==== Reco int ncontributors = eventHeader->GetVtxMult(); double zVtxRec = eventHeader->GetZVertex(); Bool_t goodRecVertex = (ncontributors>0) && (fabs(zVtxRec)<=zVtxCut); int iVtx = 0; //==== MC double zVtxMC = eventHeader->GetZVertexMC(); //==== vtx sampling /* if( zVtxMC > fVtxRatioFunc->GetXmin() && zVtxMC < fVtxRatioFunc->GetXmax() ){ double vtxRatio = fVtxRatioFunc->Eval(zVtxMC)/fVtxRatioMax; double random = gRandom->Uniform(0,1); if( random > vtxRatio ) return; } */ fhVZRawMC->Fill(zVtxMC); fhVertexZMC->Fill(ncontributors,zVtxMC); // for crosscheck MC input events fhZVtxMCAll->Fill(zVtxMC); fhZVtxRecAll->Fill(zVtxRec); if(triggeredEventMB){ fhVertexZTrigg->Fill(ncontributors,zVtxMC); // for crosscheck passing trigger condition fhZVtxMCTrigg->Fill(zVtxMC); fhZVtxRecTrigg->Fill(zVtxRec); if(ncontributors>0){//reconstructed vertex fhVZRecMC->Fill(zVtxRec); // for crosscheck passing trigger condition + reconstruted vtx fhZVtxMCTriggVtx->Fill(zVtxMC); fhZVtxRecTriggVtx->Fill(zVtxRec); } if(goodRecVertex){ fhVertexZTriggVtx->Fill(ncontributors,zVtxMC); fhVZRecAccMC->Fill(zVtxRec); } } fh2VtxCent->Fill( zVtxRec, centrality ); // TODO ? MC or REC? int nRawMultPri = 0; int nGenMultPri[AliJTrackCut::kJNTrackCuts] = {0}; int nGenMultAll[AliJTrackCut::kJNTrackCuts] = {0}; //============================================== // LOOP over MC //============================================== //if( fabs(zVtxMC) > zVtxCut ) return; int nMCTrks = 0; if( fRunHeader->IsMC() ) nMCTrks = GetJMCTracks()->GetEntriesFast(); for( int it=0; it< nMCTrks; it++ ){ AliJMCTrack * track = GetJMCTrack( it );//Always IsPhysicalPrimary if( !track ) continue; if( !track->IsTrue( AliJMCTrack::kPrimary ) ) continue; // TODO need? if( ! track->IsFinal() ) continue; double eta = track->Eta(); double pt = track->Pt(); if( fabs(eta) > etaCut ) continue; if( ! track->IsCharged() ) continue; // Isolation check if( fisIsolated ){ // Isolated tracks must fullfill fiducial acceptance cut if( fabs(eta) > etaCut - fisolCone ) continue; double isolThreshold; if( fisRelative ) isolThreshold = fisolParam * pt; else isolThreshold = fisolParam; double isolSum = 0.0; for(int ia = 0; ia < nMCTrks; ia++){ if ( ia == it ) continue; AliJMCTrack * assTrack = GetJMCTrack( ia ); if( !assTrack ) continue; if( !assTrack->IsTrue( AliJMCTrack::kPrimary ) ) continue; if(!assTrack->IsCharged()) continue; double assEta = assTrack->Eta(); if( fabs(assEta) > etaCut ) continue; if( track->DeltaR(*assTrack) < fisolCone ) isolSum += assTrack->Pt(); } if ( isolSum > isolThreshold ) continue; } nRawMultPri++; fhChargedPtMC[iVtx][iCent]->Fill(pt); //ALL charged physical primaries if(triggeredEventMB){//triggered fhChargedPtMCTrigg[iVtx][iCent]->Fill(pt); fh2DChargedPtTrigg[iVtx][iCent]->Fill(pt, eta); if(goodRecVertex){ //triggered+vertex fhChargedPtMCTriggVtx[iVtx][iCent]->Fill(pt); fh2DChargedPtTriggVtx[iVtx][iCent]->Fill(pt, eta); } } } //-------------------------------------------------------------- //---- Reconstracted TRACKS //-------------------------------------------------------------- const int nTrkCut = AliJTrackCut::kJNTrackCuts; if( ! triggeredEventMB ) return; if( ! goodRecVertex ) return; int nTrks = GetJTracks()->GetEntriesFast(); for(Int_t it = 0; it < nTrks; it++) { AliJTrack * track = GetJTrack(it); if( !track ) continue; bool isTriggered = track->GetFilterMap(); if( !isTriggered ) continue; //== init Vars of Track double eta = track->Eta(); double etaTPC = eta; double etaGCG = eta; double ptRec = track->Pt(); double ptTPC = track->PtTPC(); if( fabs(ptTPC) < 1e-2 ) ptTPC=ptRec; else{ TVector3 v(track->GetTPCTrack()); etaTPC = v.Eta(); } double ptGCG = track->PtGCG(); if( fabs(ptGCG) < 1e-2 ) ptGCG=ptRec; else{ TVector3 v(track->GetGCGTrack()); etaGCG = v.Eta(); } double ptMC = -1; int iPrimary = kJFake; //== Skip tracks with out of Eta if( fabs(eta) > etaCut && fabs(etaTPC)>etaCut && fabs(etaGCG)>etaCut) continue; //== Find MC Info for( int imc=0;imc<nMCTrks;imc++ ){ AliJMCTrack * mcTrack = GetJMCTrack(imc); if( !mcTrack || !mcTrack->IsTrue( AliJMCTrack::kPrimary ) ) continue; if( mcTrack && (TMath::Abs(track->GetLabel()) == TMath::Abs(mcTrack->GetLabel())) ){ iPrimary = kJPhysicsPrimary; ptMC = mcTrack->Pt(); break; } } //== FILL HIST for( int icut=0;icut<nTrkCut;icut++ ){ if( IsSelected( track ,icut) ){ // ====== check isolation if( fisIsolated ){ // Isolated tracks must fullfill fiducial acceptance cut if( fabs(eta) > etaCut - fisolCone ) continue; double isolThreshold; if( fisRelative ) isolThreshold = fisolParam * ptRec; else isolThreshold = fisolParam; double isolSum = 0.0; for(int ia = 0; ia < nTrks; ia++){ if ( ia == it ) continue; AliJTrack * assTrack = GetJTrack( ia ); if( !assTrack ) continue; if( !IsSelected(assTrack,icut) ) continue; double assEta = assTrack->Eta(); if( fabs(assEta) > etaCut ) continue; if( track->DeltaR(*assTrack) < fisolCone ) isolSum += assTrack->Pt(); } if ( isolSum > isolThreshold )continue; } if( fabs(eta) < etaCut ){ fh2DChargedPtAll[iVtx][iCent][icut]->Fill(ptRec, eta); // IS THIS OK? Compare next line! fh2DChargedPtRec[iVtx][iCent][icut]->Fill(ptMC, eta); // IS THIS OK? Compare next line! fhChargedPtMCRecoCentVtx[iVtx][iCent][icut][iPrimary][kJGlobal]->Fill( ptRec ); if( iPrimary == kJPhysicsPrimary ) nGenMultPri[icut]++; nGenMultAll[icut]++; //fhDCA2VertexXY[iVtx][iCent][icut]->Fill( track->GetDCAtoVertexXY() ); //fhDCA2VertexZ[iVtx][iCent][icut]->Fill( track->GetDCAtoVertexZ() ); } if( fabs(etaTPC) < etaCut ) fhChargedPtMCRecoCentVtx[iVtx][iCent][icut][iPrimary][kJTPCOnly]->Fill( ptTPC ); if( fabs(etaGCG) < etaCut ) fhChargedPtMCRecoCentVtx[iVtx][iCent][icut][iPrimary][kJGCG]->Fill( ptGCG ); if( (icut==0 && fabs(etaTPC) < etaCut) || (icut!=0&&fabs(eta)<etaCut) ) fhChargedPtMCRecoCentVtx[iVtx][iCent][icut][iPrimary][kJMCTrack]->Fill( ptMC ); } } } for( int icut=0;icut<nTrkCut;icut++ ){ fh2MultGenRawPrimary[icut]->Fill( nRawMultPri, nGenMultPri[icut] ); fh2MultGenRawAll[icut]->Fill( nRawMultPri, nGenMultAll[icut] ); } //cout<<"DEBUG END AliJEfficiencyScanner::UserExec"<<endl; } //______________________________________________________________________________ void AliJEfficiencyScanner::Init() { // Intialisation of parameters } //______________________________________________________________________________ void AliJEfficiencyScanner::Terminate(Option_t *) { // termination }
38.247619
214
0.606366
ilyafokin
742e18e3aa0c43c34256769c137ef61c1d0d2523
335
cc
C++
leetcode/115.cc
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
leetcode/115.cc
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
leetcode/115.cc
zofvbeaf/algorithm-practices
9772808fdf1b73ac55887291d9fb680e90b60958
[ "MIT" ]
null
null
null
class Solution { public: int numDistinct(string s, string t) { unsigned int n = s.size(), m = t.size(); if(!m || !n || n < m) return 0; if(s == t) return 1; vector<unsigned int> f(m, 0); for(auto c : s) { for(int i = m-1; i > 0; --i) if(c == t[i]) f[i] += f[i-1]; if(c == t[0]) ++f[0]; } return f[m-1]; } };
20.9375
42
0.480597
zofvbeaf
742ece0a31c69a5d1aa13bc8968655f0db93691a
291
cpp
C++
Ejercicios/Ejercicio 43/calculadora.cpp
MarvinMonnar/cpp.
b71b981d711cfc416a74a9abc8b10c70fe544717
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio 43/calculadora.cpp
MarvinMonnar/cpp.
b71b981d711cfc416a74a9abc8b10c70fe544717
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio 43/calculadora.cpp
MarvinMonnar/cpp.
b71b981d711cfc416a74a9abc8b10c70fe544717
[ "MIT" ]
null
null
null
int sumar (int a, int b) { return a + b ; } int restar (int a, int b) { return a - b ; } int calcular (int a, int b, char operador) { if (operador == '+') { return sumar (a, b); } if (operador == '-') { return restar (a, b); } throw "Operador no valido"; }
8.558824
42
0.508591
MarvinMonnar
74324514c5c0c065815b7efca2924fbce238de33
346
hpp
C++
HugeCTR/include/graph_wrapper.hpp
xjqbest/HugeCTR
0b1c92d5e65891dfdd90d917bc6d520d0ca5d1e1
[ "Apache-2.0" ]
130
2021-10-11T11:55:28.000Z
2022-03-31T21:53:07.000Z
HugeCTR/include/graph_wrapper.hpp
xjqbest/HugeCTR
0b1c92d5e65891dfdd90d917bc6d520d0ca5d1e1
[ "Apache-2.0" ]
72
2021-10-09T04:59:09.000Z
2022-03-31T11:27:54.000Z
HugeCTR/include/graph_wrapper.hpp
xjqbest/HugeCTR
0b1c92d5e65891dfdd90d917bc6d520d0ca5d1e1
[ "Apache-2.0" ]
29
2021-11-03T22:35:01.000Z
2022-03-30T13:11:59.000Z
#pragma once #include <cuda_runtime.h> #include <functional> namespace HugeCTR { struct GraphWrapper { bool initialized = false; cudaGraph_t graph; cudaGraphExec_t graph_exec; void capture(std::function<void(cudaStream_t)> workload, cudaStream_t stream); void exec(cudaStream_t stream); }; } // namespace HugeCTR
19.222222
81
0.716763
xjqbest
2936a1d047d2f3c0d50519ec416d2ce273c70a2c
1,717
cpp
C++
assignments/a1-hello/particles.cpp
foqiashahid112/animation-toolkit
17950435e1efbd243877193e7a8966b7abfd8788
[ "MIT" ]
null
null
null
assignments/a1-hello/particles.cpp
foqiashahid112/animation-toolkit
17950435e1efbd243877193e7a8966b7abfd8788
[ "MIT" ]
null
null
null
assignments/a1-hello/particles.cpp
foqiashahid112/animation-toolkit
17950435e1efbd243877193e7a8966b7abfd8788
[ "MIT" ]
null
null
null
#include "atkui/framework.h" #include <random> #include <cstdlib> using namespace glm; class particle{ public: particle(vec3 currentPosition, vec3 velocity, vec3 RGBcolor){ currentPos =currentPosition; vel = velocity; color = RGBcolor; } vec3 currentPos; vec3 vel; vec3 color; }; class Particles : public atkui::Framework { public: Particles() : atkui::Framework(atkui::Orthographic) { } virtual void setup() { for(int i = 0; i < 150; i++){ float rand = 20 + (std::rand() % 200) ; vec3 baseColor = vec3(0.2,0.8,0.2); vec3 current = 500.0f * abs(agl::randomUnitVector()); current[2] = 0; particle pNew = particle(current, rand * vec3(1,1,0), baseColor + fRand(-0.4,0.4)); myParticles.push_back(pNew); } } virtual void scene() { for(particle& p : myParticles){ setColor(p.color); double radius = 10; if(p.currentPos[0] > width()){ p.currentPos[0] = 0; } if(p.currentPos[1] > height()){ p.currentPos[1] = 0; } p.currentPos = p.currentPos + p.vel * dt(); drawSphere(p.currentPos, radius); } } //https://stackoverflow.com/questions/2704521/generate-random-double-numbers-in-c //Modified Sachin singh jagawat's solution virtual vec3 fRand(double fMin, double fMax) { double f1 = ((double)rand()) / RAND_MAX; f1 = fMin + (fMax - fMin) * f1; double f2 = ((double)rand()) / RAND_MAX; f2 = fMin + (fMax - fMin) * f2; double f3 = ((double)rand()) / RAND_MAX; f3 = fMin + (fMax - fMin) * f3; return vec3(f1,f2,f3); } std::vector<particle> myParticles; }; int main(int argc, char** argv) { Particles viewer; viewer.run(); return 0; }
24.884058
89
0.607455
foqiashahid112
293780ef181a8e0e8f36b2709ad2012ff8091761
15,834
cc
C++
main/src/App/vtk_cad.cc
marcomanno/ploygon_triangulation
c98b99e3f9598252ffc27eb202939f0183ac872b
[ "Apache-2.0" ]
null
null
null
main/src/App/vtk_cad.cc
marcomanno/ploygon_triangulation
c98b99e3f9598252ffc27eb202939f0183ac872b
[ "Apache-2.0" ]
null
null
null
main/src/App/vtk_cad.cc
marcomanno/ploygon_triangulation
c98b99e3f9598252ffc27eb202939f0183ac872b
[ "Apache-2.0" ]
null
null
null
// // This simple example shows how to do basic rendering and pipeline // creation using C++. // #include "open_file.hh" #include "vtkCylinderSource.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkProperty.h" #include "vtkCamera.h" #include "vtkTextActor.h" #include "vtkTextProperty.h" #include "vtkVertex.h" #include <vtkVersion.h> #include <vtkSmartPointer.h> #include <vtkChartXY.h> #include <vtkTable.h> #include <vtkPlot.h> #include <vtkFloatArray.h> #include <vtkContextView.h> #include <vtkContextScene.h> #include <vtkPen.h> #include "Topology/iterator.hh" #include "Import/import.hh" #include "Boolean/boolean.hh" #include "Geo/bspline_fiting.hh" #include "Geo/evalnurbs.hh" #include <map> #include <iostream> template<size_t idxT> void example_function(); typedef void(*ExamplePtr)(); static std::map<size_t, ExamplePtr>& example_table() { static std::map<size_t, ExamplePtr> exmpls_; return exmpls_; } template <size_t nmbrT> struct Examples { Examples() { example_table()[nmbrT] = example_function<nmbrT>; } }; #define EXAMPLE(nmbr) \ Examples<nmbr> ex_##nmbr; \ template<> void example_function<nmbr>() int main() { std::cout << "Select test:" << std::endl; for (const auto& test : example_table()) { std::cout << test.first << std::endl; } size_t sel; std::cin >> sel; example_table()[sel](); return 0; } namespace { template <class T> struct deleter { void operator()(T* _vpdm) { _vpdm->Delete(); } }; template<typename T> using VtkUniquePtr = std::unique_ptr<T, deleter<T>>; void render_actors(std::vector<vtkPolyData*>& _ply_dats, Geo::VectorD3* _clrs = nullptr) { // Create the graphics structure. The renderer renders into the // render window. The render window interactor captures mouse events // and will perform appropriate camera or actor manipulation // depending on the nature of the events. // vtkRenderer *renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); //// Setup the text and add it to the renderer //vtkSmartPointer<vtkTextActor> textActor = vtkSmartPointer<vtkTextActor>::New(); //textActor->SetInput("Hello world"); //textActor->SetPosition2(10, 40); //textActor->GetTextProperty()->SetFontSize(24); //textActor->GetTextProperty()->SetColor(1.0, 0.0, 0.0); //renderer->AddActor2D(textActor); std::vector<std::tuple<VtkUniquePtr<vtkPolyDataMapper>, VtkUniquePtr<vtkActor>>> vtk_del; for (auto ply_dat : _ply_dats) { // The mapper is responsible for pushing the geometry into the graphics // library. It may also do color mapping, if scalars or other attributes // are defined. // vtkPolyDataMapper* actor_map = vtkPolyDataMapper::New(); actor_map->SetInputData(ply_dat); // The actor is a grouping mechanism: besides the geometry (mapper), it // also has a property, transformation matrix, and/or texture map. // Here we set its color and rotate it -22.5 degrees. vtkActor* actor = vtkActor::New(); vtk_del.emplace_back(actor_map, actor); actor->SetMapper(actor_map); if (_clrs != nullptr) actor->GetProperty()->SetColor((_clrs++)->data()); else actor->GetProperty()->SetColor(1.0000, 0.3882, 0.2784); //actor->RotateX(30.0); //actor->RotateY(-45.0); actor->GetProperty()->SetRepresentationToWireframe(); actor->GetProperty()->SetPointSize(5); // Add the actors to the renderer, set the background and size // renderer->AddActor(actor); } renderer->SetBackground(0.1, 0.2, 0.4); renWin->SetSize(800, 800); // We'll zoom in a little by accessing the camera and invoking a "Zoom" // method on it. renderer->ResetCamera(); renderer->GetActiveCamera()->Zoom(1.5); renderer->GetActiveCamera()->SetParallelProjection(1); renWin->Render(); // This starts the event loop and as a side effect causes an initial render. iren->Start(); // Exiting from here, we have to delete all the instances that // have been created. renderer->Delete(); renWin->Delete(); iren->Delete(); } vtkPolyData* make_tessellation(Topo::Wrap<Topo::Type::BODY> _body) { Topo::Iterator<Topo::Type::BODY, Topo::Type::VERTEX> vert_it(_body); std::vector<Topo::Wrap<Topo::Type::VERTEX>> all_verts; for (size_t i = 0; i < vert_it.size(); ++i) all_verts.push_back(vert_it.get(i)); std::sort(all_verts.begin(), all_verts.end()); all_verts.erase(std::unique(all_verts.begin(), all_verts.end()), all_verts.end()); vtkPolyData* poly_dat = vtkPolyData::New(); auto newPoints = vtkPoints::New(); newPoints->Allocate(all_verts.size()); for (auto v : all_verts) { Geo::Point pt; v->geom(pt); newPoints->InsertNextPoint(pt[0], pt[1], pt[2]); } vtkSmartPointer<vtkCellArray> vertices = vtkSmartPointer<vtkCellArray>::New(); for (int id = 0; id < all_verts.size(); ++id) { vtkVertex* vertex = vtkSmartPointer<vtkVertex>::New(); vertex->GetPointIds()->SetId(0, id); vertices->InsertNextCell(vertex); } poly_dat->SetPoints(newPoints); poly_dat->SetVerts(vertices); newPoints->Delete(); Topo::Iterator<Topo::Type::BODY, Topo::Type::FACE> face_it(_body); auto newPolys = vtkCellArray::New(); newPolys->Allocate(face_it.size()); for (size_t i = 0; i < face_it.size(); ++i) { std::vector<vtkIdType> pts; auto f = face_it.get(i); Topo::Iterator<Topo::Type::FACE, Topo::Type::VERTEX> fv(f); for (size_t j = 0; j < fv.size(); ++j) { auto v = fv.get(j); auto it = std::lower_bound(all_verts.begin(), all_verts.end(), v); if (it != all_verts.end() && *it == v) { pts.push_back(it - all_verts.begin()); } } newPolys->InsertNextCell(pts.size(), pts.data()); } poly_dat->SetPolys(newPolys); return poly_dat; } } EXAMPLE(0) { std::cout << "Insertfilenumber:"; int files_nmbr = 0; std::cin >> files_nmbr; std::vector<vtkPolyData*> poly_dats; Geo::VectorD3 rb[2] = { { 1, 0, 0 },{ 0,0,1 } }; std::vector<Geo::VectorD3> cols; for (int i = 0; i < files_nmbr; ++i) { auto body = IO::load_obj(open_file().c_str()); Topo::Iterator<Topo::Type::BODY, Topo::Type::VERTEX> bv_it(body); for (auto& x : bv_it) { Geo::Point pt; x->geom(pt); pt[0] += 0.00000002 * i; x->set_geom(pt); } poly_dats.push_back(make_tessellation(body)); cols.push_back(rb[i % 2]); } // "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/result.obj"); render_actors(poly_dats, cols.data()); } EXAMPLE(1) { // This creates a polygonal cylinder model with eight circumferential facets. // vtkPolyData *poly_dat = vtkPolyData::New(); auto newPoints = vtkPoints::New(); newPoints->Allocate(8); for (int idx = 0; idx < 8; ++idx) { double vv[2] = { -1, 1 }; newPoints->InsertNextPoint( vv[(idx & 4) > 0], vv[(idx & 2) > 0], vv[(idx & 1) > 0]); } poly_dat->SetPoints(newPoints); newPoints->Delete(); //output->GetPointData()->SetNormals(newNormals); //newNormals->Delete(); //output->GetPointData()->SetTCoords(newTCoords); //newTCoords->Delete(); auto newPolys = vtkCellArray::New(); newPolys->Allocate(6); { vtkIdType pts[4] = { 0, 1, 3, 2 }; newPolys->InsertNextCell(4, pts); } { vtkIdType pts[4] = { 4, 5, 7, 6 }; newPolys->InsertNextCell(4, pts); } { vtkIdType pts[4] = { 0, 1, 5, 4 }; newPolys->InsertNextCell(4, pts); } { vtkIdType pts[4] = { 2, 3, 7, 6 }; newPolys->InsertNextCell(4, pts); } { vtkIdType pts[4] = { 0, 2, 6, 4 }; newPolys->InsertNextCell(4, pts); } { vtkIdType pts[4] = { 1, 3, 7, 5 }; newPolys->InsertNextCell(4, pts); } poly_dat->SetPolys(newPolys); newPolys->Delete(); std::vector<vtkPolyData*> poly_dats{ poly_dat }; render_actors(poly_dats); } EXAMPLE(2) { auto body = IO::load_obj( "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/pyramid.OBJ"); vtkPolyData* poly_dat = make_tessellation(body); std::vector<vtkPolyData*> poly_dats{ poly_dat }; render_actors(poly_dats); } EXAMPLE(3) { auto body0 = IO::load_obj( "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/TUNA.OBJ"); auto body1 = IO::load_obj( "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/TUNA.OBJ"); Topo::Iterator<Topo::Type::BODY, Topo::Type::VERTEX> vert_it(body1); const Geo::VectorD3 oofs{ .1, .1, .1 }; for (size_t i = 0; i < vert_it.size(); ++i) { Geo::Point pt; vert_it.get(i)->geom(pt); pt += oofs; vert_it.get(i)->set_geom(pt); } std::vector<vtkPolyData*> poly_dats; //poly_dats.push_back(make_tessellation(body0)); //poly_dats.push_back(make_tessellation(body1)); auto booler = Boolean::ISolver::make(); booler->init(body0, body1); auto inters = booler->compute(Boolean::Operation::DIFFERENCE); poly_dats.push_back(make_tessellation(inters)); IO::save_obj("C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/result.obj", inters); render_actors(poly_dats); } EXAMPLE(4) { auto body0 = IO::load_obj( "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/cube.obj"); auto body1 = IO::load_obj( "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/cube.obj"); Topo::Iterator<Topo::Type::BODY, Topo::Type::VERTEX> vert_it(body1); const Geo::VectorD3 oofs{ .5, .5, .5 }; for (size_t i = 0; i < vert_it.size(); ++i) { Geo::Point pt; vert_it.get(i)->geom(pt); pt += oofs; vert_it.get(i)->set_geom(pt); } std::vector<vtkPolyData*> poly_dats; #if 0 poly_dats.push_back(make_tessellation(body0)); poly_dats.push_back(make_tessellation(body1)); #else auto booler = Boolean::ISolver::make(); booler->init(body0, body1); auto inters = booler->compute(Boolean::Operation::INTERSECTION); poly_dats.push_back(make_tessellation(inters)); #endif render_actors(poly_dats); } EXAMPLE(5) { auto body0 = IO::load_obj( "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/cube_00.obj"); auto body1 = IO::load_obj( "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/cube_00.obj"); Topo::Iterator<Topo::Type::BODY, Topo::Type::VERTEX> vert_it(body1); const Geo::VectorD3 oofs{ .5, .5, .5 }; for (size_t i = 0; i < vert_it.size(); ++i) { Geo::Point pt; vert_it.get(i)->geom(pt); pt += oofs; vert_it.get(i)->set_geom(pt); } std::vector<vtkPolyData*> poly_dats; #if 0 poly_dats.push_back(make_tessellation(body0)); poly_dats.push_back(make_tessellation(body1)); #else auto booler = Boolean::ISolver::make(); booler->init(body0, body1); auto inters = booler->compute(Boolean::Operation::DIFFERENCE); poly_dats.push_back(make_tessellation(inters)); IO::save_obj("C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/cube_00_out.obj", inters); #endif render_actors(poly_dats); } EXAMPLE(6) { auto body0 = IO::load_obj( "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/TUNA.OBJ"); auto body1 = IO::load_obj( "C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/TUNA.OBJ"); Topo::Iterator<Topo::Type::BODY, Topo::Type::VERTEX> vert_it(body1); const Geo::VectorD3 oofs{ 0.01, 0.01, 0.01 }; for (size_t i = 0; i < vert_it.size(); ++i) { Geo::Point pt; vert_it.get(i)->geom(pt); pt += oofs; vert_it.get(i)->set_geom(pt); } std::vector<vtkPolyData*> poly_dats; #if 0 poly_dats.push_back(make_tessellation(body0)); poly_dats.push_back(make_tessellation(body1)); #else auto booler = Boolean::ISolver::make(); booler->init(body0, body1); auto result = booler->compute(Boolean::Operation::DIFFERENCE); poly_dats.push_back(make_tessellation(result)); IO::save_obj("C:/Users/marco/OneDrive/Documents/PROJECTS/polytriagnulation/mesh/result.obj", result); #endif render_actors(poly_dats); } EXAMPLE(7) { std::vector<double> knots = { 0, 0, 1./64, 1./32, 0.0625, 0.125, 0.25, 0.5, 1, 1 }; struct Function0 : public Geo::IBsplineFitting<2>::IFunction { const double coe_ = M_PI * 3 / 2; virtual Geo::VectorD<2> evaluate(const double _t) const { return Geo::VectorD<2>{sin(_t * coe_), cos(_t * coe_)}; } virtual Geo::VectorD<2> closest_point( const Geo::VectorD<2>& _pt, const double) const { return _pt / Geo::length(_pt); } }; struct Function1 : public Geo::IBsplineFitting<2>::IFunction { const double one_third = 1. / 3, two_third = 2. / 3; virtual Geo::VectorD<2> evaluate(const double _t) const { if (_t < one_third) return Geo::VectorD<2>{ _t * 3, 1 }; if (_t > two_third) return Geo::VectorD<2>{ 1. - _t, -1. }; return Geo::VectorD<2>{ 1., 3. - _t * 6. }; } virtual Geo::VectorD<2> closest_point( const Geo::VectorD<2>& _pt, const double _t) const { if (_t < one_third) { double x = std::max(std::min(_pt[0], 1.), 0.); return Geo::VectorD<2>{ x, 1. }; } if (_t > two_third) { double x = std::max(std::min(_pt[0], 1.), 0.); return Geo::VectorD<2>{ x, -1. }; } double y = std::max(std::min(_pt[1], 1.), -1.); return Geo::VectorD<2>{ 1., y }; } }; const Function1 func; auto bsp_fit = Geo::IBsplineFitting<2>::make(); bsp_fit->init(2, knots, func); //bsp_fit->set_parameter_correction_iterations(4); //bsp_fit->set_samples_per_interval(256); bsp_fit->compute(); Geo::Nub<Geo::VectorD<2>, double> ev_nub; std::vector<Geo::VectorD<2>> opt_ctr_pts(bsp_fit->X()); ev_nub.init(opt_ctr_pts, knots); std::vector<vtkPolyData*> poly_dats = { vtkPolyData::New(), vtkPolyData::New() }; vtkPoints* newPoints[2]; vtkCellArray* newPolys[2]; for (auto i : { 0, 1 }) { newPoints[i] = vtkPoints::New(); newPoints[i]->Allocate(130); newPolys[i] = vtkCellArray::New(); newPolys[i]->Allocate(64); } vtkIdType idxs[4] = { 0, 2, 3, 1 }; std::ofstream plot("table.txt"); for (double x = 0; x <= 1.; x += 1. / 256) { const double t = knots.back() * x + knots.front() * (1 - x); Geo::VectorD<2> pt[2]; pt[0] = func.evaluate(t); ev_nub.eval(t, &pt[1], &pt[1] + 1); auto dd = pt[1] - pt[0]; double dist = Geo::length(pt[1]) - 1; if (pt[1][1] > 0 && pt[1][0] < 0 || x == 0 || x == 1) dist = Geo::length(pt[1] - pt[0]); #define SEP << " " << plot << /*t SEP Geo::length(dd) SEP dd[0] SEP dd[1] SEP */ dist << std::endl; for (auto i : { 0, 1 }) { for (auto z : { 0., 0.1 }) newPoints[i]->InsertNextPoint(pt[i][0], pt[i][1], 0.1* i + z); if (x > 0) newPolys[i]->InsertNextCell(4, idxs); } if (x > 0) for (auto& idx : idxs) idx += 2; } for (auto i : { 0, 1 }) { poly_dats[i]->SetPoints(newPoints[i]); newPoints[i]->Delete(); poly_dats[i]->SetPolys(newPolys[i]); newPolys[i]->Delete(); } Geo::VectorD3 cols[2] = { { 1, 0, 0 },{ 0, 0, 1 } }; render_actors(poly_dats, cols); }
30.626692
109
0.625363
marcomanno
2938faf77b20d7c7ec88dbcae3064c3a4bd1102e
6,306
cc
C++
gpio.cc
pablogad/libpt6312
068e4cbb34e7cedf28225f1750093cb35fe14c8f
[ "MIT" ]
null
null
null
gpio.cc
pablogad/libpt6312
068e4cbb34e7cedf28225f1750093cb35fe14c8f
[ "MIT" ]
null
null
null
gpio.cc
pablogad/libpt6312
068e4cbb34e7cedf28225f1750093cb35fe14c8f
[ "MIT" ]
null
null
null
// -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*- #include "gpio.h" #define BCM2708_PERI_BASE 0x20000000 #define BCM2709_PERI_BASE 0x3F000000 #define BCM2711_PERI_BASE 0xFE000000 #define GPIO_REGISTER_OFFSET 0x200000 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #define REGISTER_BLOCK_SIZE (4*1024) // GPIO setup macros. Always use INP_GPIO(x) before using OUT_GPIO(x) or SET_GPIO_ALT(x,y) #define INP_GPIO(g) *(gpio_port_+((g)/10)) &= ~(7<<(((g)%10)*3)) #define OUT_GPIO(g) *(gpio_port_+((g)/10)) |= (1<<(((g)%10)*3)) #define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3)) #define GET_GPIO(g) (*(gpio+13)&(1<<g)) // 0 if LOW, (1<<g) if HIGH #define GPIO_SET *(gpio+7) // sets bits which are 1 ignores bits which are 0 #define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0 /*static*/ const uint32_t GPIO::kValidBits = ((1 << 2) | (1 << 3) | (1 << 4) | (1 << 7)| (1 << 8) | (1 << 9) | (1 << 10) | (1 << 11) | (1 << 14) | (1 << 15)| (1 <<17) | (1 << 18)| (1 << 22) | (1 << 23) | (1 << 24) | (1 << 25)| (1 << 27)); enum RaspberryPiModel { PI_MODEL_1, PI_MODEL_2, PI_MODEL_3, PI_MODEL_4 }; static int ReadFileToBuffer(char *buffer, size_t size, const char *filename) { const int fd = open(filename, O_RDONLY); if (fd < 0) return -1; ssize_t r = read(fd, buffer, size - 1); // assume one read enough buffer[r >= 0 ? r : 0] = '\0'; close(fd); return r; } static RaspberryPiModel DetermineRaspberryModel() { char buffer[4096]; if (ReadFileToBuffer(buffer, sizeof(buffer), "/proc/cpuinfo") < 0) { fprintf(stderr, "Reading cpuinfo: Could not determine Pi model\n"); return PI_MODEL_3; // safe guess fallback. } static const char RevisionTag[] = "Revision"; const char *revision_key; if ((revision_key = strstr(buffer, RevisionTag)) == NULL) { fprintf(stderr, "non-existent Revision: Could not determine Pi model\n"); return PI_MODEL_3; } unsigned int pi_revision; if (sscanf(index(revision_key, ':') + 1, "%x", &pi_revision) != 1) { fprintf(stderr, "Unknown Revision: Could not determine Pi model\n"); return PI_MODEL_3; } // https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md const unsigned pi_type = (pi_revision >> 4) & 0xff; switch (pi_type) { case 0x00: /* A */ case 0x01: /* B, Compute Module 1 */ case 0x02: /* A+ */ case 0x03: /* B+ */ case 0x05: /* Alpha ?*/ case 0x06: /* Compute Module1 */ case 0x09: /* Zero */ case 0x0c: /* Zero W */ return PI_MODEL_1; case 0x04: /* Pi 2 */ return PI_MODEL_2; case 0x11: /* Pi 4 */ return PI_MODEL_4; default: /* a bunch of versions represneting Pi 3 */ return PI_MODEL_3; } } static volatile uint32_t *mmap_bcm_register(off_t register_offset) { off_t base = BCM2709_PERI_BASE; // safe fallback guess. switch (DetermineRaspberryModel()) { case PI_MODEL_1: base = BCM2708_PERI_BASE; break; case PI_MODEL_2: base = BCM2709_PERI_BASE; break; case PI_MODEL_3: base = BCM2709_PERI_BASE; break; case PI_MODEL_4: base = BCM2711_PERI_BASE; break; } int mem_fd = open("/dev/gpiomem", O_RDWR|O_SYNC); if (mem_fd < 0) { // Try fallback to old-school way. mem_fd = open("/dev/mem", O_RDWR|O_SYNC); } if (mem_fd < 0) return NULL; uint32_t *result = (uint32_t*) mmap(NULL, // Any adddress in our space will do REGISTER_BLOCK_SIZE, // Map length PROT_READ|PROT_WRITE, // Enable r/w on GPIO registers. MAP_SHARED, mem_fd, // File to map base + register_offset // Offset to bcm register ); close(mem_fd); if (result == MAP_FAILED) { perror("mmap error: "); fprintf(stderr, "MMapping from base 0x%lx, offset 0x%lx\n", (long)base, (long)register_offset); return NULL; } return result; } static void busy_wait_nanos_rpi_1(long nanos) { if (nanos < 70) return; // The following loop is determined empirically on a 700Mhz RPi for (uint32_t i = (nanos - 70) >> 2; i != 0; --i) { asm("nop"); } } static void busy_wait_nanos_rpi_2(long nanos) { if (nanos < 20) return; // The following loop is determined empirically on a 900Mhz RPi 2 for (uint32_t i = (nanos - 20) * 100 / 110; i != 0; --i) { asm(""); } } static void busy_wait_nanos_rpi_3(long nanos) { if (nanos < 20) return; for (uint32_t i = (nanos - 15) * 100 / 73; i != 0; --i) { asm(""); } } static void busy_wait_nanos_rpi_4(long nanos) { if (nanos < 20) return; // Interesting, the Pi4 is _slower_ than the Pi3 ? At least for this busy loop for (uint32_t i = (nanos - 5) * 100 / 132; i != 0; --i) { asm(""); } } // -- public interface GPIO::GPIO() : input_bits_(0), output_bits_(0), gpio_port_(NULL) {} uint32_t GPIO::InitInputs(uint32_t inputs) { if (gpio_port_ == NULL) { fprintf(stderr, "Attempt to init inputs but not initialized.\n"); return 0; } inputs &= kValidBits; // Sanitize input. input_bits_ = inputs; for (uint32_t b = 0; b < 27; ++b) { if (inputs & (1 << b)) { INP_GPIO(b); } } return input_bits_; } uint32_t GPIO::InitOutputs(uint32_t outputs) { if (gpio_port_ == NULL) { fprintf(stderr, "Attempt to init outputs but not initialized.\n"); return 0; } outputs &= kValidBits; // Sanitize input. output_bits_ = outputs; for (uint32_t b = 0; b < 27; ++b) { if (outputs & (1 << b)) { INP_GPIO(b); // for writing, we first need to set as input. OUT_GPIO(b); } } return output_bits_; } bool GPIO::Init() { if (gpio_port_ == NULL) { const RaspberryPiModel model = DetermineRaspberryModel(); gpio_port_ = mmap_bcm_register(GPIO_REGISTER_OFFSET); switch (model) { case PI_MODEL_1: busy_wait_impl_ = busy_wait_nanos_rpi_1; break; case PI_MODEL_2: busy_wait_impl_ = busy_wait_nanos_rpi_2; break; case PI_MODEL_3: busy_wait_impl_ = busy_wait_nanos_rpi_3; break; case PI_MODEL_4: busy_wait_impl_ = busy_wait_nanos_rpi_4; break; } } return gpio_port_ != NULL; }
30.463768
92
0.621313
pablogad
293b00cc509d5365ac435ac9d368e545b0a9856b
340
cpp
C++
WayTooLong2.cpp
AmitHasanShuvo/Programming
f47ecc626e518a0bf5f9f749afd15ce67bbe737b
[ "MIT" ]
8
2019-05-26T19:24:13.000Z
2021-03-24T17:36:14.000Z
WayTooLong2.cpp
AmitHasanShuvo/Programming
f47ecc626e518a0bf5f9f749afd15ce67bbe737b
[ "MIT" ]
null
null
null
WayTooLong2.cpp
AmitHasanShuvo/Programming
f47ecc626e518a0bf5f9f749afd15ce67bbe737b
[ "MIT" ]
1
2020-04-19T04:59:54.000Z
2020-04-19T04:59:54.000Z
#include <iostream> using namespace std; int main() { int n; string s; cin >> n; while (n--) { cin >> s; if (s.length > 10) { cout << s [0] << s.length() - 2 << s[s.length() - 1] << endl; } else { cout << s <<endl; } } return 0; }
14.782609
73
0.358824
AmitHasanShuvo
293c36ddd2874c631ae47e70850b37497fc89e71
2,773
cpp
C++
source/ParadiseCracked.WidescreenFix/dllmain.cpp
Sergeanur/WidescreenFixesPack
7e159be860a870476a97c322a0c4dd244e50cee7
[ "MIT" ]
null
null
null
source/ParadiseCracked.WidescreenFix/dllmain.cpp
Sergeanur/WidescreenFixesPack
7e159be860a870476a97c322a0c4dd244e50cee7
[ "MIT" ]
null
null
null
source/ParadiseCracked.WidescreenFix/dllmain.cpp
Sergeanur/WidescreenFixesPack
7e159be860a870476a97c322a0c4dd244e50cee7
[ "MIT" ]
null
null
null
#include "stdafx.h" struct Screen { int Width; int Height; float fWidth; float fHeight; float fAspectRatio; } Screen; void Init() { CIniReader iniReader(""); Screen.Width = iniReader.ReadInteger("MAIN", "ResX", 0); Screen.Height = iniReader.ReadInteger("MAIN", "ResY", 0); if (!Screen.Width || !Screen.Height) std::tie(Screen.Width, Screen.Height) = GetDesktopRes(); Screen.fWidth = static_cast<float>(Screen.Width); Screen.fHeight = static_cast<float>(Screen.Height); Screen.fAspectRatio = (Screen.fWidth / Screen.fHeight); auto pattern = hook::pattern("68 58 02 00 00 68 20 03 00 00"); injector::WriteMemory(pattern.count(1).get(0).get<uint32_t>(1), Screen.Width, true); injector::WriteMemory(pattern.count(1).get(0).get<uint32_t>(6), Screen.Height, true); pattern = hook::pattern("BE 20 03 00 00"); for (size_t i = 0; i < pattern.size(); ++i) { injector::WriteMemory(pattern.get(i).get<uint32_t>(1), Screen.Width, true); } pattern = hook::pattern("BF 58 02 00 00"); for (size_t i = 0; i < pattern.size(); ++i) { injector::WriteMemory(pattern.get(i).get<uint32_t>(1), Screen.Height, true); } pattern = hook::pattern("74 22 48 75 25 68"); injector::WriteMemory<uint8_t>(pattern.count(1).get(0).get<uint32_t>(0), 0xEB, true); pattern = hook::pattern("83 7D F0 02 75 ? 8B 45 08"); injector::WriteMemory<uint8_t>(pattern.count(1).get(0).get<uint32_t>(4), 0xEB, true); pattern = hook::pattern("C7 45 D0 20 03 00 00"); for (size_t i = 0; i < pattern.size(); ++i) { injector::WriteMemory(pattern.get(i).get<uint32_t>(3), Screen.Width, true); } pattern = hook::pattern("C7 45 D4 58 02 00 00"); for (size_t i = 0; i < pattern.size(); ++i) { injector::WriteMemory(pattern.get(i).get<uint32_t>(3), Screen.Height, true); } pattern = hook::pattern("C7 85 5C FF FF FF 20 03 00 00"); injector::WriteMemory(pattern.count(1).get(0).get<uint32_t>(6), Screen.Width, true); pattern = hook::pattern("C7 85 60 FF FF FF 58 02 00 00"); injector::WriteMemory(pattern.count(1).get(0).get<uint32_t>(6), Screen.Height, true); Screen.fAspectRatio = (Screen.fHeight / Screen.fWidth); pattern = hook::pattern("D9 05 ? ? ? ? 83 EC 10 D9 5C 24 0C"); injector::WriteMemory<float>(*pattern.count(1).get(0).get<uint32_t*>(2), Screen.fAspectRatio, true); } CEXP void InitializeASI() { std::call_once(CallbackHandler::flag, []() { CallbackHandler::RegisterCallback(Init, hook::pattern("83 EC 58 53 56 57 89 65 E8")); }); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { if (reason == DLL_PROCESS_ATTACH) { } return TRUE; }
33.011905
104
0.635052
Sergeanur
293e5316bf711593f8a4a216551e2bd2fc3252f5
9,613
cpp
C++
Project 10-16/15 Geometry Shader Beginning/GameApp.cpp
flygod1159/DirectX11-With-Windows-SDK
236acb9c658af6fa22c5319871fc88c2e80f6bb1
[ "MIT" ]
null
null
null
Project 10-16/15 Geometry Shader Beginning/GameApp.cpp
flygod1159/DirectX11-With-Windows-SDK
236acb9c658af6fa22c5319871fc88c2e80f6bb1
[ "MIT" ]
1
2020-02-21T17:11:24.000Z
2020-02-21T17:11:24.000Z
Project 10-16/15 Geometry Shader Beginning/GameApp.cpp
huangten/DirectX11-With-Windows-SDK
148b6306a078618f82b02ae25969dbad2831e456
[ "MIT" ]
null
null
null
#include "GameApp.h" #include "d3dUtil.h" #include "DXTrace.h" using namespace DirectX; GameApp::GameApp(HINSTANCE hInstance) : D3DApp(hInstance), m_ShowMode(Mode::SplitedTriangle), m_VertexCount() { } GameApp::~GameApp() { } bool GameApp::Init() { if (!D3DApp::Init()) return false; // 务必先初始化所有渲染状态,以供下面的特效使用 RenderStates::InitAll(m_pd3dDevice.Get()); if (!m_BasicEffect.InitAll(m_pd3dDevice.Get())) return false; if (!InitResource()) return false; #ifndef USE_IMGUI // 初始化鼠标,键盘不需要 m_pMouse->SetWindow(m_hMainWnd); m_pMouse->SetMode(DirectX::Mouse::MODE_ABSOLUTE); #endif return true; } void GameApp::OnResize() { // 释放D2D的相关资源 m_pColorBrush.Reset(); m_pd2dRenderTarget.Reset(); D3DApp::OnResize(); #ifndef USE_IMGUI // 为D2D创建DXGI表面渲染目标 ComPtr<IDXGISurface> surface; HR(m_pSwapChain->GetBuffer(0, __uuidof(IDXGISurface), reinterpret_cast<void**>(surface.GetAddressOf()))); D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED)); HRESULT hr = m_pd2dFactory->CreateDxgiSurfaceRenderTarget(surface.Get(), &props, m_pd2dRenderTarget.GetAddressOf()); surface.Reset(); if (hr == E_NOINTERFACE) { OutputDebugStringW(L"\n警告:Direct2D与Direct3D互操作性功能受限,你将无法看到文本信息。现提供下述可选方法:\n" L"1. 对于Win7系统,需要更新至Win7 SP1,并安装KB2670838补丁以支持Direct2D显示。\n" L"2. 自行完成Direct3D 10.1与Direct2D的交互。详情参阅:" L"https://docs.microsoft.com/zh-cn/windows/desktop/Direct2D/direct2d-and-direct3d-interoperation-overview""\n" L"3. 使用别的字体库,比如FreeType。\n\n"); } else if (hr == S_OK) { // 创建固定颜色刷和文本格式 HR(m_pd2dRenderTarget->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::White), m_pColorBrush.GetAddressOf())); HR(m_pdwriteFactory->CreateTextFormat(L"宋体", nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 15, L"zh-cn", m_pTextFormat.GetAddressOf())); } else { // 报告异常问题 assert(m_pd2dRenderTarget); } #endif // 更新投影矩阵 m_BasicEffect.SetProjMatrix(XMMatrixPerspectiveFovLH(XM_PI / 3, AspectRatio(), 1.0f, 1000.0f)); } void GameApp::UpdateScene(float dt) { // 更新每帧变化的值 if (m_ShowMode == Mode::SplitedTriangle) { m_BasicEffect.SetWorldMatrix(XMMatrixIdentity()); } else { static float phi = 0.0f, theta = 0.0f; phi += 0.2f * dt, theta += 0.3f * dt; m_BasicEffect.SetWorldMatrix(XMMatrixRotationX(phi) * XMMatrixRotationY(theta)); } #ifdef USE_IMGUI if (ImGui::Begin("Geometry Shader Beginning")) { static int curr_item = 0; static const char* modes[] = { "Splited Triangle", "Cylinder w/o Cap" }; if (ImGui::Combo("Mode", &curr_item, modes, ARRAYSIZE(modes))) { m_ShowMode = static_cast<Mode>(curr_item); if (curr_item == 0) { ResetTriangle(); m_BasicEffect.SetRenderSplitedTriangle(m_pd3dImmediateContext.Get()); } else { ResetRoundWire(); m_BasicEffect.SetRenderCylinderNoCap(m_pd3dImmediateContext.Get()); } // 输入装配阶段的顶点缓冲区设置 UINT stride = curr_item ? sizeof(VertexPosNormalColor) : sizeof(VertexPosColor); // 跨越字节数 UINT offset = 0; // 起始偏移量 m_pd3dImmediateContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &stride, &offset); } if (curr_item == 1) { static bool show_normal = false; if (ImGui::Checkbox("Show Normal", &show_normal)) { m_ShowMode = show_normal ? Mode::CylinderNoCapWithNormal : Mode::CylinderNoCap; } } } ImGui::End(); ImGui::Render(); #else // 更新鼠标事件,获取相对偏移量 Mouse::State mouseState = m_pMouse->GetState(); Mouse::State lastMouseState = m_MouseTracker.GetLastState(); m_MouseTracker.Update(mouseState); Keyboard::State keyState = m_pKeyboard->GetState(); m_KeyboardTracker.Update(keyState); // 切换显示模式 if (m_KeyboardTracker.IsKeyPressed(Keyboard::D1)) { m_ShowMode = Mode::SplitedTriangle; ResetTriangle(); // 输入装配阶段的顶点缓冲区设置 UINT stride = sizeof(VertexPosColor); // 跨越字节数 UINT offset = 0; // 起始偏移量 m_pd3dImmediateContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &stride, &offset); m_BasicEffect.SetRenderSplitedTriangle(m_pd3dImmediateContext.Get()); } else if (m_KeyboardTracker.IsKeyPressed(Keyboard::D2)) { m_ShowMode = Mode::CylinderNoCap; ResetRoundWire(); // 输入装配阶段的顶点缓冲区设置 UINT stride = sizeof(VertexPosNormalColor); // 跨越字节数 UINT offset = 0; // 起始偏移量 m_pd3dImmediateContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &stride, &offset); m_BasicEffect.SetRenderCylinderNoCap(m_pd3dImmediateContext.Get()); } // 显示法向量 if (m_KeyboardTracker.IsKeyPressed(Keyboard::Q)) { if (m_ShowMode == Mode::CylinderNoCap) m_ShowMode = Mode::CylinderNoCapWithNormal; else if (m_ShowMode == Mode::CylinderNoCapWithNormal) m_ShowMode = Mode::CylinderNoCap; } #endif } void GameApp::DrawScene() { assert(m_pd3dImmediateContext); assert(m_pSwapChain); m_pd3dImmediateContext->ClearRenderTargetView(m_pRenderTargetView.Get(), reinterpret_cast<const float*>(&Colors::Black)); m_pd3dImmediateContext->ClearDepthStencilView(m_pDepthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); // 应用常量缓冲区的变化 m_BasicEffect.Apply(m_pd3dImmediateContext.Get()); m_pd3dImmediateContext->Draw(m_VertexCount, 0); // 绘制法向量,绘制完后记得归位 if (m_ShowMode == Mode::CylinderNoCapWithNormal) { m_BasicEffect.SetRenderNormal(m_pd3dImmediateContext.Get()); // 应用常量缓冲区的变化 m_BasicEffect.Apply(m_pd3dImmediateContext.Get()); m_pd3dImmediateContext->Draw(m_VertexCount, 0); m_BasicEffect.SetRenderCylinderNoCap(m_pd3dImmediateContext.Get()); } #ifdef USE_IMGUI ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); #else // ****************** // 绘制Direct2D部分 // if (m_pd2dRenderTarget != nullptr) { m_pd2dRenderTarget->BeginDraw(); std::wstring text = L"切换类型:1-分裂的三角形 2-圆线构造柱面\n" L"当前模式: "; if (m_ShowMode == Mode::SplitedTriangle) text += L"分裂的三角形"; else if (m_ShowMode == Mode::CylinderNoCap) text += L"圆线构造柱面(Q-显示圆线的法向量)"; else text += L"圆线构造柱面(Q-隐藏圆线的法向量)"; m_pd2dRenderTarget->DrawTextW(text.c_str(), (UINT32)text.length(), m_pTextFormat.Get(), D2D1_RECT_F{ 0.0f, 0.0f, 600.0f, 200.0f }, m_pColorBrush.Get()); HR(m_pd2dRenderTarget->EndDraw()); } #endif HR(m_pSwapChain->Present(0, 0)); } bool GameApp::InitResource() { // ****************** // 初始化对象 // // 默认绘制三角形 ResetTriangle(); // ****************** // 初始化不会变化的值 // // 方向光 DirectionalLight dirLight; dirLight.ambient = XMFLOAT4(0.2f, 0.2f, 0.2f, 1.0f); dirLight.diffuse = XMFLOAT4(0.8f, 0.8f, 0.8f, 1.0f); dirLight.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); dirLight.direction = XMFLOAT3(-0.577f, -0.577f, 0.577f); m_BasicEffect.SetDirLight(0, dirLight); // 材质 Material material{}; material.ambient = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.0f); material.diffuse = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); material.specular = XMFLOAT4(0.5f, 0.5f, 0.5f, 5.0f); m_BasicEffect.SetMaterial(material); // 摄像机位置 m_BasicEffect.SetEyePos(XMFLOAT3(0.0f, 0.0f, -5.0f)); // 矩阵 m_BasicEffect.SetWorldMatrix(XMMatrixIdentity()); m_BasicEffect.SetViewMatrix(XMMatrixLookAtLH( XMVectorSet(0.0f, 0.0f, -5.0f, 1.0f), XMVectorZero(), XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f))); m_BasicEffect.SetProjMatrix(XMMatrixPerspectiveFovLH(XM_PI / 3, AspectRatio(), 1.0f, 1000.0f)); // 圆柱高度 m_BasicEffect.SetCylinderHeight(2.0f); // 输入装配阶段的顶点缓冲区设置 UINT stride = sizeof(VertexPosColor); // 跨越字节数 UINT offset = 0; // 起始偏移量 m_pd3dImmediateContext->IASetVertexBuffers(0, 1, m_pVertexBuffer.GetAddressOf(), &stride, &offset); // 设置默认渲染状态 m_BasicEffect.SetRenderSplitedTriangle(m_pd3dImmediateContext.Get()); return true; } void GameApp::ResetTriangle() { // ****************** // 初始化三角形 // // 设置三角形顶点 VertexPosColor vertices[] = { { XMFLOAT3(-1.0f * 3, -0.866f * 3, 0.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f) }, { XMFLOAT3(0.0f * 3, 0.866f * 3, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f) }, { XMFLOAT3(1.0f * 3, -0.866f * 3, 0.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f) } }; // 设置顶点缓冲区描述 D3D11_BUFFER_DESC vbd; ZeroMemory(&vbd, sizeof(vbd)); vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof vertices; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; // 新建顶点缓冲区 D3D11_SUBRESOURCE_DATA InitData; ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = vertices; HR(m_pd3dDevice->CreateBuffer(&vbd, &InitData, m_pVertexBuffer.ReleaseAndGetAddressOf())); // 三角形顶点数 m_VertexCount = 3; // 设置调试对象名 D3D11SetDebugObjectName(m_pVertexBuffer.Get(), "TriangleVertexBuffer"); } void GameApp::ResetRoundWire() { // ****************** // 初始化圆线 // 设置圆边上各顶点 // 必须要按顺时针设置 // 由于要形成闭环,起始点需要使用2次 // ______ // / \ // \______/ // VertexPosNormalColor vertices[41]; for (int i = 0; i < 40; ++i) { vertices[i].pos = XMFLOAT3(cosf(XM_PI / 20 * i), -1.0f, -sinf(XM_PI / 20 * i)); vertices[i].normal = XMFLOAT3(cosf(XM_PI / 20 * i), 0.0f, -sinf(XM_PI / 20 * i)); vertices[i].color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); } vertices[40] = vertices[0]; // 设置顶点缓冲区描述 D3D11_BUFFER_DESC vbd; ZeroMemory(&vbd, sizeof(vbd)); vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof vertices; vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; // 新建顶点缓冲区 D3D11_SUBRESOURCE_DATA InitData; ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = vertices; HR(m_pd3dDevice->CreateBuffer(&vbd, &InitData, m_pVertexBuffer.ReleaseAndGetAddressOf())); // 线框顶点数 m_VertexCount = 41; // 设置调试对象名 D3D11SetDebugObjectName(m_pVertexBuffer.Get(), "CylinderVertexBuffer"); }
26.628809
124
0.707688
flygod1159
293fba4f6b92bc9bdc73f3241880a8ae94864240
2,191
cc
C++
src/time_range.cc
aexoden/chatstats
07b7321cb6eed4d667ba1de9abbd29249286154f
[ "MIT" ]
null
null
null
src/time_range.cc
aexoden/chatstats
07b7321cb6eed4d667ba1de9abbd29249286154f
[ "MIT" ]
null
null
null
src/time_range.cc
aexoden/chatstats
07b7321cb6eed4d667ba1de9abbd29249286154f
[ "MIT" ]
null
null
null
/* * Copyright (c) 2012 Jason Lynch <jason@calindora.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <glibmm/regex.h> #include "time_range.hh" TimeRange::TimeRange(const Glib::ustring & start_date, const Glib::ustring & end_date, const Glib::ustring & start_time, const Glib::ustring & end_time) : start_date(start_date), end_date(end_date), start_time(start_time), end_time(end_time) { } Glib::ustring TimeRange::get_sql_expression() const { Glib::ustring expression; this->_append_sql_expression(expression, "DATE(timestamp) >= '%1'", this->start_date); this->_append_sql_expression(expression, "DATE(timestamp) < '%1'", this->end_date); this->_append_sql_expression(expression, "TIME(timestamp) >= '%1'", this->start_time); this->_append_sql_expression(expression, "TIME(timestamp) < '%1'", this->end_time); return expression; } void TimeRange::_append_sql_expression(Glib::ustring & expression, const Glib::ustring & parameter_template, const Glib::ustring & value) const { if (!value.empty()) { if (!expression.empty()) expression += " AND "; expression += Glib::ustring::compose(parameter_template, value); } }
39.125
154
0.746691
aexoden
2940fcdcd73945aed3002f0e0026e9636affb263
4,363
cpp
C++
Problem_3/memory.cpp
JHernandez2802/CSCE4600_Project2
9712fa66b60592ed1d124985bb387ffbda0a97fc
[ "MIT" ]
null
null
null
Problem_3/memory.cpp
JHernandez2802/CSCE4600_Project2
9712fa66b60592ed1d124985bb387ffbda0a97fc
[ "MIT" ]
null
null
null
Problem_3/memory.cpp
JHernandez2802/CSCE4600_Project2
9712fa66b60592ed1d124985bb387ffbda0a97fc
[ "MIT" ]
null
null
null
// File memory.cpp /***************************************************************** Programmer: Matthew Sherwood, Li Zhang, Juan Hernandez * Class: CSCE 4600 * Date: 04/27/2015 * Assignment: Project 2 * Purpose: To simulate of different scheduling disciplines to * allocate set of processes to available processors * *****************************************************************/ #include "processes.h" #include "memoryTable.h" #include <vector> int INTERVAL=50;//every 50 cycle, process arrive static int MEM_SIZE; static unsigned char *MEMORY_POOL; static unsigned char *MEM_POINTER; static long MEM_START ; c_Proc** Proccess; void re_malloc(c_Proc* p); void my_malloc(c_Proc* p); vector<memoryTable*> memorylist; vector<memoryTable*> tmplist; int check(c_Proc* p){//free space or not int position=-1; int space; for(int i=0;i<memorylist.size();i++){ if((memorylist.at(i)->Memspace()>=p->mem())&&(memorylist.at(i)->getfree())){ space=memorylist.at(i)->Memspace(); position=i; break; } } for(int i=position;i<memorylist.size();i++){ if((memorylist.at(i)->Memspace()>=p->mem())&&(memorylist.at(i)->getfree())) if(memorylist.at(i)->Memspace()<space){ space=memorylist.at(i)->Memspace(); position=i; } } return position; } void compact(){ // memoryTable* newtable=new memoryTable(-1,(long)MEM_POINTER,(long)(MEM_POINTER+MEM_SIZE*sizeof(char))); // newtable->setFree(true); // tmplist.push_back(newtable);//initail memTlb // for(int i=0;i<memorylist.size();i++){ // if(memorylist.at(i)->ProcNum>0){ // // } // } // memorylist.clear(); // memorylist=tmplist; } void re_malloc(c_Proc* p){ int position=check(p); if(position!=-1){//can malloc long MEM_END=(long)(tmplist.at(position)->getStart()+p->mem()*sizeof(char));//size of memory memoryTable* newtable=new memoryTable(p->pid(),memorylist.at(position)->getStart(),MEM_END);//new block of request memoryTable* newtable2=new memoryTable(-1,MEM_END+1,memorylist.at(position)->getEnd());//new block from memorylist.at(position)->setId(-2); newtable2->setFree(true); memorylist.push_back(newtable); memorylist.push_back(newtable2); } } void my_malloc(c_Proc* p){//using best fit int position=check(p); if(position!=-1){//can malloc long MEM_END=(long)(memorylist.at(position)->getStart()+p->mem()*sizeof(char));//size of memory memoryTable* newtable=new memoryTable(p->pid(),memorylist.at(position)->getStart(),MEM_END);//new block of request memoryTable* newtable2=new memoryTable(-1,MEM_END+1,memorylist.at(position)->getEnd());//new block from memorylist.at(position)->setId(-2); newtable2->setFree(true); memorylist.push_back(newtable); memorylist.push_back(newtable2); } else//can not malloc { cout<<"not enough place"<<endl; } } void my_free(c_Proc* P){ int id=P->pid(); int position; for(int i=0;i<memorylist.size();i++){ if(memorylist.at(i)->getId()==id){ position=i; break; } } memorylist.at(position)->setFree(true); memorylist.at(position)->setId(-1); compact(); } void simulator(c_Proc** Proc,int total,int space){ int number=total;//total number of processes int INTERVAL=50;//every 50 cycle, process arrive Proccess=Proc; MEM_SIZE = space; MEMORY_POOL = (unsigned char*)malloc(MEM_SIZE*sizeof(char));// MEM_POINTER = MEMORY_POOL;//pointer to start of memory MEM_START = (long)MEMORY_POOL;//long int represent address memoryTable* newtable=new memoryTable(-1,(long)MEM_POINTER,(long)(MEM_POINTER+MEM_SIZE*sizeof(char))); newtable->setFree(true); memorylist.push_back(newtable);//initail memTlb for(int i=0;i<total;i++){ my_malloc(Proccess[i]); } //my_free(Proccess[]); for(int i=0;i<memorylist.size();i++) memorylist.at(i)->display(); }
35.762295
122
0.581251
JHernandez2802
29441e0dd15f1eed77b2f1dabb2b4d25a3b28687
23,791
cc
C++
src/netlicensing.cc
optimad/NetLicensingClient-cpp
ff0004cd73af75321a951a0d57dad6d37c03a441
[ "Apache-2.0" ]
null
null
null
src/netlicensing.cc
optimad/NetLicensingClient-cpp
ff0004cd73af75321a951a0d57dad6d37c03a441
[ "Apache-2.0" ]
null
null
null
src/netlicensing.cc
optimad/NetLicensingClient-cpp
ff0004cd73af75321a951a0d57dad6d37c03a441
[ "Apache-2.0" ]
null
null
null
#include "netlicensing/constants.h" #include "netlicensing/netlicensing.h" #include "netlicensing/service.h" #include "netlicensing/validation_parameters.h" #include <time.h> namespace netlicensing { /** * C++ representation of the Product Service. See NetLicensingAPI for details: * https://netlicensing.io/wiki/product-services */ /** * Creates new product object with given properties. See NetLicensingAPI for details: * https://netlicensing.io/wiki/product-services#create-product */ Product ProductService::create(Context& ctx, const Product& product) { StandardMapper<Product> productMapper; netlicensing::create(ctx, productMapper, product); return productMapper.getItems().front(); } /** * Get product object with. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Services#ProductServices-Getproduct */ Product ProductService::get(Context& ctx, const std::string& productNumber) { StandardMapper<Product> productMapper; netlicensing::get(ctx, productMapper, productNumber); return productMapper.getItems().front(); } /** * Updates product properties. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Services#ProductServices-Updateproduct */ Product ProductService::update(Context& ctx, const std::string& productNumber, const Product& product) { StandardMapper<Product> productMapper; netlicensing::update(ctx, productMapper, productNumber, product); return productMapper.getItems().front(); } /** * Deletes product. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Services#ProductServices-Deleteproduct */ void ProductService::del(Context& ctx, const std::string& productNumber, bool forceCascade) { netlicensing::del<Product>(ctx, productNumber, forceCascade); } /** * Returns all products of a vendor. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Services#ProductServices-Productslist */ std::list<Product> ProductService::list(Context& ctx, const std::string& filter) { StandardMapper<Product> productMapper; netlicensing::list(ctx, productMapper, filter); return productMapper.getItems(); } /** * C++ representation of the Product Module Service. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services */ /** * Creates new product module object with given properties. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Createproductmodule */ ProductModule ProductModuleService::create(Context& ctx, const ProductModule& productModule) { StandardMapper<ProductModule> productModuleMapper; netlicensing::create(ctx, productModuleMapper, productModule); return productModuleMapper.getItems().front(); } /** * Get product module object with. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Getproductmodule */ ProductModule ProductModuleService::get(Context& ctx, const std::string& productModuleNumber) { StandardMapper<ProductModule> productModuleMapper; netlicensing::get(ctx, productModuleMapper, productModuleNumber); return productModuleMapper.getItems().front(); } /** * Returns all product modules of a vendor. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Productmoduleslist */ std::list<ProductModule> ProductModuleService::list(Context& ctx, const std::string& filter) { StandardMapper<ProductModule> productModuleMapper; netlicensing::list(ctx, productModuleMapper, filter); return productModuleMapper.getItems(); } /** * Updates product module properties. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Updateproductmodule */ ProductModule ProductModuleService::update(Context& ctx, const std::string& productModuleNumber, const ProductModule& productModule) { StandardMapper<ProductModule> productModuleMapper; netlicensing::update(ctx, productModuleMapper, productModuleNumber, productModule); return productModuleMapper.getItems().front(); } /** * Deletes product module. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Product+Module+Services#ProductModuleServices-Deleteproductmodule */ void ProductModuleService::del(Context& ctx, const std::string& productModuleNumber, bool forceCascade) { netlicensing::del<ProductModule>(ctx, productModuleNumber, forceCascade); } /** * C++ representation of the License Template Service. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Template+Services */ /** * Creates new license template object with given properties. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Template+Services#LicenseTemplateServices-Createlicensetemplate */ LicenseTemplate LicenseTemplateService::create(Context& ctx, const LicenseTemplate& licenseTemplate) { StandardMapper<LicenseTemplate> licenseTemplateMapper; netlicensing::create(ctx, licenseTemplateMapper, licenseTemplate); return licenseTemplateMapper.getItems().front(); } /** * Get license template object with. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Template+Services#LicenseTemplateServices-Getlicensetemplate */ LicenseTemplate LicenseTemplateService::get(Context& ctx, const std::string& licenseTemplateNumber) { StandardMapper<LicenseTemplate> licenseTemplateMapper; netlicensing::get(ctx, licenseTemplateMapper, licenseTemplateNumber); return licenseTemplateMapper.getItems().front(); } /** * Returns all license templates of a vendor. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Template+Services#LicenseTemplateServices-Licensetemplateslist */ std::list<LicenseTemplate> LicenseTemplateService::list(Context& ctx, const std::string& filter) { StandardMapper<LicenseTemplate> licenseTemplateMapper; netlicensing::list(ctx, licenseTemplateMapper, filter); return licenseTemplateMapper.getItems(); } /** * Updates license template properties. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Template+Services#LicenseTemplateServices-Updatelicensetemplate */ LicenseTemplate LicenseTemplateService::update(Context& ctx, const std::string& licenseTemplateNumber, const LicenseTemplate& licenseTemplate) { StandardMapper<LicenseTemplate> licenseTemplateMapper; netlicensing::update(ctx, licenseTemplateMapper, licenseTemplateNumber, licenseTemplate); return licenseTemplateMapper.getItems().front(); } /** * Deletes license template. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Template+Services#LicenseTemplateServices-Deletelicensetemplate */ void LicenseTemplateService::del(Context& ctx, const std::string& licenseTemplateNumber, bool forceCascade) { netlicensing::del<LicenseTemplate>(ctx, licenseTemplateNumber, forceCascade); } /** * C++ representation of the Licensee Service. See NetLicensingAPI JavaDoc for details: * https://www.labs64.de/confluence/display/NLICPUB/Licensee+Services */ /** * Creates new licensee object with given properties. See NetLicensingAPI JavaDoc for details: * https://www.labs64.de/confluence/display/NLICPUB/Licensee+Services#LicenseeServices-Createlicensee */ Licensee LicenseeService::create(Context& ctx, const Licensee& licensee) { StandardMapper<Licensee> licenseeMapper; netlicensing::create(ctx, licenseeMapper, licensee); return licenseeMapper.getItems().front(); } /** * Get licensee object with. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Licensee+Services#LicenseeServices-Getlicensee */ Licensee LicenseeService::get(Context& ctx, const std::string& licenseeNumber) { StandardMapper<Licensee> licenseeMapper; netlicensing::get(ctx, licenseeMapper, licenseeNumber); return licenseeMapper.getItems().front(); } /** * Updates licensee properties. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Licensee+Services#LicenseeServices-Updatelicensee */ Licensee LicenseeService::update(Context& ctx, const std::string& number, const Licensee& licensee) { StandardMapper<Licensee> licenseeMapper; netlicensing::update(ctx, licenseeMapper, number, licensee); return licenseeMapper.getItems().front(); } /** * Deletes licensee. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Licensee+Services#LicenseeServices-Deletelicensee */ void LicenseeService::del(Context& ctx, const std::string& licenseeNumber, bool forceCascade) { netlicensing::del<Licensee>(ctx, licenseeNumber, forceCascade); } /** * Returns all licensees of a vendor. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Licensee+Services#LicenseeServices-Licenseeslist */ std::list<Licensee> LicenseeService::list(Context& ctx, const std::string& filter) { StandardMapper<Licensee> licenseeMapper; netlicensing::list(ctx, licenseeMapper, filter); return licenseeMapper.getItems(); } /** * Validates active licenses of the licensee. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Licensee+Services#LicenseeServices-Validatelicensee */ ValidationResult LicenseeService::validate(Context& ctx, const std::string& licenseeNumber, const std::string& productNumber/* = std::string()*/, const std::string& licenseeName/* = std::string()*/, const parameters_type& validationParameters) { std::string endpoint = std::string(LICENSEE_ENDPOINT_PATH) + "/" + escape_string(licenseeNumber) + "/" + ENDPOINT_PATH_VALIDATE; parameters_type params; if (!productNumber.empty()) params.push_back(std::make_pair(PRODUCT_NUMBER, escape_string(productNumber))); if (!licenseeName.empty()) params.push_back(std::make_pair(PROP_LICENSEE_NAME, escape_string(licenseeName))); // Add licensing model specific validation parameters for (parameters_type::const_iterator paramIt = validationParameters.begin(); paramIt != validationParameters.end(); ++paramIt) { params.push_back(std::make_pair(escape_string(paramIt->first), escape_string(paramIt->second))); } long http_code; std::string res = ctx.post(endpoint, params, http_code); ValidationResult validationResult; ValidationResultMapper vrm(validationResult); traverse(vrm, res); if (http_code != 200) { throw RestException(vrm.getInfos(), http_code); } return validationResult; } /** * Validates active licenses of the licensee. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Licensee+Services#LicenseeServices-Validatelicensee */ ValidationResult LicenseeService::validate(Context& ctx, const std::string& licenseeNumber, const ValidationParameters& validationParameters) { std::string endpoint = std::string(LICENSEE_ENDPOINT_PATH) + "/" + escape_string(licenseeNumber) + "/" + ENDPOINT_PATH_VALIDATE; parameters_type params; if (!escape_string(validationParameters.getProductNumber()).empty()) { params.push_back(std::make_pair(PRODUCT_NUMBER, escape_string(validationParameters.getProductNumber()))); } if (!escape_string(validationParameters.getLicenseeName()).empty()) { params.push_back(std::make_pair(PROP_LICENSEE_NAME, escape_string(validationParameters.getLicenseeName()))); } // if (!escape_string(validationParameters.getLicenseeSecret()).empty()) { // params.push_back(std::make_pair(PROP_LICENSEE_SECRET, escape_string(validationParameters.getLicenseeSecret()))); // } int paramIt = 0; for(auto const &ent1 : validationParameters.getParameters()) { auto const &productModuleNumber = ent1.first; auto const &productModuleParameters = ent1.second; params.push_back(std::make_pair(PRODUCT_MODULE_NUMBER + std::to_string(paramIt), escape_string(productModuleNumber))); for(auto const &ent2 : productModuleParameters) { auto const &inner_key = ent2.first; auto const &inner_value = ent2.second; params.push_back(std::make_pair(escape_string(inner_key) + std::to_string(paramIt), escape_string(inner_value))); } paramIt++; } long http_code; std::string res = ctx.post(endpoint, params, http_code); ValidationResult validationResult; ValidationResultMapper vrm(validationResult); traverse(vrm, res); //convert ttl in time_t Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(res.c_str(), root); if (parsingSuccessful) { Json::FastWriter fastWriter; //ttl returns with new line character ("\n") is appended at the end of the string and "\" at the begin of string. std::string ttl = fastWriter.write(root["ttl"]); struct tm ttlTime; std::size_t isNull = ttl.find("null"); if (isNull==std::string::npos) { ttlTime.tm_year = atoi(ttl.substr(1,4).c_str()) - 1900; /* years since 1900 */ ttlTime.tm_mon = atoi(ttl.substr(6, 2).c_str()) - 1; ttlTime.tm_mday = atoi(ttl.substr(9, 2).c_str()); ttlTime.tm_hour = atoi(ttl.substr(12, 2).c_str()); ttlTime.tm_min = atoi(ttl.substr(15, 2).c_str()); ttlTime.tm_sec = atoi(ttl.substr(18, 2).c_str()); } time_t rawtime = mktime(&ttlTime); validationResult.setTtl(rawtime); } if (http_code != 200) { throw RestException(vrm.getInfos(), http_code); } return validationResult; } /** * Transfer licenses between licensees.: * https://www.labs64.de/confluence/display/NLICPUB/Licensee+Services#LicenseeServices-Transferlicenses */ void LicenseeService::transfer(Context& ctx, const std::string& licenseeNumber, const std::string& sourceLicenseeNumber) { std::string endpoint = "licensee/" + escape_string(licenseeNumber) + "/" + ENDPOINT_PATH_TRANSFER; parameters_type params; if (!sourceLicenseeNumber.empty()) params.push_back(std::make_pair(SOURCE_LICENSEE_NUMBER, escape_string(sourceLicenseeNumber))); long http_code; std::string res = ctx.post(endpoint, params, http_code); } /** * C++ representation of the License. See NetLicensingAPI JavaDoc for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Services */ /** * Creates new license object with given properties. See NetLicensingAPI JavaDoc for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Services#LicenseServices-Createlicense */ License LicenseService::create(Context& ctx, const License& license) { StandardMapper<License> licenseMapper; netlicensing::create(ctx, licenseMapper, license); return licenseMapper.getItems().front(); } /** * Get license object with. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Services#LicenseServices-Getlicense */ License LicenseService::get(Context& ctx, const std::string& licenseNumber) { StandardMapper<License> licenseMapper; netlicensing::get(ctx, licenseMapper, licenseNumber); return licenseMapper.getItems().front(); } /** * Updates license properties. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Services#LicenseServices-Updatelicense */ License LicenseService::update(Context& ctx, const std::string& number, const License& license) { StandardMapper<License> licenseMapper; netlicensing::update(ctx, licenseMapper, number, license); return licenseMapper.getItems().front(); } /** * Deletes license. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Services#LicenseServices-Deletelicense */ void LicenseService::del(Context& ctx, const std::string& licenseNumber, bool forceCascade) { netlicensing::del<License>(ctx, licenseNumber, forceCascade); } /** * Returns all licenses of a vendor. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/License+Services#LicenseServices-Licenseslist */ std::list<License> LicenseService::list(Context& ctx, const std::string& filter) { StandardMapper<License> licenseMapper; netlicensing::list(ctx, licenseMapper, filter); return licenseMapper.getItems(); } /** * C++ representation of the Payment Method. See NetLicensingAPI JavaDoc for details: * https://www.labs64.de/confluence/display/NLICPUB/Payment+Method+Services */ /** * Get payment method object with. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Payment+Method+Services#PaymentMethodServices-Getpaymentmethod */ PaymentMethod PaymentMethodService::get(Context& ctx, const std::string& number) { StandardMapper<PaymentMethod> paymentMethodMapper; netlicensing::get(ctx, paymentMethodMapper, number); return paymentMethodMapper.getItems().front(); } /** * Updates payment method. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Payment+Method+Services#PaymentMethodServices-Updatepaymentmethod */ PaymentMethod PaymentMethodService::update(Context& ctx, const std::string& number, const PaymentMethod& paymentMethod) { StandardMapper<PaymentMethod> paymentMethodMapper; netlicensing::update(ctx, paymentMethodMapper, number, paymentMethod); return paymentMethodMapper.getItems().front(); } /** * Returns all payment methods. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Payment+Method+Services#PaymentMethodServices-Paymentmethodslist */ std::list<PaymentMethod> PaymentMethodService::list(Context& ctx, const std::string& filter) { StandardMapper<PaymentMethod> paymentMethodMapper; netlicensing::list(ctx, paymentMethodMapper, filter); return paymentMethodMapper.getItems(); } /** * C++ representation of the Token. See NetLicensingAPI JavaDoc for details: * https://www.labs64.de/confluence/display/NLICPUB/Token+Services */ /** * Creates new token object with given properties. See NetLicensingAPI JavaDoc for details: * https://www.labs64.de/confluence/display/NLICPUB/Token+Services#TokenServices-Createtoken */ Token TokenService::create(Context& ctx, const Token& token) { StandardMapper<Token> tokenMapper; netlicensing::create(ctx, tokenMapper, token); return tokenMapper.getItems().front(); } /** * Get token object with. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Token+Services#TokenServices-Gettoken */ Token TokenService::get(Context& ctx, const std::string& number) { StandardMapper<Token> tokenMapper; netlicensing::get(ctx, tokenMapper, number); return tokenMapper.getItems().front(); } /** * Deletes token. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Token+Services#TokenServices-Deletetoken */ void TokenService::del(Context& ctx, const std::string& number, bool forceCascade) { netlicensing::del<Token>(ctx, number, forceCascade); } /** * Returns all tokens. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Token+Services#TokenServices-Tokenslist */ std::list<Token> TokenService::list(Context& ctx, const std::string& filter) { StandardMapper<Token> tokenMapper; netlicensing::list(ctx, tokenMapper, filter); return tokenMapper.getItems(); } /** * C++ representation of the Transaction. See NetLicensingAPI JavaDoc for details: * https://www.labs64.de/confluence/display/NLICPUB/Transaction+Services */ /** * Creates new transaction object with given properties. See NetLicensingAPI JavaDoc for details: * https://www.labs64.de/confluence/display/NLICPUB/Transaction+Services#TransactionServices-Createtransaction */ Transaction TransactionService::create(Context& ctx, const Transaction& transaction) { StandardMapper<Transaction> transactionMapper; netlicensing::create(ctx, transactionMapper, transaction); return transactionMapper.getItems().front(); } /** * Updates transaction. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Transaction+Services#TransactionServices-Updatetransaction */ Transaction TransactionService::update(Context& ctx, const std::string& number, const Transaction& transaction) { StandardMapper<Transaction> transactionMapper; netlicensing::update(ctx, transactionMapper, number, transaction); return transactionMapper.getItems().front(); } /** * Get transaction object with. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Transaction+Services#TransactionServices-Gettransaction */ Transaction TransactionService::get(Context& ctx, const std::string& number) { StandardMapper<Transaction> transactionMapper; netlicensing::get(ctx, transactionMapper, number); return transactionMapper.getItems().front(); } /** * Returns all transaction. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Transaction+Services#TransactionServices-Transactionslist */ std::list<Transaction> TransactionService::list(Context& ctx, const std::string& filter) { StandardMapper<Transaction> transactionMapper; netlicensing::list(ctx, transactionMapper, filter); return transactionMapper.getItems(); } /** * C++ representation of the Utility Service. See NetLicensingAPI JavaDoc for details: * https://go.netlicensing.io/javadoc/v2/com/labs64/netlicensing/service/UtilityService.html */ /** * Returns all countries. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Utility+Services */ std::list<Country> UtilityService::listCountries(Context& ctx) { StandardMapper<Country> countryMapper; netlicensing::list(ctx, countryMapper, ""); return countryMapper.getItems(); } /** * Returns all licensing models. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Utility+Services#UtilityServices-LicensingModelslist */ std::list<LicensingModel> UtilityService::listLicensingModels(Context& ctx) { StandardMapper<LicensingModel> licensingModelsMapper; netlicensing::list(ctx, licensingModelsMapper, ""); return licensingModelsMapper.getItems(); } /** * Returns all license types. See NetLicensingAPI for details: * https://www.labs64.de/confluence/display/NLICPUB/Utility+Services#UtilityServices-LicenseTypeslist */ std::list<LicenseType> UtilityService::listLicenseTypes(Context& ctx) { StandardMapper<LicenseType> licenseTypeMapper; netlicensing::list(ctx, licenseTypeMapper, ""); return licenseTypeMapper.getItems(); } }
43.493601
146
0.741625
optimad
294497bfa2080d95dcd27985a1da3700940591dc
4,139
cpp
C++
src/Volume.cpp
dermegges/ugl
e5551f98d59c115460d1298d9082996b5da119da
[ "Apache-2.0" ]
null
null
null
src/Volume.cpp
dermegges/ugl
e5551f98d59c115460d1298d9082996b5da119da
[ "Apache-2.0" ]
null
null
null
src/Volume.cpp
dermegges/ugl
e5551f98d59c115460d1298d9082996b5da119da
[ "Apache-2.0" ]
null
null
null
/** @file Volume.cpp Copyright 2016 Computational Topology Group, University of Kaiserslautern Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author(s): C.Garth, T.Biedert */ #include "ugl/Volume.hpp" namespace ugl { /** * @brief Constructor. */ Volume::Volume() : visible(true), renderBoundingBoxDepthCube(true), cubeData(0), cubeDrawable(0) { } /** * @brief Destructor. */ Volume::~Volume() { if (this->cubeDrawable != 0) delete this->cubeDrawable; if (this->cubeData != 0) delete this->cubeData; } /** * @brief Sets the volume visibility. * @param visible */ void Volume::setVisible(bool visible) { this->visible = visible; } /** * @brief Returns volume visibility. * @return */ bool Volume::isVisible() const { return this->visible; } /** * @brief Enables (depth-only) rendering of the bounding box cube. * @param renderDepthCube */ void Volume::setRenderBoundingBoxDepthCube(bool renderDepthCube) { this->renderBoundingBoxDepthCube = renderDepthCube; } /** * @brief Returns true if the bounding box cube is rendered using depth-only mode. * @return */ bool Volume::getRenderBoundingBoxDepthCube() const { return this->renderBoundingBoxDepthCube; } /** * @brief Returns the drawable cube of the volume bounding box. * @return */ MeshDrawable &Volume::getBoundingBoxDrawable() { if (this->cubeDrawable == 0) this->initBoundingBoxDrawable(); return *this->cubeDrawable; } /** * @brief Initialize internal volume cube representation. */ void Volume::initBoundingBoxDrawable() { // Clean previous if (this->cubeDrawable != 0) delete this->cubeDrawable; if (this->cubeData != 0) delete this->cubeData; // Create new this->cubeData = new MeshData(); ugl::BoundingBox boundingBox = this->getBoundingBox(); glm::vec3 min = boundingBox.getMin(); glm::vec3 max = boundingBox.getMax(); this->cubeData->addPoint(glm::vec3(min.x, min.y, min.z)); this->cubeData->addPoint(glm::vec3(max.x, min.y, min.z)); this->cubeData->addPoint(glm::vec3(max.x, max.y, min.z)); this->cubeData->addPoint(glm::vec3(min.x, max.y, min.z)); this->cubeData->addPoint(glm::vec3(min.x, min.y, max.z)); this->cubeData->addPoint(glm::vec3(max.x, min.y, max.z)); this->cubeData->addPoint(glm::vec3(max.x, max.y, max.z)); this->cubeData->addPoint(glm::vec3(min.x, max.y, max.z)); this->cubeData->addTriangle(glm::uvec3(0, 1, 2)); this->cubeData->addTriangle(glm::uvec3(0, 2, 3)); this->cubeData->addTriangle(glm::uvec3(4, 6, 5)); this->cubeData->addTriangle(glm::uvec3(4, 7, 6)); this->cubeData->addTriangle(glm::uvec3(1, 5, 6)); this->cubeData->addTriangle(glm::uvec3(1, 6, 2)); this->cubeData->addTriangle(glm::uvec3(0, 3, 4)); this->cubeData->addTriangle(glm::uvec3(4, 3, 7)); this->cubeData->addTriangle(glm::uvec3(3, 2, 7)); this->cubeData->addTriangle(glm::uvec3(2, 6, 7)); this->cubeData->addTriangle(glm::uvec3(0, 4, 1)); this->cubeData->addTriangle(glm::uvec3(1, 4, 5)); this->cubeDrawable = new MeshDrawable(*this->cubeData); } /** * @brief Returns whether the volume has a mask, i.e., a texture describing where volume rendering should (not) be done. * @return */ bool Volume::hasMaskTexture() const { return false; } /** * @brief Returns the masking texture. * @return */ GLuint Volume::getMaskTexture() const { return 0; } /** * @brief Returns the resolution of the mask texture. * @return */ glm::ivec3 Volume::getMaskResolution() const { return this->getIntensityResolution(); } }
22.617486
120
0.669727
dermegges
294af1b378db035cfb4dd468656132b77182c39d
443
cpp
C++
src/software/gui/geom/geometry_conversion.cpp
scveloso/Software
ac882d3df0aa0d108e5157c076c82c030d023e12
[ "MIT" ]
null
null
null
src/software/gui/geom/geometry_conversion.cpp
scveloso/Software
ac882d3df0aa0d108e5157c076c82c030d023e12
[ "MIT" ]
null
null
null
src/software/gui/geom/geometry_conversion.cpp
scveloso/Software
ac882d3df0aa0d108e5157c076c82c030d023e12
[ "MIT" ]
null
null
null
#include "software/gui/geom/geometry_conversion.h" QPointF createQPointF(const Point& point) { return QPointF(point.x(), point.y()); } QRectF createQRectF(const Rectangle& rectangle) { return QRectF(createQPointF(rectangle.nwCorner()), createQPointF(rectangle.seCorner())); } QLineF createQLineF(const Segment& segment) { return QLineF(createQPointF(segment.getSegStart()), createQPointF(segment.getEnd())); }
24.611111
89
0.724605
scveloso
29522cada724b26ebd22502132b90211b9527c67
8,799
hpp
C++
app/liblsl/lslboost/boost/mpl/aux_/full_lambda.hpp
mvidaldp/liblsl-android-builder
e48402fb88ca1b381fd38c70e105df8bd0f3902d
[ "MIT" ]
58
2018-12-08T23:53:50.000Z
2022-03-26T14:14:40.000Z
app/liblsl/lslboost/boost/mpl/aux_/full_lambda.hpp
mvidaldp/liblsl-android-builder
e48402fb88ca1b381fd38c70e105df8bd0f3902d
[ "MIT" ]
125
2018-11-21T15:42:39.000Z
2022-03-29T12:15:54.000Z
app/liblsl/lslboost/boost/mpl/aux_/full_lambda.hpp
mvidaldp/liblsl-android-builder
e48402fb88ca1b381fd38c70e105df8bd0f3902d
[ "MIT" ]
42
2019-03-06T13:43:18.000Z
2022-03-21T08:55:34.000Z
#if !defined(BOOST_PP_IS_ITERATING) ///// header body #ifndef BOOST_MPL_AUX_FULL_LAMBDA_HPP_INCLUDED #define BOOST_MPL_AUX_FULL_LAMBDA_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #if !defined(BOOST_MPL_PREPROCESSING_MODE) # include <boost/mpl/lambda_fwd.hpp> # include <boost/mpl/bind_fwd.hpp> # include <boost/mpl/protect.hpp> # include <boost/mpl/quote.hpp> # include <boost/mpl/arg.hpp> # include <boost/mpl/bool.hpp> # include <boost/mpl/int_fwd.hpp> # include <boost/mpl/aux_/template_arity.hpp> # include <boost/mpl/aux_/na_spec.hpp> # include <boost/mpl/aux_/config/ttp.hpp> # if defined(BOOST_MPL_CFG_EXTENDED_TEMPLATE_PARAMETERS_MATCHING) # include <boost/mpl/if.hpp> # endif #endif #include <boost/mpl/aux_/lambda_arity_param.hpp> #include <boost/mpl/aux_/config/use_preprocessed.hpp> #if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) # define BOOST_MPL_PREPROCESSED_HEADER full_lambda.hpp # include <boost/mpl/aux_/include_preprocessed.hpp> #else # include <boost/mpl/limits/arity.hpp> # include <boost/mpl/aux_/preprocessor/default_params.hpp> # include <boost/mpl/aux_/preprocessor/params.hpp> # include <boost/mpl/aux_/preprocessor/enum.hpp> # include <boost/mpl/aux_/preprocessor/repeat.hpp> # include <boost/mpl/aux_/config/dmc_ambiguous_ctps.hpp> # include <boost/preprocessor/iterate.hpp> # include <boost/preprocessor/comma_if.hpp> # include <boost/preprocessor/inc.hpp> # include <boost/preprocessor/cat.hpp> namespace lslboost { namespace mpl { // local macros, #undef-ined at the end of the header # define AUX778076_LAMBDA_PARAMS(i_, param) \ BOOST_MPL_PP_PARAMS(i_, param) \ /**/ # define AUX778076_BIND_PARAMS(param) \ BOOST_MPL_PP_PARAMS( \ BOOST_MPL_LIMIT_METAFUNCTION_ARITY \ , param \ ) \ /**/ # define AUX778076_BIND_N_PARAMS(i_, param) \ BOOST_PP_COMMA_IF(i_) \ BOOST_MPL_PP_PARAMS(i_, param) \ /**/ # define AUX778076_ARITY_PARAM(param) \ BOOST_MPL_AUX_LAMBDA_ARITY_PARAM(param) \ /**/ #define n_ BOOST_MPL_LIMIT_METAFUNCTION_ARITY namespace aux { template< BOOST_MPL_PP_DEFAULT_PARAMS(n_,bool C,false) > struct lambda_or : true_ { }; template<> struct lambda_or< BOOST_MPL_PP_ENUM(n_,false) > : false_ { }; } // namespace aux #undef n_ template< typename T , typename Tag AUX778076_ARITY_PARAM(typename Arity) > struct lambda { typedef false_ is_le; typedef T result_; typedef T type; }; template< typename T > struct is_lambda_expression : lambda<T>::is_le { }; template< int N, typename Tag > struct lambda< arg<N>,Tag AUX778076_ARITY_PARAM(int_<-1>) > { typedef true_ is_le; typedef mpl::arg<N> result_; // qualified for the sake of MIPSpro 7.41 typedef mpl::protect<result_> type; }; #define BOOST_PP_ITERATION_PARAMS_1 \ (3,(0, BOOST_MPL_LIMIT_METAFUNCTION_ARITY, <boost/mpl/aux_/full_lambda.hpp>)) #include BOOST_PP_ITERATE() /// special case for 'protect' template< typename T, typename Tag > struct lambda< mpl::protect<T>,Tag AUX778076_ARITY_PARAM(int_<1>) > { typedef false_ is_le; typedef mpl::protect<T> result_; typedef result_ type; }; /// specializations for the main 'bind' form template< typename F, AUX778076_BIND_PARAMS(typename T) , typename Tag > struct lambda< bind<F,AUX778076_BIND_PARAMS(T)> , Tag AUX778076_ARITY_PARAM(int_<BOOST_PP_INC(BOOST_MPL_LIMIT_METAFUNCTION_ARITY)>) > { typedef false_ is_le; typedef bind<F, AUX778076_BIND_PARAMS(T)> result_; typedef result_ type; }; #if defined(BOOST_MPL_CFG_EXTENDED_TEMPLATE_PARAMETERS_MATCHING) template< typename F , typename Tag1 , typename Tag2 , typename Arity > struct lambda< lambda<F,Tag1,Arity> , Tag2 , int_<3> > { typedef lambda< F,Tag2 > l1; typedef lambda< Tag1,Tag2 > l2; typedef typename l1::is_le is_le; typedef bind1< quote1<aux::template_arity>, typename l1::result_ > arity_; typedef lambda< typename if_<is_le,arity_,Arity>::type,Tag2 > l3; typedef aux::le_result3<is_le, Tag2, mpl::lambda, l1, l2, l3> le_result_; typedef typename le_result_::result_ result_; typedef typename le_result_::type type; }; #elif !defined(BOOST_MPL_CFG_DMC_AMBIGUOUS_CTPS) /// workaround for MWCW 8.3+/EDG < 303, leads to ambiguity on Digital Mars template< typename F, typename Tag1, typename Tag2 > struct lambda< lambda< F,Tag1 > , Tag2 > { typedef lambda< F,Tag2 > l1; typedef lambda< Tag1,Tag2 > l2; typedef typename l1::is_le is_le; typedef aux::le_result2<is_le, Tag2, mpl::lambda, l1, l2> le_result_; typedef typename le_result_::result_ result_; typedef typename le_result_::type type; }; #endif # undef AUX778076_ARITY_PARAM # undef AUX778076_BIND_N_PARAMS # undef AUX778076_BIND_PARAMS # undef AUX778076_LAMBDA_PARAMS #if !defined(BOOST_MPL_CFG_EXTENDED_TEMPLATE_PARAMETERS_MATCHING) BOOST_MPL_AUX_NA_SPEC(2, lambda) #else BOOST_MPL_AUX_NA_SPEC2(2, 3, lambda) #endif }} #endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS #endif // BOOST_MPL_AUX_FULL_LAMBDA_HPP_INCLUDED ///// iteration, depth == 1 // For gcc 4.4 compatability, we must include the // BOOST_PP_ITERATION_DEPTH test inside an #else clause. #else // BOOST_PP_IS_ITERATING #if BOOST_PP_ITERATION_DEPTH() == 1 #define i_ BOOST_PP_FRAME_ITERATION(1) #if i_ > 0 namespace aux { # define AUX778076_RESULT(unused, i_, T) \ BOOST_PP_COMMA_IF(i_) \ typename BOOST_PP_CAT(T, BOOST_PP_INC(i_))::result_ \ /**/ # define AUX778076_TYPE(unused, i_, T) \ BOOST_PP_COMMA_IF(i_) \ typename BOOST_PP_CAT(T, BOOST_PP_INC(i_))::type \ /**/ template< typename IsLE, typename Tag , template< AUX778076_LAMBDA_PARAMS(i_, typename P) > class F , AUX778076_LAMBDA_PARAMS(i_, typename L) > struct BOOST_PP_CAT(le_result,i_) { typedef F< BOOST_MPL_PP_REPEAT(i_, AUX778076_TYPE, L) > result_; typedef result_ type; }; template< typename Tag , template< AUX778076_LAMBDA_PARAMS(i_, typename P) > class F , AUX778076_LAMBDA_PARAMS(i_, typename L) > struct BOOST_PP_CAT(le_result,i_)< true_,Tag,F,AUX778076_LAMBDA_PARAMS(i_, L) > { typedef BOOST_PP_CAT(bind,i_)< BOOST_PP_CAT(quote,i_)<F,Tag> , BOOST_MPL_PP_REPEAT(i_, AUX778076_RESULT, L) > result_; typedef mpl::protect<result_> type; }; # undef AUX778076_TYPE # undef AUX778076_RESULT } // namespace aux # define AUX778076_LAMBDA_TYPEDEF(unused, i_, T) \ typedef lambda< BOOST_PP_CAT(T, BOOST_PP_INC(i_)), Tag > \ BOOST_PP_CAT(l,BOOST_PP_INC(i_)); \ /**/ # define AUX778076_IS_LE_TYPEDEF(unused, i_, unused2) \ typedef typename BOOST_PP_CAT(l,BOOST_PP_INC(i_))::is_le \ BOOST_PP_CAT(is_le,BOOST_PP_INC(i_)); \ /**/ # define AUX778076_IS_LAMBDA_EXPR(unused, i_, unused2) \ BOOST_PP_COMMA_IF(i_) \ BOOST_PP_CAT(is_le,BOOST_PP_INC(i_))::value \ /**/ template< template< AUX778076_LAMBDA_PARAMS(i_, typename P) > class F , AUX778076_LAMBDA_PARAMS(i_, typename T) , typename Tag > struct lambda< F<AUX778076_LAMBDA_PARAMS(i_, T)> , Tag AUX778076_ARITY_PARAM(int_<i_>) > { BOOST_MPL_PP_REPEAT(i_, AUX778076_LAMBDA_TYPEDEF, T) BOOST_MPL_PP_REPEAT(i_, AUX778076_IS_LE_TYPEDEF, unused) typedef typename aux::lambda_or< BOOST_MPL_PP_REPEAT(i_, AUX778076_IS_LAMBDA_EXPR, unused) >::type is_le; typedef aux::BOOST_PP_CAT(le_result,i_)< is_le, Tag, F, AUX778076_LAMBDA_PARAMS(i_, l) > le_result_; typedef typename le_result_::result_ result_; typedef typename le_result_::type type; }; # undef AUX778076_IS_LAMBDA_EXPR # undef AUX778076_IS_LE_TYPEDEF # undef AUX778076_LAMBDA_TYPEDEF #endif // i_ > 0 template< typename F AUX778076_BIND_N_PARAMS(i_, typename T) , typename Tag > struct lambda< BOOST_PP_CAT(bind,i_)<F AUX778076_BIND_N_PARAMS(i_, T)> , Tag AUX778076_ARITY_PARAM(int_<BOOST_PP_INC(i_)>) > { typedef false_ is_le; typedef BOOST_PP_CAT(bind,i_)< F AUX778076_BIND_N_PARAMS(i_, T) > result_; typedef result_ type; }; #undef i_ #endif // BOOST_PP_ITERATION_DEPTH() #endif // BOOST_PP_IS_ITERATING
24.785915
85
0.696897
mvidaldp
2953c7b8c7ef22143c0d0a9e3378a9fc4969feea
1,884
cpp
C++
imageMultiply/imageMultiply.cpp
FreeSoftwareDevlopment/imageMultiply
d873f867ba216162d51f778c323dfa24d3f05dec
[ "MIT" ]
null
null
null
imageMultiply/imageMultiply.cpp
FreeSoftwareDevlopment/imageMultiply
d873f867ba216162d51f778c323dfa24d3f05dec
[ "MIT" ]
null
null
null
imageMultiply/imageMultiply.cpp
FreeSoftwareDevlopment/imageMultiply
d873f867ba216162d51f778c323dfa24d3f05dec
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include <filesystem> #include <wrapper_stbi.h> #include "stbi_img_write.hpp" #define s 4 #define path std::filesystem::path #define exists std::filesystem::exists int main(int argc, char* argv[]) { if (argc > 3) { int width[2], height[2], BPP[2]; memset(width, 0x00, sizeof(width)); memset(height, 0x00, sizeof(height)); memset(BPP, 0x00, sizeof(BPP)); if (!(exists(path(argv[1])) && exists(path(argv[2])))) { puts("You should give me a File Path that Work!\n"); return -1; } unsigned char* buf1 = stb_image::stbiw_load(argv[1], &width[0], &height[0], &BPP[0], s); unsigned char* buf2 = stb_image::stbiw_load(argv[2], &width[1], &height[1], &BPP[1], s); printf("IN 1:\n\tHEIGHT: %i\n\tWIDTH: %i\n\tBPP: %i\n\n" "IN 2:\n\tHEIGHT: %i\n\tWIDTH: %i\n\tBPP: %i\n", height[0], width[0], BPP[0], height[1], width[1], BPP[1]); if (height[0] != height[1] || width[0] != width[1] || BPP[0] != BPP[1]) { puts("\nThe Image Format or Size is not ==\n"); return 1; } int aSize{ width[0] * height[0] * BPP[0] }; if (aSize <= 0) return 2; for (int xr{ 0 }; xr < aSize; xr++) { buf1[xr] = (unsigned char)(((float)buf1[xr] / 0xff) * ((float)buf2[xr] / 0xff) * 0xff); } path p(argv[3]); { bool xt{ true }; std::string ext = p.extension().string(); if (ext.length() == 4) xt = ext != std::string(".png"); if (!p.has_extension() || xt) p.replace_extension(".png"); } stbi_write_png(p.string().c_str(), width[0], height[0], s, buf1, width[0] * s); printf("\nOUT:\n\tHEIGHT: %i\n\tWIDTH: %i\n", height[0], width[0]); if (buf1 != nullptr) stb_image::stbiw_image_free(buf1); if (buf2 != nullptr) stb_image::stbiw_image_free(buf2); } else { printf("imgMultiply\n<c> Sharkbyteprojects\nUsage: %s <in1> <in2> <out>\n", argv[0]); return -1; } return 0; }
28.119403
90
0.593418
FreeSoftwareDevlopment
2954c9556366ebc00eabb264f642d21b779cab56
8,641
cpp
C++
Game/world/vob.cpp
okkindel/OpenGothic
0055d51d4c96ff56fd330378b1c1a90c365d1316
[ "MIT" ]
null
null
null
Game/world/vob.cpp
okkindel/OpenGothic
0055d51d4c96ff56fd330378b1c1a90c365d1316
[ "MIT" ]
null
null
null
Game/world/vob.cpp
okkindel/OpenGothic
0055d51d4c96ff56fd330378b1c1a90c365d1316
[ "MIT" ]
null
null
null
#include "vob.h" #include <Tempest/Log> #include <Tempest/Vec> #include "interactive.h" #include "staticobj.h" #include "world/triggers/movetrigger.h" #include "world/triggers/codemaster.h" #include "world/triggers/triggerlist.h" #include "world/triggers/triggerscript.h" #include "world/triggers/triggerworldstart.h" #include "world/triggers/zonetrigger.h" #include "world/triggers/messagefilter.h" #include "world/triggers/pfxcontroller.h" #include "world/triggers/trigger.h" #include "world/triggers/touchdamage.h" #include "game/serialize.h" #include "world.h" #include "worldlight.h" using namespace Tempest; Vob::Vob(World& owner) : world(owner) { } Vob::Vob(Vob* parent, World& owner, ZenLoad::zCVobData& vob, bool startup) : world(owner), vobType(vob.vobType), parent(parent) { float v[16]={}; std::memcpy(v,vob.worldMatrix.m,sizeof(v)); pos = Tempest::Matrix4x4(v); local = pos; if(parent!=nullptr) { auto m = parent->transform(); m.inverse(); m.mul(local); local = m; } for(auto& i:vob.childVobs) { auto p = Vob::load(this,owner,std::move(i),startup); if(p!=nullptr) { childContent = ContentBit(p->childContent|childContent); child.emplace_back(std::move(p)); } } vob.childVobs.clear(); } Vob::~Vob() { } Vec3 Vob::position() const { return Vec3(pos.at(3,0),pos.at(3,1),pos.at(3,2)); } void Vob::setGlobalTransform(const Matrix4x4& p) { pos = p; local = pos; if(parent!=nullptr) { auto m = parent->transform(); m.inverse(); m.mul(local); local = m; } } void Vob::setLocalTransform(const Matrix4x4& p) { local = p; recalculateTransform(); } bool Vob::setMobState(const char* scheme, int32_t st) { bool ret = true; for(auto& i:child) ret &= i->setMobState(scheme,st); return ret; } void Vob::moveEvent() { } bool Vob::isDynamic() const { return false; } void Vob::recalculateTransform() { auto old = position(); if(parent!=nullptr) { pos = parent->transform(); pos.mul(local); } else { pos = local; } if(old != position()) { if(childContent!=cbNone) world.invalidateVobIndex(); } moveEvent(); for(auto& i:child) { i->recalculateTransform(); } } std::unique_ptr<Vob> Vob::load(Vob* parent, World& world, ZenLoad::zCVobData&& vob, bool startup) { switch(vob.vobType) { case ZenLoad::zCVobData::VT_zCVob: return std::unique_ptr<Vob>(new StaticObj(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_zCVobLevelCompo: return std::unique_ptr<Vob>(new Vob(parent,world,vob,startup)); case ZenLoad::zCVobData::VT_oCMobFire: return std::unique_ptr<Vob>(new StaticObj(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_oCMOB: // Irdotar bow-triggers // focusOverride=true return std::unique_ptr<Vob>(new Interactive(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_oCMobBed: case ZenLoad::zCVobData::VT_oCMobDoor: case ZenLoad::zCVobData::VT_oCMobInter: case ZenLoad::zCVobData::VT_oCMobContainer: case ZenLoad::zCVobData::VT_oCMobSwitch: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbMobsi); return std::unique_ptr<Vob>(new Interactive(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_oCMobLadder: //TODO: mob ladder return std::unique_ptr<Vob>(new StaticObj(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_oCMobWheel: //TODO: mob whell return std::unique_ptr<Vob>(new StaticObj(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_zCMover: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new MoveTrigger(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_zCCodeMaster: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new CodeMaster(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_zCTriggerList: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new TriggerList(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_zCTriggerScript: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new TriggerScript(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_oCTriggerWorldStart: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new TriggerWorldStart(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_oCTriggerChangeLevel: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new ZoneTrigger(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_zCTrigger: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new Trigger(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_zCMessageFilter: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new MessageFilter(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_zCPFXControler: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new PfxController(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_oCTouchDamage: if(parent!=nullptr) parent->childContent = ContentBit(parent->childContent|cbTrigger); return std::unique_ptr<Vob>(new TouchDamage(parent,world,std::move(vob),startup)); case ZenLoad::zCVobData::VT_zCVobStartpoint: { float dx = vob.rotationMatrix.v[2].x; float dy = vob.rotationMatrix.v[2].y; float dz = vob.rotationMatrix.v[2].z; world.addStartPoint(Vec3(vob.position.x,vob.position.y,vob.position.z),Vec3(dx,dy,dz),vob.vobName.c_str()); // FIXME return std::unique_ptr<Vob>(new Vob(parent,world,vob,startup)); } case ZenLoad::zCVobData::VT_zCVobSpot: { float dx = vob.rotationMatrix.v[2].x; float dy = vob.rotationMatrix.v[2].y; float dz = vob.rotationMatrix.v[2].z; world.addFreePoint(Vec3(vob.position.x,vob.position.y,vob.position.z),Vec3(dx,dy,dz),vob.vobName.c_str()); // FIXME return std::unique_ptr<Vob>(new Vob(parent,world,vob,startup)); } case ZenLoad::zCVobData::VT_oCItem: { if(startup) world.addItem(vob); // FIXME return std::unique_ptr<Vob>(new Vob(parent,world,vob,startup)); } case ZenLoad::zCVobData::VT_zCVobSound: case ZenLoad::zCVobData::VT_zCVobSoundDaytime: case ZenLoad::zCVobData::VT_oCZoneMusic: case ZenLoad::zCVobData::VT_oCZoneMusicDefault: { world.addSound(vob); // FIXME return std::unique_ptr<Vob>(new Vob(parent,world,vob,startup)); } case ZenLoad::zCVobData::VT_zCVobLight: { return std::unique_ptr<Vob>(new WorldLight(parent,world,std::move(vob),startup)); } } if(vob.objectClass=="zCVobAnimate:zCVob") { // ork flags // TODO: morph animation return std::unique_ptr<Vob>(new StaticObj(parent,world,std::move(vob),startup)); } else if(vob.objectClass=="zCVobLensFlare:zCVob" || vob.objectClass=="zCZoneVobFarPlane:zCVob" || vob.objectClass=="zCZoneVobFarPlaneDefault:zCZoneVobFarPlane:zCVob") { // WONT-IMPLEMENT } else { static std::unordered_set<std::string> cls; if(cls.find(vob.objectClass)==cls.end()){ cls.insert(vob.objectClass); Tempest::Log::d("unknown vob class ",vob.objectClass); } } return std::unique_ptr<Vob>(new Vob(parent,world,vob,startup)); } void Vob::saveVobTree(Serialize& fin) const { for(auto& i:child) i->saveVobTree(fin); save(fin); } void Vob::loadVobTree(Serialize& fin) { for(auto& i:child) i->loadVobTree(fin); load(fin); } void Vob::save(Serialize& fin) const { fin.write(vobType,pos,local); } void Vob::load(Serialize& fin) { if(fin.version()<10) return; uint8_t type = 0; fin.read(type,pos,local); if(vobType!=type) throw std::logic_error("inconsistent *.sav vs world"); }
33.622568
113
0.678162
okkindel
29556f07b555f7505007b26dc332d879a1524186
839
cpp
C++
GetHuffmanCodes/main.cpp
rNexeR/AnalisisAlgoritmos
cc9a86a93319cd412a40eed300f8249630540d19
[ "MIT" ]
null
null
null
GetHuffmanCodes/main.cpp
rNexeR/AnalisisAlgoritmos
cc9a86a93319cd412a40eed300f8249630540d19
[ "MIT" ]
null
null
null
GetHuffmanCodes/main.cpp
rNexeR/AnalisisAlgoritmos
cc9a86a93319cd412a40eed300f8249630540d19
[ "MIT" ]
null
null
null
#include "Test.h" #include <iostream> using namespace std; void getHuffmanCodes(BinaryNode *tree, map<char, string> *answer, string current) { if (tree->left != 0) { getHuffmanCodes(tree->left, answer, current + '0'); }else{ (*answer)[tree->value] = current; } if (tree->right != 0) { getHuffmanCodes(tree->right, answer, current + '1'); }else{ (*answer)[tree->value] = current; } } map<char, string> getHuffmanCodes(BinaryNode *huffman_tree) { map<char, string> answer; getHuffmanCodes(huffman_tree, &answer, ""); // for(map<char, string>::iterator i = answer.begin(); i != answer.end(); i++){ // cout<<"["<<(*i).first<<"]="<<(*i).second<<endl; // } // cout<<endl<<endl; return answer; } int main() { test(); return 0; }
19.511628
83
0.561383
rNexeR
295ad9355f5f3d2e66bbc9f3923d4c27f5fddb51
75,435
cpp
C++
src/controller/tests/data_model/TestRead.cpp
sungho1shin/connectedhomeip
050eb6d24487598a97743b6a23d41232e45bef88
[ "Apache-2.0" ]
null
null
null
src/controller/tests/data_model/TestRead.cpp
sungho1shin/connectedhomeip
050eb6d24487598a97743b6a23d41232e45bef88
[ "Apache-2.0" ]
null
null
null
src/controller/tests/data_model/TestRead.cpp
sungho1shin/connectedhomeip
050eb6d24487598a97743b6a23d41232e45bef88
[ "Apache-2.0" ]
null
null
null
/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "transport/SecureSession.h" #include <app-common/zap-generated/cluster-objects.h> #include <app/ClusterStateCache.h> #include <app/InteractionModelEngine.h> #include <app/tests/AppTestContext.h> #include <app/util/mock/Constants.h> #include <app/util/mock/Functions.h> #include <controller/ReadInteraction.h> #include <lib/support/ErrorStr.h> #include <lib/support/UnitTestRegistration.h> #include <lib/support/logging/CHIPLogging.h> #include <messaging/tests/MessagingContext.h> #include <nlunit-test.h> #include <protocols/interaction_model/Constants.h> using TestContext = chip::Test::AppContext; using namespace chip; using namespace chip::app::Clusters; using namespace chip::Protocols; namespace { constexpr EndpointId kTestEndpointId = 1; constexpr DataVersion kDataVersion = 5; enum ResponseDirective { kSendDataResponse, kSendDataError }; ResponseDirective responseDirective; // Number of reads of TestCluster::Attributes::Int16u that we have observed. // Every read will increment this count by 1 and return the new value. uint16_t totalReadCount = 0; } // namespace namespace chip { namespace app { CHIP_ERROR ReadSingleClusterData(const Access::SubjectDescriptor & aSubjectDescriptor, bool aIsFabricFiltered, const ConcreteReadAttributePath & aPath, AttributeReportIBs::Builder & aAttributeReports, AttributeValueEncoder::AttributeEncodeState * apEncoderState) { if (aPath.mClusterId >= Test::kMockEndpointMin) { return Test::ReadSingleMockClusterData(aSubjectDescriptor.fabricIndex, aPath, aAttributeReports, apEncoderState); } if (responseDirective == kSendDataResponse) { if (aPath.mClusterId == app::Clusters::TestCluster::Id && aPath.mAttributeId == app::Clusters::TestCluster::Attributes::ListFabricScoped::Id) { AttributeValueEncoder::AttributeEncodeState state = (apEncoderState == nullptr ? AttributeValueEncoder::AttributeEncodeState() : *apEncoderState); AttributeValueEncoder valueEncoder(aAttributeReports, aSubjectDescriptor.fabricIndex, aPath, kDataVersion /* data version */, aIsFabricFiltered, state); return valueEncoder.EncodeList([aSubjectDescriptor](const auto & encoder) -> CHIP_ERROR { app::Clusters::TestCluster::Structs::TestFabricScoped::Type val; val.fabricIndex = aSubjectDescriptor.fabricIndex; ReturnErrorOnFailure(encoder.Encode(val)); val.fabricIndex = (val.fabricIndex == 1) ? 2 : 1; ReturnErrorOnFailure(encoder.Encode(val)); return CHIP_NO_ERROR; }); } if (aPath.mClusterId == app::Clusters::TestCluster::Id && aPath.mAttributeId == app::Clusters::TestCluster::Attributes::Int16u::Id) { AttributeValueEncoder::AttributeEncodeState state = (apEncoderState == nullptr ? AttributeValueEncoder::AttributeEncodeState() : *apEncoderState); AttributeValueEncoder valueEncoder(aAttributeReports, aSubjectDescriptor.fabricIndex, aPath, kDataVersion /* data version */, aIsFabricFiltered, state); return valueEncoder.Encode(++totalReadCount); } AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); ReturnErrorOnFailure(aAttributeReports.GetError()); AttributeDataIB::Builder & attributeData = attributeReport.CreateAttributeData(); ReturnErrorOnFailure(attributeReport.GetError()); TestCluster::Attributes::ListStructOctetString::TypeInfo::Type value; TestCluster::Structs::TestListStructOctet::Type valueBuf[4]; value = valueBuf; uint8_t i = 0; for (auto & item : valueBuf) { item.fabricIndex = i; i++; } attributeData.DataVersion(kDataVersion); ReturnErrorOnFailure(attributeData.GetError()); AttributePathIB::Builder & attributePath = attributeData.CreatePath(); attributePath.Endpoint(aPath.mEndpointId).Cluster(aPath.mClusterId).Attribute(aPath.mAttributeId).EndOfAttributePathIB(); ReturnErrorOnFailure(attributePath.GetError()); ReturnErrorOnFailure( DataModel::Encode(*(attributeData.GetWriter()), TLV::ContextTag(to_underlying(AttributeDataIB::Tag::kData)), value)); ReturnErrorOnFailure(attributeData.EndOfAttributeDataIB().GetError()); return attributeReport.EndOfAttributeReportIB().GetError(); } AttributeReportIB::Builder & attributeReport = aAttributeReports.CreateAttributeReport(); ReturnErrorOnFailure(aAttributeReports.GetError()); AttributeStatusIB::Builder & attributeStatus = attributeReport.CreateAttributeStatus(); AttributePathIB::Builder & attributePath = attributeStatus.CreatePath(); attributePath.Endpoint(aPath.mEndpointId).Cluster(aPath.mClusterId).Attribute(aPath.mAttributeId).EndOfAttributePathIB(); ReturnErrorOnFailure(attributePath.GetError()); StatusIB::Builder & errorStatus = attributeStatus.CreateErrorStatus(); ReturnErrorOnFailure(attributeStatus.GetError()); errorStatus.EncodeStatusIB(StatusIB(Protocols::InteractionModel::Status::Busy)); attributeStatus.EndOfAttributeStatusIB(); ReturnErrorOnFailure(attributeStatus.GetError()); return attributeReport.EndOfAttributeReportIB().GetError(); } bool IsClusterDataVersionEqual(const ConcreteClusterPath & aConcreteClusterPath, DataVersion aRequiredVersion) { if (aRequiredVersion == kDataVersion) { return true; } if (Test::GetVersion() == aRequiredVersion) { return true; } return false; } bool IsDeviceTypeOnEndpoint(DeviceTypeId deviceType, EndpointId endpoint) { return false; } } // namespace app } // namespace chip namespace { class TestReadInteraction : public app::ReadHandler::ApplicationCallback { public: TestReadInteraction() {} static void TestReadAttributeResponse(nlTestSuite * apSuite, void * apContext); static void TestReadDataVersionFilter(nlTestSuite * apSuite, void * apContext); static void TestReadAttributeError(nlTestSuite * apSuite, void * apContext); static void TestReadAttributeTimeout(nlTestSuite * apSuite, void * apContext); static void TestReadEventResponse(nlTestSuite * apSuite, void * apContext); static void TestReadFabricScopedWithoutFabricFilter(nlTestSuite * apSuite, void * apContext); static void TestReadFabricScopedWithFabricFilter(nlTestSuite * apSuite, void * apContext); static void TestReadHandler_MultipleSubscriptions(nlTestSuite * apSuite, void * apContext); static void TestReadHandler_SubscriptionAppRejection(nlTestSuite * apSuite, void * apContext); static void TestReadHandler_MultipleReads(nlTestSuite * apSuite, void * apContext); static void TestReadHandler_OneSubscribeMultipleReads(nlTestSuite * apSuite, void * apContext); static void TestReadHandler_TwoSubscribesMultipleReads(nlTestSuite * apSuite, void * apContext); static void TestReadHandler_MultipleSubscriptionsWithDataVersionFilter(nlTestSuite * apSuite, void * apContext); static void TestReadHandler_SubscriptionAlteredReportingIntervals(nlTestSuite * apSuite, void * apContext); static void TestReadHandlerResourceExhaustion_MultipleSubscriptions(nlTestSuite * apSuite, void * apContext); static void TestReadHandlerResourceExhaustion_MultipleReads(nlTestSuite * apSuite, void * apContext); static void TestReadSubscribeAttributeResponseWithCache(nlTestSuite * apSuite, void * apContext); private: static constexpr uint16_t kTestMinInterval = 33; static constexpr uint16_t kTestMaxInterval = 66; CHIP_ERROR OnSubscriptionRequested(app::ReadHandler & aReadHandler, Transport::SecureSession & aSecureSession) { VerifyOrReturnError(!mEmitSubscriptionError, CHIP_ERROR_INVALID_ARGUMENT); if (mAlterSubscriptionIntervals) { ReturnErrorOnFailure(aReadHandler.SetReportingIntervals(kTestMinInterval, kTestMaxInterval)); } return CHIP_NO_ERROR; } void OnSubscriptionEstablished(app::ReadHandler & aReadHandler) { mNumActiveSubscriptions++; } void OnSubscriptionTerminated(app::ReadHandler & aReadHandler) { mNumActiveSubscriptions--; } // Issue the given number of reads in parallel and wait for them all to // succeed. static void MultipleReadHelper(nlTestSuite * apSuite, TestContext & aCtx, size_t aReadCount); // Establish the given number of subscriptions, then issue the given number // of reads in parallel and wait for them all to succeed. static void SubscribeThenReadHelper(nlTestSuite * apSuite, TestContext & aCtx, size_t aSubscribeCount, size_t aReadCount); bool mEmitSubscriptionError = false; int32_t mNumActiveSubscriptions = 0; bool mAlterSubscriptionIntervals = false; }; TestReadInteraction gTestReadInteraction; class MockInteractionModelApp : public chip::app::ClusterStateCache::Callback { public: void OnEventData(const chip::app::EventHeader & aEventHeader, chip::TLV::TLVReader * apData, const chip::app::StatusIB * apStatus) override {} void OnAttributeData(const chip::app::ConcreteDataAttributePath & aPath, chip::TLV::TLVReader * apData, const chip::app::StatusIB & status) override { if (status.mStatus == chip::Protocols::InteractionModel::Status::Success) { mNumAttributeResponse++; } } void OnError(CHIP_ERROR aError) override { mError = aError; mReadError = true; } void OnDone() override {} void OnDeallocatePaths(chip::app::ReadPrepareParams && aReadPrepareParams) override { if (aReadPrepareParams.mpAttributePathParamsList != nullptr) { delete[] aReadPrepareParams.mpAttributePathParamsList; } if (aReadPrepareParams.mpEventPathParamsList != nullptr) { delete[] aReadPrepareParams.mpEventPathParamsList; } if (aReadPrepareParams.mpDataVersionFilterList != nullptr) { delete[] aReadPrepareParams.mpDataVersionFilterList; } } int mNumAttributeResponse = 0; bool mReadError = false; CHIP_ERROR mError = CHIP_NO_ERROR; }; void TestReadInteraction::TestReadAttributeResponse(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [apSuite, &onSuccessCbInvoked](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { uint8_t i = 0; NL_TEST_ASSERT(apSuite, attributePath.mDataVersion.HasValue() && attributePath.mDataVersion.Value() == kDataVersion); auto iter = dataResponse.begin(); while (iter.Next()) { auto & item = iter.GetValue(); NL_TEST_ASSERT(apSuite, item.fabricIndex == i); i++; } NL_TEST_ASSERT(apSuite, i == 4); NL_TEST_ASSERT(apSuite, iter.GetStatus() == CHIP_NO_ERROR); onSuccessCbInvoked = true; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&onFailureCbInvoked](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { onFailureCbInvoked = true; }; Controller::ReadAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>(&ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, onSuccessCbInvoked && !onFailureCbInvoked); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients() == 0); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers() == 0); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadDataVersionFilter(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [apSuite, &onSuccessCbInvoked](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { uint8_t i = 0; auto iter = dataResponse.begin(); while (iter.Next()) { auto & item = iter.GetValue(); NL_TEST_ASSERT(apSuite, item.fabricIndex == i); i++; } NL_TEST_ASSERT(apSuite, i == 4); NL_TEST_ASSERT(apSuite, iter.GetStatus() == CHIP_NO_ERROR); onSuccessCbInvoked = true; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&onFailureCbInvoked](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { onFailureCbInvoked = true; }; Optional<DataVersion> dataVersion(kDataVersion); Controller::ReadAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, true, dataVersion); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, !onSuccessCbInvoked && !onFailureCbInvoked); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients() == 0); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers() == 0); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadSubscribeAttributeResponseWithCache(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); CHIP_ERROR err = CHIP_NO_ERROR; responseDirective = kSendDataResponse; MockInteractionModelApp delegate; chip::app::ClusterStateCache cache(delegate); auto * engine = chip::app::InteractionModelEngine::GetInstance(); err = engine->Init(&ctx.GetExchangeManager()); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); chip::app::EventPathParams eventPathParams[100]; for (uint32_t index = 0; index < 100; index++) { eventPathParams[index].mEndpointId = Test::kMockEndpoint3; eventPathParams[index].mClusterId = Test::MockClusterId(2); eventPathParams[index].mEventId = 0; } chip::app::ReadPrepareParams readPrepareParams(ctx.GetSessionBobToAlice()); readPrepareParams.mMinIntervalFloorSeconds = 0; readPrepareParams.mMaxIntervalCeilingSeconds = 4; // // Test the application callback as well to ensure we get the right number of SubscriptionEstablishment/Termination // callbacks. // app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(&gTestReadInteraction); int testId = 0; // Initial Read of E2C3A1, E2C3A2 and E3C2A2. // Expect no versions would be cached. { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = Test::kMockEndpoint2; attributePathParams1[0].mClusterId = Test::MockClusterId(3); attributePathParams1[0].mAttributeId = Test::MockAttributeId(1); attributePathParams1[1].mEndpointId = Test::kMockEndpoint2; attributePathParams1[1].mClusterId = Test::MockClusterId(3); attributePathParams1[1].mAttributeId = Test::MockAttributeId(2); attributePathParams1[2].mEndpointId = Test::kMockEndpoint3; attributePathParams1[2].mClusterId = Test::MockClusterId(2); attributePathParams1[2].mAttributeId = Test::MockAttributeId(2); readPrepareParams.mpAttributePathParamsList = attributePathParams1; readPrepareParams.mAttributePathParamsListSize = 3; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 3); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version1.HasValue()); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint3, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version2.HasValue()); delegate.mNumAttributeResponse = 0; } // Second read of E2C2A* and E3C2A2. We cannot use the stored data versions in the cache since there is no cached version from // previous test. Expect cache E2C2 version { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams2[2]; attributePathParams2[0].mEndpointId = Test::kMockEndpoint2; attributePathParams2[0].mClusterId = Test::MockClusterId(3); attributePathParams2[0].mAttributeId = kInvalidAttributeId; attributePathParams2[1].mEndpointId = Test::kMockEndpoint3; attributePathParams2[1].mClusterId = Test::MockClusterId(2); attributePathParams2[1].mAttributeId = Test::MockAttributeId(2); readPrepareParams.mpAttributePathParamsList = attributePathParams2; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); // There are supported 2 global and 3 non-global attributes in E2C2A* and 1 E3C2A2 NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 6); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version1.HasValue() && (version1.Value() == 0)); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint3, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version2.HasValue()); delegate.mNumAttributeResponse = 0; } // Third read of E2C3A1, E2C3A2, and E3C2A2. It would use the stored data versions in the cache since our subsequent read's C1A1 // path intersects with previous cached data version Expect no E2C3 attributes in report, only E3C2A1 attribute in report { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = Test::kMockEndpoint2; attributePathParams1[0].mClusterId = Test::MockClusterId(3); attributePathParams1[0].mAttributeId = Test::MockAttributeId(1); attributePathParams1[1].mEndpointId = Test::kMockEndpoint2; attributePathParams1[1].mClusterId = Test::MockClusterId(3); attributePathParams1[1].mAttributeId = Test::MockAttributeId(2); attributePathParams1[2].mEndpointId = Test::kMockEndpoint3; attributePathParams1[2].mClusterId = Test::MockClusterId(2); attributePathParams1[2].mAttributeId = Test::MockAttributeId(2); readPrepareParams.mpAttributePathParamsList = attributePathParams1; readPrepareParams.mAttributePathParamsListSize = 3; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version1.HasValue() && (version1.Value() == 0)); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint3, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version2.HasValue()); delegate.mNumAttributeResponse = 0; } // Fourth read of E2C3A* and E3C2A2. It would use the stored data versions in the cache since our subsequent read's C1A* path // intersects with previous cached data version Expect no C1 attributes in report, only E3C2A2 attribute in report { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams2[2]; attributePathParams2[0].mEndpointId = Test::kMockEndpoint2; attributePathParams2[0].mClusterId = Test::MockClusterId(3); attributePathParams2[0].mAttributeId = kInvalidAttributeId; attributePathParams2[1].mEndpointId = Test::kMockEndpoint3; attributePathParams2[1].mClusterId = Test::MockClusterId(2); attributePathParams2[1].mAttributeId = Test::MockAttributeId(2); readPrepareParams.mpAttributePathParamsList = attributePathParams2; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 1); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version1.HasValue() && (version1.Value() == 0)); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint3, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version2.HasValue()); delegate.mNumAttributeResponse = 0; } Test::BumpVersion(); // Fifth read of E2C3A1, E2C3A2 and E3C2A2. It would use the stored data versions in the cache since our subsequent read's C1A* // path intersects with previous cached data version, server's version is changed. Expect E2C3A1, E2C3A2 and E3C2A2 attribute in // report, and invalidate the cached pending and committed data version since no wildcard attributes exists in mRequestPathSet. { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = Test::kMockEndpoint2; attributePathParams1[0].mClusterId = Test::MockClusterId(3); attributePathParams1[0].mAttributeId = Test::MockAttributeId(1); attributePathParams1[1].mEndpointId = Test::kMockEndpoint2; attributePathParams1[1].mClusterId = Test::MockClusterId(3); attributePathParams1[1].mAttributeId = Test::MockAttributeId(2); attributePathParams1[2].mEndpointId = Test::kMockEndpoint3; attributePathParams1[2].mClusterId = Test::MockClusterId(2); attributePathParams1[2].mAttributeId = Test::MockAttributeId(2); readPrepareParams.mpAttributePathParamsList = attributePathParams1; readPrepareParams.mAttributePathParamsListSize = 3; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 3); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version1.HasValue()); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint3, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version2.HasValue()); delegate.mNumAttributeResponse = 0; } // Sixth read of E2C3A1, E2C3A2 and E3C2A2. It would use none stored data versions in the cache since previous read does not // cache any committed data version. Expect E2C3A1, E2C3A2 and E3C2A2 attribute in report { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams1[3]; attributePathParams1[0].mEndpointId = Test::kMockEndpoint2; attributePathParams1[0].mClusterId = Test::MockClusterId(3); attributePathParams1[0].mAttributeId = Test::MockAttributeId(1); attributePathParams1[1].mEndpointId = Test::kMockEndpoint2; attributePathParams1[1].mClusterId = Test::MockClusterId(3); attributePathParams1[1].mAttributeId = Test::MockAttributeId(2); attributePathParams1[2].mEndpointId = Test::kMockEndpoint3; attributePathParams1[2].mClusterId = Test::MockClusterId(2); attributePathParams1[2].mAttributeId = Test::MockAttributeId(2); readPrepareParams.mpAttributePathParamsList = attributePathParams1; readPrepareParams.mAttributePathParamsListSize = 3; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 3); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version1.HasValue()); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint3, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version2.HasValue()); delegate.mNumAttributeResponse = 0; } // Seventh read of E2C3A* and E3C2A2, here there is no cached data version filter // Expect E2C3A* attributes in report, and E3C2A2 attribute in report and cache latest data version { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams2[2]; attributePathParams2[0].mEndpointId = Test::kMockEndpoint2; attributePathParams2[0].mClusterId = Test::MockClusterId(3); attributePathParams2[0].mAttributeId = kInvalidAttributeId; attributePathParams2[1].mEndpointId = Test::kMockEndpoint3; attributePathParams2[1].mClusterId = Test::MockClusterId(2); attributePathParams2[1].mAttributeId = Test::MockAttributeId(2); readPrepareParams.mpAttributePathParamsList = attributePathParams2; readPrepareParams.mAttributePathParamsListSize = 2; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 6); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version1.HasValue() && (version1.Value() == 1)); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint3, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version2.HasValue()); delegate.mNumAttributeResponse = 0; } // Eighth read of E2C3A* and E3C2A2, and inject a large amount of event path list, then it would try to apply previous cache // latest data version and construct data version list but no enough memory, finally fully rollback data version filter. Expect // E2C3A* attributes in report, and E3C2A2 attribute in report { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams2[2]; attributePathParams2[0].mEndpointId = Test::kMockEndpoint2; attributePathParams2[0].mClusterId = Test::MockClusterId(3); attributePathParams2[0].mAttributeId = kInvalidAttributeId; attributePathParams2[1].mEndpointId = Test::kMockEndpoint3; attributePathParams2[1].mClusterId = Test::MockClusterId(2); attributePathParams2[1].mAttributeId = Test::MockAttributeId(2); readPrepareParams.mpAttributePathParamsList = attributePathParams2; readPrepareParams.mAttributePathParamsListSize = 2; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 64; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 6); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version1.HasValue() && (version1.Value() == 1)); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint3, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, !version2.HasValue()); delegate.mNumAttributeResponse = 0; readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; } Test::BumpVersion(); // Ninth read of E1C2A* and E2C3A* and E2C2A*, it would use C1 cached version to construct DataVersionFilter, but version has // changed in server. Expect E1C2A* and C2C3A* and E2C2A* attributes in report, and cache their versions { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams3[3]; attributePathParams3[0].mEndpointId = Test::kMockEndpoint1; attributePathParams3[0].mClusterId = Test::MockClusterId(2); attributePathParams3[0].mAttributeId = kInvalidAttributeId; attributePathParams3[1].mEndpointId = Test::kMockEndpoint2; attributePathParams3[1].mClusterId = Test::MockClusterId(3); attributePathParams3[1].mAttributeId = kInvalidAttributeId; attributePathParams3[2].mEndpointId = Test::kMockEndpoint2; attributePathParams3[2].mClusterId = Test::MockClusterId(2); attributePathParams3[2].mAttributeId = kInvalidAttributeId; readPrepareParams.mpAttributePathParamsList = attributePathParams3; readPrepareParams.mAttributePathParamsListSize = 3; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); // E1C2A* has 3 attributes and E2C3A* has 5 attributes and E2C2A* has 4 attributes NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 12); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version1.HasValue() && (version1.Value() == 2)); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version2.HasValue() && (version2.Value() == 2)); Optional<DataVersion> version3; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint1, Test::MockClusterId(2), version3) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version3.HasValue() && (version3.Value() == 2)); delegate.mNumAttributeResponse = 0; } // Tenth read of E1C2A*(3 attributes) and E2C3A*(5 attributes) and E2C2A*(4 attributes), and inject a large amount of event path // list, then it would try to apply previous cache latest data version and construct data version list with the ordering from // largest cluster size to smallest cluster size(C2, C3, C1) but no enough memory, finally partially rollback data version // filter with only C2. Expect E1C2A*, E2C2A* attributes(7 attributes) in report, { testId++; ChipLogProgress(DataManagement, "\t -- Running Read with ClusterStateCache Test ID %d", testId); app::ReadClient readClient(chip::app::InteractionModelEngine::GetInstance(), &ctx.GetExchangeManager(), cache.GetBufferedCallback(), chip::app::ReadClient::InteractionType::Read); chip::app::AttributePathParams attributePathParams3[3]; attributePathParams3[0].mEndpointId = Test::kMockEndpoint1; attributePathParams3[0].mClusterId = Test::MockClusterId(2); attributePathParams3[0].mAttributeId = kInvalidAttributeId; attributePathParams3[1].mEndpointId = Test::kMockEndpoint2; attributePathParams3[1].mClusterId = Test::MockClusterId(3); attributePathParams3[1].mAttributeId = kInvalidAttributeId; attributePathParams3[2].mEndpointId = Test::kMockEndpoint2; attributePathParams3[2].mClusterId = Test::MockClusterId(2); attributePathParams3[2].mAttributeId = kInvalidAttributeId; readPrepareParams.mpAttributePathParamsList = attributePathParams3; readPrepareParams.mAttributePathParamsListSize = 3; readPrepareParams.mpEventPathParamsList = eventPathParams; readPrepareParams.mEventPathParamsListSize = 62; err = readClient.SendRequest(readPrepareParams); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, delegate.mNumAttributeResponse == 7); NL_TEST_ASSERT(apSuite, !delegate.mReadError); Optional<DataVersion> version1; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(3), version1) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version1.HasValue() && (version1.Value() == 2)); Optional<DataVersion> version2; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint2, Test::MockClusterId(2), version2) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version2.HasValue() && (version2.Value() == 2)); Optional<DataVersion> version3; NL_TEST_ASSERT(apSuite, cache.GetVersion(Test::kMockEndpoint1, Test::MockClusterId(2), version3) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, version3.HasValue() && (version3.Value() == 2)); delegate.mNumAttributeResponse = 0; readPrepareParams.mpEventPathParamsList = nullptr; readPrepareParams.mEventPathParamsListSize = 0; } NL_TEST_ASSERT(apSuite, engine->GetNumActiveReadClients() == 0); engine->Shutdown(); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadEventResponse(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [apSuite, &onSuccessCbInvoked](const app::EventHeader & eventHeader, const auto & EventResponse) { // TODO: Need to add check when IM event server integration completes IgnoreUnusedVariable(apSuite); onSuccessCbInvoked = true; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&onFailureCbInvoked](const app::EventHeader * eventHeader, CHIP_ERROR aError) { onFailureCbInvoked = true; }; Controller::ReadEvent<TestCluster::Events::TestEvent::DecodableType>(&ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, !onFailureCbInvoked); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients() == 0); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers() == 0); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadAttributeError(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataError; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [&onSuccessCbInvoked](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { onSuccessCbInvoked = true; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&onFailureCbInvoked, apSuite](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { NL_TEST_ASSERT(apSuite, aError.IsIMStatus() && app::StatusIB(aError).mStatus == Protocols::InteractionModel::Status::Busy); onFailureCbInvoked = true; }; Controller::ReadAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>(&ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, !onSuccessCbInvoked && onFailureCbInvoked); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients() == 0); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers() == 0); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadAttributeTimeout(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataError; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [&onSuccessCbInvoked](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { onSuccessCbInvoked = true; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&onFailureCbInvoked, apSuite](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { NL_TEST_ASSERT(apSuite, aError == CHIP_ERROR_TIMEOUT); onFailureCbInvoked = true; }; Controller::ReadAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>(&ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb); ctx.ExpireSessionAliceToBob(); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 1); ctx.ExpireSessionBobToAlice(); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, !onSuccessCbInvoked && onFailureCbInvoked); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers() == 0); // // Let's put back the sessions so that the next tests (which assume a valid initialized set of sessions) // can function correctly. // ctx.CreateSessionAliceToBob(); ctx.CreateSessionBobToAlice(); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadHandler_MultipleSubscriptions(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [&numSuccessCalls](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { numSuccessCalls++; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&apSuite](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { // // We shouldn't be encountering any failures in this test. // NL_TEST_ASSERT(apSuite, false); }; auto onSubscriptionEstablishedCb = [&numSubscriptionEstablishedCalls](const app::ReadClient & readClient) { numSubscriptionEstablishedCalls++; }; // // Test the application callback as well to ensure we get the right number of SubscriptionEstablishment/Termination // callbacks. // app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(&gTestReadInteraction); // // Try to issue parallel subscriptions that will exceed the value for CHIP_IM_MAX_NUM_READ_HANDLER. // If heap allocation is correctly setup, this should result in it successfully servicing more than the number // present in that define. // for (int i = 0; i < (CHIP_IM_MAX_NUM_READ_HANDLER + 1); i++) { NL_TEST_ASSERT(apSuite, Controller::SubscribeAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, false, true) == CHIP_NO_ERROR); } ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, numSuccessCalls == (CHIP_IM_MAX_NUM_READ_HANDLER + 1)); NL_TEST_ASSERT(apSuite, numSubscriptionEstablishedCalls == (CHIP_IM_MAX_NUM_READ_HANDLER + 1)); NL_TEST_ASSERT(apSuite, gTestReadInteraction.mNumActiveSubscriptions == (CHIP_IM_MAX_NUM_READ_HANDLER + 1)); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); NL_TEST_ASSERT(apSuite, gTestReadInteraction.mNumActiveSubscriptions == 0); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); } void TestReadInteraction::TestReadHandler_SubscriptionAppRejection(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [&numSuccessCalls](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { numSuccessCalls++; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&numFailureCalls](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { numFailureCalls++; }; auto onSubscriptionEstablishedCb = [&numSubscriptionEstablishedCalls](const app::ReadClient & readClient) { numSubscriptionEstablishedCalls++; }; // // Test the application callback as well to ensure we get the right number of SubscriptionEstablishment/Termination // callbacks. // app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(&gTestReadInteraction); // // Test the application rejecting subscriptions. // gTestReadInteraction.mEmitSubscriptionError = true; NL_TEST_ASSERT(apSuite, Controller::SubscribeAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, false, true) == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, numSuccessCalls == 0); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute // implementation. // NL_TEST_ASSERT(apSuite, numFailureCalls == 0); NL_TEST_ASSERT(apSuite, numSubscriptionEstablishedCalls == 0); NL_TEST_ASSERT(apSuite, gTestReadInteraction.mNumActiveSubscriptions == 0); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); NL_TEST_ASSERT(apSuite, gTestReadInteraction.mNumActiveSubscriptions == 0); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); gTestReadInteraction.mEmitSubscriptionError = false; } void TestReadInteraction::TestReadHandler_SubscriptionAlteredReportingIntervals(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [&numSuccessCalls](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { numSuccessCalls++; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&numFailureCalls](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { numFailureCalls++; }; auto onSubscriptionEstablishedCb = [&numSubscriptionEstablishedCalls, &apSuite](const app::ReadClient & readClient) { uint16_t minInterval = 0, maxInterval = 0; CHIP_ERROR err = readClient.GetReportingIntervals(minInterval, maxInterval); NL_TEST_ASSERT(apSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, minInterval == kTestMinInterval); NL_TEST_ASSERT(apSuite, maxInterval == kTestMaxInterval); numSubscriptionEstablishedCalls++; }; // // Test the application callback as well to ensure we get the right number of SubscriptionEstablishment/Termination // callbacks. // app::InteractionModelEngine::GetInstance()->RegisterReadHandlerAppCallback(&gTestReadInteraction); // // Test the server-side application altering the subscription intervals. // gTestReadInteraction.mAlterSubscriptionIntervals = true; NL_TEST_ASSERT(apSuite, Controller::SubscribeAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, false, true) == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); // // Failures won't get routed to us here since re-subscriptions are enabled by default in the Controller::SubscribeAttribute // implementation. // NL_TEST_ASSERT(apSuite, numSuccessCalls != 0); NL_TEST_ASSERT(apSuite, numFailureCalls == 0); NL_TEST_ASSERT(apSuite, numSubscriptionEstablishedCalls == 1); NL_TEST_ASSERT(apSuite, gTestReadInteraction.mNumActiveSubscriptions == 1); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); NL_TEST_ASSERT(apSuite, gTestReadInteraction.mNumActiveSubscriptions == 0); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); app::InteractionModelEngine::GetInstance()->UnregisterReadHandlerAppCallback(); gTestReadInteraction.mAlterSubscriptionIntervals = false; } void TestReadInteraction::TestReadHandler_MultipleReads(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); static_assert(CHIP_IM_MAX_REPORTS_IN_FLIGHT <= CHIP_IM_MAX_NUM_READ_HANDLER, "How can we have more reports in flight than read handlers?"); MultipleReadHelper(apSuite, ctx, CHIP_IM_MAX_REPORTS_IN_FLIGHT); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); } void TestReadInteraction::TestReadHandler_OneSubscribeMultipleReads(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); static_assert(CHIP_IM_MAX_REPORTS_IN_FLIGHT <= CHIP_IM_MAX_NUM_READ_HANDLER, "How can we have more reports in flight than read handlers?"); static_assert(CHIP_IM_MAX_REPORTS_IN_FLIGHT > 1, "We won't do any reads"); SubscribeThenReadHelper(apSuite, ctx, 1, CHIP_IM_MAX_REPORTS_IN_FLIGHT - 1); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); } void TestReadInteraction::TestReadHandler_TwoSubscribesMultipleReads(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); static_assert(CHIP_IM_MAX_REPORTS_IN_FLIGHT <= CHIP_IM_MAX_NUM_READ_HANDLER, "How can we have more reports in flight than read handlers?"); static_assert(CHIP_IM_MAX_REPORTS_IN_FLIGHT > 2, "We won't do any reads"); SubscribeThenReadHelper(apSuite, ctx, 2, CHIP_IM_MAX_REPORTS_IN_FLIGHT - 2); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); } void TestReadInteraction::SubscribeThenReadHelper(nlTestSuite * apSuite, TestContext & aCtx, size_t aSubscribeCount, size_t aReadCount) { auto sessionHandle = aCtx.GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [&numSuccessCalls](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { numSuccessCalls++; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&apSuite](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { // // We shouldn't be encountering any failures in this test. // NL_TEST_ASSERT(apSuite, false); }; auto onSubscriptionEstablishedCb = [&numSubscriptionEstablishedCalls, &apSuite, &aCtx, aSubscribeCount, aReadCount](const app::ReadClient & readClient) { numSubscriptionEstablishedCalls++; if (numSubscriptionEstablishedCalls == aSubscribeCount) { MultipleReadHelper(apSuite, aCtx, aReadCount); } }; for (size_t i = 0; i < aSubscribeCount; ++i) { NL_TEST_ASSERT(apSuite, Controller::SubscribeAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>( &aCtx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, false, true) == CHIP_NO_ERROR); } aCtx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, numSuccessCalls == aSubscribeCount); NL_TEST_ASSERT(apSuite, numSubscriptionEstablishedCalls == aSubscribeCount); } void TestReadInteraction::MultipleReadHelper(nlTestSuite * apSuite, TestContext & aCtx, size_t aReadCount) { auto sessionHandle = aCtx.GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; responseDirective = kSendDataResponse; uint16_t firstExpectedResponse = totalReadCount + 1; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&apSuite, &numFailureCalls](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { numFailureCalls++; NL_TEST_ASSERT(apSuite, attributePath == nullptr); }; for (size_t i = 0; i < aReadCount; ++i) { // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, // it's not safe to do so. auto onSuccessCb = [&numSuccessCalls, &apSuite, firstExpectedResponse, i](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { NL_TEST_ASSERT(apSuite, dataResponse == firstExpectedResponse + i); numSuccessCalls++; }; NL_TEST_ASSERT(apSuite, Controller::ReadAttribute<TestCluster::Attributes::Int16u::TypeInfo>( &aCtx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb) == CHIP_NO_ERROR); } aCtx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, numSuccessCalls == aReadCount); NL_TEST_ASSERT(apSuite, numFailureCalls == 0); } void TestReadInteraction::TestReadHandler_MultipleSubscriptionsWithDataVersionFilter(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [apSuite, &numSuccessCalls](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { NL_TEST_ASSERT(apSuite, attributePath.mDataVersion.HasValue() && attributePath.mDataVersion.Value() == kDataVersion); numSuccessCalls++; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&apSuite](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { // // We shouldn't be encountering any failures in this test. // NL_TEST_ASSERT(apSuite, false); }; auto onSubscriptionEstablishedCb = [&numSubscriptionEstablishedCalls](const app::ReadClient & readClient) { numSubscriptionEstablishedCalls++; }; // // Try to issue parallel subscriptions that will exceed the value for CHIP_IM_MAX_NUM_READ_HANDLER. // If heap allocation is correctly setup, this should result in it successfully servicing more than the number // present in that define. // chip::Optional<chip::DataVersion> dataVersion(1); for (int i = 0; i < (CHIP_IM_MAX_NUM_READ_HANDLER + 1); i++) { NL_TEST_ASSERT(apSuite, Controller::SubscribeAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, false, true, dataVersion) == CHIP_NO_ERROR); } ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, numSuccessCalls == (CHIP_IM_MAX_NUM_READ_HANDLER + 1)); NL_TEST_ASSERT(apSuite, numSubscriptionEstablishedCalls == (CHIP_IM_MAX_NUM_READ_HANDLER + 1)); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadHandlerResourceExhaustion_MultipleSubscriptions(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; uint32_t numSubscriptionEstablishedCalls = 0; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [&numSuccessCalls](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { numSuccessCalls++; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&apSuite, &numFailureCalls](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { numFailureCalls++; NL_TEST_ASSERT(apSuite, aError == CHIP_IM_GLOBAL_STATUS(ResourceExhausted)); NL_TEST_ASSERT(apSuite, attributePath == nullptr); }; auto onSubscriptionEstablishedCb = [&numSubscriptionEstablishedCalls](const app::ReadClient & readClient) { numSubscriptionEstablishedCalls++; }; // // Artifically limit the capacity to 2 ReadHandlers. This will also validate reservation of handlers for Reads, // since the second subscription below should fail correctly. // app::InteractionModelEngine::GetInstance()->SetHandlerCapacity(2); NL_TEST_ASSERT(apSuite, Controller::SubscribeAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, false, true) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, Controller::SubscribeAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, 0, 10, onSubscriptionEstablishedCb, false, true) == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, numSuccessCalls == 1); NL_TEST_ASSERT(apSuite, numSubscriptionEstablishedCalls == 1); // Resubscription is happening for second subscribe call NL_TEST_ASSERT(apSuite, numFailureCalls == 0); app::InteractionModelEngine::GetInstance()->SetHandlerCapacity(-1); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadHandlerResourceExhaustion_MultipleReads(nlTestSuite * apSuite, void * apContext) { TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); uint32_t numSuccessCalls = 0; uint32_t numFailureCalls = 0; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [&numSuccessCalls](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { numSuccessCalls++; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&apSuite, &numFailureCalls](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { numFailureCalls++; NL_TEST_ASSERT(apSuite, aError == CHIP_IM_GLOBAL_STATUS(ResourceExhausted)); NL_TEST_ASSERT(apSuite, attributePath == nullptr); }; app::InteractionModelEngine::GetInstance()->SetHandlerCapacity(0); NL_TEST_ASSERT(apSuite, Controller::ReadAttribute<TestCluster::Attributes::ListStructOctetString::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb) == CHIP_NO_ERROR); ctx.DrainAndServiceIO(); app::InteractionModelEngine::GetInstance()->SetHandlerCapacity(-1); app::InteractionModelEngine::GetInstance()->ShutdownActiveReads(); NL_TEST_ASSERT(apSuite, numSuccessCalls == 0); NL_TEST_ASSERT(apSuite, numFailureCalls == 1); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadFabricScopedWithoutFabricFilter(nlTestSuite * apSuite, void * apContext) { /** * TODO: we cannot implement the e2e read tests w/ fabric filter since the test session has only one session, and the * ReadSingleClusterData is not the one in real applications. We should be able to move some logic out of the ember library and * make it possible to have more fabrics in test setup so we can have a better test coverage. * * NOTE: Based on the TODO above, the test is testing two separate logics: * - When a fabric filtered read request is received, the server is able to pass the required fabric index to the response * encoder. * - When a fabric filtered read request is received, the response encoder is able to encode the attribute correctly. */ TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [apSuite, &onSuccessCbInvoked](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { size_t len = 0; NL_TEST_ASSERT(apSuite, dataResponse.ComputeSize(&len) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, len > 1); onSuccessCbInvoked = true; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&onFailureCbInvoked](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { onFailureCbInvoked = true; }; Controller::ReadAttribute<TestCluster::Attributes::ListFabricScoped::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, false /* fabric filtered */); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, onSuccessCbInvoked && !onFailureCbInvoked); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients() == 0); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers() == 0); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } void TestReadInteraction::TestReadFabricScopedWithFabricFilter(nlTestSuite * apSuite, void * apContext) { /** * TODO: we cannot implement the e2e read tests w/ fabric filter since the test session has only one session, and the * ReadSingleClusterData is not the one in real applications. We should be able to move some logic out of the ember library and * make it possible to have more fabrics in test setup so we can have a better test coverage. * * NOTE: Based on the TODO above, the test is testing two separate logics: * - When a fabric filtered read request is received, the server is able to pass the required fabric index to the response * encoder. * - When a fabric filtered read request is received, the response encoder is able to encode the attribute correctly. */ TestContext & ctx = *static_cast<TestContext *>(apContext); auto sessionHandle = ctx.GetSessionBobToAlice(); bool onSuccessCbInvoked = false, onFailureCbInvoked = false; responseDirective = kSendDataResponse; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onSuccessCb = [apSuite, &onSuccessCbInvoked](const app::ConcreteDataAttributePath & attributePath, const auto & dataResponse) { size_t len = 0; NL_TEST_ASSERT(apSuite, dataResponse.ComputeSize(&len) == CHIP_NO_ERROR); NL_TEST_ASSERT(apSuite, len == 1); // TODO: Uncomment the following code after we have fabric support in unit tests. /* auto iter = dataResponse.begin(); if (iter.Next()) { auto & item = iter.GetValue(); NL_TEST_ASSERT(apSuite, item.fabricIndex == 1); } */ onSuccessCbInvoked = true; }; // Passing of stack variables by reference is only safe because of synchronous completion of the interaction. Otherwise, it's // not safe to do so. auto onFailureCb = [&onFailureCbInvoked](const app::ConcreteDataAttributePath * attributePath, CHIP_ERROR aError) { onFailureCbInvoked = true; }; Controller::ReadAttribute<TestCluster::Attributes::ListFabricScoped::TypeInfo>( &ctx.GetExchangeManager(), sessionHandle, kTestEndpointId, onSuccessCb, onFailureCb, true /* fabric filtered */); ctx.DrainAndServiceIO(); NL_TEST_ASSERT(apSuite, onSuccessCbInvoked && !onFailureCbInvoked); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadClients() == 0); NL_TEST_ASSERT(apSuite, app::InteractionModelEngine::GetInstance()->GetNumActiveReadHandlers() == 0); NL_TEST_ASSERT(apSuite, ctx.GetExchangeManager().GetNumActiveExchanges() == 0); } // clang-format off const nlTest sTests[] = { NL_TEST_DEF("TestReadAttributeResponse", TestReadInteraction::TestReadAttributeResponse), NL_TEST_DEF("TestReadDataVersionFilter", TestReadInteraction::TestReadDataVersionFilter), NL_TEST_DEF("TestReadEventResponse", TestReadInteraction::TestReadEventResponse), NL_TEST_DEF("TestReadAttributeError", TestReadInteraction::TestReadAttributeError), NL_TEST_DEF("TestReadFabricScopedWithoutFabricFilter", TestReadInteraction::TestReadFabricScopedWithoutFabricFilter), NL_TEST_DEF("TestReadFabricScopedWithFabricFilter", TestReadInteraction::TestReadFabricScopedWithFabricFilter), NL_TEST_DEF("TestReadHandler_MultipleSubscriptions", TestReadInteraction::TestReadHandler_MultipleSubscriptions), NL_TEST_DEF("TestReadHandler_SubscriptionAppRejection", TestReadInteraction::TestReadHandler_SubscriptionAppRejection), NL_TEST_DEF("TestReadHandler_MultipleSubscriptionsWithDataVersionFilter", TestReadInteraction::TestReadHandler_MultipleSubscriptionsWithDataVersionFilter), NL_TEST_DEF("TestReadHandler_MultipleReads", TestReadInteraction::TestReadHandler_MultipleReads), NL_TEST_DEF("TestReadHandler_OneSubscribeMultipleReads", TestReadInteraction::TestReadHandler_OneSubscribeMultipleReads), NL_TEST_DEF("TestReadHandler_TwoSubscribesMultipleReads", TestReadInteraction::TestReadHandler_TwoSubscribesMultipleReads), NL_TEST_DEF("TestReadHandlerResourceExhaustion_MultipleSubscriptions", TestReadInteraction::TestReadHandlerResourceExhaustion_MultipleSubscriptions), NL_TEST_DEF("TestReadHandlerResourceExhaustion_MultipleReads", TestReadInteraction::TestReadHandlerResourceExhaustion_MultipleReads), NL_TEST_DEF("TestReadAttributeTimeout", TestReadInteraction::TestReadAttributeTimeout), NL_TEST_DEF("TestReadHandler_SubscriptionAlteredReportingIntervals", TestReadInteraction::TestReadHandler_SubscriptionAlteredReportingIntervals), NL_TEST_DEF("TestReadSubscribeAttributeResponseWithCache", TestReadInteraction::TestReadSubscribeAttributeResponseWithCache), NL_TEST_SENTINEL() }; // clang-format on // clang-format off nlTestSuite sSuite = { "TestRead", &sTests[0], TestContext::InitializeAsync, TestContext::Finalize }; // clang-format on } // namespace int TestReadInteractionTest() { TestContext gContext; nlTestRunner(&sSuite, &gContext); return (nlTestRunnerStats(&sSuite)); } CHIP_REGISTER_TEST_SUITE(TestReadInteractionTest)
50.02321
159
0.705057
sungho1shin
295eb0d17b6abad78da718755b0380199969e078
624
cc
C++
src/init.cc
leozdgao/node-skia-canvas
3ea3fa92f6c5050e961717a87354e330169b12b0
[ "MIT" ]
7
2021-11-03T12:09:48.000Z
2022-03-30T02:19:07.000Z
src/init.cc
leozdgao/node-skia
3ea3fa92f6c5050e961717a87354e330169b12b0
[ "MIT" ]
4
2021-05-23T09:07:01.000Z
2021-09-25T15:04:20.000Z
src/init.cc
leozdgao/node-skia
3ea3fa92f6c5050e961717a87354e330169b12b0
[ "MIT" ]
1
2022-03-30T02:19:08.000Z
2022-03-30T02:19:08.000Z
#include <napi.h> #include "Canvas.h" #include "CanvasGradient.h" #include "CanvasPattern.h" #include "CanvasRenderingContext2D.h" #include "FontManager.h" #include "Image.h" #include "ImageData.h" #include "TextMetrics.h" static Napi::Object Init(Napi::Env env, Napi::Object exports) { Canvas::Init(env, exports); CanvasGradient::Init(env, exports); CanvasPattern::Init(env, exports); CanvasRenderingContext2D::Init(env, exports); FontManager::Init(env, exports); Image::Init(env, exports); ImageData::Init(env, exports); TextMetrics::Init(env, exports); return exports; } NODE_API_MODULE(hello, Init)
24.96
63
0.733974
leozdgao
296335e5ba4f05778a7680f620a5589983e85375
20,201
cpp
C++
src/lib/coil/common/coil/stringutil.cpp
r-kurose/OpenRTM-aist
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
[ "RSA-MD" ]
null
null
null
src/lib/coil/common/coil/stringutil.cpp
r-kurose/OpenRTM-aist
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
[ "RSA-MD" ]
null
null
null
src/lib/coil/common/coil/stringutil.cpp
r-kurose/OpenRTM-aist
258c922c55a97c6d1265dbf45e1e8b2ea29b2d86
[ "RSA-MD" ]
null
null
null
// -*- C++ -*- /*! * @file StringUtil.cpp * @brief String operation utility * @date $Date: 2007-12-31 03:08:07 $ * @author Noriaki Ando <n-ando@aist.go.jp> * * Copyright (C) 2006-2008 * Noriaki Ando * Task-intelligence Research Group, * Intelligent Systems Research Institute, * National Institute of * Advanced Industrial Science and Technology (AIST), Japan * All rights reserved. * * $Id: StringUtil.cpp 826 2008-08-26 08:13:39Z n-ando $ * */ #include <coil/stringutil.h> #include <array> #include <climits> #include <cstdarg> #include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <cctype> #include <regex> #include <utility> #include <unordered_set> #include <coil/OS.h> #ifdef __QNX__ using std::toupper; using std::isalpha; #endif namespace coil { /*! * @if jp * @brief string から wstring への変換 * @else * @brief string to wstring conversion * @endif */ std::wstring string2wstring(const std::string& str) { #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) int buff_size = MultiByteToWideChar(CP_UTF7, 0, str.c_str(), -1, (wchar_t*)nullptr, 0); wchar_t* ret = new wchar_t[buff_size]; MultiByteToWideChar(CP_UTF7, 0, str.c_str(), -1, ret, buff_size); std::wstring wstr(ret, ret + buff_size - 1); delete[] ret; #else std::wstring wstr(str.length(), L' '); std::copy(str.begin(), str.end(), wstr.begin()); #endif return wstr; } /*! * @if jp * @brief wstring から string への変換 * @else * @brief wstring to string conversion * @endif */ std::string wstring2string(const std::wstring& wstr) { #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) int buff_size = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, (char*)nullptr, 0, nullptr, nullptr); CHAR* ret = new CHAR[buff_size]; WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, ret, buff_size, nullptr, nullptr); std::string str(ret, ret + buff_size - 1); delete[] ret; #else std::string str(wstr.length(), ' '); std::copy(wstr.begin(), wstr.end(), str.begin()); #endif return str; } /*! * @if jp * @brief 大文字への変換 * @else * @brief Uppercase String Transformation * @endif */ std::string toUpper(std::string str) noexcept { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char x){ return static_cast<char>(std::toupper(x)); }); return str; } /*! * @if jp * @brief 小文字への変換 * @else * @brief Lowercase String Transformation * @endif */ std::string toLower(std::string str) noexcept { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char x){ return static_cast<char>(std::tolower(x)); }); return str; } /*! * @if jp * @brief 入力ストリームから1行読み込む * @else * @brief Read a line from input stream * @endif */ std::string getlinePortable(std::istream& istr) { char c; std::stringstream s; while (istr.get(c)) { if (c == '\n') { break; } else if (c == '\r') { if (istr.peek() == '\n') { istr.ignore(); } break; } else { s << c; } } return s.str(); } /*! * @if jp * @brief 文字列がエスケープされているか判断する * @else * @brief Check whether the character is escaped or not * @endif */ bool isEscaped(const std::string& str, std::string::size_type pos) { if (pos == 0) { return false; } --pos; size_t i = 0; for ( ; str[pos] == '\\'; ++i) { if (pos == 0) { break; } --pos; } // If the number of \ is odd, delimiter is escaped. return (i % 2) == 1; } /*! * @if jp * @brief 文字列をエスケープする * @else * @brief Escape string * @endif */ std::string escape(const std::string& str) { std::string ret; ret.reserve(str.length()*2); std::for_each(str.begin(), str.end(), [&ret](char c) { switch (c) { case '\t': ret += "\\t"; break; case '\n': ret += "\\n"; break; case '\f': ret += "\\f"; break; case '\r': ret += "\\r"; break; case '\\': ret += "\\\\"; break; default: ret += c; break; } }); return ret; } /*! * @if jp * @brief 文字列のエスケープを戻す * @else * @brief Unescape string * @endif */ std::string unescape(std::string str) noexcept { std::string::size_type wp{0}; bool is_escaped{false}; for(std::string::size_type rp{0}; rp < str.length(); ++rp) { if (!is_escaped) { if (str[rp] != '\\') str[wp++] = str[rp]; else is_escaped = true; } else { is_escaped = false; switch (str[rp]) { case 't': str[wp++] = '\t'; break; case 'n': str[wp++] = '\n'; break; case 'f': str[wp++] = '\f'; break; case 'r': str[wp++] = '\r'; break; case '\"': str[wp++] = '\"'; break; case '\'': str[wp++] = '\''; break; default: str[wp++] = str[rp]; break; } } } str.resize(wp); return str; } /*! * @if jp * @brief 文字列の空白文字を削除する * @else * @brief Erase blank characters of string * @endif */ std::string eraseBlank(std::string str) noexcept { str.erase(std::remove_if(str.begin(), str.end(), [](unsigned char x){ return std::isblank(x); }), str.end()); return str; } /*! * @if jp * @brief 文字列の先頭の空白文字を削除する * @else * @brief Erase the head blank characters of string * @endif */ std::string eraseHeadBlank(std::string str) noexcept { return str.erase(0, str.find_first_not_of(" \t")); } /*! * @if jp * @brief 文字列の末尾の空白文字を削除する * @else * @brief Erase the tail blank characters of string * @endif */ std::string eraseTailBlank(std::string str) noexcept { return str.erase(str.find_last_not_of(" \t") + 1); // npos + 1 = 0 } /*! * @if jp * @brief 文字列の先頭・末尾の空白文字を削除する * @else * @brief Erase the head blank and the tail blank characters of string * @endif */ std::string eraseBothEndsBlank(std::string str) noexcept { return eraseHeadBlank(eraseTailBlank(std::move(str))); } /*! * @if jp * @brief 文字列を正規化する * @else * @brief Erase the head/tail blank and replace upper case to lower case * @endif */ std::string normalize(std::string str) noexcept { return toLower(eraseBothEndsBlank(std::move(str))); } /*! * @if jp * @brief 文字列を置き換える * @else * @brief Replace string * @endif */ std::string replaceString(std::string str, const std::string& from, const std::string& to) { if (from.empty()) { return str; } for (std::string::size_type pos{str.find(from, 0)}; pos != std::string::npos; pos = str.find(from, pos + to.length())) { str.replace(pos, from.length(), to); } return str; } /*! * @if jp * @brief 文字列を分割文字で分割する * @else * @brief Split string by delimiter * @endif */ vstring split(const std::string& input, const std::string& delimiter, bool ignore_empty) { if (input.empty()) { return {}; } if (delimiter.empty()) { return {eraseBothEndsBlank(input)}; } vstring results; std::string::size_type pos{0}; for (auto found_pos = input.find(delimiter, pos); found_pos != std::string::npos; found_pos = input.find(delimiter, pos)) { std::string str{eraseBothEndsBlank(input.substr(pos, found_pos - pos))}; if (!(ignore_empty && str.empty())) { results.emplace_back(std::move(str)); } pos = found_pos + delimiter.length(); } std::string str{eraseBothEndsBlank(input.substr(pos))}; if (!(ignore_empty && str.empty())) { results.emplace_back(std::move(str)); } return results; } /*! * @if jp * @brief 与えられた文字列をbool値に変換する * @else * @brief Convert given string into bool value * @endif */ bool toBool(std::string str, std::string yes, std::string no, bool default_value) { std::string s = toUpper(std::move(str)); if (s.find(toUpper(std::move(yes))) != std::string::npos) return true; else if (s.find(toUpper(std::move(no))) != std::string::npos) return false; else return default_value; } /*! * @if jp * @brief 文字列リスト中にある文字列が含まれるかどうかを判断する * @else * @brief Include if a string is included in string list * @endif */ bool includes(const vstring& list, std::string value, bool ignore_case) { std::string const& v{ignore_case ? toLower(std::move(value)) : value}; for (auto const& str : list) { std::string const& x{ignore_case ? toLower(str) : str}; if (v == x) return true; } return false; } /*! * @if jp * @brief 文字列リスト中にある文字列が含まれるかどうかを判断する * @else * @brief Include if a string is included in string list * @endif */ bool includes(const std::string& list, std::string value, bool ignore_case) { return includes(split(list, ","), std::move(value), ignore_case); } /*! * @if jp * @brief 与えられた文字列が絶対パスかどうかを判断する * @else * @brief Investigate whether the given string is absolute path or not * @endif */ bool isAbsolutePath(const std::string& str) { static std::regex const path{ "(?:" "^/" // UNIX absolute path R"(|^[a-zA-Z]{1}:\\)" // Windows absolute path R"(|^\\\\)" // Windows network file path ")"} ; return std::regex_search(str, path); } /*! * @if jp * @brief 与えられた文字列がURLかどうかを判断する * @else * @brief Investigate whether the given string is URL or not * @endif */ bool isURL(const std::string& str) { static std::regex const url{R"(\w://)"}; return std::regex_search(str, url); } bool isIPv4(const std::string& str) { // IPv4 address must be dotted-decimal format. // not support: 0x1.0x1.0x1.0x1, 01.01.01.01, 100.100000 static std::regex const ipv4{ "(?:(?:" R"(\d)" // x R"(|[1-9]\d)" // Xx R"(|1\d\d)" // 1xx R"(|2[0-4]\d)" // 2Xx R"(|25[0-5])" // 25x ")\\.){3}" // <num>.<num>.<num>. "(?:" R"(\d)" // x R"(|[1-9]\d)" // Xx R"(|1\d\d)" // 1xx R"(|2[0-4]\d)" // 2Xx R"(|25[0-5])" // 25X ")"}; // <num> return std::regex_match(str, ipv4); } bool isIPv6(const std::string& str) { // IPv6 address must be // 1111:1111:1111:1111:1111:1111:1111:1111 static std::regex const ipv6{ "(?:[0-9a-fA-F]{1,4}:){7}" // xxxx:xxxx: ... "[0-9a-fA-F]{1,4}"}; // xxxx return std::regex_match(str, ipv6); } bool isIPPort(const std::string& str) { static std::regex const port{ "(?:" R"(\d)" // x R"(|[1-9]\d{1,3})" // Xx, Xxx, Xxxx R"(|[1-5]\d{4})" // Xxxxx R"(|6[0-4]\d{3})" // 6Xxxx R"(|65[0-4]\d{2})" // 65Xxx R"(|655[0-2]\d)" // 655Xx R"(|6553[0-5])" // 6553X ")"}; return std::regex_match(str, port); } /*! * @if jp * @brief URLパラメータをmapstringに分解して返す * * URLパラメータ表現 something?key0=value0&key1=value1.... のうち * '?' 以降の部分を分解して、std::map<std::string, std::string> 形式 * に変換する。与えられた文字列を左からサーチし、'?' より右側の部分に * ついて解析を行う。'&'で分割し、左から '=' を検索し、最初の '=' の * 右辺と左辺をそれぞれ、key と value として map に格納する。 * * @param str 分解対象文字列 * @return mapstring 型の key/valueデータ * * @else * @brief Investigate whether the given string is URL or not * * URL parameter description such as * something?key0=value0&key1=value1.... is analyzed. Right hand * side string of '?' character is decomposed and it is converted * into std::map<std::string, std::string> type.The following string * are devided by '&' and then '=' character is * searched. Right-hand-side value and left-hand-side value of '=' * are stored as key and value in the map. * * @param str The target string for decomposed * * @return decomposed key-values in map * * @endif */ coil::mapstring urlparam2map(const std::string& str) { std::string::size_type qpos = str.find('?'); if (qpos == std::string::npos) { qpos = 0; } else { ++qpos; } coil::vstring params = coil::split(str.substr(qpos), "&"); std::map<std::string, std::string> retmap; for (auto & param : params) { std::string::size_type pos = param.find('='); if (pos != std::string::npos) { retmap[param.substr(0, pos)] = param.substr(pos + 1); } else { retmap[param] = std::string(""); } } return retmap; } /*! * @if jp * @brief 与えられた文字列をstd::stringに変換 * @else * @brief Convert the given string to std::string. * @endif */ template<> bool stringTo<std::string>(std::string& val, const char* str) { if (str == nullptr) { return false; } val = str; return true; } /*! * @if jp * @brief 与えられた文字列をboolに変換 * @else * @brief Convert the given string to bool. * @endif */ template <> bool stringTo<bool>(bool& val, const char* str) { if (str == nullptr) { return false; } std::string boolstr{coil::normalize(str)}; if (boolstr == "true" || boolstr == "1" || boolstr == "yes" || boolstr == "on") { val = true; return true; } else if (boolstr == "false" || boolstr == "0" || boolstr == "no" || boolstr == "off") { val = false; return true; } else { } return false; } /*! * @if jp * @brief 与えられた文字列をstd::chrono::duratoin<double>に変換 * @else * @brief Convert the given string to std::chrono::duratoin<double>. * @endif */ template<> bool stringTo<std::chrono::duration<double>>(std::chrono::duration<double>& val, const char* str) { double num; if (stringTo(num, str)) { val = std::chrono::duration<double>(num); return true; } else { return false; } } /*! * @if jp * @brief 与えられた文字列 (実数、単位[s]) をstd::chrono::duratoin<>に変換 * @else * @brief Convert the given string to std::chrono::duratoin<>. * @endif */ template<typename duration> bool stringToDuration(duration& val, const char* str) { std::chrono::duration<double> val_d; if (stringTo(val_d, str)) { val = std::chrono::duration_cast<duration>(val_d); return true; } else { return false; } } /*! * @if jp * @brief 与えられた文字列 (実数、単位[s]) をstd::chrono::nanosecondsに変換 * @else * @brief Convert the given string to std::chrono::nanoseconds. * @endif */ template<> bool stringTo<std::chrono::nanoseconds>(std::chrono::nanoseconds& val, const char* str) { return stringToDuration(val, str); } /*! * @if jp * @brief 与えられた文字列 (実数、単位[s]) をstd::chrono::microsecondsに変換 * @else * @brief Convert the given string to std::chrono::microseconds. * @endif */ template<> bool stringTo<std::chrono::microseconds>(std::chrono::microseconds& val, const char* str) { return stringToDuration(val, str); } /*! * @if jp * @brief 与えられた文字列 (実数、単位[s]) をstd::chrono::millisecondsに変換 * @else * @brief Convert the given string to std::chrono::milliseconds. * @endif */ template<> bool stringTo<std::chrono::milliseconds>(std::chrono::milliseconds& val, const char* str) { return stringToDuration(val, str); } /*! * @if jp * @brief 与えられた文字列 (実数、単位[s]) をstd::chrono::secondsに変換 * @else * @brief Convert the given string to std::chrono::seconds. * @endif */ template<> bool stringTo<std::chrono::seconds>(std::chrono::seconds& val, const char* str) { return stringToDuration(val, str); } /*! * @if jp * @brief 与えられた文字列 (実数、単位[s]) をstd::chrono::minutesに変換 * @else * @brief Convert the given string to std::chrono::minutes. * @endif */ template<> bool stringTo<std::chrono::minutes>(std::chrono::minutes& val, const char* str) { return stringToDuration(val, str); } /*! * @if jp * @brief 与えられた文字列 (実数、単位[s]) をstd::chrono::hoursに変換 * @else * @brief Convert the given string to std::chrono::hours. * @endif */ template<> bool stringTo<std::chrono::hours>(std::chrono::hours& val, const char* str) { return stringToDuration(val, str); } /*! * @if jp * @brief 与えられた文字列リストから重複を削除 * @else * @brief Eliminate duplication from the given string list * @endif */ vstring unique_sv(vstring sv) { std::unordered_set<std::string> set{std::make_move_iterator(sv.begin()), std::make_move_iterator(sv.end()), sv.size()}; #if (defined(__GNUC__) && (__GNUC__ < 5) && !defined(__clang__)) \ || (defined(_MSC_VER) && (_MSC_VER < 1900)) sv.clear(); for (auto&& itr : set) { sv.emplace_back(std::move(itr)); } #else sv.assign(std::make_move_iterator(set.begin()), std::make_move_iterator(set.end())); #endif return sv; } /*! * @if jp * @brief 与えられた文字列リストからCSVを生成 * @else * @brief Create CSV file from the given string list * @endif */ std::string flatten(vstring sv, const std::string& delimiter) { if (sv.empty()) { return ""; } std::string str = std::string(); for (size_t i(0), len(sv.size() - 1); i < len; ++i) { str += sv[i] + delimiter; } return str + sv.back(); } /*! * @if jp * @brief 与えられた文字列リストを引数リストに変換 * @else * @brief Convert the given string list into the argument list * @endif */ Argv::Argv(const vstring& args) { // make m_args. m_args.reserve(args.size()); for (auto&& arg : args) { m_args.emplace_back(arg.c_str(), arg.c_str() + arg.size() + 1); } // make m_argv. m_argv.reserve(m_args.size() + 1); for(auto&& arg : m_args) { m_argv.emplace_back(arg.data()); } m_argv.emplace_back(nullptr); } #if defined(_MSC_VER) && (_MSC_VER < 1900) // Visual Studio 2013 Argv::Argv(Argv&& x) noexcept { *this = std::move(x); } Argv& Argv::operator=(Argv&& x) noexcept { m_argv = std::move(x.m_argv); m_args = std::move(x.m_args); return *this; } #endif Argv::~Argv() = default; // No inline for gcc warning, too big. /*! * @if jp * @brief 指定された書式に変換 * @else * @brief Convert it into a format given with an argumen * @endif */ std::string sprintf(char const * __restrict fmt, ...) { std::array<char, 1024> str; va_list ap; va_start(ap, fmt); #ifdef WIN32 _vsnprintf_s(&str[0], str.size() - 1, _TRUNCATE, fmt, ap); #else vsnprintf(&str[0], str.size() - 1, fmt, ap); #endif va_end(ap); return &str[0]; } /*! * @if jp * @brief 文字列中の環境変数を置き換える * * 文字列中に${}で囲まれた文字列がある場合に、環境変数と置き換える * 例:${RTM_ROOT}\bin -> C:\Program Files (x86)\OpenRTM-aist\1.1.2\ * * @param str 置き換え前の文字列 * @return 置き換え後の文字列 * * @else * @brief * * @param str * @return * * @return * * @endif */ std::string replaceEnv(std::string str) { static std::regex const e{R"(\$\{(\w+)\})"}; // ${xxx} std::smatch m; while (std::regex_search(str, m, e)) { std::string env; coil::getenv(m.str(1).c_str(), env); // env="" if getenv() fail. str.replace(m.position(), m.length(), env); } return str; } } // namespace coil
24.2509
108
0.545221
r-kurose
2964367ce43a9a1716b78f12eb378cf58a7585de
1,874
cpp
C++
test/training_data/plag_original_codes/04_034.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
13
2021-01-20T19:53:16.000Z
2021-11-14T16:30:32.000Z
test/training_data/plag_original_codes/04_034.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
test/training_data/plag_original_codes/04_034.cpp
xryuseix/SA-Plag
167f7a2b2fa81ff00fd5263772a74c2c5c61941d
[ "MIT" ]
null
null
null
// 引用元 : https://atcoder.jp/contests/abc073/submissions/10044155 // 得点 : 400 // コード長 : 2443 // 実行時間 : 16 #include <bits/stdc++.h> #include <cmath> #include <numeric> using namespace std; #define rep(i,a,b) for(int64_t i=(a); i<(b); ++i) // a ≦ i < b #define Rrep(i,a,b) for(int64_t i=(a);i>=(b);--i) // reverse repeat. a から b まで減少. #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(), (a).rend() //逆イテレータ #define RANGE(a,b,c) (a).begin()+(b),(a).begin()+(c) // [b,c) イテレータ #define INF 1000000000000000 #define MOD 1000000007 using PII = pair<int64_t, int64_t>; using VI = vector<int64_t>; using VVI = vector<VI>; using VS = vector<string>; using VP = vector<PII>; using i64 = int64_t; template<typename T> void invec(vector<T> &A){for(T& a : A) cin >> a;} // input vector int main() { cin.tie(0); ios::sync_with_stdio(false); int N, M, R; cin >> N >> M >> R; VI r(R); invec(r); sort(ALL(r)); VVI d(N+1, VI(N+1, INF)); rep(i, 1, N+1) d[i][i] = 0; rep(i, 0, M){ int64_t a, b, c; cin >> a >> b >> c; d[a][b] = c; d[b][a] = c; } rep(k, 1, N+1) rep(i, 1, N+1) if (d[i][k] < INF) rep(j, 1, N+1) if (d[k][j] < INF) d[i][j] = min(d[i][j], d[i][k] + d[k][j]); i64 mini = INF; do { i64 dist = 0; rep(i, 0, R-1) dist += d[r[i]][r[i+1]]; mini = min(mini, dist); } while(next_permutation(ALL(r))); cout << mini << "\n"; return 0; } // 書いて考える.場合分け.情報整理. // 単純に分かる量から. // 境界,出力文字列 チェック.行末にスペース入れない. // 可読性優先.高速化次点. // まずは全探索,分割,次にDP // 制限を見る.境界に注意.求めたい量の変域.動かせる量. // 偶奇,逆から,ソート,出現回数,出現位置,DP, 余事象,包除 // データ構造. 問題の特徴量.単調性,二分探索 // 存在判定:構成方法,入力の特徴 // gcd, lcm ,素因数分解. // 例外を十分に含む一般化.想像力の限界 // 小さい系から例示 // 代数的処理.前処理によるクエリ高速化. // 始めは過剰に例示・場合分けしてもいい.各場合を確実に対処. // 自明な例から処理,除外. // 小数のときは,精度の設定する.doubel 変数に数値を入力するときは 123. とする. // テストケース作成は数表あり // 実行エラー:vector添え字超え.0割り.
25.324324
87
0.571505
xryuseix
2964f818d384b7becc09b311d0717462512431d2
2,210
cpp
C++
src/serac/infrastructure/profiling.cpp
bendudson/serac
d7cf1349e8830f852d868911b80a90a68dc123ec
[ "BSD-3-Clause" ]
null
null
null
src/serac/infrastructure/profiling.cpp
bendudson/serac
d7cf1349e8830f852d868911b80a90a68dc123ec
[ "BSD-3-Clause" ]
null
null
null
src/serac/infrastructure/profiling.cpp
bendudson/serac
d7cf1349e8830f852d868911b80a90a68dc123ec
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019-2022, Lawrence Livermore National Security, LLC and // other Serac Project Developers. See the top-level LICENSE file for // details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "serac/infrastructure/profiling.hpp" #include "serac/infrastructure/logger.hpp" #ifdef SERAC_USE_CALIPER #include <optional> #endif namespace serac::profiling { #ifdef SERAC_USE_CALIPER namespace { std::optional<cali::ConfigManager> mgr; } // namespace #endif void initializeCaliper(const std::string& options) { #ifdef SERAC_USE_CALIPER mgr = cali::ConfigManager(); auto check_result = mgr->check(options.c_str()); if (check_result.empty()) { mgr->add(options.c_str()); } else { SLIC_WARNING_ROOT("Caliper options invalid, ignoring: " << check_result); } // Defaults, should probably always be enabled mgr->add("event-trace, runtime-report"); mgr->start(); #else // Silence warning static_cast<void>(options); #endif } void terminateCaliper() { #ifdef SERAC_USE_CALIPER if (mgr) { mgr->stop(); mgr->flush(); } mgr.reset(); #endif } /// @cond namespace detail { void setCaliperMetadata([[maybe_unused]] const std::string& name, [[maybe_unused]] double data) { #ifdef SERAC_USE_CALIPER cali_set_global_double_byname(name.c_str(), data); #endif } void setCaliperMetadata([[maybe_unused]] const std::string& name, [[maybe_unused]] int data) { #ifdef SERAC_USE_CALIPER cali_set_global_int_byname(name.c_str(), data); #endif } void setCaliperMetadata([[maybe_unused]] const std::string& name, [[maybe_unused]] const std::string& data) { #ifdef SERAC_USE_CALIPER cali_set_global_string_byname(name.c_str(), data.c_str()); #endif } void setCaliperMetadata([[maybe_unused]] const std::string& name, [[maybe_unused]] unsigned int data) { #ifdef SERAC_USE_CALIPER cali_set_global_uint_byname(name.c_str(), data); #endif } void startCaliperRegion([[maybe_unused]] const char* name) { #ifdef SERAC_USE_CALIPER CALI_MARK_BEGIN(name); #endif } void endCaliperRegion([[maybe_unused]] const char* name) { #ifdef SERAC_USE_CALIPER CALI_MARK_END(name); #endif } } // namespace detail /// @endcond } // namespace serac::profiling
22.1
107
0.726244
bendudson
297429099ea067c13ea2516bee08d4b9bf0c0f70
178
cpp
C++
src/cpu/insts/Cli.cpp
ammubhave/emu
ff9501719f3cc53207a8931d85c19d24c86dccdc
[ "MIT" ]
null
null
null
src/cpu/insts/Cli.cpp
ammubhave/emu
ff9501719f3cc53207a8931d85c19d24c86dccdc
[ "MIT" ]
null
null
null
src/cpu/insts/Cli.cpp
ammubhave/emu
ff9501719f3cc53207a8931d85c19d24c86dccdc
[ "MIT" ]
null
null
null
#include "gen/Cli.h" #include "cpu/Cpu.h" #include "cpu/insts/Util.h" namespace emu::cpu::insts { void Cli::execute(Cpu& cpu) { IF = false; } } // namespace emu::cpu::insts
16.181818
43
0.646067
ammubhave
29752d0e474f5eef01d05adb816cffcca4ad7df1
677
cpp
C++
000/36.cpp
correipj/ProjectEuler
0173d8ec7f309b4f0c243a94351772b1be55e8bf
[ "Unlicense" ]
null
null
null
000/36.cpp
correipj/ProjectEuler
0173d8ec7f309b4f0c243a94351772b1be55e8bf
[ "Unlicense" ]
null
null
null
000/36.cpp
correipj/ProjectEuler
0173d8ec7f309b4f0c243a94351772b1be55e8bf
[ "Unlicense" ]
null
null
null
// https://projecteuler.net/problem=36 // Double-base palindromes #include <iostream> #include <vector> using namespace std; vector<int> base(int n, int b) { vector<int> v; while(n) { v.insert(v.begin(), n % b); n /= b; } return v; } bool isPalindrome(int n, int b) { int rev = 0; for (int k = n; k > 0; k /= b) rev = rev * b + k % b; return n == rev; } int main(int argc, char* argv[]) { unsigned long sum = 0; for (int n = 1; n < 1000000; n += 2) { if (!isPalindrome(n, 2)) continue; if (!isPalindrome(n, 10)) continue; sum += n; } printf("sum = %d\n", sum); getchar(); return 0; }
14.404255
42
0.524372
correipj
29768a9c78928137a26bc830aec3fd174513b766
11,314
cpp
C++
UAlbertaBot/Source/TransportManager.cpp
xu-kj/sc1bot
a3a3fd6b2e2cc20460ced35ca61f077880626b77
[ "MIT" ]
null
null
null
UAlbertaBot/Source/TransportManager.cpp
xu-kj/sc1bot
a3a3fd6b2e2cc20460ced35ca61f077880626b77
[ "MIT" ]
16
2021-04-01T05:16:27.000Z
2021-04-28T06:18:59.000Z
UAlbertaBot/Source/TransportManager.cpp
xu-kj/sc1bot
a3a3fd6b2e2cc20460ced35ca61f077880626b77
[ "MIT" ]
null
null
null
#include "TransportManager.h" #include "BaseLocationManager.h" #include "Global.h" #include "Micro.h" #include "MapTools.h" using namespace UAlbertaBot; TransportManager::TransportManager() { } void TransportManager::executeMicro(const BWAPI::Unitset &targets) { const BWAPI::Unitset &transportUnits = getUnits(); if (transportUnits.empty()) { return; } } void TransportManager::calculateMapEdgeVertices() { auto enemyBaseLocation = Global::Bases().getPlayerStartingBaseLocation(BWAPI::Broodwar->enemy()); if (!enemyBaseLocation) { return; } const BWAPI::Position basePosition = BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation()); const std::vector<BWAPI::TilePosition> &closestTobase = Global::Map().getClosestTilesTo(basePosition); std::set<BWAPI::Position> unsortedVertices; int minX = std::numeric_limits<int>::max(); int minY = minX; int maxX = std::numeric_limits<int>::min(); int maxY = maxX; //compute mins and maxs for (auto &tile : closestTobase) { if (tile.x > maxX) maxX = tile.x; else if (tile.x < minX) minX = tile.x; if (tile.y > maxY) maxY = tile.y; else if (tile.y < minY) minY = tile.y; } m_minCorner = BWAPI::Position(minX, minY) * 32 + BWAPI::Position(16, 16); m_maxCorner = BWAPI::Position(maxX, maxY) * 32 + BWAPI::Position(16, 16); //add all(some) edge tiles! for (int x = minX; x <= maxX; x += 5) { unsortedVertices.insert(BWAPI::Position(x, minY) * 32 + BWAPI::Position(16, 16)); unsortedVertices.insert(BWAPI::Position(x, maxY) * 32 + BWAPI::Position(16, 16)); } for (int y = minY; y <= maxY; y += 5) { unsortedVertices.insert(BWAPI::Position(minX, y) * 32 + BWAPI::Position(16, 16)); unsortedVertices.insert(BWAPI::Position(maxX, y) * 32 + BWAPI::Position(16, 16)); } std::vector<BWAPI::Position> sortedVertices; BWAPI::Position current = *unsortedVertices.begin(); m_mapEdgeVertices.push_back(current); unsortedVertices.erase(current); // while we still have unsorted vertices left, find the closest one remaining to current while (!unsortedVertices.empty()) { double bestDist = 1000000; BWAPI::Position bestPos; for (const BWAPI::Position &pos : unsortedVertices) { double dist = pos.getDistance(current); if (dist < bestDist) { bestDist = dist; bestPos = pos; } } current = bestPos; sortedVertices.push_back(bestPos); unsortedVertices.erase(bestPos); } m_mapEdgeVertices = sortedVertices; } void TransportManager::drawTransportInformation(int x = 0, int y = 0) { if (!Config::Debug::DrawUnitTargetInfo) { return; } for (size_t i(0); i < m_mapEdgeVertices.size(); ++i) { BWAPI::Broodwar->drawCircleMap(m_mapEdgeVertices[i], 4, BWAPI::Colors::Green, false); BWAPI::Broodwar->drawTextMap(m_mapEdgeVertices[i], "%d", i); } } void TransportManager::update() { if (!m_transportShip && getUnits().size() > 0) { m_transportShip = *getUnits().begin(); } // calculate enemy region vertices if we haven't yet if (m_mapEdgeVertices.empty()) { calculateMapEdgeVertices(); } moveTroops(); moveTransport(); drawTransportInformation(); } void TransportManager::moveTransport() { if (!m_transportShip || !m_transportShip->exists() || !(m_transportShip->getHitPoints() > 0)) { return; } // If I didn't finish unloading the troops, wait BWAPI::UnitCommand currentCommand(m_transportShip->getLastCommand()); if ((currentCommand.getType() == BWAPI::UnitCommandTypes::Unload_All || currentCommand.getType() == BWAPI::UnitCommandTypes::Unload_All_Position) && m_transportShip->getLoadedUnits().size() > 0) { return; } if (m_to.isValid() && m_from.isValid()) { followPerimeter(m_to, m_from); } else { followPerimeter(); } } void TransportManager::moveTroops() { if (!m_transportShip || !m_transportShip->exists() || !(m_transportShip->getHitPoints() > 0)) { return; } //unload zealots if close enough or dying int transportHP = m_transportShip->getHitPoints() + m_transportShip->getShields(); auto enemyBaseLocation = Global::Bases().getPlayerStartingBaseLocation(BWAPI::Broodwar->enemy()); if (enemyBaseLocation && (m_transportShip->getDistance(enemyBaseLocation->getPosition()) < 300 || transportHP < 100) && m_transportShip->canUnloadAtPosition(m_transportShip->getPosition())) { //unload troops //and return? // get the unit's current command BWAPI::UnitCommand currentCommand(m_transportShip->getLastCommand()); // if we've already told this unit to unload, wait if (currentCommand.getType() == BWAPI::UnitCommandTypes::Unload_All || currentCommand.getType() == BWAPI::UnitCommandTypes::Unload_All_Position) { return; } //else unload m_transportShip->unloadAll(m_transportShip->getPosition()); } } void TransportManager::followPerimeter(int clockwise) { BWAPI::Position goTo = getFleePosition(clockwise); if (Config::Debug::DrawUnitTargetInfo) { BWAPI::Broodwar->drawCircleMap(goTo, 5, BWAPI::Colors::Red, true); } Micro::SmartMove(m_transportShip, goTo); } void TransportManager::followPerimeter(BWAPI::Position to, BWAPI::Position from) { static int following = 0; if (following) { followPerimeter(following); return; } //assume we're near FROM! if (m_transportShip->getDistance(from) < 50 && m_waypoints.empty()) { //compute waypoints std::pair<int, int> wpIDX = findSafePath(to, from); bool valid = (wpIDX.first > -1 && wpIDX.second > -1); UAB_ASSERT_WARNING(valid, "waypoints not valid! (transport mgr)"); m_waypoints.push_back(m_mapEdgeVertices[wpIDX.first]); m_waypoints.push_back(m_mapEdgeVertices[wpIDX.second]); BWAPI::Broodwar->printf("WAYPOINTS: [%d] - [%d]", wpIDX.first, wpIDX.second); Micro::SmartMove(m_transportShip, m_waypoints[0]); } else if (m_waypoints.size() > 1 && m_transportShip->getDistance(m_waypoints[0]) < 100) { BWAPI::Broodwar->printf("FOLLOW PERIMETER TO SECOND WAYPOINT!"); //follow perimeter to second waypoint! //clockwise or counterclockwise? int closestPolygonIndex = getClosestVertexIndex(m_transportShip); UAB_ASSERT_WARNING(closestPolygonIndex != -1, "Couldn't find a closest vertex"); if (m_mapEdgeVertices[(closestPolygonIndex + 1) % m_mapEdgeVertices.size()].getApproxDistance(m_waypoints[1]) < m_mapEdgeVertices[(closestPolygonIndex - 1) % m_mapEdgeVertices.size()].getApproxDistance(m_waypoints[1])) { BWAPI::Broodwar->printf("FOLLOW clockwise"); following = 1; followPerimeter(following); } else { BWAPI::Broodwar->printf("FOLLOW counter clockwise"); following = -1; followPerimeter(following); } } else if (m_waypoints.size() > 1 && m_transportShip->getDistance(m_waypoints[1]) < 50) { //if close to second waypoint, go to destination! following = 0; Micro::SmartMove(m_transportShip, to); } } int TransportManager::getClosestVertexIndex(BWAPI::UnitInterface *unit) { int closestIndex = -1; double closestDistance = 10000000; for (size_t i(0); i < m_mapEdgeVertices.size(); ++i) { double dist = unit->getDistance(m_mapEdgeVertices[i]); if (dist < closestDistance) { closestDistance = dist; closestIndex = i; } } return closestIndex; } int TransportManager::getClosestVertexIndex(BWAPI::Position p) { int closestIndex = -1; double closestDistance = 10000000; for (size_t i(0); i < m_mapEdgeVertices.size(); ++i) { double dist = p.getApproxDistance(m_mapEdgeVertices[i]); if (dist < closestDistance) { closestDistance = dist; closestIndex = i; } } return closestIndex; } std::pair<int, int> TransportManager::findSafePath(BWAPI::Position to, BWAPI::Position from) { BWAPI::Broodwar->printf("FROM: [%d,%d]", from.x, from.y); BWAPI::Broodwar->printf("TO: [%d,%d]", to.x, to.y); //closest map edge point to destination int endPolygonIndex = getClosestVertexIndex(to); //BWAPI::Broodwar->printf("end indx: [%d]", endPolygonIndex); UAB_ASSERT_WARNING(endPolygonIndex != -1, "Couldn't find a closest vertex"); BWAPI::Position enemyEdge = m_mapEdgeVertices[endPolygonIndex]; auto *enemyBaseLocation = Global::Bases().getPlayerStartingBaseLocation(BWAPI::Broodwar->enemy()); BWAPI::Position enemyPosition = enemyBaseLocation->getPosition(); //find the projections on the 4 edges UAB_ASSERT_WARNING((m_minCorner.isValid() && m_maxCorner.isValid()), "Map corners should have been set! (transport mgr)"); std::vector<BWAPI::Position> p; p.push_back(BWAPI::Position(from.x, m_minCorner.y)); p.push_back(BWAPI::Position(from.x, m_maxCorner.y)); p.push_back(BWAPI::Position(m_minCorner.x, from.y)); p.push_back(BWAPI::Position(m_maxCorner.x, from.y)); int d1 = p[0].getApproxDistance(enemyPosition); int d2 = p[1].getApproxDistance(enemyPosition); int d3 = p[2].getApproxDistance(enemyPosition); int d4 = p[3].getApproxDistance(enemyPosition); //have to choose the two points that are not max or min (the sides!) int maxIndex = (d1 > d2 ? d1 : d2) > (d3 > d4 ? d3 : d4) ? (d1 > d2 ? 0 : 1) : (d3 > d4 ? 2 : 3); int minIndex = (d1 < d2 ? d1 : d2) < (d3 < d4 ? d3 : d4) ? (d1 < d2 ? 0 : 1) : (d3 < d4 ? 2 : 3); if (maxIndex > minIndex) { p.erase(p.begin() + maxIndex); p.erase(p.begin() + minIndex); } else { p.erase(p.begin() + minIndex); p.erase(p.begin() + maxIndex); } //get the one that works best from the two. BWAPI::Position waypoint = (enemyEdge.getApproxDistance(p[0]) < enemyEdge.getApproxDistance(p[1])) ? p[0] : p[1]; int startPolygonIndex = getClosestVertexIndex(waypoint); return std::pair<int, int>(startPolygonIndex, endPolygonIndex); } BWAPI::Position TransportManager::getFleePosition(int clockwise) { UAB_ASSERT_WARNING(!m_mapEdgeVertices.empty(), "We should have a transport route!"); // if this is the first flee, we will not have a previous perimeter index if (m_currentRegionVertexIndex == -1) { // so return the closest position in the polygon int closestPolygonIndex = getClosestVertexIndex(m_transportShip); UAB_ASSERT_WARNING(closestPolygonIndex != -1, "Couldn't find a closest vertex"); if (closestPolygonIndex == -1) { return BWAPI::Position(BWAPI::Broodwar->self()->getStartLocation()); } else { // set the current index so we know how to iterate if we are still fleeing later m_currentRegionVertexIndex = closestPolygonIndex; return m_mapEdgeVertices[closestPolygonIndex]; } } // if we are still fleeing from the previous frame, get the next location if we are close enough else { double distanceFromCurrentVertex = m_mapEdgeVertices[m_currentRegionVertexIndex].getDistance(m_transportShip->getPosition()); // keep going to the next vertex in the perimeter until we get to one we're far enough from to issue another move command while (distanceFromCurrentVertex < 128 * 2) { m_currentRegionVertexIndex = (m_currentRegionVertexIndex + clockwise * 1) % m_mapEdgeVertices.size(); distanceFromCurrentVertex = m_mapEdgeVertices[m_currentRegionVertexIndex].getDistance(m_transportShip->getPosition()); } return m_mapEdgeVertices[m_currentRegionVertexIndex]; } } void TransportManager::setTransportShip(BWAPI::UnitInterface *unit) { m_transportShip = unit; } void TransportManager::setFrom(BWAPI::Position from) { if (from.isValid()) { m_from = from; } } void TransportManager::setTo(BWAPI::Position to) { if (to.isValid()) { m_to = to; } }
28.074442
195
0.712657
xu-kj
2976a7d4c18e04d49b99b11dc2a7cba85406a3b9
910
cpp
C++
Problems/Timus/1083_Factorials/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
Problems/Timus/1083_Factorials/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
1
2019-05-09T19:17:00.000Z
2019-05-09T19:17:00.000Z
Problems/Timus/1083_Factorials/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; unsigned long calculateFact(unsigned int n, unsigned int k, unsigned int remain) { if (n == remain) return remain; else return n * calculateFact(n - k, k, remain); } unsigned long calculateFactIterative(unsigned int n, unsigned int k, unsigned int remain) { unsigned long result = 1; while (n != remain) { result *= n; if (n > k) n -= k; else break; } return result * remain; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); // freopen("output.txt", "wt", stdout); #endif unsigned int n; cin >> n; std::string lenk; getline(cin, lenk); unsigned int k = lenk.size() - 1; if ((n % k) == 0) cout << calculateFactIterative(n, k, 1); else cout << calculateFactIterative(n, k, n % k); }
19.782609
89
0.57033
grand87
297d337cc8cc2c2d88c78eba211db3f8738a6e08
534
cpp
C++
GameEngine/KekEngine/src/entity.cpp
oborotev/BJTU-GDI
938c9d749946e0363bdd28d35e0a134e96607358
[ "MIT" ]
null
null
null
GameEngine/KekEngine/src/entity.cpp
oborotev/BJTU-GDI
938c9d749946e0363bdd28d35e0a134e96607358
[ "MIT" ]
null
null
null
GameEngine/KekEngine/src/entity.cpp
oborotev/BJTU-GDI
938c9d749946e0363bdd28d35e0a134e96607358
[ "MIT" ]
null
null
null
// // Created by storm on 26/03/16. // # include "entity.h" Entity::Entity(const int &x, const int &y) { this->_x = x; this->_y = y; } const int &Entity::getX() { return (this->_x); } const int &Entity::getY() { return (this->_y); } void Entity::setY(const double &y) { this->_y = y; } void Entity::setX(const double &x) { this->_x = x; } void Entity::addDialog(const std::string &dialog) { this->_dialogs.push_back(dialog); } void Entity::cleanDialogs() { this->_dialogs.clear(); }
13.02439
52
0.582397
oborotev
29810f801e0104ecdaea3d7f156182e57ade6742
8,211
cpp
C++
libs/ContainerKit/tests/CircularQueue_test.cpp
HPezz/LekaOS
e4c16f52e2c7bd3d75c9d5aefe94eb67dbf5a694
[ "Apache-2.0" ]
2
2021-10-30T20:51:30.000Z
2022-01-12T11:18:34.000Z
libs/ContainerKit/tests/CircularQueue_test.cpp
HPezz/LekaOS
e4c16f52e2c7bd3d75c9d5aefe94eb67dbf5a694
[ "Apache-2.0" ]
343
2021-07-15T12:57:08.000Z
2022-03-29T10:14:06.000Z
libs/ContainerKit/tests/CircularQueue_test.cpp
HPezz/LekaOS
e4c16f52e2c7bd3d75c9d5aefe94eb67dbf5a694
[ "Apache-2.0" ]
3
2021-12-30T02:53:24.000Z
2022-01-11T22:08:05.000Z
// Leka - LekaOS // Copyright 2021 APF France handicap (based on work by Mbed-OS) // SPDX-License-Identifier: Apache-2.0 #include "CircularQueue.h" #include <array> #include <memory> #include "gtest/gtest.h" #include "stubs/mbed/mbed_critical.h" using namespace leka; class CircularQueueTest : public testing::Test { protected: void SetUp() override { spy_mbed_critical_enter_calls = 0; spy_mbed_critical_exit_calls = 0; } // void TearDown() override {} static constexpr auto TEST_BUFFER_SIZE {10}; CircularQueue<int, TEST_BUFFER_SIZE> buf {}; }; TEST_F(CircularQueueTest, initialization) { EXPECT_NE(&buf, nullptr); } TEST_F(CircularQueueTest, pushOneItemPopOneItem) { int item = 0; buf.push(1); bool ret = buf.pop(item); EXPECT_TRUE(ret); EXPECT_EQ(item, 1); } TEST_F(CircularQueueTest, reset) { buf.push(1); EXPECT_EQ(buf.size(), 1); buf.reset(); EXPECT_EQ(buf.size(), 0); } TEST_F(CircularQueueTest, sizeWhenEmpty) { auto size = buf.size(); EXPECT_EQ(size, 0); } TEST_F(CircularQueueTest, sizeWhenNotEmpty) { buf.push(1); auto size = buf.size(); EXPECT_EQ(size, 1); } TEST_F(CircularQueueTest, sizeWhenFull) { auto items = std::array<int, TEST_BUFFER_SIZE> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; buf.push(items.data(), std::size(items)); auto size = buf.size(); EXPECT_EQ(size, TEST_BUFFER_SIZE); } TEST_F(CircularQueueTest, isEmptyWhenEmpty) { auto is_empty = buf.empty(); EXPECT_TRUE(is_empty); } TEST_F(CircularQueueTest, isEmptyWhenNotEmpty) { buf.push(1); auto is_empty = buf.empty(); EXPECT_FALSE(is_empty); } TEST_F(CircularQueueTest, isEmptyWhenFull) { auto items = std::array<int, TEST_BUFFER_SIZE> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; buf.push(items.data(), std::size(items)); auto is_empty = buf.empty(); EXPECT_FALSE(is_empty); } TEST_F(CircularQueueTest, popOneItemWhenEmpty) { int item = 0; bool ret = buf.pop(item); EXPECT_FALSE(ret); } TEST_F(CircularQueueTest, popMutipleItemsWhenEmpty) { std::array<int, 3> items {}; bool ret = buf.pop(items.data(), std::size(items)); EXPECT_FALSE(ret); } TEST_F(CircularQueueTest, pushPopMultipleItems) { auto items = std::array<int, TEST_BUFFER_SIZE> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < TEST_BUFFER_SIZE; i++) { auto items_popped = std::array<int, TEST_BUFFER_SIZE> {}; buf.push(items.data(), i); EXPECT_EQ(buf.size(), i); int number_of_items = buf.pop(items_popped.data(), i); EXPECT_EQ(buf.size(), 0); EXPECT_EQ(number_of_items, i); EXPECT_TRUE(0 == memcmp(items.data(), items_popped.data(), i)); } } TEST_F(CircularQueueTest, pushOneItemToMakeFull) { auto items = std::array<int, TEST_BUFFER_SIZE - 1> {1, 2, 3, 4, 5, 6, 7, 8, 9}; buf.push(items.data(), std::size(items)); EXPECT_FALSE(buf.full()); buf.push(10); auto expected_items = std::array<int, TEST_BUFFER_SIZE> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto actual_items = std::array<int, TEST_BUFFER_SIZE> {}; auto ret = buf.pop(actual_items.data(), std::size(actual_items)); EXPECT_TRUE(buf.empty()); EXPECT_FALSE(buf.full()); EXPECT_EQ(actual_items, expected_items); } TEST_F(CircularQueueTest, pushOneItemWhenAlreadyFull) { auto items = std::array<int, TEST_BUFFER_SIZE - 1> {1, 2, 3, 4, 5, 6, 7, 8, 9}; buf.push(items.data(), std::size(items)); EXPECT_FALSE(buf.full()); buf.push(10); EXPECT_TRUE(buf.full()); buf.push(11); auto expected_items = std::array<int, TEST_BUFFER_SIZE> {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; auto actual_items = std::array<int, TEST_BUFFER_SIZE> {}; auto ret = buf.pop(actual_items.data(), std::size(actual_items)); EXPECT_TRUE(buf.empty()); EXPECT_FALSE(buf.full()); EXPECT_EQ(actual_items, expected_items); } TEST_F(CircularQueueTest, pushItemsWithOverflow) { auto items = std::array<int, TEST_BUFFER_SIZE> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto items_popped = std::array<int, TEST_BUFFER_SIZE> {}; buf.push(-1); // there is now not enough space for all the elements, old ones should be overwritten buf.push(items.data(), TEST_BUFFER_SIZE); int number_of_items = buf.pop(items_popped.data(), TEST_BUFFER_SIZE); EXPECT_EQ(number_of_items, TEST_BUFFER_SIZE); EXPECT_TRUE(0 == memcmp(items.data(), items_popped.data(), TEST_BUFFER_SIZE)); // there is a difference where the overflow is caused by a smaller write // and the buffer should retain part of old values buf.push(-1); buf.push(-2); buf.push(items.data(), TEST_BUFFER_SIZE - 1); // -1 is overwritten but -2 is kept int popped_number; buf.pop(popped_number); EXPECT_EQ(popped_number, -2); buf.pop(items_popped.data(), TEST_BUFFER_SIZE - 1); EXPECT_TRUE(0 == memcmp(items.data(), items_popped.data(), TEST_BUFFER_SIZE - 1)); } TEST_F(CircularQueueTest, pushMoreItemsThanBufferCapacity) { auto items = std::array<int, TEST_BUFFER_SIZE + 1> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; auto items_popped = std::array<int, TEST_BUFFER_SIZE> {}; // the loop creates different amounts of existing elements prior to write over capacity for (int i = 0; i < TEST_BUFFER_SIZE; i++) { for (int j = 0; j < i; j++) { buf.push(-1); } // first element should be dropped buf.push(items.data(), TEST_BUFFER_SIZE + 1); int number_of_items = buf.pop(items_popped.data(), TEST_BUFFER_SIZE + 1); EXPECT_EQ(number_of_items, TEST_BUFFER_SIZE); EXPECT_EQ(buf.size(), 0); EXPECT_TRUE(0 == memcmp(items.data() + 1, items_popped.data(), TEST_BUFFER_SIZE)); } } TEST_F(CircularQueueTest, peekOneItem) { buf.push(42); EXPECT_EQ(buf.size(), 1); int item = 0; bool ret = buf.peek(item); EXPECT_TRUE(ret); EXPECT_EQ(item, 42); EXPECT_EQ(buf.size(), 1); } TEST_F(CircularQueueTest, peekOneItemWhenEmpty) { EXPECT_EQ(buf.size(), 0); int item = 0; bool ret = buf.peek(item); EXPECT_FALSE(ret); EXPECT_EQ(item, 0); EXPECT_EQ(buf.size(), 0); } TEST_F(CircularQueueTest, peekOneItemAtPosition) { buf.push(42); buf.push(43); buf.push(44); EXPECT_EQ(buf.size(), 3); int item = 0; bool ret = false; ret = buf.peekAt(0, item); EXPECT_TRUE(ret); EXPECT_EQ(item, 42); EXPECT_EQ(buf.size(), 3); ret = buf.peekAt(1, item); EXPECT_TRUE(ret); EXPECT_EQ(item, 43); EXPECT_EQ(buf.size(), 3); ret = buf.peekAt(2, item); EXPECT_TRUE(ret); EXPECT_EQ(item, 44); EXPECT_EQ(buf.size(), 3); } TEST_F(CircularQueueTest, peekOneItemAtPositionWhenEmpty) { EXPECT_EQ(buf.size(), 0); int item = 0; bool ret = false; ret = buf.peekAt(0, item); EXPECT_FALSE(ret); EXPECT_EQ(item, 0); ret = buf.peekAt(1, item); EXPECT_FALSE(ret); EXPECT_EQ(item, 0); } TEST_F(CircularQueueTest, peekOneItemAtPositionBiggerThanSize) { buf.push(42); buf.push(43); buf.push(44); EXPECT_EQ(buf.size(), 3); int item = 0; bool ret = false; ret = buf.peekAt(3, item); EXPECT_FALSE(ret); EXPECT_EQ(item, 0); ret = buf.peekAt(4, item); EXPECT_FALSE(ret); EXPECT_EQ(item, 0); } TEST_F(CircularQueueTest, criticalSectionForPush) { buf.push(1); EXPECT_TRUE(spy_mbed_critical_enter_was_called()); EXPECT_TRUE(spy_mbed_critical_exit_was_called()); } TEST_F(CircularQueueTest, criticalSectionForPop) { int item = 0; bool ret = buf.pop(item); EXPECT_TRUE(spy_mbed_critical_enter_was_called()); EXPECT_TRUE(spy_mbed_critical_exit_was_called()); } TEST_F(CircularQueueTest, hasPattern) { auto items = std::array {0, 1, 2, 0x2A, 0x2B, 0x2C, 0x2D, 7, 8, 9}; auto pattern = std::array {0x2A, 0x2B, 0x2C, 0x2D}; buf.push(items.data(), std::size(items)); int pos = 0; auto ret = buf.hasPattern(pattern.data(), std::size(pattern), pos); EXPECT_TRUE(ret); EXPECT_EQ(pos, 3); } TEST_F(CircularQueueTest, hasNotPattern) { auto items = std::array {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto pattern = std::array {0x2A, 0x2B, 0x2C, 0x2D}; buf.push(items.data(), std::size(items)); int pos = 0; auto ret = buf.hasPattern(pattern.data(), std::size(pattern), pos); EXPECT_FALSE(ret); EXPECT_EQ(pos, 0); } TEST_F(CircularQueueTest, hasOnlyPartOfPattern) { auto items = std::array {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto pattern = std::array {2, 3, 4, 0x2D}; buf.push(items.data(), std::size(items)); int pos = 0; auto ret = buf.hasPattern(pattern.data(), std::size(pattern), pos); EXPECT_FALSE(ret); EXPECT_EQ(pos, 0); }
21.272021
91
0.689197
HPezz
2981d9aa32083e1d38efee9472e2929f29db6915
1,525
hpp
C++
libraries/chain/include/betterchain/chain/contracts/betterchain_contract.hpp
betterchainio/betterchain
29f82c25ae6812beaf09f8d7069932474bea9f8b
[ "MIT" ]
3
2018-01-18T07:12:34.000Z
2018-01-22T10:00:29.000Z
libraries/chain/include/betterchain/chain/contracts/betterchain_contract.hpp
betterchainio/betterchain
29f82c25ae6812beaf09f8d7069932474bea9f8b
[ "MIT" ]
null
null
null
libraries/chain/include/betterchain/chain/contracts/betterchain_contract.hpp
betterchainio/betterchain
29f82c25ae6812beaf09f8d7069932474bea9f8b
[ "MIT" ]
2
2018-01-30T01:03:10.000Z
2019-02-28T09:04:06.000Z
/** * @file * @copyright defined in BetterChain/LICENSE.txt */ #pragma once #include <betterchain/chain/apply_context.hpp> #include <betterchain/chain/types.hpp> namespace betterchain { namespace chain { namespace contracts { /** * @defgroup native_action_handlers Native Action Handlers */ ///@{ void apply_betterchain_newaccount(apply_context& context); void apply_betterchain_updateauth(apply_context&); void apply_betterchain_deleteauth(apply_context&); void apply_betterchain_linkauth(apply_context&); void apply_betterchain_unlinkauth(apply_context&); void apply_betterchain_postrecovery(apply_context&); void apply_betterchain_passrecovery(apply_context&); void apply_betterchain_vetorecovery(apply_context&); void apply_betterchain_transfer(apply_context& context); void apply_betterchain_lock(apply_context& context); void apply_betterchain_claim(apply_context&); void apply_betterchain_unlock(apply_context&); void apply_betterchain_okproducer(apply_context&); void apply_betterchain_setproducer(apply_context&); void apply_betterchain_setproxy(apply_context&); void apply_betterchain_setcode(apply_context&); void apply_betterchain_setabi(apply_context&); void apply_betterchain_nonce(apply_context&); void apply_betterchain_onerror(apply_context&); ///@} end action handlers share_type get_betterchain_balance( const chainbase::database& db, const account_name& account ); } } } /// namespace betterchain::contracts
31.770833
100
0.78623
betterchainio
2983a363235db51a4ba0d157cfa23b056476c5ab
6,496
cpp
C++
hexapod_emlid/Navio/NavioLib/PCA9685.cpp
helios57/hexapod
82b4fc54f49e0acca62a42635ba8844abdb541a7
[ "MIT" ]
null
null
null
hexapod_emlid/Navio/NavioLib/PCA9685.cpp
helios57/hexapod
82b4fc54f49e0acca62a42635ba8844abdb541a7
[ "MIT" ]
null
null
null
hexapod_emlid/Navio/NavioLib/PCA9685.cpp
helios57/hexapod
82b4fc54f49e0acca62a42635ba8844abdb541a7
[ "MIT" ]
null
null
null
/* PCA9685 driver code is placed under the BSD license. Written by Mikhail Avkhimenia (mikhail.avkhimenia@emlid.com) Copyright (c) 2014, Emlid Limited, www.emlid.com 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 Emlid Limited 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 EMLID LIMITED 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 "../NavioLib/PCA9685.h" /** PCA9685 constructor. * @param address I2C address * @see PCA9685_DEFAULT_ADDRESS */ PCA9685::PCA9685(uint8_t address) { this->devAddr = address; } /** Power on and prepare for general usage. * This method reads prescale value stored in PCA9685 and calculate frequency based on it. * Then it enables auto-increment of register address to allow for faster writes. * And finally the restart is performed to enable clocking. */ void PCA9685::initialize() { this->frequency = getFrequency(); I2Cdev::writeBit(devAddr, PCA9685_RA_MODE1, PCA9685_MODE1_AI_BIT, 1); restart(); } /** Verify the I2C connection. * @return True if connection is valid, false otherwise */ bool PCA9685::testConnection() { uint8_t data; int8_t status = I2Cdev::readByte(devAddr, PCA9685_RA_PRE_SCALE, &data); if (status > 0) return true; else return false; } /** Put PCA9685 to sleep mode thus turning off the outputs. * @see PCA9685_MODE1_SLEEP_BIT */ void PCA9685::sleep() { I2Cdev::writeBit(devAddr, PCA9685_RA_MODE1, PCA9685_MODE1_SLEEP_BIT, 1); } /** Disable sleep mode and start the outputs. * @see PCA9685_MODE1_SLEEP_BIT * @see PCA9685_MODE1_RESTART_BIT */ void PCA9685::restart() { I2Cdev::writeByte(devAddr, PCA9685_RA_MODE1, (1 << PCA9685_MODE1_SLEEP_BIT)); I2Cdev::writeByte(devAddr, PCA9685_RA_MODE1, ((1 << PCA9685_MODE1_SLEEP_BIT) | (1 << PCA9685_MODE1_EXTCLK_BIT))); I2Cdev::writeByte(devAddr, PCA9685_RA_MODE1, ((1 << PCA9685_MODE1_RESTART_BIT) | (1 << PCA9685_MODE1_EXTCLK_BIT) | (1 << PCA9685_MODE1_AI_BIT))); } /** Calculate prescale value based on the specified frequency and write it to the device. * @return Frequency in Hz * @see PCA9685_RA_PRE_SCALE */ float PCA9685::getFrequency() { uint8_t data; I2Cdev::readByte(devAddr, PCA9685_RA_PRE_SCALE, &data); return 24576000.f / 4096.f / (data + 1); } /** Calculate prescale value based on the specified frequency and write it to the device. * @param Frequency in Hz * @see PCA9685_RA_PRE_SCALE */ void PCA9685::setFrequency(float frequency) { sleep(); usleep(10000); uint8_t prescale = roundf(24576000.f / 4096.f / frequency) - 1; I2Cdev::writeByte(devAddr, PCA9685_RA_PRE_SCALE, prescale); this->frequency = getFrequency(); restart(); } /** Set channel start offset of the pulse and it's length * @param Channel number (0-15) * @param Offset (0-4095) * @param Length (0-4095) * @see PCA9685_RA_LED0_ON_L */ void PCA9685::setPWM(uint8_t channel, uint16_t offset, uint16_t length) { uint8_t data[4] = {0, 0, 0, 0}; if(length == 0) { data[3] = 0x10; } else if(length >= 4096) { data[1] = 0x10; } else { data[0] = offset & 0xFF; data[1] = offset >> 8; data[2] = length & 0xFF; data[3] = length >> 8; } I2Cdev::writeBytes(devAddr, PCA9685_RA_LED0_ON_L + 4 * channel, 4, data); } /** Set channel's pulse length * @param Channel number (0-15) * @param Length (0-4095) * @see PCA9685_RA_LED0_ON_L */ void PCA9685::setPWM(uint8_t channel, uint16_t length) { setPWM(channel, 0, length); } /** Set channel's pulse length in milliseconds * @param Channel number (0-15) * @param Length in milliseconds * @see PCA9685_RA_LED0_ON_L */ void PCA9685::setPWMmS(uint8_t channel, float length_mS) { setPWM(channel, round((length_mS * 4096.f) / (1000.f / frequency))); } /** Set channel's pulse length in microseconds * @param Channel number (0-15) * @param Length in microseconds * @see PCA9685_RA_LED0_ON_L */ void PCA9685::setPWMuS(uint8_t channel, float length_uS) { setPWM(channel, round((length_uS * 4096.f) / (1000000.f / frequency))); } /** Set start offset of the pulse and it's length for all channels * @param Offset (0-4095) * @param Length (0-4095) * @see PCA9685_RA_ALL_LED_ON_L */ void PCA9685::setAllPWM(uint16_t offset, uint16_t length) { uint8_t data[4] = {offset & 0xFF, offset >> 8, length & 0xFF, length >> 8}; I2Cdev::writeBytes(devAddr, PCA9685_RA_ALL_LED_ON_L, 4, data); } /** Set pulse length for all channels * @param Length (0-4095) * @see PCA9685_RA_ALL_LED_ON_L */ void PCA9685::setAllPWM(uint16_t length) { setAllPWM(0, length); } /** Set pulse length in milliseconds for all channels * @param Length in milliseconds * @see PCA9685_RA_ALL_LED_ON_L */ void PCA9685::setAllPWMmS(float length_mS) { setAllPWM(round((length_mS * 4096.f) / (1000.f / frequency))); } /** Set pulse length in microseconds for all channels * @param Length in microseconds * @see PCA9685_RA_ALL_LED_ON_L */ void PCA9685::setAllPWMuS(float length_uS) { setAllPWM(round((length_uS * 4096.f) / (1000000.f / frequency))); }
34.553191
90
0.705819
helios57
29840304ac1dc2563bb150214bc160422a8f4a89
2,094
cc
C++
policies/DIF/EFCP/DTCP/RcvrFC/RcvrFCPolicyDefaultWithCounters/RcvrFCPolicyDefaultWithCounters.cc
karlhto/RINA
68fe850c7871d59fb882e06fa55432088d12cc51
[ "MIT" ]
30
2015-01-19T15:02:24.000Z
2021-11-05T09:29:48.000Z
policies/DIF/EFCP/DTCP/RcvrFC/RcvrFCPolicyDefaultWithCounters/RcvrFCPolicyDefaultWithCounters.cc
karlhto/RINA
68fe850c7871d59fb882e06fa55432088d12cc51
[ "MIT" ]
20
2015-01-14T16:22:03.000Z
2020-10-14T14:17:06.000Z
policies/DIF/EFCP/DTCP/RcvrFC/RcvrFCPolicyDefaultWithCounters/RcvrFCPolicyDefaultWithCounters.cc
karlhto/RINA
68fe850c7871d59fb882e06fa55432088d12cc51
[ "MIT" ]
13
2015-01-22T09:16:50.000Z
2020-09-03T09:47:14.000Z
// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // /** * @file RcvrFCPolicyDefaultWithCounters.cc * @author Kleber Leal (kal2@cin.ufpe.br) * @date Jun 19, 2017 * @brief This policy registers the goodput and number os packets received * @detail */ #include "DIF/EFCP/DTCP/RcvrFC/RcvrFCPolicyDefaultWithCounters/RcvrFCPolicyDefaultWithCounters.h" Register_Class(RcvrFCPolicyDefaultWithCounters); RcvrFCPolicyDefaultWithCounters::RcvrFCPolicyDefaultWithCounters() { // TODO Auto-generated constructor stub } RcvrFCPolicyDefaultWithCounters::~RcvrFCPolicyDefaultWithCounters() { // TODO Auto-generated destructor stub } void RcvrFCPolicyDefaultWithCounters::initialize() { sigStatPktRcvd = registerSignal("packets_received"); sigStatGoodput = registerSignal("goodput"); pktRcvd = 0; lastPktRcvd = 0; m1 = new cMessage("measure"); scheduleAt(simTime(), m1); } bool RcvrFCPolicyDefaultWithCounters::run(DTPState* dtpState,DTCPState* dtcpState) { Enter_Method("RcvrFCPolicyDefaultWithCounters"); pktRcvd++; emit(sigStatPktRcvd, pktRcvd); return true; } void RcvrFCPolicyDefaultWithCounters::handleMessage(cMessage* msg) { if(msg->isSelfMessage()){ if(!strcmp(msg->getName(), "measure")){ emit(sigStatGoodput, pktRcvd - lastPktRcvd); lastPktRcvd = pktRcvd; m1 = new cMessage("measure"); scheduleAt(simTime()+1, m1); } delete(msg); } }
32.215385
97
0.722541
karlhto
298572373c8d0464d0468981987a577ec0d990a6
70,859
cpp
C++
src/VAnaSumRunParameter.cpp
Eventdisplay/Eventdisplay
01ef380cf53a44f95351960a297a2d4f271a4160
[ "BSD-3-Clause" ]
11
2019-12-10T13:34:46.000Z
2021-08-24T15:39:35.000Z
src/VAnaSumRunParameter.cpp
Eventdisplay/Eventdisplay
01ef380cf53a44f95351960a297a2d4f271a4160
[ "BSD-3-Clause" ]
53
2019-11-19T13:14:36.000Z
2022-02-16T14:22:27.000Z
src/VAnaSumRunParameter.cpp
pivosb/Eventdisplay
6b299a1d3f77ddb641f98a511a37a5045ddd6b47
[ "BSD-3-Clause" ]
3
2020-05-07T13:52:46.000Z
2021-06-25T09:49:21.000Z
/*! \class VAnaSumRunParameter * * */ #include "VAnaSumRunParameter.h" /* definition of data class for anasum run parameters */ VAnaSumRunParameterDataClass::VAnaSumRunParameterDataClass() { fEventDisplayVersion = ""; fRunOn = 0; fRunOnFileName = ""; fRunOff = 0; fRunOffFileName = ""; fMJDOn = 0.; fMJDOff = 0.; fMJDOnStart = 0.; fMJDOnStop = 0.; fTarget = ""; fTargetRAJ2000 = 0.; fTargetDecJ2000 = -90.; fTargetRA = 0.; fTargetDec = 0.; fPairOffset = 0.; fOff_Target = ""; fOff_TargetRAJ2000 = 0.; fOff_TargetDecJ2000 = -90.; fOff_WobbleNorth = 0.; fOff_WobbleWest = 0.; fWobbleNorth = 0.; // [deg] fWobbleWest = 0.; // [deg] fWobbleNorthMod = 0.; // [deg] fWobbleWestMod = 0.; // [deg] fSkyMapCentreNorth = 0.; fSkyMapCentreWest = 0.; fSkyMapCentreRAJ2000 = 0.; fSkyMapCentreDecJ2000 = 0.; fTargetShiftNorth = 0.; fTargetShiftWest = 0.; fTargetShiftRAJ2000 = 0.; fTargetShiftDecJ2000 = 0.; fNTel = 4; fTelToAna = ""; fMaxTelID = fNTel; fBackgroundModel = 0; fSourceRadius = 0.; // actually radius^2 fmaxradius = 0.; // maximum accepted distance from camera center [deg] fCutFile = ""; fAcceptanceFile = ""; fRunWiseRadialAcceptance = false; fListOfExclusionRegions = 0; fEffectiveAreaFile = ""; // file with effective areas, use NOFILE if not avaible // ON/OFF MODEL fOO_alpha = 0.; // RING BACKGROUND MODEL fRM_RingRadius = 0.; // ring radius [deg] fRM_RingWidth = 0.; // ring width [deg] // REFLECTED REGION MODEL fRE_distanceSourceOff = 0.2; // minimal distance of off source regions in number of background regions from the source region fRE_nMinoffsource = 3; // minmum number of off source regions (default 3) fRE_nMaxoffsource = 7; // maximum number of off source regions (default 7) // TEMPLATE MODEL fTE_mscw_min = 0.; fTE_mscw_max = 0.; fTE_mscl_min = 0.; fTE_mscl_max = 0.; } VAnaSumRunParameterDataClass::~VAnaSumRunParameterDataClass() { /* if( fListOfExclusionRegions ) { delete fListOfExclusionRegions; } */ } //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// VAnaSumRunParameter::VAnaSumRunParameter() { // default version number (important for reading of run parameters from root file) fVersion = 6; // bin size for sky maps [deg] // must be the same for all runs (add up sky maps) fSkyMapBinSize = 0.01; fSkyMapBinSizeUC = 0.05; fSkyMapSizeXmin = -2.; fSkyMapSizeXmax = 2.; fSkyMapSizeYmin = -2.; fSkyMapSizeYmax = 2.; // sky maps are centred around this point fSkyMapCentreNorth = 0.; fSkyMapCentreWest = 0.; fSkyMapCentreRAJ2000 = 0.; fSkyMapCentreDecJ2000 = 0.; // position relative to which 1D histograms are filled fTargetShiftNorth = 0.; // [deg] fTargetShiftWest = 0.; // [deg]; fTargetShiftRAJ2000 = 0.; fTargetShiftDecJ2000 = 0.; // parameter for energy spectra (in log E) fEnergyReconstructionSpectralIndex = 2.5; fReconstructionType = GEO; fEnergyReconstructionMethod = 1; fEffectiveAreaVsEnergyMC = 1; // default: use effective areas vs reconstructed energy (accurate method) fEnergySpectrumBinSize = 0.05; fEnergyEffectiveAreaSmoothingIterations = -1; fEnergyEffectiveAreaSmoothingThreshold = -1.; fDeadTimeCalculationMethod = 0; // background model fTMPL_fBackgroundModel = 0; fTMPL_RM_RingRadius = 0.; fTMPL_RM_RingWidth = 0.; fTMPL_RE_distanceSourceOff = 0.; fTMPL_RE_nMinoffsource = 0; fTMPL_RE_nMaxoffsource = 0; fTMPL_RE_RemoveOffRegionsRandomly = false; // cut, effective areas and acceptance files fTMPL_SourceRadius = 0.; fTMPL_maxradius = 0.; fTMPL_CutFile = ""; fTMPL_AcceptanceFile = ""; fTMPL_EffectiveAreaFile = ""; // length of time intervals in seconds for rate plots and short term histograms fTimeIntervall = 4. * 60.; fWriteEventTree = 2; // Binned Likelihood fLikelihoodAnalysis = false; // if 0, use default 1D radial acceptance // if >0, use alternate 2D-dependent acceptance f2DAcceptanceMode = 0 ; // USE2DACCEPTANCE // use run-wise radial acceptance curve fRunWiseRadialAcceptance = false; // for deadtime fraction storage fScalarDeadTimeFrac = 0.0 ; // set monte carlo zenith angles setMCZenith(); // exclusion regions // (this is just a placeholder, full list of // exclusion region is kept in // VAnaSumRunParameterDataClass ) fExclusionRegions = new VExclusionRegions(); } VAnaSumRunParameter::~VAnaSumRunParameter() { if( fExclusionRegions ) { delete fExclusionRegions; } } int VAnaSumRunParameter::returnWithError( string iL, string iM, string iC ) { cout << endl; cout << iL << endl; cout << iM << endl; if( iC.size() > 0 ) { cout << "correct writing: " << endl; cout << iC << endl; } return 0; } /* read run parameters from an ascii file */ int VAnaSumRunParameter::readRunParameter( string i_filename, bool fIgnoreZeroExclusionRegion ) { ifstream is; is.open( i_filename.c_str(), ifstream::in ); if( !is ) { string itemp = getDirectory_EVNDISPParameterFiles(); itemp += "/" + i_filename; is.open( itemp.c_str(), ifstream::in ); if( !is ) { cout << "no file found to read run parameters: " << itemp << endl; exit( EXIT_FAILURE ); } i_filename = itemp; } cout << "Reading anasum parameters from " << i_filename << " :" << endl; cout << endl; string is_line; string temp; string temp2; // loop over all lines in the run parameter file while( getline( is, is_line ) ) { if( is_line.size() > 0 ) { istringstream is_stream( is_line ); is_stream >> temp; if( temp != "*" ) { continue; } // print runparameter to stdout cout << is_line << endl; if( (is_stream>>std::ws).eof() ) { return returnWithError( "VAnaSumRunParameter::readRunParameter: not enough parameters", is_line ); } is_stream >> temp; if( (is_stream>>std::ws).eof() ) { return returnWithError( "VAnaSumRunParameter::readRunParameter: not enough parameters", is_line ); } is_stream >> temp2; if( temp == "TIMEMASKFILE" ) { fTimeMaskFile = temp2; // check if timemask file needs an additional path ifstream is_test; is_test.open( fTimeMaskFile.c_str(), ifstream::in ); if( !is_test ) { string iDIR_temp = i_filename.substr( 0, i_filename.rfind( "/" ) ); iDIR_temp += "/" + fTimeMaskFile; is_test.open( iDIR_temp.c_str(), ifstream::in ); if( !is_test ) { cout << "Error opening time mask file: " << fTimeMaskFile << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } else { fTimeMaskFile = iDIR_temp; } } is_test.close(); } else if( temp == "GAMMAHADRONCUT" ) { fTMPL_CutFile = temp2; } else if( temp == "RADIALACCEPTANCEFILE" ) { fTMPL_AcceptanceFile = temp2; } else if( temp == "EFFECTIVEAREAFILE" ) { fTMPL_EffectiveAreaFile = temp2; } else if( temp == "REFLECTEDREGION" ) { fTMPL_fBackgroundModel = eREFLECTEDREGION; fTMPL_RE_distanceSourceOff = atof( temp2.c_str() ); if( !(is_stream>>std::ws).eof() ) { is_stream >> temp2; fTMPL_RE_nMinoffsource = atoi( temp2.c_str() ); } else { returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* REFLECTEDREGION dist noff_min noff_max" ); } if( !(is_stream>>std::ws).eof() ) { is_stream >> temp2; fTMPL_RE_nMaxoffsource = atoi( temp2.c_str() ); } else { returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* REFLECTEDREGION dist noff_min noff_max" ); } } else if( temp == "REFLECTEDREGION_OFFREMOVAL" ) { if( !(is_stream>>std::ws).eof() ) { is_stream >> temp2; fTMPL_RE_RemoveOffRegionsRandomly = bool( atoi( temp2.c_str() ) ); } } else if( temp == "RINGBACKGROUND" ) { fTMPL_fBackgroundModel = eRINGMODEL; fTMPL_RM_RingRadius = atof( temp2.c_str() ); // important: filling here temporary the // area ratio of off-to-on regions if( !(is_stream>>std::ws).eof() ) { is_stream >> temp2; fTMPL_RM_RingWidth = atof( temp2.c_str() ); } else { returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* RINGBACKGROUND ring_radius ring_area" ); } } else if( temp == "SKYMAPBINSIZE" ) { fSkyMapBinSize = atof( temp2.c_str() ); } else if( temp == "SKYMAPBINSIZEUC" ) { fSkyMapBinSizeUC = atof( temp2.c_str() ); } else if( temp == "SKYMAPSIZEX" ) { fSkyMapSizeXmin = atof( temp2.c_str() ); fSkyMapSizeXmin = -1. *TMath::Abs( fSkyMapSizeXmin ); fSkyMapSizeXmax = TMath::Abs( fSkyMapSizeXmin ); } else if( temp == "SKYMAPSIZEY" ) { fSkyMapSizeYmin = atof( temp2.c_str() ); fSkyMapSizeYmin = -1. *TMath::Abs( fSkyMapSizeYmin ); fSkyMapSizeYmax = TMath::Abs( fSkyMapSizeYmin ); } else if( temp == "BRIGHTSTARCATALOGUE" ) { if( fExclusionRegions ) { fExclusionRegions->setStarCatalogue( temp2 ); } } else if( temp == "BRIGHTSTARSETTINGS" ) { double iMinBrightness = atof( temp2.c_str() ); double iExclusionRadiusDeg = -1.; string iStarBand = ""; if( !(is_stream>>std::ws).eof() ) { is_stream >> iExclusionRadiusDeg; } if( !(is_stream>>std::ws).eof() ) { is_stream >> iStarBand; } if( fExclusionRegions ) { fExclusionRegions->addBrightStarSettings( iMinBrightness, iExclusionRadiusDeg, iStarBand ); } } else if( temp == "SKYMAPCENTRE_XY" ) { if( checkNumberOfArguments( is_line ) != 4 ) { return returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* SKYMAPCENTRE_XY x y" ); } fSkyMapCentreWest = -1.*atof( temp2.c_str() ); is_stream >> temp2; fSkyMapCentreNorth = -1.*atof( temp2.c_str() ); } else if( temp == "SKYMAPCENTRE_RADECJ2000_DEG" ) { if( checkNumberOfArguments( is_line ) != 4 ) { return returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* SKYMAPCENTRE_RADECJ2000_DEG (RA(deg) DEC(deg)" ); } fSkyMapCentreRAJ2000 = atof( temp2.c_str() ); is_stream >> temp2; fSkyMapCentreDecJ2000 = atof( temp2.c_str() ); } else if( temp == "SKYMAPCENTRE_RADECJ2000_HOUR" ) { if( checkNumberOfArguments( is_line ) != 8 ) { return returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* SKYMAPCENTRE_RADECJ2000_HOUR RA(Hour Min Sec) DEC(Deg Min Sec)" ); } // ra double h = ( double )atof( temp2.c_str() ); is_stream >> temp2; double m = ( double )atof( temp2.c_str() ); is_stream >> temp2; double s = ( double )atof( temp2.c_str() ); fSkyMapCentreRAJ2000 = VSkyCoordinatesUtilities::getRightAscension_inDegrees_fromHour( h, m, s ); // dec is_stream >> temp2; h = ( double )atof( temp2.c_str() ); is_stream >> temp2; m = ( double )atof( temp2.c_str() ); is_stream >> temp2; s = ( double )atof( temp2.c_str() ); fSkyMapCentreDecJ2000 = VSkyCoordinatesUtilities::getDeclination_inDegrees_fromHour( h, m, s ); } else if( temp == "TARGETXYSHIFT" ) { if( checkNumberOfArguments( is_line ) != 4 ) { return returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* TARGETXYSHIFT x y" ); } fTargetShiftWest = -1.*atof( temp2.c_str() ); is_stream >> temp2; fTargetShiftNorth = -1.*atof( temp2.c_str() ); } else if( temp == "TARGETPOSITION_RADECJ2000_DEG" ) { if( checkNumberOfArguments( is_line ) != 4 ) { return returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* TARGETPOSITION_RADECJ2000_DEG (RA(deg) DEC(deg)" ); } fTargetShiftRAJ2000 = atof( temp2.c_str() ); is_stream >> temp2; fTargetShiftDecJ2000 = atof( temp2.c_str() ); } else if( temp == "TARGETPOSITION_RADECJ2000_HOUR" ) { if( checkNumberOfArguments( is_line ) != 8 ) { return returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* TARGETPOSITION_RADECJ2000_HOUR RA(Hour Min Sec) DEC(Deg Min Sec)" ); } // ra double h = ( double )atof( temp2.c_str() ); is_stream >> temp2; double m = ( double )atof( temp2.c_str() ); is_stream >> temp2; double s = ( double )atof( temp2.c_str() ); fTargetShiftRAJ2000 = VSkyCoordinatesUtilities::getRightAscension_inDegrees_fromHour( h, m, s ); // dec is_stream >> temp2; h = ( double )atof( temp2.c_str() ); is_stream >> temp2; m = ( double )atof( temp2.c_str() ); is_stream >> temp2; s = ( double )atof( temp2.c_str() ); fTargetShiftDecJ2000 = VSkyCoordinatesUtilities::getDeclination_inDegrees_fromHour( h, m, s ); } else if( temp == "REGIONTOEXCLUDE" || temp == "REGIONTOEXCLUDE_RADECJ2000_DEG" ) { if( checkNumberOfArguments( is_line ) < 5 ) { return returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* REGIONTOEXCLUDE (West(deg) North(deg) Radius(deg)) (or * REGIONTOEXCLUDE_RADECJ2000_DEG (RA(deg) DEC(deg) Radius(deg)) OR * REGIONTOEXCLUDE (West(deg) North(deg) Radius1(deg) Radius2(deg) RotAngle(deg)) (or * REGIONTOEXCLUDE_RADECJ2000_DEG (RA(deg) DEC(deg) Radius1(deg) Radius2(deg) RotAngle(deg)). Check if you want extended or point source!" ); } double iExcludeFromBackground_West = -1.; double iExcludeFromBackground_North = -1.; double iExcludeFromBackground_RAJ2000 = -99.; double iExcludeFromBackground_DecJ2000 = -99.; double iExcludeFromBackground_Radius1 = -1.; double iExcludeFromBackground_Radius2 = -1.; double iExcludeFromBackground_RotAngle = -1.; string iExcludeFromBackground_Name = ""; if( temp == "REGIONTOEXCLUDE" ) { iExcludeFromBackground_West = -1.* ( double )atof( temp2.c_str() ); is_stream >> temp2; iExcludeFromBackground_North = -1.* ( double )atof( temp2.c_str() ); } else if( temp == "REGIONTOEXCLUDE_RADECJ2000_DEG" ) { iExcludeFromBackground_RAJ2000 = ( double )atof( temp2.c_str() ); is_stream >> temp2; iExcludeFromBackground_DecJ2000 = ( double )atof( temp2.c_str() ); } // for circular region if( checkNumberOfArguments( is_line ) == 5 || checkNumberOfArguments( is_line ) == 6 ) { is_stream >> temp2; iExcludeFromBackground_Radius1 = ( double )atof( temp2.c_str() ); iExcludeFromBackground_Radius2 = iExcludeFromBackground_Radius1; iExcludeFromBackground_RotAngle = 0.; } // for ellipsoidal region else if( checkNumberOfArguments( is_line ) == 7 || checkNumberOfArguments( is_line ) == 8 ) { is_stream >> temp2; iExcludeFromBackground_Radius1 = ( double )atof( temp2.c_str() ); is_stream >> temp2; iExcludeFromBackground_Radius2 = ( double )atof( temp2.c_str() ); is_stream >> temp2; iExcludeFromBackground_RotAngle = ( double ) atof( temp2.c_str() ); } else { return returnWithError( "VAnaSumRunparameter: wrong number of parameters: ", is_line, "Check if you want point or extended source in AnasumRunParameter file!" ); } // read name in if( !(is_stream>>std::ws).eof() ) { is_stream >> iExcludeFromBackground_Name; } bool i_this_is_a_zero_exclusionregion = false; if( fIgnoreZeroExclusionRegion ) { if( TMath::Abs( iExcludeFromBackground_North ) < 1.e-2 && TMath::Abs( iExcludeFromBackground_West ) < 1.e-2 ) { i_this_is_a_zero_exclusionregion = true; } } if( fExclusionRegions && !i_this_is_a_zero_exclusionregion ) { fExclusionRegions->addExclusionRegion( iExcludeFromBackground_North, iExcludeFromBackground_West, iExcludeFromBackground_RAJ2000, iExcludeFromBackground_DecJ2000, iExcludeFromBackground_Radius1, iExcludeFromBackground_Radius2, iExcludeFromBackground_RotAngle, iExcludeFromBackground_Name ); } } else if( temp == "REGIONTOEXCLUDE_RADECJ2000_HOUR" ) { if( checkNumberOfArguments( is_line ) < 9 ) { return returnWithError( "VAnaSumRunparameter: not enough parameters: ", is_line, "* REGIONTOEXCLUDE_RADECJ2000_HOUR (RA(Hour Min Sec) DEC(Deg Min Sec) Radius(deg)) OR * REGIONTOEXCLUDE_RADECJ2000_HOUR (RA(Hour Min Sec) DEC(Deg Min Sec) Radius1(deg) Radius2(deg) RotAngle(deg)). Check if you want extended or point source!" ); } double iExcludeFromBackground_RAJ2000 = -1.; double iExcludeFromBackground_DecJ2000 = -1.; double iExcludeFromBackground_Radius1 = -1.; double iExcludeFromBackground_Radius2 = -1.; double iExcludeFromBackground_RotAngle = -1.; string iExcludeFromBackground_Name = ""; // ra double h = ( double )atof( temp2.c_str() ); is_stream >> temp2; double m = ( double )atof( temp2.c_str() ); is_stream >> temp2; double s = ( double )atof( temp2.c_str() ); iExcludeFromBackground_RAJ2000 = VSkyCoordinatesUtilities::getRightAscension_inDegrees_fromHour( h, m, s ); // dec is_stream >> temp2; h = ( double )atof( temp2.c_str() ); is_stream >> temp2; m = ( double )atof( temp2.c_str() ); is_stream >> temp2; s = ( double )atof( temp2.c_str() ); iExcludeFromBackground_DecJ2000 = VSkyCoordinatesUtilities::getDeclination_inDegrees_fromHour( h, m, s ); // for circular exclusion region if( checkNumberOfArguments( is_line ) == 9 || checkNumberOfArguments( is_line ) == 10 ) { is_stream >> temp2; iExcludeFromBackground_Radius1 = ( double )atof( temp2.c_str() ); iExcludeFromBackground_Radius2 = iExcludeFromBackground_Radius1; iExcludeFromBackground_RotAngle = 0.; } // for ellipsoidal exclusion region else if( checkNumberOfArguments( is_line ) == 11 || checkNumberOfArguments( is_line ) == 12 ) { is_stream >> temp2; iExcludeFromBackground_Radius1 = ( double )atof( temp2.c_str() ); is_stream >> temp2; iExcludeFromBackground_Radius2 = ( double )atof( temp2.c_str() ); is_stream >> temp2; iExcludeFromBackground_RotAngle = ( double )atof( temp2.c_str() ); } else { return returnWithError( "VAnaSumRunparameter: wrong number of parameters: ", is_line, "Check if you want point or extended source in AnasumRunParameter file!" ); } // read name in if( !(is_stream>>std::ws).eof() ) { is_stream >> iExcludeFromBackground_Name; } if( fExclusionRegions ) { fExclusionRegions->addExclusionRegion( -1., -1., iExcludeFromBackground_RAJ2000, iExcludeFromBackground_DecJ2000, iExcludeFromBackground_Radius1, iExcludeFromBackground_Radius2, iExcludeFromBackground_RotAngle, iExcludeFromBackground_Name ); } } else if( temp == "ENERGYBINSIZE" ) { fEnergySpectrumBinSize = atof( temp2.c_str() ); } else if( temp == "ENERGYEFFECTIVEAREAS" ) { if( temp2 == "MC" ) { fEffectiveAreaVsEnergyMC = 0; } else if( temp2 == "REC" ) { fEffectiveAreaVsEnergyMC = 1; } else { cout << "Unknown parameter for ENERGYEFFECTIVEAREAS in parameter file " << i_filename << ": " << temp2 << endl; cout << "use MC or REC (default)" << endl; return 0; } } else if( temp == "ENERGYRECONSTRUCTIONMETHOD" ) { fEnergyReconstructionMethod = ( unsigned int )atoi( temp2.c_str() ); // print a clear warning if method 0 is selected if( fEnergyReconstructionMethod == 0 ) { cout << endl; cout << "WARNING: energy reconstruction 0 is no longer valid. For any standard analysise, please use method 1 by:" << endl; cout << " open your anasum run parameter file and replace " << endl; cout << "* ENERGYRECONSTRUCTIONMETHOD 0" << endl; cout << " by " << endl; cout << "* ENERGYRECONSTRUCTIONMETHOD 1" << endl; cout << "(if you really want to use method 0, you will have to look into the code to find the detour)" << endl; return 0; } // horrible detour to make sure that users don't use the wrong method else if( fEnergyReconstructionMethod == 100 ) { if( fReconstructionType == NOT_SET ) { cout << "Warning: using energy reconstruction method 0" << endl; fEnergyReconstructionMethod = 0; fReconstructionType = ENERGY_ER; } else { cout << "Warning: Analysis type has already been set, this line has no effect." << endl; } } else if( fEnergyReconstructionMethod > 1 ) { cout << "Unknown parameter for ENERGYRECONSTRUCTIONMETHOD in parameter file " << i_filename << ": " << temp2 << endl; cout << "allowed values are 0 and 1" << endl; return 0; } } else if( temp == "ReconstructionType" ) { if( temp2 == "GEO" ) { fReconstructionType = GEO; } else if( temp2 == "ENERGY_ER" ) { cout << "Warning: using energy reconstruction method 0" << endl; fReconstructionType = ENERGY_ER; fEnergyReconstructionMethod = 0; } else if( temp2 == "DEEPLEARNER" ) { fReconstructionType = DEEPLEARNER; } else { fReconstructionType = NOT_SET; cout << "VAnasumRunParameter::readRunParameter warning: Unknown analysis type "; cout << temp2 << ", will use GammaHadron cut file to decide." << endl; } } else if( temp == "DEADTIMECALCULATIONMETHOD" ) { fDeadTimeCalculationMethod = atoi( temp2.c_str() ); if( fDeadTimeCalculationMethod != 0 && fDeadTimeCalculationMethod != 1 ) { cout << "Unknown dead time calculation method (0=scalar method, 1=time difference)" << endl; return 0; } } else if( temp == "RATEINTERVALLLENGTH" ) { fTimeIntervall = atof( temp2.c_str() ) * 60.; } // expect spectral index positive else if( temp == "ENERGYSPECTRALINDEX" ) { fEnergyReconstructionSpectralIndex = fabs( atof( temp2.c_str() ) ); } // effective area smoothing else if( temp == "ENERGYEFFAREASMOOTHITER" ) { fEnergyEffectiveAreaSmoothingIterations = atoi( temp2.c_str() ); } else if( temp == "ENERGYEFFAREASMOOTHTHRESH" ) { fEnergyEffectiveAreaSmoothingThreshold = atof( temp2.c_str() ); } //////////////////////////////////////////// // Option USE2DACCEPTANCE within ANASUM.runparameter // * USE2DACCEPTANCE 0 // use normal radial acceptance // * USE2DACCEPTANCE 1 // use simple 2d acceptance model else if( temp == "USE2DACCEPTANCE" ) { f2DAcceptanceMode = ( unsigned int )atoi( temp2.c_str() ) ; } else if( temp == "USERUNWISERADIALACCEPTANCE" ) { fRunWiseRadialAcceptance = true; } /////////////////////////////////////////////////////////// // WRITEEVENTTREE // write tree tree with on/off into anasum output file else if( temp == "WRITEEVENTTREE" ) { fWriteEventTree = ( unsigned int )atoi( temp2.c_str() ); } /// enable likelihood analysis /// else if (temp == "ENABLEBINNEDLIKELIHOOD") { unsigned int tmpLikelihood = ( unsigned int )atoi( temp2.c_str() ) ; if( tmpLikelihood == 1) { fLikelihoodAnalysis = true; } } else { cout << "Warning: unknown line in parameter file " << i_filename << ": " << endl; cout << is_line << endl; } } } if( fTMPL_CutFile.size() > 0 ) { fTMPL_SourceRadius = readSourceRadius( fTMPL_CutFile ); if( fTMPL_SourceRadius <= 0. ) { cout << "error in reading run parameters: "; cout << "invalid source radius " << fTMPL_SourceRadius << endl; exit( EXIT_FAILURE ); } // note: fTMPL_RM_RingWidth is overwritten to carry to correct variable fTMPL_RM_RingWidth = getRingWidth( TMath::Pi() * fTMPL_SourceRadius, fTMPL_RM_RingRadius, fTMPL_RM_RingWidth ); fTMPL_maxradius = readMaximumDistance( fTMPL_CutFile ); if( fTMPL_maxradius < 0. ) { cout << "error in reading run parameters: "; cout << "invalid maximum distance " << fTMPL_maxradius << endl; exit( EXIT_FAILURE ); } } else { fTMPL_SourceRadius = 0.1; fTMPL_maxradius = 2.0; } // prelimary: require same extension in x and y if( fabs( fSkyMapSizeXmax - fSkyMapSizeYmax ) > 1.e-3 ) { return returnWithError( "VAnaSumRunParameter::readRunParameter: x and y extension of the sky map should be the same (preliminary)", "" ); } is.close(); cout << "========================================================" << endl; cout << " end reading run parameters " << endl; cout << "========================================================" << endl; cout << endl; return 1; } /* * this is used by the radial acceptance code */ int VAnaSumRunParameter::loadSimpleFileList( string i_listfilename ) { int i_nline = 0; ifstream is; is.open( i_listfilename.c_str(), ifstream::in ); if( !is ) { cout << " VAnaSumRunParameter:::loadSimpleFileList error: file with list of runs not found : " << i_listfilename << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } string is_line; string temp; VAnaSumRunParameterDataClass i_sT; reset( i_sT ); cout << "Reading simple run list from: " << i_listfilename << endl; while( getline( is, is_line ) ) { if( is_line.size() > 0 ) { istringstream is_stream( is_line ); is_stream >> temp; // read run list i_sT.fRunOn = atoi( temp.c_str() ); i_sT.fRunOff = atoi( temp.c_str() ); // fill the runlist vector i_sT.f2DAcceptanceMode = f2DAcceptanceMode ; // USE2DACCEPTANCE i_sT.fRunWiseRadialAcceptance = fRunWiseRadialAcceptance; fRunList.push_back( i_sT ); // fill the runlist map fMapRunList[i_sT.fRunOn] = fRunList.back(); ++i_nline; } } return i_nline; } /* read long run list */ int VAnaSumRunParameter::loadLongFileList( string i_listfilename, bool bShortList, bool bTotalAnalysisOnly ) { int i_nline = 0; ifstream is; is.open( i_listfilename.c_str(), ifstream::in ); if( !is ) { cout << " VAnaSumRunParameter::loadLongFileList error: file with list of runs not found : " << i_listfilename << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } string is_line; string temp; VAnaSumRunParameterDataClass i_sT; reset( i_sT ); cout << "Reading long run list from (S" << bShortList << ", TA" << bTotalAnalysisOnly << "): " << i_listfilename << endl; while( getline( is, is_line ) ) { if( is_line.size() > 0 ) { istringstream is_stream( is_line ); is_stream >> temp; if( temp != "*" ) { continue; } int narg = checkNumberOfArguments( is_line ); // check version number if( narg == 3 ) { is_stream >> temp; if( temp == "VERSION" || temp == "Version" || temp == "version" ) { is_stream >> temp; fVersion = atoi( temp.c_str() ); continue; } } checkNumberOfArguments( -1, narg, i_listfilename, is_line, fVersion, bShortList ); is_stream >> temp; // read run list i_sT.fRunOn = atoi( temp.c_str() ); is_stream >> temp; i_sT.fRunOff = atoi( temp.c_str() ); // short list, only read run numbers and target name if( bShortList ) { // fill the runlist vector i_sT.f2DAcceptanceMode = f2DAcceptanceMode ; // USE2DACCEPTANCE i_sT.fRunWiseRadialAcceptance = fRunWiseRadialAcceptance; fRunList.push_back( i_sT ); // fill the runlist map fMapRunList[i_sT.fRunOn] = fRunList.back(); ++i_nline; continue; } // offset in min between on and off run (positive if off run after on run) // (now read from VEvndispRunParameter) if( fVersion < 6 ) { is_stream >> temp; i_sT.fPairOffset = atof( temp.c_str() ); } // cut selector (now in cut file, therefore ignored) is_stream >> temp; //////////// // cut file // (in >=7, cuts are read from the effective area file if( fVersion < 7 ) { is_stream >> temp; i_sT.fCutFile = temp; // source radius (actually (source radius)^2 ) // (read theta2 cut from cut file) if( !bTotalAnalysisOnly ) { i_sT.fSourceRadius = readSourceRadius( i_sT.fCutFile ); } else { i_sT.fSourceRadius = 0.1; } if( i_sT.fSourceRadius <= 0. ) { cout << "VAnaSumRunParameter::loadLongFileList: error in run list: " << endl; cout << is_line << endl; cout << "invalid source radius " << i_sT.fSourceRadius << endl; exit( EXIT_FAILURE ); } } // background model is_stream >> temp; if( temp == "RE" ) { i_sT.fBackgroundModel = eREFLECTEDREGION; } else if( temp == "RB" ) { i_sT.fBackgroundModel = eRINGMODEL; } else if( temp == "OO" || temp == "ONOFF" ) { i_sT.fBackgroundModel = eONOFF; } else if( temp == "TML" ) { i_sT.fBackgroundModel = eTEMPLATE; } else { i_sT.fBackgroundModel = atoi( temp.c_str() ); } checkNumberOfArguments( i_sT.fBackgroundModel, narg, i_listfilename, is_line, fVersion, bShortList ); // maximum distance for events from camera center // (read maximum distance from cut file) if( fVersion < 2 ) { is_stream >> temp; i_sT.fmaxradius = atof( temp.c_str() ); } else if( fVersion < 7 ) { if( !bTotalAnalysisOnly ) { i_sT.fmaxradius = readMaximumDistance( i_sT.fCutFile ); } else { i_sT.fmaxradius = 2.0; } if( i_sT.fmaxradius < 0. ) { cout << "VAnaSumRunParameter::loadLongFileList: error in run list: " << endl; cout << is_line << endl; cout << "invalid maximum distance " << i_sT.fmaxradius << endl; exit( EXIT_FAILURE ); } } // file for effective areas is_stream >> temp; i_sT.fEffectiveAreaFile = temp; // cuts are in the effective area files if( fVersion >= 7 ) { if( i_sT.fEffectiveAreaFile.find( "IGNOREEFFECTIVEAREA" ) != string::npos ) { cout << "VAnaSumRunParameter::loadLongFileList warning: "; cout << "ignore effective areas - cannot read cuts from effective area files" << endl; } else { // check if IRF runparameters are consistent with ANASUM.runparameter file checkAnasumParameter( i_sT.fEffectiveAreaFile ); i_sT.fCutFile = temp; // source radius (actually (source radius)^2 ) // (read theta2 cut from cut file) if( !bTotalAnalysisOnly ) { readCutParameter( i_sT.fCutFile, i_sT.fSourceRadius, i_sT.fmaxradius ); } else { i_sT.fSourceRadius = 0.1; i_sT.fmaxradius = 2.0; } if( i_sT.fSourceRadius <= 0. ) { cout << "VAnaSumRunParameter::loadLongFileList: error in run list: " << endl; cout << is_line << endl; cout << "invalid source radius " << i_sT.fSourceRadius << endl; exit( EXIT_FAILURE ); } } } // background model dependend parameters // // if( i_sT.fBackgroundModel == eONOFF ) // { // nothing here // } if( i_sT.fBackgroundModel == eRINGMODEL ) { is_stream >> temp; i_sT.fRM_RingRadius = atof( temp.c_str() ); is_stream >> temp; i_sT.fRM_RingWidth = getRingWidth( TMath::Pi() * i_sT.fSourceRadius, i_sT.fRM_RingRadius, atof( temp.c_str() ) ); is_stream >> temp; i_sT.fAcceptanceFile = temp; } else if( i_sT.fBackgroundModel == eREFLECTEDREGION ) { is_stream >> temp; i_sT.fRE_distanceSourceOff = atof( temp.c_str() ); is_stream >> temp; i_sT.fRE_nMinoffsource = atoi( temp.c_str() ); is_stream >> temp; i_sT.fRE_nMaxoffsource = atoi( temp.c_str() ); if( i_sT.fRE_nMaxoffsource > 10 ) { cout << "VAnaSumRunParameter::loadLongFileList():"; cout << "warning, a large number of reflection regions might introduce a gradient into sky maps (consider values <10)" << endl; } is_stream >> temp; i_sT.fAcceptanceFile = temp; } ///////////////// else if( i_sT.fBackgroundModel == eTEMPLATE ) { is_stream >> temp; i_sT.fTE_mscw_min = atof( temp.c_str() ); is_stream >> temp; i_sT.fTE_mscw_max = atof( temp.c_str() ); is_stream >> temp; i_sT.fTE_mscl_min = atof( temp.c_str() ); is_stream >> temp; i_sT.fTE_mscl_max = atof( temp.c_str() ); cout << "DO NOT USE " << endl; exit( EXIT_SUCCESS ); } else if( i_sT.fBackgroundModel == eONOFF ) { // off runs are weighted the same as on runs i_sT.fOO_alpha = 1.; } // fill the runlist vector i_sT.f2DAcceptanceMode = f2DAcceptanceMode ; // USE2DACCEPTANCE i_sT.fRunWiseRadialAcceptance = fRunWiseRadialAcceptance; fRunList.push_back( i_sT ); // fill the runlist map fMapRunList[i_sT.fRunOn] = fRunList.back(); ++i_nline; } } cout << "\t finished reading " << i_nline << " lines from run list " << endl; return i_nline; } void VAnaSumRunParameter::printStereoParameter( int ion ) { for( unsigned int i = 0; i < fRunList.size(); i++ ) { if( fRunList[i].fRunOn == ion ) { printStereoParameter( i ); } } } void VAnaSumRunParameter::printStereoParameter( unsigned int i ) { if( i < fRunList.size() ) { int ioff = fRunList[i].fRunOff; cout << "Stereo analysis for run: " << fRunList[i].fRunOn << "\t" << ioff; cout << " (run " << i + 1 << " out of " << fRunList.size() << ")"; if( fRunList[i].fEventDisplayVersion.size() > 0 ) { cout << ", eventdisplay version " << fRunList[i].fEventDisplayVersion; } cout << endl; cout << "\t Object: " << fRunList[i].fTarget; cout << " (background: " << fRunList[i].fOff_Target << ")" << endl; cout << "\t Wobble: (N" << fRunList[i].fWobbleNorth << ", W" << fRunList[i].fWobbleWest << ")"; cout << ", sky maps centred at (ra,dec) (" << fSkyMapCentreRAJ2000 << ", " << fSkyMapCentreDecJ2000 << ")"; cout << ", target shift: (N" << fRunList[i].fTargetShiftNorth << ", W" << fRunList[i].fTargetShiftWest << ")"; cout << " (RA/DEC)_J2000 [" << fRunList[i].fTargetShiftRAJ2000 << ", " << fRunList[i].fTargetShiftDecJ2000 << "]" << endl; cout << "\t user defined exclusion regions:" << endl; if( fExclusionRegions ) { fExclusionRegions->printExclusionRegions(); } cout << "\t number of telescopes: " << fRunList[i].fNTel << endl; cout << "\t time interval for rate plots: " << fTimeIntervall << " s (" << fTimeIntervall / 60. << " min)" << endl; cout << "\t effective areas from " << fRunList[i].fEffectiveAreaFile << endl; cout << "\t sky plot binning [deg] " << fSkyMapBinSize << "\t" << fSkyMapBinSizeUC << endl; cout << "\t sky plot size [deg]: " << fSkyMapSizeXmin << " < X < " << fSkyMapSizeXmax; cout << ", " << fSkyMapSizeYmin << " < Y < " << fSkyMapSizeYmax << endl; cout << "\t energy spectra parameters (binsize, log10): " << fEnergySpectrumBinSize; if( fEffectiveAreaVsEnergyMC == 0 ) { cout << " (use effective area A_MC)"; } else if( fEffectiveAreaVsEnergyMC == 1 ) { cout << " (use effective area A_REC)"; } cout << ", Method " << fEnergyReconstructionMethod << endl; cout << "\t dead time calculation method: "; if( fDeadTimeCalculationMethod == 0 ) { cout << "scalar method" << endl; } else { cout << "tdiff method" << endl; } cout << "\t background model: "; if( fRunList[i].fBackgroundModel == eONOFF ) { cout << "ON/OFF BACKGROUND MODEL" << endl; cout << "\t theta2 cut: " << fRunList[i].fSourceRadius << " deg2" << endl; cout << "\t maximum distance to camera center: " << fRunList[i].fmaxradius << endl; } else if( fRunList[i].fBackgroundModel == eRINGMODEL ) { cout << "RING BACKROUND MODEL" << endl; cout << "\t theta2 cut: " << fRunList[i].fSourceRadius << " deg2" << endl; cout << "\t ring radius: " << fRunList[i].fRM_RingRadius << " deg" << endl; cout << "\t ring width: " << fRunList[i].fRM_RingWidth << " deg" << endl; cout << "\t area ratio source region to ring: " << 2 * fRunList[i].fRM_RingRadius* fRunList[i].fRM_RingWidth / fRunList[i].fSourceRadius << endl; cout << "\t acceptance file: " << fRunList[i].fAcceptanceFile << endl; cout << "\t maximum distance to camera center: " << fRunList[i].fmaxradius << " deg" << endl; } else if( fRunList[i].fBackgroundModel == eREFLECTEDREGION ) { cout << "REFLECTED REGIONS BACKGROUND MODEL"; if( fTMPL_RE_RemoveOffRegionsRandomly ) { cout << " (excess regions are removed randomly)"; } cout << endl; cout << "\t theta2 cut: " << fRunList[i].fSourceRadius << " deg2" << endl; cout << "\t distance to source region: " << fRunList[i].fRE_distanceSourceOff << endl; cout << "\t minimum number of off source regions: " << fRunList[i].fRE_nMinoffsource << endl; cout << "\t maximum number of off source regions: " << fRunList[i].fRE_nMaxoffsource << endl; cout << "\t acceptance file (for theta2 plots): " << fRunList[i].fAcceptanceFile << endl; cout << "\t maximum distance to camera center: " << fRunList[i].fmaxradius << " deg" << endl; } if( fRunWiseRadialAcceptance ) { cout << "\t Using run-wise radial acceptance curves" << endl; } } cout << endl; } int VAnaSumRunParameter::checkNumberOfArguments( string is ) { // get rid of trailing spaces while( is.rfind( " " ) > is.size() - 2 ) { is = is.substr( 0, is.size() - 1 ); } // Need to remove newline character from the string // since it is counted as an additional parameter is.erase(std::remove(is.begin(), is.end(), '\n'), is.end()); is.erase(std::remove(is.begin(), is.end(), '\r'), is.end()); istringstream is_stream( is ); string itemp; int z = 0; while( !(is_stream>>std::ws).eof() ) { is_stream >> itemp; z++; } return z; } void VAnaSumRunParameter::checkNumberOfArguments( int im, int narg, string i_listfilename, string is_line, int iversion, bool bShortList ) { if( bShortList && narg > 3 ) { return; } int n_tot = 0; if( im == -1 ) { n_tot = 10; } else if( im == 0 ) { n_tot = 12; } else if( im == 1 ) { n_tot = 16; } else if( im == 2 ) { n_tot = 16; } else if( im == 3 ) { n_tot = 15; } else { cout << "VAnaSumRunParameter::checkNumberOfArguments error: unknown background model" << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } // wobble offsets removed with version >=3 if( iversion > 2 ) { n_tot -= 2; } if( iversion > 3 ) { n_tot -= 2; } if( iversion > 4 && ( im == 1 || im == 3 ) ) { n_tot -= 1; } if( iversion > 5 ) { n_tot -= 1; // no more RA offset for off runs } if( iversion > 6 ) { n_tot -= 1; // no more cut file } if( ( im == -1 && narg < n_tot ) || ( im >= 0 && narg != n_tot ) ) { cout << "error: not enough/too many parameter in " << i_listfilename << ": " << endl; cout << is_line << endl; cout << "expected " << n_tot << " parameter, found " << narg << " parameters" << endl; cout << "(" << im << ", " << narg << ", run list version " << iversion; if( bShortList ) { cout << ", shortlist"; } cout << ")" << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } } void VAnaSumRunParameter::reset( VAnaSumRunParameterDataClass it ) { it.fRunOn = 0; it.fRunOff = 0; it.fTarget = "target"; it.fPairOffset = 0.; it.fWobbleNorth = 0.; it.fWobbleWest = 0.; it.fWobbleNorthMod = 0.; it.fWobbleWestMod = 0.; it.fOff_WobbleNorth = 0.; it.fOff_WobbleWest = 0.; it.fNTel = 4; it.fMaxTelID = it.fNTel; it.fTelToAnalyze.clear(); it.fBackgroundModel = 0; it.fSourceRadius = 0.; it.fmaxradius = 0.; it.fAcceptanceFile = ""; it.fOO_alpha = 0.; it.fRM_RingRadius = 0.; it.fRM_RingWidth = 0.; it.fAcceptanceFile = ""; it.fRE_distanceSourceOff = 0.; it.fRE_nMinoffsource = 0; it.fRE_nMaxoffsource = 0; it.fAcceptanceFile = ""; it.fTE_mscw_min = 0.; it.fTE_mscw_max = 0.; it.fTE_mscl_min = 0.; it.fTE_mscl_max = 0.; } /* * calculate ring width for the ring background model * * a_on = Area of on region * rr = ring radius * rat = area ratio of off-to-on regions * * inner radius of ring: rr - ring width / 2 * outer radius of ring: rr + ring width / 2 * */ double VAnaSumRunParameter::getRingWidth( double a_on, double rr, double rat ) { if( rr == 0. ) { return 0.; } return rat / 4. / TMath::Pi() / rr * a_on * 2.; } double VAnaSumRunParameter::readSourceRadius( string ifile ) { VGammaHadronCuts iC; iC.setNTel( 1 ); // irrelevant - but suppresses some warnings if( !iC.readCuts( ifile, 0 ) ) { return -1; }; if( iC.getTheta2Cut_max() < 0. && iC.getDirectionCutSelector() == 2 ) { return iC.getAngularResolutionAbsoluteMaximum(); } return iC.getTheta2Cut_max(); } /* * read some parameters from gamma/hadron cuts (root file) * */ bool VAnaSumRunParameter::readCutParameter( string ifile, double& iSourceRadius, double& iMaximumDistance ) { iSourceRadius = -1.; iMaximumDistance = -1.; string iEffFile = VUtilities::testFileLocation( ifile, "EffectiveAreas", true ); TFile* iF = new TFile( iEffFile.c_str() ); if( iF->IsZombie() ) { cout << "VAnaSumRunParameter::readCutParameter error opening file to read direction cuts: " << endl; cout << "\t" << ifile << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } VGammaHadronCuts* iC = ( VGammaHadronCuts* )iF->Get( "GammaHadronCuts" ); if( !iC ) { cout << "VAnaSumRunParameter::readCutParameter error reading direction cut from file: " << endl; cout << "\t" << ifile << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } if( iC->getTheta2Cut_max() < 0. && iC->getDirectionCutSelector() == 2 ) { iSourceRadius = iC->getAngularResolutionAbsoluteMaximum(); } else { iSourceRadius = iC->getTheta2Cut_max(); } iMaximumDistance = iC->fCut_CameraFiducialSize_max; if( iF ) { iF->Close(); } return true; } /* * get gamma/hadron parameters from a file * * Note: file stays open */ VGammaHadronCuts* VAnaSumRunParameter::getGammaHadronCuts( string ifile ) { string iEffFile = VUtilities::testFileLocation( ifile, "EffectiveAreas", true ); TFile* iF = new TFile( iEffFile.c_str() ); if( iF->IsZombie() ) { cout << "VAnaSumRunParameter::getGammaHadronCuts: error opening file to read direction cuts: " << endl; cout << "\t" << ifile << endl; return 0; } VGammaHadronCuts* iC = ( VGammaHadronCuts* )iF->Get( "GammaHadronCuts" ); if( !iC ) { cout << "VAnaSumRunParameter::getGammaHadronCuts error reading direction cut from file: " << endl; cout << "\t" << ifile << endl; return 0; } return iC; } bool VAnaSumRunParameter::setRunTimes( unsigned int i, double iMJDStart, double iMJDStopp ) { if( i >= fRunList.size() ) { return false; } fRunList[i].fMJDOnStart = iMJDStart; fRunList[i].fMJDOnStop = iMJDStopp; if( fMapRunList.find( fRunList[i].fRunOn ) != fMapRunList.end() ) { fMapRunList[fRunList[i].fRunOn].fMJDOnStart = iMJDStart; fMapRunList[fRunList[i].fRunOn].fMJDOnStop = iMJDStopp; } return true; } /* * Check if requested anasum runparameter make sense, i.e., * - energy reconstruction method should be the same as in effective area file * - spectral index should be in the range of simulated index range * */ bool VAnaSumRunParameter::checkAnasumParameter( string ifile ) { string iEffFile = VUtilities::testFileLocation( ifile, "EffectiveAreas", true ); TFile* iF = new TFile( iEffFile.c_str() ); if( iF->IsZombie() ) { cout << "VAnaSumRunParameter::checkAnasumParameter error opening file to read IRF parameters: " << endl; cout << "\t" << ifile << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } VInstrumentResponseFunctionRunParameter* iIRF = ( VInstrumentResponseFunctionRunParameter* )iF->Get( "makeEffectiveArea_runparameter" ); if( !iIRF ) { cout << "VAnaSumRunParameter::checkAnasumParameter error reading IRF parameter from file: " << endl; cout << "\t" << ifile << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } else { // check energy reconstruction method if( iIRF->fEnergyReconstructionMethod != fEnergyReconstructionMethod ) { cout << "VAnaSumRunParameter::checkAnasumParameter error in energy reconstruction method specified in runparameter file. " << endl; cout << "\t Effective area file (" << ifile << ") uses energy reconstruction method " << iIRF->fEnergyReconstructionMethod << endl; cout << "\t but energy reconstruction method " << fEnergyReconstructionMethod << " is requested in the anasum runparameter file. " << endl; cout << "exiting..." << endl; exit( EXIT_FAILURE ); } // check spectral index range double iIndexMin = iIRF->fSpectralIndexMin; double iIndexMax = iIRF->fSpectralIndexMin + iIRF->fNSpectralIndex * iIRF->fSpectralIndexStep; if( fEnergyReconstructionSpectralIndex < iIndexMin || fEnergyReconstructionSpectralIndex > iIndexMax ) { cout << "VAnaSumRunParameter::checkAnasumParameter warning: spectral index out of range. " << endl; cout << "\t Requested spectral index (" << fEnergyReconstructionSpectralIndex << ") is outsided the range simulated [" << iIndexMin << "-" << iIndexMax << "]." << endl << endl; } } if( iF ) { iF->Close(); } return true; } double VAnaSumRunParameter::readMaximumDistance( string ifile ) { VGammaHadronCuts iC; iC.setNTel( 1 ); // irrelevant - but suppressed printing of warnings to screen if( !iC.readCuts( ifile, 0 ) ) { return -1; } return iC.fCut_CameraFiducialSize_max; } unsigned int VAnaSumRunParameter::getMaxNumberofTelescopes() { unsigned int iMax = 0; for( unsigned int i = 0; i < fRunList.size(); i++ ) { if( fRunList[i].fNTel > iMax ) { iMax = fRunList[i].fNTel; } } return iMax; } bool VAnaSumRunParameter::setTargetShifts( unsigned int i, double west, double north, double ra, double dec ) { if( i < fRunList.size() ) { if( fMapRunList.find( fRunList[i].fRunOn ) != fMapRunList.end() ) { fMapRunList[fRunList[i].fRunOn].fTargetShiftWest = west; fMapRunList[fRunList[i].fRunOn].fTargetShiftNorth = north; fMapRunList[fRunList[i].fRunOn].fTargetShiftRAJ2000 = ra; fMapRunList[fRunList[i].fRunOn].fTargetShiftDecJ2000 = dec; } return true; } return false; } bool VAnaSumRunParameter::setSkyMapCentreJ2000( unsigned int i, double ra, double dec ) { if( i < fRunList.size() ) { fRunList[i].fSkyMapCentreRAJ2000 = ra; fRunList[i].fSkyMapCentreDecJ2000 = dec; if( fMapRunList.find( fRunList[i].fRunOn ) != fMapRunList.end() ) { fMapRunList[fRunList[i].fRunOn].fSkyMapCentreRAJ2000 = ra; fMapRunList[fRunList[i].fRunOn].fSkyMapCentreDecJ2000 = dec; } return true; } return false; } bool VAnaSumRunParameter::setTargetRADecJ2000( unsigned int i, double ra, double dec, string iTargetName ) { if( i < fRunList.size() ) { fRunList[i].fTargetRAJ2000 = ra; fRunList[i].fTargetDecJ2000 = dec; fRunList[i].fTarget = iTargetName; if( fMapRunList.find( fRunList[i].fRunOn ) != fMapRunList.end() ) { fMapRunList[fRunList[i].fRunOn].fTargetRAJ2000 = ra; fMapRunList[fRunList[i].fRunOn].fTargetDecJ2000 = dec; fMapRunList[fRunList[i].fRunOn].fTarget = iTargetName; } // set centre of stereo maps (if this parameter is not set in the file runparameter.dat) if( TMath::Abs( fSkyMapCentreNorth ) < 1.e-8 && TMath::Abs( fSkyMapCentreWest ) < 1.e-8 && TMath::Abs( fSkyMapCentreRAJ2000 ) < 1.e-8 && TMath::Abs( fSkyMapCentreDecJ2000 ) < 1.e-8 ) { fRunList[i].fSkyMapCentreNorth = 0.; fRunList[i].fSkyMapCentreWest = 0.; fRunList[i].fSkyMapCentreRAJ2000 = ra; fRunList[i].fSkyMapCentreDecJ2000 = dec; if( fMapRunList.find( fRunList[i].fRunOn ) != fMapRunList.end() ) { fMapRunList[fRunList[i].fRunOn].fSkyMapCentreNorth = 0.; fMapRunList[fRunList[i].fRunOn].fSkyMapCentreWest = 0.; fMapRunList[fRunList[i].fRunOn].fSkyMapCentreRAJ2000 = ra; fMapRunList[fRunList[i].fRunOn].fSkyMapCentreDecJ2000 = dec; } } return true; } return false; } bool VAnaSumRunParameter::setTargetRADec_currentEpoch( unsigned int i, double ra, double dec ) { if( i < fRunList.size() ) { fRunList[i].fTargetRA = ra; fRunList[i].fTargetDec = dec; if( fMapRunList.find( fRunList[i].fRunOn ) != fMapRunList.end() ) { fMapRunList[fRunList[i].fRunOn].fTargetRA = ra; fMapRunList[fRunList[i].fRunOn].fTargetDec = dec; } return true; } return false; } void VAnaSumRunParameter::getEventdisplayRunParameter( string fDatadir ) { cout << "\t reading run parameter from mscw file (may take a second...)" << endl; char i_temp[200]; int i_run; string i_treename = "data"; string fPrefix = ""; string fSuffix = ".mscw.root"; for( unsigned int i = 0; i < fRunList.size(); i++ ) { i_run = fRunList[i].fRunOn; sprintf( i_temp, "%s/%s%d%s", fDatadir.c_str(), fPrefix.c_str(), i_run, fSuffix.c_str() ); TFile* i_f = new TFile( i_temp ); if( i_f->IsZombie() ) { cout << "VAnaSumRunParameter::getEventdisplayRunParameter fatal error: file not found, " << i_temp << endl; exit( -1 ); } VEvndispRunParameter* iParV2 = ( VEvndispRunParameter* )i_f->Get( "runparameterV2" ); if( iParV2 ) { fRunList[i].fEventDisplayVersion = iParV2->getEVNDISP_VERSION(); fRunList[i].fTarget = iParV2->fTargetName; fRunList[i].fTargetRAJ2000 = iParV2->fTargetRA; fRunList[i].fTargetDecJ2000 = iParV2->fTargetDec; fRunList[i].fWobbleNorth = iParV2->fWobbleNorth; fRunList[i].fWobbleWest = -1.*iParV2->fWobbleEast; fRunList[i].fWobbleNorthMod = iParV2->fWobbleNorth; fRunList[i].fWobbleWestMod = -1.*iParV2->fWobbleEast; fRunList[i].fNTel = ( int )iParV2->fTelToAnalyze.size(); fRunList[i].fTelToAnalyze = iParV2->fTelToAnalyze; } i_f->Close(); // get maximum telescope ID fRunList[i].fMaxTelID = 0; for( unsigned int t = 0; t < fRunList[i].fTelToAnalyze.size(); t++ ) { if( fRunList[i].fTelToAnalyze[t] > fRunList[i].fMaxTelID ) { fRunList[i].fMaxTelID = fRunList[i].fTelToAnalyze[t]; } } // go from T1 = 0 to T1 = 1 fRunList[i].fMaxTelID += 1; } ////////////////////////////////////////////////////////////////////////////// // background (off) runs for( unsigned int i = 0; i < fRunList.size(); i++ ) { i_run = fRunList[i].fRunOff; sprintf( i_temp, "%s/%s%d%s", fDatadir.c_str(), fPrefix.c_str(), i_run, fSuffix.c_str() ); TFile* i_f = new TFile( i_temp ); if( i_f->IsZombie() ) { cout << "VAnaSumRunParameter::getEventdisplayRunParameter fatal error: off file not found, " << i_temp << endl; exit( EXIT_FAILURE ); } VEvndispRunParameter* iParV2 = ( VEvndispRunParameter* )i_f->Get( "runparameterV2" ); if( iParV2 ) { fRunList[i].fPairOffset = iParV2->fTargetRAOffset * 24. * 60. / 360.; fRunList[i].fOff_Target = iParV2->fTargetName; fRunList[i].fOff_TargetRAJ2000 = iParV2->fTargetRA; fRunList[i].fOff_TargetDecJ2000 = iParV2->fTargetDec; fRunList[i].fOff_WobbleNorth = iParV2->fWobbleNorth; fRunList[i].fOff_WobbleWest = -1.*iParV2->fWobbleEast; if( TMath::Abs( fRunList[i].fPairOffset ) > 1.e-3 ) { cout << "\t on/off pair offset in RA: " << fRunList[i].fPairOffset << endl; cout << "\t Warning: pair offset for on/off analysis not taken into account"; cout << "- this part of the analysis needs development work" << endl; } } i_f->Close(); } } void VAnaSumRunParameter::getWobbleOffsets( string fDatadir ) { cout << "\t read wobble offsets from root files (may take a second...)" << endl; char i_temp[200]; int i_run; string i_treename = "data"; string fPrefix = ""; string fSuffix = ".mscw.root"; for( unsigned int i = 0; i < fRunList.size(); i++ ) { i_run = fRunList[i].fRunOn; sprintf( i_temp, "%s%s%d%s", fDatadir.c_str(), fPrefix.c_str(), i_run, fSuffix.c_str() ); TFile* i_f = new TFile( i_temp ); if( i_f->IsZombie() ) { cout << "VAnaSumRunParameter::getWobbleOffset fatal error: file not found, " << i_temp << endl; exit( EXIT_FAILURE ); } TTree* i_tree = ( TTree* )i_f->Get( i_treename.c_str() ); if( !i_tree ) { cout << "VAnaSumRunParameter::getWobbleOffset tree not found " << i_treename << endl; exit( EXIT_FAILURE ); } i_tree->GetEntry( 1 ); if( i_tree->GetBranch( "WobbleN" ) && i_tree->GetBranch( "WobbleE" ) ) { fRunList[i].fWobbleNorth = i_tree->GetBranch( "WobbleN" )->GetLeaf( "WobbleN" )->GetValue(); fRunList[i].fWobbleWest = -1.*i_tree->GetBranch( "WobbleE" )->GetLeaf( "WobbleE" )->GetValue(); fRunList[i].fWobbleNorthMod = i_tree->GetBranch( "WobbleN" )->GetLeaf( "WobbleN" )->GetValue(); fRunList[i].fWobbleWestMod = -1.*i_tree->GetBranch( "WobbleE" )->GetLeaf( "WobbleE" )->GetValue(); } else { cout << endl; cout << "VAnaSumRunParameter::getWobbleOffset error: cannot determine wobble offset for run " << fRunList[i].fRunOn << " from mscw_energy output file" << endl; cout << "\t old file version?" << endl; exit( EXIT_SUCCESS ); } i_f->Close(); } } /*! observe that these are hardwired values according to the VERITAS simulation sets */ void VAnaSumRunParameter::setMCZenith() { fMCZe.clear(); fMCZe.push_back( 0.0 ); fMCZe.push_back( 20.0 ); fMCZe.push_back( 30.0 ); fMCZe.push_back( 35.0 ); fMCZe.push_back( 40.0 ); fMCZe.push_back( 45.0 ); fMCZe.push_back( 50.0 ); fMCZe.push_back( 55.0 ); fMCZe.push_back( 60.0 ); fMCZe.push_back( 65.0 ); } /* write exclusion regions into root file (into the current directory) */ bool VAnaSumRunParameter::writeListOfExcludedSkyRegions( int ionRun ) { if( ionRun < 0 && fExclusionRegions ) { return fExclusionRegions->writeExclusionRegionTree(); } else { for( unsigned int i = 0; i < fRunList.size(); i++ ) { if( fRunList[i].fRunOn == ionRun && fRunList[i].fListOfExclusionRegions ) { fRunList[i].fListOfExclusionRegions->writeExclusionRegionTree( ionRun ); } } } return false; } /* read list of exclusion regions from a anasum file */ bool VAnaSumRunParameter::getListOfExcludedSkyRegions( TFile* f, int iRunOn ) { if( fExclusionRegions ) { return fExclusionRegions->readExclusionRegionTree( f, iRunOn ); } return false; } /* * return largest star exclusion radius * */ double VAnaSumRunParameter::getLargestStarExlusionRadius() { if( fExclusionRegions ) { return fExclusionRegions->getLargestStarExlusionRadius(); } return 0.; } vector< VListOfExclusionRegions* > VAnaSumRunParameter::getExclusionRegions( unsigned int iRunCounter ) { if( iRunCounter < fRunList.size() && fRunList[iRunCounter].fListOfExclusionRegions ) { return fRunList[iRunCounter].fListOfExclusionRegions->getListOfExclusionRegions(); } vector< VListOfExclusionRegions* > a; return a; } /* initialize exclusion regions */ bool VAnaSumRunParameter::initializeExclusionRegions( unsigned int iRunCounter, VStarCatalogue* iCatalogue, double iSkyMapCentre_ra_deg, double iSkyMapCentre_dec_deg, double iCameraCentre_ra_deg, double iCameraCentre_dec_deg ) { if( iRunCounter >= fRunList.size() ) { return false; } if( !fRunList[iRunCounter].fListOfExclusionRegions ) { fRunList[iRunCounter].fListOfExclusionRegions = new VExclusionRegions(); } // copy stuff from general list if( fExclusionRegions ) { fRunList[iRunCounter].fListOfExclusionRegions->setStarCatalogue( fExclusionRegions->fStarCatalogue ); fRunList[iRunCounter].fListOfExclusionRegions->addBrightStarSettings( fExclusionRegions->getBrightStarSettings() ); for( unsigned int i = 0; i < fExclusionRegions->fExclusionRegions.size(); i++ ) { if( fExclusionRegions->fExclusionRegions[i] ) { fRunList[iRunCounter].fListOfExclusionRegions->addExclusionRegion( fExclusionRegions->fExclusionRegions[i]->fExcludeFromBackground_North, fExclusionRegions->fExclusionRegions[i]->fExcludeFromBackground_West, fExclusionRegions->fExclusionRegions[i]->fExcludeFromBackground_RAJ2000, fExclusionRegions->fExclusionRegions[i]->fExcludeFromBackground_DecJ2000, fExclusionRegions->fExclusionRegions[i]->fExcludeFromBackground_Radius1, fExclusionRegions->fExclusionRegions[i]->fExcludeFromBackground_Radius2, fExclusionRegions->fExclusionRegions[i]->fExcludeFromBackground_RotAngle, fExclusionRegions->fExclusionRegions[i]->fExcludeFromBackground_StarName ); } } // for consistency: make sure that that general list if correct (not used) fExclusionRegions->initializeExclusionRegions( iCatalogue, iSkyMapCentre_ra_deg, iSkyMapCentre_dec_deg, iCameraCentre_ra_deg, iCameraCentre_dec_deg ); } // initialize exclusion regions fRunList[iRunCounter].fListOfExclusionRegions->initializeExclusionRegions( iCatalogue, iSkyMapCentre_ra_deg, iSkyMapCentre_dec_deg, iCameraCentre_ra_deg, iCameraCentre_dec_deg ); // print list to screen fRunList[iRunCounter].fListOfExclusionRegions->printExclusionRegions(); return true; }
37.630908
455
0.521613
Eventdisplay
298719e599e3fed057231f0a70317f2e4eac46c7
9,745
cpp
C++
source/graphmanager.cpp
sydernee/TBC-Despeect
427ce8a7f985ff93fe2dfaf86d1288a272376376
[ "MIT" ]
1
2018-09-11T06:59:46.000Z
2018-09-11T06:59:46.000Z
source/graphmanager.cpp
TheBlackCat-SWE/Despeect
427ce8a7f985ff93fe2dfaf86d1288a272376376
[ "MIT" ]
3
2018-06-20T11:20:54.000Z
2018-06-24T13:51:21.000Z
source/graphmanager.cpp
sydernee/Despeect
427ce8a7f985ff93fe2dfaf86d1288a272376376
[ "MIT" ]
1
2018-09-18T14:51:25.000Z
2018-09-18T14:51:25.000Z
#include "graphmanager.hpp" #include <QFocusEvent> #include <QGraphicsItemGroup> #include <QGraphicsView> #include "arc.hpp" #include "DSItem.hpp" #include "node.hpp" #include "QInputDialog" #include "QLineEdit" #include <QMessageBox> GraphManager::GraphManager():Graph(new QGraphicsScene()),Relations(),RelationsModel(new QStandardItemModel()) { //when an item in the relations model get checked or unchecked graph manager will tell to the graph to hide or show the relation connect(RelationsModel,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(changeRelationVisibility(QStandardItem*))); connect(Graph,SIGNAL(selectionChanged()),this,SLOT(notifySelection())); Graph->setStickyFocus(1); } GraphManager::~GraphManager(){ clear(); delete Graph; delete RelationsModel; } void GraphManager::linkGraphModel(QGraphicsView* v){ v->setScene(Graph); } void GraphManager::linkRelationModel(QListView* v){ v->setModel(RelationsModel); } bool GraphManager::printRelation(const QString &id, const DSItem *SpeectNode, const QColor &Color) { //items that must have their relations check QVector<const DSItem*>ToBeChecked; //generate the relation QGraphicsRectItem* parentRelation=generateRelation(id,Color); //if no error in generation of relations if(parentRelation!=NULL){ //add to graph the relation Graph->addItem(parentRelation); //add to nodes that must be checked the head node ToBeChecked.push_back(SpeectNode); Node* t=new Node(SpeectNode->getSItem(),QString::fromStdString(SpeectNode->getPath()),id,QString::fromStdString(SpeectNode->getName()), Radius+10,Radius+20,Radius,Color,parentRelation, QMap<std::string,std::string> (SpeectNode->getFeatMap())); Printed.insert(QString::fromStdString(SpeectNode->getId()),t); FixHeadPosition(*t); //cicle till there is no more nodes to be checked while(!ToBeChecked.isEmpty()) { //fix the relations and print next and daughter checkRelations(ToBeChecked,id,Color,parentRelation); } } } #include "iostream" void GraphManager::clear() { //clear the vector and the Relations Relations.clear(); Printed.clear(); //clear the graph (delete all items inside) Graph->clear(); //clear the relationsModel and delete all item in it for(int i=0;i<RelationsModel->rowCount();++i) { delete RelationsModel->item(i); } RelationsModel->clear(); } QGraphicsRectItem *GraphManager::generateRelation(const QString &id, const QColor &color) { if(!Relations.contains(id)) { RelationsModel->appendRow(generateItem(id,color)); QGraphicsRectItem* t=new QGraphicsRectItem(); Relations.insert(id,t); return t; } return NULL; } QStandardItem *GraphManager::generateItem(const QString &id,const QColor&color) { QStandardItem* item=new QStandardItem(id); item->setBackground(QBrush(color)); item->setCheckable(true); item->setEditable(false); item->setCheckState(Qt::Checked); item->setSelectable(false); return item; } void GraphManager::PositionNode(Node &me) { while(me.collidingItems().size()>1){ me.setX(me.x()+(4*Radius)); } } void GraphManager::FixHeadPosition(Node &me) { while(me.collidingItems().size()>1){ me.setY(me.y()+(4*Radius)); } } void GraphManager::checkRelations(QVector<const DSItem*> &tbc, const QString& relation, const QColor& color, QGraphicsItem *parentRelation) { //take first item const DSItem* toBeChecked=tbc.takeFirst(); //get the items const DSItem* parent=toBeChecked->parent(); const DSItem* child=toBeChecked->child(); const DSItem* next=toBeChecked->next(); const DSItem* previous=toBeChecked->previous(); //find which node represent the items Node* me = Printed.value(QString::fromStdString(toBeChecked->getId())); //if find the node continue otherwise stop and fail if(me) { foreach(Node* node,Printed) { //If item is equal and have different relation draw a dashed line if(toBeChecked->IsEqual(node->getRelation().toStdString(),node->getId().toStdString())==2) { Line* a=new Line(Radius,QColor(qRgb(0,0,0)),1,NULL); connect(node,SIGNAL(notifyVisibilityChange(bool)),a,SLOT(changeVisibility(bool))); connect(node,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateEndPoint(QPointF))); connect(me,SIGNAL(notifyVisibilityChange(bool)),a,SLOT(changeVisibility(bool))); connect(me,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateStartPoint(QPointF))); Graph->addItem(a); a->UpdateStartPoint(me->pos()); a->UpdateEndPoint(node->pos()); } if(me->getRelation() == node->getRelation()) { //otherwise check if it's my father in the same relation if(parent && parent->getPath() == node->getPath().toStdString()) { Arc* a=new Arc(10,Radius,color,0,0,parentRelation,false); connect(node,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateEndPoint(QPointF))); connect(me,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateStartPoint(QPointF))); a->UpdateEndPoint(node->pos()); delete parent; parent = nullptr; } //and check if it's my prev in the same relations //not in exclusive else because don t know if it's impossible to happen in speect HRG if(previous && previous->getPath() == node->getPath().toStdString()) { Arc* a=new Arc(10,Radius,color,0,0,parentRelation,false); connect(node,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateEndPoint(QPointF))); connect(me,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateStartPoint(QPointF))); a->UpdateEndPoint(node->pos()); delete previous; previous = nullptr; } } } //if exist add the next nodes to the printed items and to the one that must be checked if(next) { tbc.push_front(next); Node* temp=new Node(next->getSItem(),QString::fromStdString(next->getPath()),relation,QString::fromStdString(next->getName()), me->pos().x()+4*Radius,me->pos().y(),Radius,color,parentRelation, QMap<std::string,std::string> (next->getFeatMap())); Printed.insert(QString::fromStdString(next->getId()), temp); temp->clearFocus(); Arc* a=new Arc(10,Radius,color,0,1,parentRelation,false); connect(temp,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateEndPoint(QPointF))); connect(me,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateStartPoint(QPointF))); PositionNode(*temp); a->UpdateEndPoint(temp->pos()); } //if exist add the daughter to the printed items and to the one that must be checked if(child) { tbc.push_front(child); Node* temp=new Node(child->getSItem(),QString::fromStdString(child->getPath()),relation,QString::fromStdString(child->getName()), me->pos().x(),me->pos().y()+4*Radius,Radius,color,parentRelation, QMap<std::string,std::string> (child->getFeatMap())); Printed.insert(QString::fromStdString(child->getId()),temp); temp->clearFocus(); Arc* a=new Arc(10,Radius,color,0,1,parentRelation,false); connect(temp,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateEndPoint(QPointF))); connect(me,SIGNAL(notifyPositionChange(QPointF)),a,SLOT(UpdateStartPoint(QPointF))); PositionNode(*temp); a->UpdateEndPoint(temp->pos()); } me->notifyPositionChange(me->pos()); } } void GraphManager::changeRelationVisibilityList(QStringList allKeys,QStringList checkedKeys) { // start with clean state: hide all the Relations for(int i = 0; i < allKeys.length();++i){ auto it = Relations.find(allKeys.at(i)); if(it != Relations.end()) { (*it)->setVisible(false); } } // show only checked relations // unchecked ones remain hidden for(int i = 0; i < checkedKeys.length();++i){ auto it = Relations.find(checkedKeys.at(i)); if(it != Relations.end()) (*it)->setVisible(true); } } void GraphManager::changeRelationVisibility(QStandardItem *key) { //find the item that represent the relation in the graph model and hide it auto it=Relations.find(key->text()); if(it!=Relations.end()) (*it)->setVisible(!(*it)->isVisible()); } void GraphManager::notifySelection() { QList<QGraphicsItem*> selected(Graph->selectedItems()); if(!selected.empty()) { auto myNode=std::find(Printed.begin(),Printed.end(),Graph->focusItem()); if(myNode!=Printed.end()) { focusSignal((*myNode)->getRelation(),(*myNode)->getPath(),true); } } else { Graph->clearFocus(); cleardetails(); } } void GraphManager::selectItem(const QString &relation, const QString &path) { foreach(Node* item,Printed) { if(item->getPath() == path && item->getRelation() == relation) { item->setFocus(); } } }
37.625483
143
0.622884
sydernee
298746ffd6b0caa17717543afceffb3733b2dcc3
20,373
cpp
C++
sources/ide/ide.cpp
dabroz/dablang
60c9b0310cee1488fbde1dbbc2fd411a9cc6dbce
[ "MIT" ]
1
2015-11-29T22:32:55.000Z
2015-11-29T22:32:55.000Z
sources/ide/ide.cpp
dabroz/dablang
60c9b0310cee1488fbde1dbbc2fd411a9cc6dbce
[ "MIT" ]
null
null
null
sources/ide/ide.cpp
dabroz/dablang
60c9b0310cee1488fbde1dbbc2fd411a9cc6dbce
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "resource.h" //#define WXUSINGDLL #define wxUSE_EXTENDED_RTTI 1 //qValue * compileText(std::map<qString, qString> & filemap); #ifdef _DEBUG #pragma comment(lib, "wxbase29ud.lib") #pragma comment(lib, "wxmsw29ud_core.lib") #pragma comment(lib, "wxmsw29ud_stc.lib") #pragma comment(lib, "wxtiffd.lib") #pragma comment(lib, "wxpngd.lib") #pragma comment(lib, "wxjpegd.lib") #pragma comment(lib, "wxscintillad.lib") #pragma comment(lib, "wxzlibd.lib") #else #pragma comment(lib, "wxbase29u.lib") #pragma comment(lib, "wxmsw29u_core.lib") #pragma comment(lib, "wxmsw29u_stc.lib") #pragma comment(lib, "wxtiff.lib") #pragma comment(lib, "wxpng.lib") #pragma comment(lib, "wxjpeg.lib") #pragma comment(lib, "wxscintilla.lib") #pragma comment(lib, "wxzlib.lib") #endif #pragma comment(lib, "comctl32.lib") #pragma comment(lib, "rpcrt4.lib") class MyApp : public wxApp { public: virtual bool OnInit(); }; bool is_whitespace(char c) { return (c==' '||c=='\n'||c=='\r'||c=='\t'); } qString trim(const qString & s) { int i1 = 0; int i2 = s.length(); while (i1 < s.length() && is_whitespace(s[i1])) i1++; while (i2 > 0 && is_whitespace(s[i2 - 1])) i2--; if (i2<=i1) return ""; return s.substr(i1,i2-i1); } void AddDef( std::map<qString, qString> & values, const qString & e ) { qString s = e.substr(e.find("define")+6); //replace_all(s, ";", ""); s = trim(s); int i2 = s.length(); while (!is_whitespace(s[i2-1])) i2--; qString key = trim(s.substr(0,i2)); qString val = trim(s.substr(i2)); values[key] = val; } void AddVar( std::map<qString, qString>& values, const qString & e ) { qString s = e; replace_all(s, "const uint32", ""); replace_all(s, "=", ""); replace_all(s, ";", ""); s = trim(s); int i2 = s.length(); while (!is_whitespace(s[i2-1])) i2--; qString key = trim(s.substr(0,i2)); qString val = trim(s.substr(i2)); values[key] = val; } qString XVal(const qString & vv) { unsigned v = 0; if ((vv.length()>=2) && vv[0]=='0' && (vv[1]=='x' ||vv[1]=='X') && (1 == sscanf(vv.c_str(), "%x", &v))) {} else if (1 == sscanf(vv.c_str(), "%d", &v)) {} else { v = 0; } char msg[128]; sprintf(msg, "0x%08x", v); return msg; } qString FixDefsText( const qString & s1 ) { qString s = s1 + "\n"; std::vector<qString> ss; qString l = ""; std::map<qString, qString> values; for (int i = 0; i < s.length(); i++) { if (s[i] == '\n') { qString ll = trim(l); qdtprintf("'%s' -> '%s'\n", l.c_str(),ll.c_str()); l = ""; if (ll.length()) ss.push_back(ll); } else l += s[i]; } for (int i = 0; i < ss.size(); i++) { const qString & e = ss[i]; if (e[0] == '#') AddDef(values, e); else AddVar(values, e); } int maxl = 0; for (std::map<qString, qString>::iterator it = values.begin(), end = values.end(); it != end; ++it) { maxl = std::max(maxl, (int)it->first.length()); } qString ret = ""; qString group = ""; for (std::map<qString, qString>::iterator it = values.begin(), end = values.end(); it != end; ++it) { qString agroup = ""; int iq = it->first.find('_'); if (iq != qString::npos) agroup = it->first.substr(0, iq); if (agroup != group) { if (ret.length()) ret += "\n"; group = agroup; } ret += "const uint32 " + it->first + qString(maxl-it->first.length(), ' ') + " = " + XVal(it->second) + ";\n"; } return ret; } const int STYLE_ANN = 50; enum { ID_MAINWIN_QUIT = wxID_HIGHEST + 1, ID_TOOLBAR, ID_RUN, ID_RUNINTERNAL, ID_PAUSE, ID_STOP, ID_COMPILE, ID_ERRORS, ID_SAVE, ID_DEFS, ID_MENURUN, ID_MENUUPDATE }; DABCORE_API void setFile(const char *name, const qString&body); bool runCode(qValue * prog) { // PLACEHOLDER return false; } void SpawnProcek(qString & ss) { // PLACEHOLDER } qValue * compileText(std::map<qString, qString> & filemap) { // PLACEHOLDER return 0; } void StopProcIfRunning() { // PLACEHOLDER } void turboRun( std::string & ll ) { SpawnProcek(ll); } bool dablangIsProcessRunning() { // PLACEHOLDER return false; } void SendUpdatesToProcess(const char *txt) { // PLACEHOLDER } bool subupdatecompiled(const char *txt, qValue * last) { // PLACEHOLDER return false; } // TEMPORARY //extern std::vector<qError> compileErrors; //std::vector<qError> compileErrors; extern std::map<qString, std::vector<qneu_Function *>> functions; std::map<qString, std::vector<qneu_Function *>> functions; wxBitmap* GetBitmapFromMemory(const char* t_data, const DWORD t_size, int type = wxBITMAP_TYPE_PNG) { wxMemoryInputStream a_is(t_data, t_size); return new wxBitmap(wxImage(a_is, type, -1), -1); } bool LoadDataFromResource(char*& t_data, DWORD& t_dataSize, int resID, LPWSTR resType = RT_RCDATA) { bool r_result = false; HGLOBAL a_resHandle = 0; HRSRC a_resource; a_resource = FindResource(0, MAKEINTRESOURCE(resID), resType); if (0 != a_resource) { a_resHandle = LoadResource(NULL, a_resource); if (0 != a_resHandle) { t_data = (char*)LockResource(a_resHandle); t_dataSize = SizeofResource(NULL, a_resource); r_result = true; } } return r_result; } wxBitmap* CreateBitmapFromPngResource(int resID) { char* a_data = 0; DWORD a_dataSize = 0; if (LoadDataFromResource(a_data, a_dataSize, resID)) { return GetBitmapFromMemory(a_data, a_dataSize); } return 0; } class MyFrame : public wxFrame { public: void OnQuit (wxCommandEvent& Event); wxToolBar * toolBar; wxListCtrl * files; wxNotebook * editors; wxNotebook * _tools; wxTextCtrl * _output; wxListCtrl * _errors; int _toolbar_currentX; std::vector<wxStyledTextCtrl *> _codes; std::vector<wxString> _filenames; std::vector<int> _dirtyflag; qValue * lastCompile; std::string _lastCompileText; void OnMenuRunUpdate(wxCommandEvent& Event) { if (!dablangIsProcessRunning()) return; int s = editors->GetSelection(); if (subupdatecompiled(_codes[s]->GetText().c_str().AsChar(), lastCompile)) { SendUpdatesToProcess(_codes[s]->GetText().c_str().AsChar()); } else ShowErrors(); } bool Compile() { lastCompile = 0; std::map<qString, qString> files; _lastCompileText = ""; for (int i = 0; i < _filenames.size(); i++) { qString s = _codes[i]->GetText().c_str().AsChar(); _lastCompileText += s+"\n\n"; files[_filenames[i].c_str().AsChar()] = _codes[i]->GetText().c_str().AsChar(); } //lastCompile = dab_Module * mod = dab_CompileFiles(files, 0); _compileErrors = mod->_errors; bool bb = ShowErrors(); lastCompile = 0; if (!lastCompile || bb) return false; return true; } bool Run(bool internal) { if (internal) return runCode(lastCompile); turboRun(_lastCompileText); return true; } std::vector<qError> _compileErrors; bool ShowErrors() { bool ret = false; _errors->DeleteAllItems(); for (int i = 0; i < _codes.size(); i++) _codes[i]->AnnotationClearAll(); std::map<qString, std::map<int, qString> > annotations; std::map<qString, std::map<int, qString> > annotationsStyle; std::sort(_compileErrors.begin(), _compileErrors.end()); for (int i = 0; i < _compileErrors.size(); i++) { qError & qe = _compileErrors[i]; _errors->InsertItem(i, "", qe.error?0:1); if (qe.error) ret = true; wxString ss = wxString::Format("%s C%04d: %s", qe.error?"error":"warning", qe.num, qe.desc.c_str()); _errors->SetItem(i, 1, wxString::Format(wxT("%d"),i+1)); // num _errors->SetItem(i, 2, ss.c_str()); // desc _errors->SetItem(i, 3, qe.file.c_str()); // file _errors->SetItem(i, 4, wxString::Format(wxT("%d"),qe.line)); // line _errors->SetItem(i, 5, wxString::Format(wxT("%d"),qe.start)); // col int L = qe.line - 1; qString ssR = annotations[qe.file][L]; bool adden= false; if (ssR != "") {ssR += "\n";adden=true;} ssR += ss.c_str().AsChar(); annotations[qe.file][L] = ssR; char zz = qe.error?50:51; for (int q = 0; q < ss.length()+adden?1:0; q++) { annotationsStyle[qe.file][L] += zz; } } for (std::map<qString, std::map<int, qString> > ::iterator it = annotations.begin(), e = annotations.end(); it != e; ++it) { const qString & file = it->first; for (std::map<int, qString>::iterator it2 = it->second.begin(), end2 = it->second.end(); it2 != end2; ++it2) { int line = it2->first; qString & text = it2->second; qString & styles = annotationsStyle[file][line]; wxStyledTextCtrl * ed = EditorForCompiled(file); //ed->AnnotationSetStyle(it2->first, STYLE_ANN); if (!ed) continue; if (line<0) line=0; ed->AnnotationSetText(line, text.c_str()); ed->AnnotationSetStyles(line, styles.c_str()); } } for (int i = 0; i < _codes.size(); i++) { _codes[i]->AnnotationSetVisible(2); _codes[i]->Refresh(); } return ret; } wxStyledTextCtrl * EditorForCompiled(const qString & f) { for (int i = 0; i < _filenames.size(); i++) { if (_filenames[i] == f) return _codes[i]; } return 0; } void OnErrorClick(wxListEvent & event) { qError & e = _compileErrors[event.GetIndex()]; int line = e.line - 1; for (int i = 0; i < _filenames.size(); i++) { if (_filenames[i] == e.file) { editors->SetSelection(i); } } if (line >= 0) EditorForCompiled(e.file)->ScrollToLine(line); } wxFont & Courier() { static wxFont * f = 0; if (!f) { HFONT ff = CreateFontA(16, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH | FF_DONTCARE, (char*)"Courier New"); wxNativeFontInfo nfi; nfi.SetPointSize(10); nfi.SetFaceName("Courier New"); f = new wxFont(nfi, ff); } return *f; } void UpdateDirtyMarkers() { for (int i = 0; i < _filenames.size(); i++) { editors->SetPageText(i, ((_dirtyflag[i])?("* "):("")) + _filenames[i]); } } void onKeyPress(wxStyledTextEvent& evt) { wxStyledTextCtrl * ed = dynamic_cast<wxStyledTextCtrl*>(evt.GetEventObject()); qString sss = evt.GetText().c_str().AsChar(); int kk = evt.GetKey(); if (kk == '(') { int current = ed->GetCurrentLine(); wxString line = ed->GetLine(current); int pos = ed->GetCurrentPos() - ed->PositionFromLine(current); int startword = pos - 1; while (startword > 0 && isalnum(line[startword - 1])) startword--; qString word = line.substr(startword,pos-startword-1).c_str().AsChar(); if (functions.count(word)) { qString ss; std::vector<qneu_Function *> & funs = functions[word]; for (int i = 0; i < funs.size(); i++) { if (i) ss+="\n"; ss += funs[i]->returntype->name() + " "; ss += funs[i]->name; ss += "("; for (int j = 0; j < funs[i]->args.size(); j++) { if (j) ss += ", "; ss += funs[i]->args[j].type->name() + " "; ss += funs[i]->args[j].name; } ss += ")"; } ed->CallTipShow(ed->GetCurrentPos(), ss.c_str()); } } if (kk == ')') { ed->CallTipCancel(); } if (kk == '}') { int curLine = ed->GetCurrentLine(); ed->SetLineIndentation(curLine, std::max(0, ed->GetLineIndentation(curLine) - 4)); } if (kk == '\r' || kk == '\n') { int curLine = ed->GetCurrentLine(); int lineLength = ed->GetLineLength(curLine); if (curLine > 0 && lineLength <= 2) { int prevLineLength = ed->GetLineLength(curLine - 1); wxString line = ed->GetLine(curLine - 1); wxString prepend; qString qline = line.c_str().AsChar(); for (int i = 0; i < line.length(); i++) { if (line[i] == ' ' || line[i] == '\t') prepend += line[i]; else break; } if (trim(qline) == "{") prepend += "\t"; ed->ReplaceSelection(prepend); } } } void onTextChange(wxStyledTextEvent& evt) { wxStyledTextCtrl * ed = dynamic_cast<wxStyledTextCtrl*>(evt.GetEventObject()); int f = evt.GetModificationType(); if (f & (wxSTC_MOD_INSERTTEXT | wxSTC_MOD_DELETETEXT | wxSTC_MOD_CHANGEFOLD)) { for (int i = 0; i < _filenames.size(); i++) { if (_codes[i] == ed) { _dirtyflag[i] = true; } } UpdateDirtyMarkers(); } } void AddFile(wxString filename) { wxString ff = filename.substr(2); FILE * f = fopen(filename.c_str(), "rb"); if (!f) *(int*)0 = 0; fseek(f, 0, SEEK_END); int l = ftell(f); fseek(f, 0, SEEK_SET); char * data = new char[l]; fread(data, 1, l, f); fclose(f); wxString txt(data, l); delete [] data; files->InsertItem(_codes.size(), ff); wxStyledTextCtrl * ed = new wxStyledTextCtrl (editors); _codes.push_back(ed); _filenames.push_back(ff); _dirtyflag.push_back(0); ed->AppendText(txt); editors->AddPage(ed, ff); ed->SetLexer(wxSTC_LEX_CPP); wxFont ffq = Courier(); int q = ffq.GetPointSize(); for (int Nr = 0; Nr < wxSTC_STYLE_LASTPREDEFINED; Nr++) { ed->StyleSetFont (Nr, ffq); } ed->StyleSetFont(STYLE_ANN, ffq); ed->StyleSetBackground(STYLE_ANN, wxColour(0x9999FF)); ed->StyleSetFont(STYLE_ANN + 1, ffq); ed->StyleSetBackground(STYLE_ANN + 1, wxColour(0xC0FFFF)); //ed->Indica ed->Connect(wxEVT_STC_MODIFIED, wxStyledTextEventHandler(MyFrame::onTextChange), NULL, this); ed->Connect(wxEVT_STC_CHARADDED, wxStyledTextEventHandler(MyFrame::onKeyPress), NULL, this); wxChar* MyKeyWords = _T("for while if return struct int void float float4 cstring else break true false double int8 int16 int32 int64 uint8 uint16 uint32 uint64 byte typedef const"); ed->StyleSetForeground(wxSTC_C_COMMENT, wxColor(0,100,0)); ed->StyleSetForeground(wxSTC_C_COMMENTLINE, wxColor(0,125,0)); ed->StyleSetForeground(wxSTC_C_STRING, wxColor(128,0,0)); ed->StyleSetForeground(wxSTC_C_WORD, wxColor(0,0,200)); ed->SetKeyWords(0,MyKeyWords); ed->SetTabWidth (4); ed->SetUseTabs (false); ed->SetTabIndents (true); ed->SetBackSpaceUnIndents (true); ed->SetIndent (4); ed->SetMarginType(0, wxSTC_MARGIN_NUMBER); ed->SetMarginWidth(0, ed->TextWidth(wxSTC_STYLE_LINENUMBER, "_99999")); //ed->OnChar } void ReloadFilesInProject() { _codes.clear(); editors->DeleteAllPages(); files->DeleteAllItems(); wxString f = wxFindFirstFile("./*.dab"); while ( !f.empty() ) { AddFile(f); f = wxFindNextFile(); } } void AddToolbarItem(int id, const char * name, int imgID) { wxBitmap * bmp = CreateBitmapFromPngResource(imgID); toolBar->AddTool(id, bmp?*bmp:wxNullBitmap, wxNullBitmap, false, _toolbar_currentX, -1, (wxObject *) NULL, name); _toolbar_currentX += 16 + 5; delete bmp; } MyFrame() : wxFrame (NULL, -1, wxT("Dablang IDE"), wxPoint(300,100), wxSize(1100,700)) { wxMenu* fileMenu = new wxMenu; wxMenuBar* menuBar = new wxMenuBar; fileMenu->Append(ID_SAVE, wxT("Save\tCtrl-S")); fileMenu->Append(ID_MENURUN, wxT("Run\tF5")); fileMenu->Append(ID_MENUUPDATE, wxT("Update this module\tF8")); fileMenu->Append (ID_MAINWIN_QUIT, wxT("&Quit")); menuBar->Append (fileMenu, wxT("&File")); SetMenuBar (menuBar); CreateStatusBar (2); SetStatusText (wxT("Hello!")); CreateToolBar(wxNO_BORDER|wxHORIZONTAL|wxTB_FLAT, ID_TOOLBAR); GetToolBar()->SetMargins( 2, 2 ); wxBitmap* toolBarBitmaps[9]; toolBar = GetToolBar(); wxInitAllImageHandlers(); _toolbar_currentX = 5; AddToolbarItem(wxID_NEW, "New file", IDX_NEW); AddToolbarItem(wxID_OPEN, "Open file", IDX_OPEN); AddToolbarItem(wxID_SAVE, "Save file", IDX_SAVE); toolBar->AddSeparator(); AddToolbarItem(wxID_CUT, "Cut", IDX_CUT); AddToolbarItem(wxID_COPY, "Copy", IDX_COPY); AddToolbarItem(wxID_PASTE, "Paste", IDX_PASTE); toolBar->AddSeparator(); AddToolbarItem(ID_DEFS, "Fix definitions", IDX_DEFS); toolBar->AddSeparator(); AddToolbarItem(ID_COMPILE, "Compile", IDX_COMPILE); AddToolbarItem(ID_RUN, "Run", IDX_PLAY); AddToolbarItem(ID_RUNINTERNAL, "Run internally", IDX_PLAY_INTERNAL); AddToolbarItem(ID_PAUSE, "Pause", IDX_PAUSE); AddToolbarItem(ID_STOP, "Stop", IDX_STOP); toolBar->Realize(); wxSplitterWindow * _splitglobal = new wxSplitterWindow(this, -1); wxSplitterWindow * _split = new wxSplitterWindow(_splitglobal, -1); editors = new wxNotebook(_split, wxID_ANY, wxDefaultPosition, wxDefaultSize); files = new wxListCtrl(_split, wxID_ANY, wxDefaultPosition, wxDefaultSize, /*wxLC_HRULES|wxLC_VRULES|*/wxLC_REPORT); files->InsertColumn(0, "File"); _split->SplitVertically(editors, files); _tools = new wxNotebook(_splitglobal, wxID_ANY, wxDefaultPosition, wxDefaultSize); _errors = new wxListCtrl(_tools, ID_ERRORS, wxDefaultPosition, wxDefaultSize, /*wxLC_HRULES|wxLC_VRULES|*/wxLC_REPORT|wxLC_SINGLE_SEL); _errors->InsertColumn(0, ""); _errors->InsertColumn(1, ""); _errors->InsertColumn(2, "Description"); _errors->InsertColumn(3, "File"); _errors->InsertColumn(4, "Line"); _errors->InsertColumn(5, "Column"); wxImageList * il = new wxImageList(16, 16); wxBitmap * b1 = CreateBitmapFromPngResource(IDX_IC_ERROR); wxBitmap * b2 = CreateBitmapFromPngResource(IDX_IC_WARNING); il->Add(*b1); il->Add(*b2); delete b1; delete b2; _errors->AssignImageList(il, wxIMAGE_LIST_SMALL); _errors->SetColumnWidth(0, 25); _errors->SetColumnWidth(1, 35); _errors->SetColumnWidth(2, 600); _errors->SetColumnWidth(3, 150); _tools->AddPage(_errors, "Error List"); _output = new wxTextCtrl(_tools, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_PROCESS_ENTER|wxTE_PROCESS_TAB|wxTE_RICH); _output->SetFont(Courier()); _tools->AddPage(_output, "Output"); _splitglobal->SplitHorizontally(_split, _tools); ReloadFilesInProject(); _splitglobal->SetSashPosition(400); _splitglobal->SetSashGravity(1); _split->SetSashPosition(-200); _split->SetMinimumPaneSize(200); _split->SetSashGravity(1); _split->UpdateSize(); _split->SetSashPosition(-200); _split->UpdateSize(); } void updateOutput(const qString & s) { _output->AppendText(s.c_str()); } void clearOutput() { _output->Clear(); } void OnToolCompile(wxCommandEvent& event) { if (Compile()) { SetStatusText("Build successful!"); } else { SetStatusText("Build failed!"); } } void OnToolRunInternal(wxCommandEvent& event) { Subrun(true); } void OnToolRun(wxCommandEvent& event) { Subrun(false); } void Subrun(bool internal) { bool dablangIsProcessRunning(); if (dablangIsProcessRunning()) { if (wxNO == wxMessageBox("Application is already running. Do you want to restart it?", "Dablang IDE", wxYES_NO | wxCENTRE | wxICON_EXCLAMATION)) return; else { StopProcIfRunning(); } } if (Compile()) { clearOutput(); Run(internal); } } void OnMenuRun(wxCommandEvent& Event) { Subrun(false); } void OnMenuSave (wxCommandEvent& Event) { OnToolSave(wxCommandEvent()); } void OnToolStop(wxCommandEvent& event) { void StopProcIfRunning(); StopProcIfRunning(); } void OnToolDefs(wxCommandEvent& event) { int s = editors->GetSelection(); _codes[s]->SetText(FixDefsText(_codes[s]->GetText().c_str().AsChar()).c_str()); } void OnToolSave(wxCommandEvent& event) { int s = editors->GetSelection(); wxString body = _codes[s]->GetText(); wxString fn = _filenames[s]; _dirtyflag[s] = 0; UpdateDirtyMarkers(); setFile(fn.c_str().AsChar(), body.c_str().AsChar()); } DECLARE_EVENT_TABLE() }; void MyFrame::OnQuit (wxCommandEvent& WXUNUSED(Event)) { Close (true); } IMPLEMENT_APP_NO_MAIN(MyApp) BEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(ID_SAVE, MyFrame::OnMenuSave) EVT_MENU(ID_MENURUN, MyFrame::OnMenuRun) EVT_MENU(ID_MENUUPDATE, MyFrame::OnMenuRunUpdate) EVT_MENU(ID_MAINWIN_QUIT, MyFrame::OnQuit) EVT_TOOL(ID_COMPILE, MyFrame::OnToolCompile) EVT_TOOL(ID_RUN, MyFrame::OnToolRun) EVT_TOOL(ID_DEFS, MyFrame::OnToolDefs) EVT_TOOL(ID_RUNINTERNAL, MyFrame::OnToolRunInternal) EVT_TOOL(ID_STOP, MyFrame::OnToolStop) EVT_TOOL(wxID_SAVE, MyFrame::OnToolSave) EVT_LIST_ITEM_ACTIVATED(ID_ERRORS, MyFrame::OnErrorClick) END_EVENT_TABLE() MyFrame * frame = 0; void clearOutput() { frame->clearOutput(); } void updateOutput(const qString & s) { if (frame) frame->updateOutput(s); } bool MyApp::OnInit() { frame = new MyFrame; frame->Show(); _CrtSetDbgFlag (0); return true; } void goIDE() { wxEntry(0,0); } int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { goIDE(); return 0; }
23.471198
164
0.652874
dabroz
298906c56ba245801397465a490017c95fa3d8d7
8,375
cpp
C++
Tests/AK/TestTypeTraits.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
650
2019-03-01T13:33:03.000Z
2022-03-15T09:26:44.000Z
Tests/AK/TestTypeTraits.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
51
2019-04-03T08:32:38.000Z
2019-05-19T13:44:28.000Z
Tests/AK/TestTypeTraits.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
33
2019-03-26T05:47:59.000Z
2021-11-22T18:18:45.000Z
/* * Copyright (c) 2020-2021, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibTest/TestCase.h> #include <AK/StdLibExtras.h> #include <AK/TypeList.h> #define STATIC_EXPECT_EQ(lhs, rhs) \ static_assert(IsSame<lhs, rhs>, ""); #define STATIC_EXPECT_FALSE(Expression) \ static_assert(!Expression, ""); #define STATIC_EXPECT_TRUE(Expression) \ static_assert(Expression, ""); #define EXPECT_TRAIT_TRUE(trait, ...) \ for_each_type<TypeList<__VA_ARGS__>>([]<typename T>(TypeWrapper<T>) { \ STATIC_EXPECT_TRUE(trait<T>); \ }) #define EXPECT_TRAIT_FALSE(trait, ...) \ for_each_type<TypeList<__VA_ARGS__>>([]<typename T>(TypeWrapper<T>) { \ STATIC_EXPECT_FALSE(trait<T>); \ }) #define EXPECT_EQ_WITH_TRAIT(trait, ListA, ListB) \ for_each_type_zipped<ListA, ListB>([]<typename A, typename B>(TypeWrapper<A>, TypeWrapper<B>) { \ STATIC_EXPECT_EQ(trait<A>, B); \ }) #define EXPECT_VARIADIC_TRAIT_TRUE(trait, ...) \ static_assert(trait<__VA_ARGS__>) #define EXPECT_VARIADIC_TRAIT_FALSE(trait, ...) \ static_assert(!trait<__VA_ARGS__>) struct Empty { }; enum class Enummer : u8 { Dummmy, }; TEST_CASE(FundamentalTypeClassification) { EXPECT_TRAIT_TRUE(IsVoid, void); EXPECT_TRAIT_FALSE(IsVoid, int, Empty, std::nullptr_t); EXPECT_TRAIT_TRUE(IsNullPointer, std::nullptr_t); EXPECT_TRAIT_FALSE(IsNullPointer, void, int, Empty, decltype(0)); EXPECT_TRAIT_TRUE(IsFloatingPoint, float, double, long double); EXPECT_TRAIT_FALSE(IsFloatingPoint, int, Empty, std::nullptr_t, void); EXPECT_TRAIT_TRUE(IsArithmetic, float, double, long double, bool, size_t); EXPECT_TRAIT_TRUE(IsArithmetic, char, signed char, unsigned char, char8_t, char16_t, char32_t); EXPECT_TRAIT_TRUE(IsArithmetic, short, int, long, long long); EXPECT_TRAIT_TRUE(IsArithmetic, unsigned short, unsigned int, unsigned long, unsigned long long); EXPECT_TRAIT_FALSE(IsArithmetic, void, std::nullptr_t, Empty); EXPECT_TRAIT_TRUE(IsFundamental, void, std::nullptr_t); EXPECT_TRAIT_TRUE(IsFundamental, float, double, long double, bool, size_t); EXPECT_TRAIT_TRUE(IsFundamental, char, signed char, unsigned char, char8_t, char16_t, char32_t); EXPECT_TRAIT_TRUE(IsFundamental, short, int, long, long long); EXPECT_TRAIT_TRUE(IsFundamental, unsigned short, unsigned int, unsigned long, unsigned long long); EXPECT_TRAIT_FALSE(IsFundamental, Empty, int*, int&); EXPECT_TRAIT_FALSE(IsSigned, unsigned); EXPECT_TRAIT_FALSE(IsSigned, unsigned short); EXPECT_TRAIT_FALSE(IsSigned, unsigned char); EXPECT_TRAIT_FALSE(IsSigned, unsigned long); EXPECT_TRAIT_TRUE(IsSigned, int); EXPECT_TRAIT_TRUE(IsSigned, short); EXPECT_TRAIT_TRUE(IsSigned, long); EXPECT_TRAIT_TRUE(IsUnsigned, unsigned); EXPECT_TRAIT_TRUE(IsUnsigned, unsigned short); EXPECT_TRAIT_TRUE(IsUnsigned, unsigned char); EXPECT_TRAIT_TRUE(IsUnsigned, unsigned long); EXPECT_TRAIT_FALSE(IsUnsigned, int); EXPECT_TRAIT_FALSE(IsUnsigned, short); EXPECT_TRAIT_FALSE(IsUnsigned, long); EXPECT_TRAIT_TRUE(IsEnum, Enummer); EXPECT_TRAIT_FALSE(IsEnum, Empty); EXPECT_TRAIT_FALSE(IsEnum, int); EXPECT_TRAIT_FALSE(IsEnum, void); EXPECT_TRAIT_FALSE(IsEnum, std::nullptr_t); } TEST_CASE(AddConst) { // clang-format off using NoConstList = TypeList<int, const int, Empty, const Empty>; using YesConstList = TypeList<const int, const int, const Empty, const Empty>; // clang-format on EXPECT_EQ_WITH_TRAIT(AddConst, NoConstList, YesConstList); } TEST_CASE(UnderlyingType) { using Type = UnderlyingType<Enummer>; STATIC_EXPECT_EQ(Type, u8); } TEST_CASE(RemoveCVReference) { using TestTypeList = TypeList<int, int&, int const&, int volatile&, int const volatile&, int&&, int const&&, int volatile&&, int const volatile&&>; using ResultTypeList = TypeList<int, int, int, int, int, int, int, int, int>; EXPECT_EQ_WITH_TRAIT(RemoveCVReference, TestTypeList, ResultTypeList); } TEST_CASE(AddReference) { STATIC_EXPECT_EQ(AddLvalueReference<int>, int&); STATIC_EXPECT_EQ(AddLvalueReference<int&>, int&); STATIC_EXPECT_EQ(AddLvalueReference<int&&>, int&); STATIC_EXPECT_EQ(AddRvalueReference<int>, int&&); STATIC_EXPECT_EQ(AddRvalueReference<int&>, int&); STATIC_EXPECT_EQ(AddRvalueReference<int&&>, int&&); STATIC_EXPECT_EQ(AddLvalueReference<void>, void); } TEST_CASE(IsConvertible) { struct A { }; struct B { B(A); }; struct C { A a; operator A() { return a; }; }; struct D { }; EXPECT_VARIADIC_TRAIT_TRUE(IsConvertible, A, B); EXPECT_VARIADIC_TRAIT_FALSE(IsConvertible, B, A); EXPECT_VARIADIC_TRAIT_TRUE(IsConvertible, C, A); EXPECT_VARIADIC_TRAIT_FALSE(IsConvertible, A, C); EXPECT_VARIADIC_TRAIT_FALSE(IsConvertible, D, A); EXPECT_VARIADIC_TRAIT_FALSE(IsConvertible, A, D); } TEST_CASE(IsAssignable) { EXPECT_VARIADIC_TRAIT_FALSE(IsAssignable, int, int); EXPECT_VARIADIC_TRAIT_TRUE(IsAssignable, int&, int); EXPECT_VARIADIC_TRAIT_FALSE(IsAssignable, int, void); struct A { }; EXPECT_TRAIT_TRUE(IsCopyAssignable, A); EXPECT_TRAIT_TRUE(IsTriviallyCopyAssignable, A); EXPECT_TRAIT_TRUE(IsMoveAssignable, A); EXPECT_TRAIT_TRUE(IsTriviallyMoveAssignable, A); struct B { B& operator=(const B&) { return *this; } B& operator=(B&&) { return *this; } }; EXPECT_TRAIT_TRUE(IsCopyAssignable, B); EXPECT_TRAIT_FALSE(IsTriviallyCopyAssignable, B); EXPECT_TRAIT_TRUE(IsMoveAssignable, B); EXPECT_TRAIT_FALSE(IsTriviallyMoveAssignable, B); struct C { C& operator=(const C&) = delete; C& operator=(C&&) = delete; }; EXPECT_TRAIT_FALSE(IsCopyAssignable, C); EXPECT_TRAIT_FALSE(IsTriviallyCopyAssignable, C); EXPECT_TRAIT_FALSE(IsMoveAssignable, C); EXPECT_TRAIT_FALSE(IsTriviallyMoveAssignable, C); } TEST_CASE(IsConstructible) { struct A { }; EXPECT_TRAIT_TRUE(IsCopyConstructible, A); EXPECT_TRAIT_TRUE(IsTriviallyCopyConstructible, A); EXPECT_TRAIT_TRUE(IsMoveConstructible, A); EXPECT_TRAIT_TRUE(IsTriviallyMoveConstructible, A); struct B { B(const B&) { } B(B&&) { } }; EXPECT_TRAIT_TRUE(IsCopyConstructible, B); EXPECT_TRAIT_FALSE(IsTriviallyCopyConstructible, B); EXPECT_TRAIT_TRUE(IsMoveConstructible, B); EXPECT_TRAIT_FALSE(IsTriviallyMoveConstructible, B); struct C { C(const C&) = delete; C(C&&) = delete; }; EXPECT_TRAIT_FALSE(IsCopyConstructible, C); EXPECT_TRAIT_FALSE(IsTriviallyCopyConstructible, C); EXPECT_TRAIT_FALSE(IsMoveConstructible, C); EXPECT_TRAIT_FALSE(IsTriviallyMoveConstructible, C); struct D { D(int); }; EXPECT_VARIADIC_TRAIT_TRUE(IsConstructible, D, int); EXPECT_VARIADIC_TRAIT_TRUE(IsConstructible, D, char); EXPECT_VARIADIC_TRAIT_FALSE(IsConstructible, D, const char*); EXPECT_VARIADIC_TRAIT_FALSE(IsConstructible, D, void); } TEST_CASE(IsDestructible) { struct A { }; EXPECT_TRAIT_TRUE(IsDestructible, A); EXPECT_TRAIT_TRUE(IsTriviallyDestructible, A); struct B { ~B() { } }; EXPECT_TRAIT_TRUE(IsDestructible, B); EXPECT_TRAIT_FALSE(IsTriviallyDestructible, B); struct C { ~C() = delete; }; EXPECT_TRAIT_FALSE(IsDestructible, C); EXPECT_TRAIT_FALSE(IsTriviallyDestructible, C); } TEST_CASE(CommonType) { using TCommon0 = CommonType<int, float, char>; EXPECT_VARIADIC_TRAIT_TRUE(IsSame, TCommon0, float); using TCommon1 = CommonType<int, int, int, char>; EXPECT_VARIADIC_TRAIT_TRUE(IsSame, TCommon1, int); struct Foo { }; using TCommon2 = CommonType<Foo, Foo, Foo>; EXPECT_VARIADIC_TRAIT_TRUE(IsSame, TCommon2, Foo); struct Bar { operator Foo(); }; using TCommon3 = CommonType<Bar, Foo, Bar>; EXPECT_VARIADIC_TRAIT_TRUE(IsSame, TCommon3, Foo); }
31.133829
151
0.684776
r00ster91
298ef4a7eeff743181fdbd8991b1ad78983f2200
1,751
cpp
C++
Gimbal/srml/shit_mountain.cpp
scutrobotlab/RM2021_Hero
c36c9d039100cb7a87a5177ca6b20f8f3e3c0daa
[ "Apache-2.0" ]
3
2021-08-25T07:10:48.000Z
2021-12-14T12:23:58.000Z
Gimbal/srml/shit_mountain.cpp
scutrobotlab/RM2021_Hero
c36c9d039100cb7a87a5177ca6b20f8f3e3c0daa
[ "Apache-2.0" ]
null
null
null
Gimbal/srml/shit_mountain.cpp
scutrobotlab/RM2021_Hero
c36c9d039100cb7a87a5177ca6b20f8f3e3c0daa
[ "Apache-2.0" ]
2
2022-01-20T09:43:38.000Z
2022-03-06T01:37:36.000Z
/** ****************************************************************************** * Copyright (c) 2019 - ~, SCUT-RobotLab Development Team * @file shit_mountain.cpp * @author M3chD09 rinngo17@foxmail.com * @brief Library full of shit. * @date 2021-04-05 * @version 1.0 * ****************************************************************************** * @attention * * if you had modified this file, please make sure your code does not have many * bugs, update the version Number, write dowm your name and the date, the most * important is make sure the users will have clear and definite understanding * through your new brief. * * <h2><center>&copy; Copyright (c) 2019 - ~, SCUT-RobotLab Development Team. * All rights reserved.</center></h2> ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "shit_mountain.h" using namespace shit; /* Private define ------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private type --------------------------------------------------------------*/ /* Private function declarations ---------------------------------------------*/ /* Function prototypes -------------------------------------------------------*/ /** * @brief Get the number of the specified input port pin * @param GPIO_Pin specifies the port number to get. * This parameter can be GPIO_PIN_x where x can be (0..15). * @retval The x of GPIO_PIN_x */ uint16_t shit::get_gpio_pin_num(uint16_t GPIO_Pin) { uint16_t x = 0; while (GPIO_Pin >>= 1)x++; return x; }
38.911111
80
0.446031
scutrobotlab
298f7a46735c087e379d14fa6a608e38c7db0a34
2,676
cpp
C++
src/modules/cpu.cpp
hypergig/Waybar
3945c7766891148c339a77118b7c1dbe709af407
[ "MIT" ]
1
2021-10-03T19:46:42.000Z
2021-10-03T19:46:42.000Z
src/modules/cpu.cpp
hypergig/Waybar
3945c7766891148c339a77118b7c1dbe709af407
[ "MIT" ]
1
2019-08-29T08:39:54.000Z
2019-08-29T08:39:54.000Z
src/modules/cpu.cpp
hypergig/Waybar
3945c7766891148c339a77118b7c1dbe709af407
[ "MIT" ]
1
2020-01-18T22:09:36.000Z
2020-01-18T22:09:36.000Z
#include "modules/cpu.hpp" #include <numeric> waybar::modules::Cpu::Cpu(const std::string& id, const Json::Value& config) : ALabel(config, "cpu", id, "{usage}%", 10) { thread_ = [this] { dp.emit(); thread_.sleep_for(interval_); }; } auto waybar::modules::Cpu::update() -> void { // TODO: as creating dynamic fmt::arg arrays is buggy we have to calc both auto cpu_load = getCpuLoad(); auto [cpu_usage, tooltip] = getCpuUsage(); if (tooltipEnabled()) { label_.set_tooltip_text(tooltip); } label_.set_markup(fmt::format(format_, fmt::arg("load", cpu_load), fmt::arg("usage", cpu_usage))); getState(cpu_usage); } uint16_t waybar::modules::Cpu::getCpuLoad() { struct sysinfo info = {0}; if (sysinfo(&info) == 0) { float f_load = 1.F / (1U << SI_LOAD_SHIFT); uint16_t load = info.loads[0] * f_load * 100 / get_nprocs(); return load; } throw std::runtime_error("Can't get Cpu load"); } std::tuple<uint16_t, std::string> waybar::modules::Cpu::getCpuUsage() { if (prev_times_.empty()) { prev_times_ = parseCpuinfo(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } std::vector<std::tuple<size_t, size_t>> curr_times = parseCpuinfo(); std::string tooltip; uint16_t usage = 0; for (size_t i = 0; i < curr_times.size(); ++i) { auto [curr_idle, curr_total] = curr_times[i]; auto [prev_idle, prev_total] = prev_times_[i]; const float delta_idle = curr_idle - prev_idle; const float delta_total = curr_total - prev_total; uint16_t tmp = 100 * (1 - delta_idle / delta_total); if (i == 0) { usage = tmp; tooltip = fmt::format("Total: {}%", tmp); } else { tooltip = tooltip + fmt::format("\nCore{}: {}%", i - 1, tmp); } } prev_times_ = curr_times; return {usage, tooltip}; } std::vector<std::tuple<size_t, size_t>> waybar::modules::Cpu::parseCpuinfo() { std::ifstream info(data_dir_); if (!info.is_open()) { throw std::runtime_error("Can't open " + data_dir_); } std::vector<std::tuple<size_t, size_t>> cpuinfo; std::string line; while (getline(info, line)) { if (line.substr(0, 3).compare("cpu") != 0) { break; } std::stringstream sline(line.substr(5)); std::vector<size_t> times; for (size_t time = 0; sline >> time; times.push_back(time)) ; size_t idle_time = 0; size_t total_time = 0; if (times.size() >= 4) { idle_time = times[3]; total_time = std::accumulate(times.begin(), times.end(), 0); } cpuinfo.emplace_back(idle_time, total_time); } return cpuinfo; }
31.857143
100
0.607623
hypergig
2992ad0945d24bc4ff3b0de9758997f2a01411d5
7,081
cxx
C++
Servers/ServerManager/vtkPVProcessModuleBatchHelper.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
Servers/ServerManager/vtkPVProcessModuleBatchHelper.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
Servers/ServerManager/vtkPVProcessModuleBatchHelper.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPVProcessModuleBatchHelper.h" #include "vtkProcessModule.h" #include "vtkPVProcessModuleBatchHelperConfig.h" #include "vtkObjectFactory.h" #include "vtkPVBatchOptions.h" #include "vtkSMApplication.h" #include "vtkSMProperty.h" #include "vtkSMProxyManager.h" #include "vtkTclUtil.h" #include "vtkWindows.h" #include <vtksys/SystemTools.hxx> #include <vtksys/ios/sstream> vtkCxxRevisionMacro(vtkPVProcessModuleBatchHelper, "$Revision$"); vtkStandardNewMacro(vtkPVProcessModuleBatchHelper); EXTERN void TclSetLibraryPath _ANSI_ARGS_((Tcl_Obj * pathPtr)); extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp); extern "C" int Vtkpvservermanagertcl_Init(Tcl_Interp *interp); extern "C" int Vtkpvservercommontcl_Init(Tcl_Interp *interp); //---------------------------------------------------------------------------- static Tcl_Interp *vtkPVProcessModuleBatchHelperInitializeTcl(int argc, char *argv[], ostream *err) { Tcl_Interp *interp; char *args; char buf[100]; (void)err; // The call to Tcl_FindExecutable has to be executed *now*, it does more // than just finding the executable (for ex:, it will set variables // depending on the value of TCL_LIBRARY, TK_LIBRARY) vtkTclApplicationInitExecutable(argc, argv); // Create the interpreter interp = Tcl_CreateInterp(); args = Tcl_Merge(argc - 1, argv + 1); Tcl_SetVar(interp, (char *)"argv", args, TCL_GLOBAL_ONLY); ckfree(args); sprintf(buf, "%d", argc-1); Tcl_SetVar(interp, (char *)"argc", buf, TCL_GLOBAL_ONLY); Tcl_SetVar(interp, (char *)"argv0", argv[0], TCL_GLOBAL_ONLY); Tcl_SetVar(interp, (char *)"tcl_interactive", (char *)"0", TCL_GLOBAL_ONLY); const char* relative_dirs[] = { "../lib/TclTk/lib", "TclTk/lib", ".." VTK_PV_TclTk_INSTALL_DIR, // for exe in PREFIX/bin "../.." VTK_PV_TclTk_INSTALL_DIR, // for exe in PREFIX/lib/paraview-V.v 0 }; vtkTclApplicationInitTclTk(interp, relative_dirs); // Init Tcl int status; status = Tcl_Init(interp); if (status != TCL_OK) { if (err) { *err << "Tcl_Init error: " << Tcl_GetStringResult(interp) << endl; } return NULL; } // Initialize VTK Vtkcommontcl_Init(interp); Vtkpvservermanagertcl_Init(interp); Vtkpvservercommontcl_Init(interp); return interp; } //---------------------------------------------------------------------------- vtkPVProcessModuleBatchHelper::vtkPVProcessModuleBatchHelper() { this->SMApplication = vtkSMApplication::New(); this->ShowProgress = 0; this->Filter = 0; this->CurrentProgress = 0; } //---------------------------------------------------------------------------- vtkPVProcessModuleBatchHelper::~vtkPVProcessModuleBatchHelper() { this->SMApplication->Finalize(); this->SMApplication->Delete(); this->SetFilter(0); } //---------------------------------------------------------------------------- void vtkPVProcessModuleBatchHelper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- int vtkPVProcessModuleBatchHelper::RunGUIStart(int argc, char **argv, int numServerProcs, int myId) { (void)myId; vtksys_ios::ostringstream err; Tcl_Interp *interp = vtkPVProcessModuleBatchHelperInitializeTcl(argc, argv, &err); if (!interp) { #ifdef _WIN32 ::MessageBox(0, err.str().c_str(), "ParaView error: InitializeTcl failed", MB_ICONERROR|MB_OK); #else cerr << "ParaView error: InitializeTcl failed" << endl << err.str().c_str() << endl; #endif return 1; } (void)numServerProcs; this->SMApplication->Initialize(); vtkSMProperty::SetCheckDomains(0); vtkSMProxyManager* proxm = vtkSMObject::GetProxyManager(); proxm->InstantiateGroupPrototypes("filters"); vtkPVBatchOptions* boptions = vtkPVBatchOptions::SafeDownCast(this->ProcessModule->GetOptions()); char* file = vtksys::SystemTools::DuplicateString(boptions->GetBatchScriptName()); int res = 0; // make exit do nothing in batch scripts if(Tcl_GlobalEval(interp, "proc exit {} {}") != TCL_OK) { cerr << "\n Script: \n" << "proc exit {} {}" << "\n Returned Error on line " << interp->errorLine << ": \n" << Tcl_GetStringResult(interp) << endl; res = 1; } // add this window as a variable if ( Tcl_EvalFile(interp, file) != TCL_OK ) { cerr << "Script: \n" << boptions->GetBatchScriptName() << "\n Returned Error on line " << interp->errorLine << ": \n " << Tcl_GetStringResult(interp) << endl; res = 1; } delete [] file; Tcl_DeleteInterp(interp); Tcl_Finalize(); this->ProcessModule->Exit(); // Exiting: CLean up. return res; } //---------------------------------------------------------------------------- void vtkPVProcessModuleBatchHelper::ExitApplication() { } //---------------------------------------------------------------------------- void vtkPVProcessModuleBatchHelper::SendPrepareProgress() { } //---------------------------------------------------------------------------- void vtkPVProcessModuleBatchHelper::CloseCurrentProgress() { if ( this->ShowProgress ) { while ( this->CurrentProgress <= 10 ) { cout << "."; this->CurrentProgress ++; } cout << "]" << endl; } this->CurrentProgress = 0; } //---------------------------------------------------------------------------- void vtkPVProcessModuleBatchHelper::SendCleanupPendingProgress() { this->CloseCurrentProgress(); this->ShowProgress = 0; this->SetFilter(0); } //---------------------------------------------------------------------------- void vtkPVProcessModuleBatchHelper::SetLocalProgress(const char* filter, int val) { val /= 10; int new_progress = 0; if ( !filter || !this->Filter || strcmp(filter, this->Filter) != 0 ) { this->CloseCurrentProgress(); this->SetFilter(filter); new_progress = 1; } if ( !this->ShowProgress ) { new_progress = 1; this->ShowProgress = 1; } if ( new_progress ) { if ( filter[0] == 'v' && filter[1] == 't' && filter[2] == 'k' ) { filter += 3; } cout << "Process " << filter << " ["; cout.flush(); } while ( this->CurrentProgress <= val ) { cout << "."; cout.flush(); this->CurrentProgress ++; } }
28.668016
99
0.570682
matthb2
2992bc3c1836daabe9954802c28f2b919f7a4ba4
2,079
hpp
C++
include/network.hpp
jaistark/sp
911933c65f950e6bc51451840068ca9249554846
[ "BSD-2-Clause" ]
28
2015-03-04T08:34:40.000Z
2022-02-13T05:59:11.000Z
include/network.hpp
jaistark/sp
911933c65f950e6bc51451840068ca9249554846
[ "BSD-2-Clause" ]
null
null
null
include/network.hpp
jaistark/sp
911933c65f950e6bc51451840068ca9249554846
[ "BSD-2-Clause" ]
14
2015-03-04T08:34:42.000Z
2020-12-08T16:13:37.000Z
#ifndef _NETWORK_HPP_ #define _NETWORK_HPP_ #include "common.hpp" #include "Snap.h" #include "snap_tools.hpp" // Keep track of the number of triples in which a pair of nodes is involved. class Counts { public: Counts() {}; Counts(int n) { counts_.resize(n); } ~Counts() {}; // Increment sum of T(:, v, w) void Increment(int v, int w); // 1 / sum(T(:, v, w)) double GetProb(int v, int w); int size() { return counts_.size(); } private: std::vector< std::map<int, int> > counts_; }; // This class wraps a network with its triple list. class Network { public: Network() {} // Construct a network from file. // // data_dir is the directory of where the data is located // name is the location of the Network(std::string data_dir, std::string name, int triple_type); Network(std::string network_path, std::string trips_path); // graph is the graph object // triples is the list of triples (e.g., directed 3-cycles) // cut is the partition we are going to use on the network. Network(PNGraph& graph, std::vector<Tuple>& triples, std::vector<int>& cut); int NumNodes() { return graph_->GetNodes(); } int NumEdges() { return graph_->GetEdges(); } int Density() { return GraphDensity(graph_); } int NodeIndex(int i); PNGraph& graph() { return graph_; } Counts& counts() { return counts_; } std::vector<Tuple>& triples() { return triples_; } private: // Update the triples after the cut. void UpdateTriples(); // Whether or not a triple should be kept after the cut. bool KeepTriple(Tuple& tuple) { return keep_vector_[tuple.first] && keep_vector_[tuple.second] && keep_vector_[tuple.third]; } PNGraph graph_; std::vector<Tuple> triples_; std::vector<int> cut_; std::vector<int> keep_vector_; std::vector<int> index_; std::vector<int> reverse_index_; Counts counts_; }; // Default method to retrieve a network for file. Network GetNetwork(int network, int triple_type); #endif // _NETWORK_HPP_
27
76
0.650794
jaistark
29940ebfdf8682b1149cbb2819c41e4dc4bdb2ee
3,259
cpp
C++
src/Gui/Selectors/SelectInstrument.cpp
waddlesplash/ragingmidi
7153bf68667fba7540541dddcd3ae5e5a02572f9
[ "MIT" ]
13
2015-05-06T05:35:22.000Z
2021-05-31T21:11:45.000Z
src/Gui/Selectors/SelectInstrument.cpp
waddlesplash/ragingmidi
7153bf68667fba7540541dddcd3ae5e5a02572f9
[ "MIT" ]
null
null
null
src/Gui/Selectors/SelectInstrument.cpp
waddlesplash/ragingmidi
7153bf68667fba7540541dddcd3ae5e5a02572f9
[ "MIT" ]
3
2020-06-14T16:49:44.000Z
2021-12-06T07:58:45.000Z
/* * Raging MIDI (https://github.com/waddlesplash/ragingmidi). * * Copyright (c) 2012-2013 WaddleSplash & contributors (see AUTHORS.txt). * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall * be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "SelectInstrument.h" #include "ui_SelectInstrument.h" #include <QPushButton> SelectInstrument::SelectInstrument(QWidget* parent) : QDialog(parent), ui(new Ui::SelectInstrument) { ui->setupUi(this); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); ui->midiInstr->resizeColumnToContents(0); ui->midiInstr->resizeColumnToContents(1); } SelectInstrument::~SelectInstrument() { delete ui; } void SelectInstrument::setInsName(QString name) { int top = ui->midiInstr->topLevelItemCount(); for (int i = 0; i < top; i++) { QTreeWidgetItem* curItem = ui->midiInstr->topLevelItem(i); if (curItem->text(0) == name) { ui->midiInstr->setCurrentItem(curItem); return; } } } void SelectInstrument::setInsNum(int num) { QString var = QString::number(num); int top = ui->midiInstr->topLevelItemCount(); for (int i = 0; i < top; i++) { QTreeWidgetItem* curItem = ui->midiInstr->topLevelItem(i); if (curItem->text(0) == var) { ui->midiInstr->setCurrentItem(curItem); return; } } } QString SelectInstrument::insName() { return ui->midiInstr->selectedItems().at(0)->text(1); } int SelectInstrument::insNum() { return ui->midiInstr->selectedItems().at(0)->text(0).toInt(); } void SelectInstrument::on_searchLE_textChanged(const QString&) { int top = ui->midiInstr->topLevelItemCount(); for (int i = 0; i < top; i++) { QTreeWidgetItem* curItem = ui->midiInstr->topLevelItem(i); curItem->setHidden(false); } if (ui->searchLE->text() == "") { return; } QStringList terms = ui->searchLE->text().split(" "); QString curTerm; for (int i = 0; i < top; i++) { QTreeWidgetItem* curItem = ui->midiInstr->topLevelItem(i); foreach (curTerm, terms) { if (!curItem->text(1).contains(curTerm, Qt::CaseInsensitive)) { curItem->setHidden(true); } } } } void SelectInstrument::on_midiInstr_itemClicked() { ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); } void SelectInstrument::on_midiInstr_itemDoubleClicked(QTreeWidgetItem*, int) { this->accept(); }
28.840708
83
0.717398
waddlesplash
2996b0c47dc3a0659ac515bbb630661af306c228
9,876
hpp
C++
boost/boost/geometry/index/detail/rtree/node/weak_dynamic.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
24
2015-08-25T05:35:37.000Z
2020-10-24T14:21:59.000Z
boost/boost/geometry/index/detail/rtree/node/weak_dynamic.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
97
2015-08-25T16:11:16.000Z
2019-03-17T00:54:32.000Z
boost/boost/geometry/index/detail/rtree/node/weak_dynamic.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
9
2015-08-26T03:11:38.000Z
2018-03-21T07:16:29.000Z
// Boost.Geometry Index // // R-tree nodes based on static conversion, storing dynamic-size containers // // Copyright (c) 2011-2014 Adam Wulkiewicz, Lodz, Poland. // // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_WEAK_DYNAMIC_HPP #define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_WEAK_DYNAMIC_HPP namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { namespace index { namespace detail { namespace rtree { template <typename Value, typename Parameters, typename Box, typename Allocators, typename Tag> struct weak_internal_node : public weak_node<Value, Parameters, Box, Allocators, Tag> { typedef geofeatures_boost::container::vector < rtree::ptr_pair<Box, typename Allocators::node_pointer>, typename Allocators::internal_node_allocator_type::template rebind < rtree::ptr_pair<Box, typename Allocators::node_pointer> >::other > elements_type; template <typename Al> inline weak_internal_node(Al const& al) : elements(al) {} elements_type elements; }; template <typename Value, typename Parameters, typename Box, typename Allocators, typename Tag> struct weak_leaf : public weak_node<Value, Parameters, Box, Allocators, Tag> { typedef geofeatures_boost::container::vector < Value, typename Allocators::leaf_allocator_type::template rebind < Value >::other > elements_type; template <typename Al> inline weak_leaf(Al const& al) : elements(al) {} elements_type elements; }; // nodes traits template <typename Value, typename Parameters, typename Box, typename Allocators> struct node<Value, Parameters, Box, Allocators, node_weak_dynamic_tag> { typedef weak_node<Value, Parameters, Box, Allocators, node_weak_dynamic_tag> type; }; template <typename Value, typename Parameters, typename Box, typename Allocators> struct internal_node<Value, Parameters, Box, Allocators, node_weak_dynamic_tag> { typedef weak_internal_node<Value, Parameters, Box, Allocators, node_weak_dynamic_tag> type; }; template <typename Value, typename Parameters, typename Box, typename Allocators> struct leaf<Value, Parameters, Box, Allocators, node_weak_dynamic_tag> { typedef weak_leaf<Value, Parameters, Box, Allocators, node_weak_dynamic_tag> type; }; // visitor traits template <typename Value, typename Parameters, typename Box, typename Allocators, bool IsVisitableConst> struct visitor<Value, Parameters, Box, Allocators, node_weak_dynamic_tag, IsVisitableConst> { typedef weak_visitor<Value, Parameters, Box, Allocators, node_weak_dynamic_tag, IsVisitableConst> type; }; // allocators template <typename Allocator, typename Value, typename Parameters, typename Box> class allocators<Allocator, Value, Parameters, Box, node_weak_dynamic_tag> : public Allocator::template rebind< typename internal_node< Value, Parameters, Box, allocators<Allocator, Value, Parameters, Box, node_weak_dynamic_tag>, node_weak_dynamic_tag >::type >::other , public Allocator::template rebind< typename leaf< Value, Parameters, Box, allocators<Allocator, Value, Parameters, Box, node_weak_dynamic_tag>, node_weak_dynamic_tag >::type >::other { typedef typename Allocator::template rebind< Value >::other value_allocator_type; public: typedef Allocator allocator_type; typedef Value value_type; typedef typename value_allocator_type::reference reference; typedef typename value_allocator_type::const_reference const_reference; typedef typename value_allocator_type::size_type size_type; typedef typename value_allocator_type::difference_type difference_type; typedef typename value_allocator_type::pointer pointer; typedef typename value_allocator_type::const_pointer const_pointer; typedef typename Allocator::template rebind< typename node<Value, Parameters, Box, allocators, node_weak_dynamic_tag>::type >::other::pointer node_pointer; typedef typename Allocator::template rebind< typename internal_node<Value, Parameters, Box, allocators, node_weak_dynamic_tag>::type >::other internal_node_allocator_type; typedef typename Allocator::template rebind< typename leaf<Value, Parameters, Box, allocators, node_weak_dynamic_tag>::type >::other leaf_allocator_type; inline allocators() : internal_node_allocator_type() , leaf_allocator_type() {} template <typename Alloc> inline explicit allocators(Alloc const& alloc) : internal_node_allocator_type(alloc) , leaf_allocator_type(alloc) {} inline allocators(BOOST_FWD_REF(allocators) a) : internal_node_allocator_type(geofeatures_boost::move(a.internal_node_allocator())) , leaf_allocator_type(geofeatures_boost::move(a.leaf_allocator())) {} inline allocators & operator=(BOOST_FWD_REF(allocators) a) { internal_node_allocator() = ::geofeatures_boost::move(a.internal_node_allocator()); leaf_allocator() = ::geofeatures_boost::move(a.leaf_allocator()); return *this; } #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES inline allocators & operator=(allocators const& a) { internal_node_allocator() = a.internal_node_allocator(); leaf_allocator() = a.leaf_allocator(); return *this; } #endif void swap(allocators & a) { geofeatures_boost::swap(internal_node_allocator(), a.internal_node_allocator()); geofeatures_boost::swap(leaf_allocator(), a.leaf_allocator()); } bool operator==(allocators const& a) const { return leaf_allocator() == a.leaf_allocator(); } template <typename Alloc> bool operator==(Alloc const& a) const { return leaf_allocator() == leaf_allocator_type(a); } Allocator allocator() const { return Allocator(leaf_allocator()); } internal_node_allocator_type & internal_node_allocator() { return *this; } internal_node_allocator_type const& internal_node_allocator() const { return *this; } leaf_allocator_type & leaf_allocator() { return *this; } leaf_allocator_type const& leaf_allocator() const { return *this; } }; // create_node_impl template <typename BaseNodePtr, typename Node> struct create_weak_node { template <typename AllocNode> static inline BaseNodePtr apply(AllocNode & alloc_node) { typedef geofeatures_boost::container::allocator_traits<AllocNode> Al; typedef typename Al::pointer P; P p = Al::allocate(alloc_node, 1); if ( 0 == p ) throw_runtime_error("geofeatures_boost::geometry::index::rtree node creation failed"); scoped_deallocator<AllocNode> deallocator(p, alloc_node); Al::construct(alloc_node, geofeatures_boost::addressof(*p), alloc_node); deallocator.release(); return p; } }; // destroy_node_impl template <typename Node> struct destroy_weak_node { template <typename AllocNode, typename BaseNodePtr> static inline void apply(AllocNode & alloc_node, BaseNodePtr n) { typedef geofeatures_boost::container::allocator_traits<AllocNode> Al; typedef typename Al::pointer P; P p(&static_cast<Node&>(rtree::get<Node>(*n))); Al::destroy(alloc_node, geofeatures_boost::addressof(*p)); Al::deallocate(alloc_node, p, 1); } }; // create_node template <typename Allocators, typename Value, typename Parameters, typename Box, typename Tag> struct create_node< Allocators, weak_internal_node<Value, Parameters, Box, Allocators, Tag> > { static inline typename Allocators::node_pointer apply(Allocators & allocators) { return create_weak_node< typename Allocators::node_pointer, weak_internal_node<Value, Parameters, Box, Allocators, Tag> >::apply(allocators.internal_node_allocator()); } }; template <typename Allocators, typename Value, typename Parameters, typename Box, typename Tag> struct create_node< Allocators, weak_leaf<Value, Parameters, Box, Allocators, Tag> > { static inline typename Allocators::node_pointer apply(Allocators & allocators) { return create_weak_node< typename Allocators::node_pointer, weak_leaf<Value, Parameters, Box, Allocators, Tag> >::apply(allocators.leaf_allocator()); } }; // destroy_node template <typename Allocators, typename Value, typename Parameters, typename Box, typename Tag> struct destroy_node< Allocators, weak_internal_node<Value, Parameters, Box, Allocators, Tag> > { static inline void apply(Allocators & allocators, typename Allocators::node_pointer n) { destroy_weak_node< weak_internal_node<Value, Parameters, Box, Allocators, Tag> >::apply(allocators.internal_node_allocator(), n); } }; template <typename Allocators, typename Value, typename Parameters, typename Box, typename Tag> struct destroy_node< Allocators, weak_leaf<Value, Parameters, Box, Allocators, Tag> > { static inline void apply(Allocators & allocators, typename Allocators::node_pointer n) { destroy_weak_node< weak_leaf<Value, Parameters, Box, Allocators, Tag> >::apply(allocators.leaf_allocator(), n); } }; }} // namespace detail::rtree }}} // namespace geofeatures_boost::geometry::index #endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_NODE_WEAK_DYNAMIC_HPP
33.477966
136
0.713548
tonystone
299758d7f508ace9b2ab100079be214083dbe839
4,569
cpp
C++
app/src/render/render_task.cpp
shuyanglin/antimony-interactive
4787dea233c62015babb0da5e299d9f41d500905
[ "MIT", "Unlicense" ]
null
null
null
app/src/render/render_task.cpp
shuyanglin/antimony-interactive
4787dea233c62015babb0da5e299d9f41d500905
[ "MIT", "Unlicense" ]
null
null
null
app/src/render/render_task.cpp
shuyanglin/antimony-interactive
4787dea233c62015babb0da5e299d9f41d500905
[ "MIT", "Unlicense" ]
null
null
null
#include <boost/python.hpp> #include <boost/format.hpp> #include <QApplication> #include <QDebug> #include <QTime> #include "render/render_task.h" #include "render/render_image.h" #include "fab/types/shape.h" #include "fab/types/transform.h" using namespace boost::python; RenderTask::RenderTask(PyObject *s, QMatrix4x4 matrix, float scale, int refinement) : QObject(NULL), shape(s), matrix(matrix), scale(scale), refinement(refinement), image(NULL), is_empty(false) { Py_INCREF(shape); } RenderTask::~RenderTask() { if (image) delete image; Py_DECREF(shape); } RenderTask* RenderTask::getNext() const { return refinement ? new RenderTask(shape, matrix, scale*2, refinement - 1) : NULL; } bool RenderTask::hasFinishedRender() const { // Checks that the rendering was completed // (rather than halted mid-render) return image && (image->halt_flag == 0); } DepthImageItem* RenderTask::getDepthImage(Viewport* viewport) { Q_ASSERT(image); auto d = image->addToViewport(viewport); delete image; image = NULL; return d; } void RenderTask::render() { QTime timer; timer.start(); extract<Shape> get_shape(shape); Q_ASSERT(get_shape.check()); Shape s = get_shape(); if (!isinf(s.bounds.xmin) && !isinf(s.bounds.xmax) && !isinf(s.bounds.xmin) && !isinf(s.bounds.xmax)) { if (isinf(s.bounds.zmin) || isinf(s.bounds.zmax)) render2d(s); else render3d(s); image->moveToThread(QApplication::instance()->thread()); } else { is_empty = true; } time_taken = timer.elapsed(); emit(finished()); } void RenderTask::render3d(Shape s) { Transform T = getTransform(matrix); Shape transformed = s.map(T); image = new RenderImage( transformed.bounds, matrix.inverted() * QVector3D( (transformed.bounds.xmin + transformed.bounds.xmax)/2, (transformed.bounds.ymin + transformed.bounds.ymax)/2, (transformed.bounds.zmin + transformed.bounds.zmax)/2), scale); connect(this, &RenderTask::halt, image, &RenderImage::halt); image->render(&transformed); if (s.r != -1 && s.g != -1 && s.g != -1) image->setColor(QColor(s.r, s.g, s.b)); } void RenderTask::render2d(Shape s) { QMatrix4x4 matrix_flat = matrix; matrix_flat(0, 2) = 0; matrix_flat(1, 2) = 0; matrix_flat(2, 0) = 0; matrix_flat(2, 1) = 0; matrix_flat(2, 2) = 1; Shape s_flat(s.math, Bounds(s.bounds.xmin, s.bounds.ymin, 0, s.bounds.xmax, s.bounds.ymax, 0)); Transform T_flat = getTransform(matrix_flat); Shape transformed = s_flat.map(T_flat); // Render the flattened shape, but with bounds equivalent to the shape's // position in a 3D bounding box. Bounds b3d = Bounds(s.bounds.xmin, s.bounds.ymin, 0, s.bounds.xmax, s.bounds.ymax, 0.0001). map(getTransform(matrix)); image = new RenderImage( b3d, matrix.inverted() * QVector3D((b3d.xmin + b3d.xmax)/2, (b3d.ymin + b3d.ymax)/2, (b3d.zmin + b3d.zmax)/2), scale); connect(this, &RenderTask::halt, image, &RenderImage::halt); image->render(&transformed); if (matrix(1,2)) image->applyGradient(matrix(2,2) > 0); if (s.r != -1 && s.g != -1 && s.g != -1) image->setColor(QColor(s.r, s.g, s.b)); image->setNormals( sqrt(pow(matrix(0,2),2) + pow(matrix(1,2),2)), fabs(matrix(2,2))); image->setFlat(true); } Transform RenderTask::getTransform(QMatrix4x4 m) { QMatrix4x4 mf = m.inverted(); QMatrix4x4 mi = mf.inverted(); Transform T = Transform( (boost::format("++*Xf%g*Yf%g*Zf%g") % mf(0,0) % mf(0,1) % mf(0,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mf(1,0) % mf(1,1) % mf(1,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mf(2,0) % mf(2,1) % mf(2,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mi(0,0) % mi(0,1) % mi(0,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mi(1,0) % mi(1,1) % mi(1,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mi(2,0) % mi(2,1) % mi(2,2)).str()); return T; }
27.359281
76
0.548917
shuyanglin
299ceb19c210ba3fca0db238e2298a4926b5ce7d
1,673
cpp
C++
Engine/Src/Ancona/Framework/Serializing/Archive.cpp
ild-games/Ancona
6a4f520f97d17648a6dd3ba0582cd51da4f9e809
[ "MIT" ]
11
2018-04-15T21:00:48.000Z
2021-12-30T20:55:21.000Z
Engine/Src/Ancona/Framework/Serializing/Archive.cpp
tlein/Ancona
6a4f520f97d17648a6dd3ba0582cd51da4f9e809
[ "MIT" ]
58
2016-04-17T20:41:25.000Z
2017-02-27T01:21:46.000Z
Engine/Src/Ancona/Framework/Serializing/Archive.cpp
ild-games/Ancona
6a4f520f97d17648a6dd3ba0582cd51da4f9e809
[ "MIT" ]
4
2018-05-04T17:03:20.000Z
2021-02-12T21:26:57.000Z
#include <Ancona/Framework/Serializing/Archive.hpp> #include <Ancona/System/Log.hpp> using namespace ild; Archive::Archive( rapidjson::Value * root, std::shared_ptr<SerializingContext> context, bool loading, rapidjson::MemoryPoolAllocator<> & allocator, bool snapshotSave) : _loading(loading), _snapshotSave(snapshotSave), _root(root), _context(context), _allocator(allocator) { _jsonBranch.push(_root); } rapidjson::Value & Archive::CurrentBranch() { return *_jsonBranch.top(); } bool Archive::EnterProperty(const std::string & name, bool createIfMissing, const rapidjson::Type typeToCreate) { if (!CurrentBranch().HasMember(name)) { if (createIfMissing) { rapidjson::Value key(name, _allocator); CurrentBranch().AddMember(key, rapidjson::Value(typeToCreate), _allocator); } else { return false; } } _jsonBranch.push(&(CurrentBranch())[name]); return true; } bool Archive::EnterProperty(const int & index, bool createIfMissing, const rapidjson::Type typeToCreate) { if (index >= CurrentBranch().Size()) { if (createIfMissing) { ILD_Assert(index == CurrentBranch().Size(), "Cannot add a new value to a json array beyond the size"); CurrentBranch().PushBack(rapidjson::Value(typeToCreate), _allocator); } else { return false; } } _jsonBranch.push(&(CurrentBranch())[index]); return true; } void Archive::ExitProperty() { _jsonBranch.pop(); } bool Archive::HasProperty(const std::string & name) { return CurrentBranch().HasMember(name); }
26.140625
114
0.649731
ild-games
29a2b24c1192b0cceeb3a25b3783a1bcc37f0666
9,454
cpp
C++
src/test/unit/lang/parser/other_test.cpp
drezap/stan
9b319ed125e2a7d14d0c9c246d2f462dad668537
[ "BSD-3-Clause" ]
1
2019-07-05T01:40:40.000Z
2019-07-05T01:40:40.000Z
src/test/unit/lang/parser/other_test.cpp
drezap/stan
9b319ed125e2a7d14d0c9c246d2f462dad668537
[ "BSD-3-Clause" ]
null
null
null
src/test/unit/lang/parser/other_test.cpp
drezap/stan
9b319ed125e2a7d14d0c9c246d2f462dad668537
[ "BSD-3-Clause" ]
1
2020-07-14T11:36:09.000Z
2020-07-14T11:36:09.000Z
#include <gtest/gtest.h> #include <iostream> #include <fstream> #include <istream> #include <sstream> #include <exception> #include <stdexcept> #include <test/unit/lang/utility.hpp> TEST(lang_parser,good_trunc) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_trunc.stan")); } TEST(lang_parser,good_vec_constraints) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_trunc.stan")); } TEST(lang_parser,good_const) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_const.stan")); } TEST(lang_parser,good_matrix_ops) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_matrix_ops.stan")); } TEST(lang_parser,good_funs) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_funs.stan")); } TEST(lang_parser,good_vars) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_vars.stan")); } TEST(lang_parser,good_intercept_var) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_intercept_var.stan")); } TEST(lang_parser,good_cov) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_cov.stan")); } TEST(lang_parser,good_local_var_array_size) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_local_var_array_size.stan")); } TEST(lang_parser,parsable_test_bad1) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad1.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad2) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad2.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad3) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad3.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad4) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad4.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad5) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad5.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad6) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad6.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad7) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad7.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad8) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad8.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad9) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad9.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad10) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad10.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad11) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad11.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_fun_name) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_fun_name.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_vec_rvec_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_vec_rvec_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_vec_arr_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_vec_arr_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_rvec_vec_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_rvec_vec_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_rvec_arr_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_rvec_arr_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_arr_vec_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_arr_vec_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_arr_rvec_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_arr_rvec_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_vec_rvec_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_vec_rvec_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_vec_arr_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_vec_arr_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_rvec_vec_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_rvec_vec_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_rvec_arr_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_rvec_arr_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_arr_vec_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_arr_vec_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_arr_rvec_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_arr_rvec_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_vec_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_vec_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_rvec_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_rvec_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_sigma_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_sigma_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_len_data) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_len_data.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_sigma_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_sigma_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_len_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_len_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_sigma_vec_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_sigma_vec_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_len_vec_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_len_vec_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_sigma_rvec_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_sigma_rvec_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_bad_cov_exp_quad_len_rvec_param) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_cov_exp_quad_len_rvec_param.stan"), std::invalid_argument); } TEST(lang_parser,parsable_test_good_fun_name) { EXPECT_TRUE(is_parsable("src/test/test-models/bad/lang/good_fun_name.stan")); } TEST(langParser,parsableBadPeriods) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_periods_data.stan"), std::invalid_argument); EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_periods_tdata.stan"), std::invalid_argument); EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_periods_params.stan"), std::invalid_argument); EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_periods_tparams.stan"), std::invalid_argument); EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_periods_gqs.stan"), std::invalid_argument); EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_periods_local.stan"), std::invalid_argument); } TEST(langParser,declareVarWithSameNameAsModel) { EXPECT_THROW(is_parsable("src/test/test-models/bad/lang/bad_model_name_var.stan"), std::invalid_argument); } TEST(lang_parser, infVariableName) { test_parsable("good_inf"); } TEST(lang_parser, declarations_function_signatures) { test_parsable("declarations"); } // illegal, but will parse TEST(lang_parser, illegal_generated_quantities) { test_parsable("illegal_generated_quantities"); } // illegal, but will parse TEST(lang_parser, illegal_transformed_data) { test_parsable("illegal_transformed_data"); } // illegal, but will parse TEST(lang_parser, illegal_transformed_parameters) { test_parsable("illegal_transformed_parameters"); } TEST(lang_parser, increment_log_prob) { test_parsable("increment_log_prob"); } TEST(lang_parser, intFun) { test_parsable("int_fun"); } TEST(lang_parser, print_chars) { test_parsable("print_chars"); } TEST(lang_parser, print_indexing) { test_parsable("print_indexing"); }
33.764286
99
0.757351
drezap
29a3ae6abd137dcfab3add163490d2f3393b6ef0
1,209
cc
C++
src/xenia/base/console_app_main_posix.cc
amessier/xenia
6b45cf84472c26436d4a5db61a7b50dab301e398
[ "BSD-3-Clause" ]
3,100
2018-05-03T10:04:39.000Z
2022-03-31T04:51:53.000Z
src/xenia/base/console_app_main_posix.cc
amessier/xenia
6b45cf84472c26436d4a5db61a7b50dab301e398
[ "BSD-3-Clause" ]
671
2018-05-04T00:51:22.000Z
2022-03-31T15:20:22.000Z
src/xenia/base/console_app_main_posix.cc
amessier/xenia
6b45cf84472c26436d4a5db61a7b50dab301e398
[ "BSD-3-Clause" ]
877
2018-05-03T21:01:17.000Z
2022-03-31T19:43:14.000Z
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2021 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <string> #include <vector> #include "xenia/base/console_app_main.h" #include "xenia/base/cvar.h" #include "xenia/base/logging.h" extern "C" int main(int argc, char** argv) { xe::ConsoleAppEntryInfo entry_info = xe::GetConsoleAppEntryInfo(); if (!entry_info.transparent_options) { cvar::ParseLaunchArguments(argc, argv, entry_info.positional_usage, entry_info.positional_options); } // Initialize logging. Needs parsed cvars. xe::InitializeLogging(entry_info.name); std::vector<std::string> args; for (int n = 0; n < argc; n++) { args.emplace_back(argv[n]); } int result = entry_info.entry_point(args); xe::ShutdownLogging(); return result; }
31
79
0.515302
amessier
29a6b20f400037c996befe49a6a3f0d8abb48311
6,374
cpp
C++
src/ufile.cpp
pranav-pointer/ulib-win
b67f644ed11c849e3c93b909f90d443df7be4e4c
[ "Apache-2.0" ]
4
2016-09-07T07:02:52.000Z
2019-06-22T08:55:53.000Z
src/ufile.cpp
dbremner/ulib-win
2ad600df92351ea12b79cad769056ab111e2f9bf
[ "Apache-2.0" ]
null
null
null
src/ufile.cpp
dbremner/ulib-win
2ad600df92351ea12b79cad769056ab111e2f9bf
[ "Apache-2.0" ]
3
2019-06-22T16:00:39.000Z
2022-03-09T13:46:27.000Z
/* * ===================================================================================== * * Filename: ufile.cpp * * Description: implement of UFile class * * Version: 1.0 * Created: 2009-7-22 20:29:39 * Revision: none * Compiler: gcc * * Author: huys (hys), huys03@gmail.com * Company: hu * * ===================================================================================== */ #include <windows.h> #include <tchar.h> #include <cassert> #include <cstdio> #include "ufile.h" UFile::UFile() : UKernelObject() { ::ZeroMemory(m_sFilename, sizeof(m_sFilename)); m_hObj = INVALID_HANDLE_VALUE; } UFile::~UFile() { if (isOpen()) { close(); } } bool UFile::isOpen() const { return (m_hObj != INVALID_HANDLE_VALUE && m_hObj != 0 ); } bool UFile::open( LPCSTR lpFilename /*= _T("defalut")*/ ) { assert( !::IsBadStringPtr(lpFilename, -1) ); lstrcpy(m_sFilename, lpFilename); m_hObj = ::CreateFile( m_sFilename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); return ( INVALID_HANDLE_VALUE != m_hObj); } bool UFile::create( LPCTSTR lpFilename /*= _T("default")*/ ) { assert( !::IsBadStringPtr(lpFilename, -1) ); lstrcpy(m_sFilename, lpFilename); m_hObj = ::CreateFile( m_sFilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); return ( INVALID_HANDLE_VALUE != m_hObj); } bool UFile::write( LPBYTE lpData, DWORD dwNumOfBytes ) { assert( INVALID_HANDLE_VALUE != m_hObj ); assert( NULL != lpData ); assert( !::IsBadStringPtr((LPTSTR)lpData, dwNumOfBytes) ); if( dwNumOfBytes == 0 ) return TRUE; // avoid Win32 "null-write" option DWORD dwNumOfBytesWriten = 0; BOOL bOk = TRUE; while (dwNumOfBytesWriten < dwNumOfBytes) { bOk = ::WriteFile( m_hObj, lpData+dwNumOfBytesWriten, dwNumOfBytes-dwNumOfBytesWriten, &dwNumOfBytesWriten, NULL); if (!bOk) { return false; } } return true; } bool UFile::read( LPBYTE lpBuffer, DWORD dwBufSize, LPDWORD dwNumOfBytesRead ) { BOOL bOk = TRUE; bOk = ::ReadFile(m_hObj, lpBuffer, dwBufSize, dwNumOfBytesRead, NULL); if (!bOk) { return false; } return true; } DWORD UFile::seek(LONG lOffset, DWORD dwFrom) { assert( INVALID_HANDLE_VALUE != m_hObj ); return ::SetFilePointer(m_hObj, lOffset, NULL, dwFrom); } DWORD UFile::pos() { return this->seek(0, FILE_CURRENT); } bool UFile::lock(DWORD dwOffset, DWORD dwSize) { assert( INVALID_HANDLE_VALUE != m_hObj ); return TRUE == ::LockFile(m_hObj, dwOffset, 0, dwSize, 0); } bool UFile::unlock(DWORD dwOffset, DWORD dwSize) { assert( INVALID_HANDLE_VALUE != m_hObj ); return TRUE == ::UnlockFile(m_hObj, dwOffset, 0, dwSize, 0); } bool UFile::flush() { assert( INVALID_HANDLE_VALUE != m_hObj ); return TRUE == ::FlushFileBuffers(m_hObj); } DWORD UFile::size() const { assert( INVALID_HANDLE_VALUE != m_hObj ); return ::GetFileSize(m_hObj, NULL); } DWORD UFile::type() const { assert( INVALID_HANDLE_VALUE != m_hObj ); return ::GetFileType(m_hObj); } bool UTempFile::open() { TCHAR szTempFileName[MAX_PATH]; TCHAR lpTempPathBuffer[MAX_PATH]; DWORD dwRetVal = 0; UINT uRetVal = 0; dwRetVal = GetTempPath(MAX_PATH, lpTempPathBuffer); if (dwRetVal > MAX_PATH || (dwRetVal == 0)) { return false; } // Generates a temporary file name. uRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files TEXT("ULIB_DEMO"), // temp file name prefix 0, // create unique name szTempFileName); // buffer for name if (uRetVal == 0) { return false; } return UFile::create(szTempFileName); } bool UTempFile::move(LPCTSTR lpNewFileName) { // close(); // Moves the temporary file to the new text file, allowing for differnt // drive letters or volume names. BOOL fSuccess = ::MoveFileEx(UFile::name(), lpNewFileName, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED); return TRUE == fSuccess; } UCFile::UCFile(const char *sFilename) : m_pFile(NULL) { if (NULL != sFilename) { strcpy(m_sFilename, sFilename); } } UCFile::~UCFile() { if (m_pFile) { close(); } } // bool UCFile::create(bool bOverwriten /*= true*/) { const char *sMode = (bOverwriten ? "w":"w+"); m_pFile = fopen(m_sFilename, sMode); return true; } // bool UCFile::open(const char *mode) { m_pFile = fopen(m_sFilename, mode); return true; } bool UCFile::close() { fclose(m_pFile); m_pFile = NULL; return true; } bool UCFile::reopen(const char *mode) { freopen(m_sFilename, mode, m_pFile); return true; } bool UCFile::isOpen() const { return (NULL == m_pFile); } bool UCFile::isEOF() const { return 0 != feof(m_pFile); } bool UCFile::read(void *buf, size_t size) { return 1 == fread(buf, size, 1, m_pFile); } bool UCFile::write(const void *buf, size_t size) { return 1 == fwrite(buf, size, 1, m_pFile); } size_t UCFile::size() { size_t s = 0; this->seek(0, SEEK_END); s = this->tell(); this->rewind(); return s; } bool UCFile::directStdOut(const char *mode) { m_pFile = freopen(m_sFilename, mode, stdout); return true; } bool UCFile::directStdErr(const char *mode) { m_pFile = freopen(m_sFilename, mode, stderr); return true; } bool UCFile::directStdIn(const char *mode) { m_pFile = freopen(m_sFilename, mode, stdin); return true; } bool UCFile::flush() { fflush(m_pFile); return true; } bool UCFile::seek(long int offset, int origin) { return (0 != fseek(m_pFile, offset, origin) ); } long UCFile::tell() { return ftell(m_pFile); } void UCFile::rewind() { ::rewind(m_pFile); } UCTempFile::UCTempFile() : UCFile(NULL) {} bool UCTempFile::open() { return (0 != assign(tmpfile())); }
20.107256
88
0.577659
pranav-pointer