hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
690095aced1b3f275984c0857daade52d479cd4a
11,997
cc
C++
tensorflow/core/kernels/epu_conv_ops.cc
tangcongyuan/tensorflow-r1.9
4dbef31044a95ce318dee304e163582fa68b1d75
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/epu_conv_ops.cc
tangcongyuan/tensorflow-r1.9
4dbef31044a95ce318dee304e163582fa68b1d75
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/epu_conv_ops.cc
tangcongyuan/tensorflow-r1.9
4dbef31044a95ce318dee304e163582fa68b1d75
[ "Apache-2.0" ]
null
null
null
#define USE_EIGEN_TENSOR #define EIGEN_USE_THREADS #if GOOGLE_CUDA #define EIGEN_USE_GPU #endif // GOOGLE_CUDA #include "tensorflow/core/kernels/conv_ops.h" #include <string.h> #include <map> #include <vector> #include "tensorflow/core/common_runtime/epu/epu_device.h" #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_slice.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/kernels/conv_2d.h" #include "tensorflow/core/kernels/deep_conv2d.h" #include "tensorflow/core/kernels/ops_util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/util/padding.h" #include "tensorflow/core/util/tensor_format.h" #include "tensorflow/core/util/use_cudnn.h" #ifdef TENSORFLOW_USE_LIBXSMM_CONVOLUTIONS #include "tensorflow/core/kernels/xsmm_conv2d.h" #endif #if GOOGLE_CUDA #include "tensorflow/core/kernels/conv_ops_gpu.h" #include "tensorflow/core/platform/stream_executor.h" #endif // GOOGLE_CUDA namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; template <typename Device, typename T> class Conv2DEpuOp : public BinaryOp<T> { public: explicit Conv2DEpuOp(OpKernelConstruction* context) : BinaryOp<T>(context) { OP_REQUIRES_OK(context, context->GetAttr("dilations", &dilations_)); OP_REQUIRES_OK(context, context->GetAttr("strides", &strides_)); string data_format; OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format)); OP_REQUIRES(context, FormatFromString(data_format, &data_format_), errors::InvalidArgument("Invalid data format")); OP_REQUIRES_OK(context, context->GetAttr("use_cudnn_on_gpu", &use_cudnn_)); use_cudnn_ &= CanUseCudnn(); cudnn_use_autotune_ = CudnnUseAutotune(); OP_REQUIRES(context, dilations_.size() == 4, errors::InvalidArgument("Sliding window dilations field must " "specify 4 dimensions")); OP_REQUIRES(context, strides_.size() == 4, errors::InvalidArgument("Sliding window strides field must " "specify 4 dimensions")); const int64 stride_n = GetTensorDim(strides_, data_format_, 'N'); const int64 stride_c = GetTensorDim(strides_, data_format_, 'C'); const int64 stride_h = GetTensorDim(strides_, data_format_, 'H'); const int64 stride_w = GetTensorDim(strides_, data_format_, 'W'); OP_REQUIRES( context, stride_n == 1 && stride_c == 1, errors::InvalidArgument("Current implementation does not yet support " "strides in the batch and depth dimensions.")); OP_REQUIRES(context, stride_h > 0 && stride_w > 0, errors::InvalidArgument( "Row and column strides should be larger than 0.")); const int64 dilation_n = GetTensorDim(dilations_, data_format_, 'N'); const int64 dilation_c = GetTensorDim(dilations_, data_format_, 'C'); const int64 dilation_h = GetTensorDim(dilations_, data_format_, 'H'); const int64 dilation_w = GetTensorDim(dilations_, data_format_, 'W'); OP_REQUIRES(context, dilation_n == 1 && dilation_c == 1, errors::InvalidArgument( "Current implementation does not yet support " "dilations in the batch and depth dimensions.")); OP_REQUIRES( context, dilation_h > 0 && dilation_w > 0, errors::InvalidArgument("Dilated rates should be larger than 0.")); OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_)); } void Compute(OpKernelContext* context) override { // Input tensor is of the following dimensions: // [ batch, in_rows, in_cols, in_depth ] VLOG(0) << "\33[42m Enter " << this->name() << " Compute \33[0m"; const Tensor& input = context->input(0); // Input filter is of the following dimensions: // [ filter_rows, filter_cols, in_depth, out_depth] const Tensor& filter = context->input(1); // For 2D convolution, there should be 4 dimensions. OP_REQUIRES(context, input.dims() == 4, errors::InvalidArgument("input must be 4-dimensional", input.shape().DebugString())); OP_REQUIRES(context, filter.dims() == 4, errors::InvalidArgument("filter must be 4-dimensional: ", filter.shape().DebugString())); for (int i = 0; i < 3; i++) { OP_REQUIRES( context, FastBoundsCheck(filter.dim_size(i), std::numeric_limits<int>::max()), errors::InvalidArgument("filter too large")); } // The last dimension for input is in_depth. It must be the same as the // filter's in_depth or be evenly divisible by filter's in_depth. const int64 in_depth = GetTensorDim(input, data_format_, 'C'); const int64 patch_depth = filter.dim_size(2); OP_REQUIRES(context, in_depth % patch_depth == 0, errors::InvalidArgument( "input depth must be evenly divisible by filter depth: ", in_depth, " vs ", patch_depth)); // The last dimension for filter is out_depth. const int out_depth = static_cast<int>(filter.dim_size(3)); // The second dimension for input is rows/height. // The first dimension for filter is rows/height. const int64 input_rows_raw = GetTensorDim(input, data_format_, 'H'); OP_REQUIRES( context, FastBoundsCheck(input_rows_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("Input rows too large")); const int input_rows = static_cast<int>(input_rows_raw); const int filter_rows = static_cast<int>(filter.dim_size(0)); // The third dimension for input is columns/width. // The second dimension for filter is columns/width. const int64 input_cols_raw = GetTensorDim(input, data_format_, 'W'); OP_REQUIRES( context, FastBoundsCheck(input_cols_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("Input cols too large")); const int input_cols = static_cast<int>(input_cols_raw); const int filter_cols = static_cast<int>(filter.dim_size(1)); // The first dimension for input is batch. const int64 batch_raw = GetTensorDim(input, data_format_, 'N'); OP_REQUIRES(context, FastBoundsCheck(batch_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("batch is too large")); const int batch = static_cast<int>(batch_raw); // For now we take the stride and dilation from the second and third // dimensions only (we do not support striding or dilation on the batch or // depth dimension). const int stride_rows = GetTensorDim(strides_, data_format_, 'H'); const int stride_cols = GetTensorDim(strides_, data_format_, 'W'); const int dilation_rows = GetTensorDim(dilations_, data_format_, 'H'); const int dilation_cols = GetTensorDim(dilations_, data_format_, 'W'); int64 out_rows = 0, out_cols = 0, pad_rows = 0, pad_cols = 0; OP_REQUIRES_OK(context, GetWindowedOutputSizeV2( input_rows, filter_rows, dilation_rows, stride_rows, padding_, &out_rows, &pad_rows)); OP_REQUIRES_OK(context, GetWindowedOutputSizeV2( input_cols, filter_cols, dilation_cols, stride_cols, padding_, &out_cols, &pad_cols)); TensorShape out_shape = ShapeFromFormat(data_format_, batch, out_rows, out_cols, out_depth); // Output tensor is of the following dimensions: // [ in_batch, out_rows, out_cols, out_depth ] Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, out_shape, &output)); VLOG(0) << "\33[1;33m ============================================ \33[0m\n"; VLOG(0) << "\33[1;33m ============================================ \33[0m\n"; VLOG(0) << "\33[1;33m ============================================ \33[0m\n"; VLOG(0) << "\33[1;33m ============================================ \33[0m\n"; VLOG(0) << "\33[1;33m ============================================ \33[0m\n"; VLOG(0) << "\33[1;33m ============================================ \33[0m\n"; VLOG(0) << "\33[1;33m ============================================ \33[0m\n"; VLOG(0) << "\33[1;33m ================== in EPU Conv2D Op =============== \33[0m\n" << "Conv2D: in_depth = " << in_depth << ", patch_depth = " << patch_depth << ", input_cols = " << input_cols << ", filter_cols = " << filter_cols << ", input_rows = " << input_rows << ", filter_rows = " << filter_rows << ", stride_rows = " << stride_rows << ", stride_cols = " << stride_cols << ", dilation_rows = " << dilation_rows << ", dilation_cols = " << dilation_cols << ", out_depth = " << out_depth; // If there is nothing to compute, return. if (out_shape.num_elements() == 0) { return; } // We only support same stride along rows/cols dimension assert (stride_rows == stride_cols); printf("input.TotalBytes() = %lu\n", input.TotalBytes()); printf("filter.TotalBytes() = %lu\n", filter.TotalBytes()); printf("output->TotalBytes() = %lu\n", output->TotalBytes()); const auto input_ptr = input.flat<T>().data(); const auto weight_ptr = filter.flat<T>().data(); auto output_ptr = output->flat<T>().data(); // TODO(pwchou): we use nullptr as bias_ptr and output as 2nd input temporarily. const auto bias_ptr = nullptr; const auto second_input_ptr = output->flat<T>().data(); // RunEpuConvolution(input_ptr, weight_ptr, output_ptr, bias_ptr, // second_input_ptr, input_rows, input_cols, in_depth, // filter_rows, filter_cols, pad_rows, pad_cols, out_rows, // out_cols, out_depth, stride_rows, // /*relu=*/false, /*maxpool=*/false); /* #ifdef TENSORFLOW_USE_LIBXSMM_CONVOLUTIONS if (LaunchXsmmConvOp<Device, T>::Run( context, input, filter, batch, input_rows, input_cols, in_depth, filter_rows, filter_cols, pad_rows, pad_cols, out_rows, out_cols, out_depth, dilation_rows, dilation_cols, stride_rows, stride_cols, output, data_format_)) { return; } #endif if (LaunchDeepConvOp<Device, T>::Run( context, input, filter, batch, input_rows, input_cols, in_depth, filter_rows, filter_cols, pad_rows, pad_cols, out_rows, out_cols, out_depth, dilation_rows, dilation_cols, stride_rows, stride_cols, output, data_format_)) { return; } launcher_(context, use_cudnn_, cudnn_use_autotune_, input, filter, dilation_rows, dilation_cols, stride_rows, stride_cols, padding_, output, data_format_); */ } private: std::vector<int32> dilations_; std::vector<int32> strides_; bool use_cudnn_; Padding padding_; TensorFormat data_format_; bool cudnn_use_autotune_; TF_DISALLOW_COPY_AND_ASSIGN(Conv2DEpuOp); }; #define REGISTER_EPU(T) \ REGISTER_KERNEL_BUILDER( \ Name("Conv2D").Device(DEVICE_EPU).TypeConstraint<T>("T"), \ Conv2DEpuOp<EPUDevice, T>); TF_CALL_half(REGISTER_EPU); }
43.467391
87
0.631241
[ "shape", "vector" ]
6901582348e44f1f60380dcc40114fc5bbc561cc
8,102
cpp
C++
src/Engine/bitboard.cpp
vieiramauricio/Chessqdl
3c76a626dbb9ed8880539a90f72e175a9e07e9fb
[ "MIT" ]
6
2019-11-20T04:02:12.000Z
2022-02-16T15:49:39.000Z
src/Engine/bitboard.cpp
vieiramauricio/Chessqdl
3c76a626dbb9ed8880539a90f72e175a9e07e9fb
[ "MIT" ]
null
null
null
src/Engine/bitboard.cpp
vieiramauricio/Chessqdl
3c76a626dbb9ed8880539a90f72e175a9e07e9fb
[ "MIT" ]
1
2020-10-02T23:44:18.000Z
2020-10-02T23:44:18.000Z
#include "bitboard.hpp" #include "const.hpp" #include <string> #include <iostream> #include <cctype> using namespace chessqdl; /** * @details Initializes bitboards in order to obtain the following board: <br><br> * r n b q k b n r <br> * p p p p p p p p <br> * - - - - - - - - <br> * - - - - - - - - <br> * - - - - - - - - <br> * - - - - - - - - <br> * P P P P P P P P <br> * R N B Q K B N R <br> * * note that upper case letters represent white pieces while lower case letters are black pieces. <br> * # represents an empty square */ Bitboard::Bitboard() { bitBoards[nBlack] = 0xffffL << 48; bitBoards[nWhite] = 0xffffL; bitBoards[nColor] = bitBoards[nWhite] | bitBoards[nBlack]; bitBoards[nPawn] = (0xffL << 48) | (0xffL << 8); bitBoards[nKnight] = 0x42L | (0x42L << 56); bitBoards[nBishop] = 0x24L | (0x24L << 56); bitBoards[nRook] = 0x81L | (0x81L << 56); bitBoards[nQueen] = 0x8L | (0x8L << 56); bitBoards[nKing] = 0x10L | (0x10L << 56); } /** * @details Constructor that uses a custom board, represented by the \p fen string. */ Bitboard::Bitboard(std::string fen) { // Just to make sure that all bitboards start with value 0x0; for (auto& b : bitBoards) b.reset(); int pos = 56; for (unsigned long int i = 0; i < fen.find_first_of(' '); i++) { switch (tolower(fen[i])) { case '/': // do not increment counter because '/' does not represent any position pos -= 17; break; case 'p': bitBoards[nPawn].set(pos); if (fen[i] == 'P') bitBoards[nWhite].set(pos); else bitBoards[nBlack].set(pos); break; case 'n': bitBoards[nKnight].set(pos); if (fen[i] == 'N') bitBoards[nWhite].set(pos); else bitBoards[nBlack].set(pos); break; case 'b': bitBoards[nBishop].set(pos); if (fen[i] == 'B') bitBoards[nWhite].set(pos); else bitBoards[nBlack].set(pos); break; case 'r': bitBoards[nRook].set(pos); if (fen[i] == 'R') bitBoards[nWhite].set(pos); else bitBoards[nBlack].set(pos); break; case 'q': bitBoards[nQueen].set(pos); if (fen[i] == 'Q') bitBoards[nWhite].set(pos); else bitBoards[nBlack].set(pos); break; case 'k': bitBoards[nKing].set(pos); if (fen[i] == 'K') bitBoards[nWhite].set(pos); else bitBoards[nBlack].set(pos); break; // Is digit. Skip next n squares default: pos += fen[i] - '0' - 1; // -1 because it will be incremented at the end break; } pos++; } bitBoards[nColor] = bitBoards[nBlack] | bitBoards[nWhite]; } /** * @details This method performs an AND operation between the bitboard containing all pawns and the bitboard containing all pieces of the desired color */ U64 Bitboard::getPawns(enumColor color) { return bitBoards[nPawn] & bitBoards[color]; } /** * @details This method performs an AND operation between the bitboard containing all knights and the bitboard containing all pieces of the desired color */ U64 Bitboard::getKnights(enumColor color) { return bitBoards[nKnight] & bitBoards[color]; } /** * @details This method performs an AND operation between the bitboard containing all bishops and the bitboard containing all pieces of the desired color */ U64 Bitboard::getBishops(enumColor color) { return bitBoards[nBishop] & bitBoards[color]; } /** * @details This method performs an AND operation between the bitboard containing all rooks and the bitboard containing all pieces of the desired color */ U64 Bitboard::getRooks(enumColor color) { return bitBoards[nRook] & bitBoards[color]; } /** * @details This method performs an AND operation between the bitboard containing all queens and the bitboard containing all pieces of the desired color */ U64 Bitboard::getQueens(enumColor color) { return bitBoards[nQueen] & bitBoards[color]; } /** * @details This method performs an AND operation between the bitboard containing all kings and the bitboard containing all pieces of the desired color */ U64 Bitboard::getKing(enumColor color) { return bitBoards[nKing] & bitBoards[color]; } /** * @details This method returns a bitboard containing all pieces that match the parameter color. */ U64 Bitboard::getPieces(enumColor color) { return bitBoards[color]; } /** * @details This method returns a bitboard containing all pieces that match the parameter type. */ U64 Bitboard::getPieces(enumPiece type) { return bitBoards[type]; } /** * @details This method returns a bitboard containing all pieces at index \p i */ U64 Bitboard::getPiecesAt(int i) { return bitBoards[i]; } /** * @details This method performs and AND operation between all white and black pieces, resulting in a bitboard that contains all the pieces on the board. */ U64 Bitboard::getAllPieces() { return bitBoards[nColor]; } /** * @details Returns a copy of the std::array with the bitBoards attribute of the Bitboard class. */ BitbArray Bitboard::getBitBoards() { return bitBoards; } /** * @details Performs a OR operation between the all white pieces and all black pieces. Result is stored on the nColor bitboard, which contains all pieces on the board. */ void Bitboard::updateBitboard() { bitBoards[nColor] = bitBoards[nWhite] | bitBoards[nBlack]; } /** * @details Resets the bit of index \p idx of the bitboard \p color */ void Bitboard::resetBit(enumColor color, int idx) { bitBoards[color].reset(idx); } /** * @details Resets the bit of index \p idx of the bitboard \p piece */ void Bitboard::resetBit(enumPiece piece, int idx) { bitBoards[piece].reset(idx); } /** * @details Resets the bit of index \p idx of the bitboard \p i */ void Bitboard::resetBit(int i, int idx) { bitBoards[i].reset(idx); } /** * @details Sets the bit of index \p idx of the bitboard \p color */ void Bitboard::setBit(enumColor color, int idx) { bitBoards[color].set(idx); } /** * @details Sets the bit of index \p idx of the bitboard \p piece */ void Bitboard::setBit(enumPiece piece, int idx) { bitBoards[piece].set(idx); } /** * @details Sets the bit of index \p idx of the bitboard \p i */ void Bitboard::setBit(int i, int idx) { bitBoards[i].set(idx); } /** * @details Tests the bit of index \p idx of the bitboard \p color */ bool Bitboard::testBit(enumColor color, int idx) { return bitBoards[color].test(idx); } /** * @details Tests the bit of index \p idx of the bitboard \p piece */ bool Bitboard::testBit(enumPiece piece, int idx) { return bitBoards[piece].test(idx); } /** * @details Tests the bit of index \p idx of the bitboard \p i */ bool Bitboard::testBit(int i, int idx) { return bitBoards[i].test(idx); } /** * @details Converts the board from bitboards to a fancy string and prints it to stdout. */ void Bitboard::printBoard() { std::vector<std::string> board; std::string aux; long unsigned int i; for (i = 0; i < 64ul; i++) board.push_back("-"); for (i = 0; i < 64ul; i++) { if (bitBoards[nPawn].test(i)) { if (bitBoards[nBlack].test(i)) board[i] = "♟"; else board[i] = "♙"; } } for (i = 0; i < 64ul; i++) { if (bitBoards[nKnight].test(i)) { if (bitBoards[nBlack].test(i)) board[i] = "♞"; else board[i] = "♘"; } } for (i = 0; i < 64ul; i++) { if (bitBoards[nBishop].test(i)) { if (bitBoards[nBlack].test(i)) board[i] = "♝"; else board[i] = "♗"; } } for (i = 0; i < 64ul; i++) { if (bitBoards[nRook].test(i)) { if (bitBoards[nBlack].test(i)) board[i] = "♜"; else board[i] = "♖"; } } for (i = 0; i < 64ul; i++) { if (bitBoards[nQueen].test(i)) { if (bitBoards[nBlack].test(i)) board[i] = "♛"; else board[i] = "♕"; } } for (i = 0; i < 64ul; i++) { if (bitBoards[nKing].test(i)) { if (bitBoards[nBlack].test(i)) board[i] = "♚"; else board[i] = "♔"; } } for (i = 0; i < 64; i += 8) { std::cout << "\033[1;33m" << (64 - i) / 8 << " \033[0m"; for (int j = int(i + 7); j >= int(i); j--) std::cout << board[63 - j] << " "; std::cout << std::endl; } std::cout << " \033[1;33ma b c d e f g h\033[0m" << std::endl; }
23.899705
167
0.637373
[ "vector" ]
690ac6c28c223f130be34f1c562f533860e6ae07
682
cpp
C++
test/append_test.cpp
CppPhil/graph_algorithms
6742fccf83a85fd7b1e500ac495b35c7d0670b84
[ "Unlicense" ]
null
null
null
test/append_test.cpp
CppPhil/graph_algorithms
6742fccf83a85fd7b1e500ac495b35c7d0670b84
[ "Unlicense" ]
null
null
null
test/append_test.cpp
CppPhil/graph_algorithms
6742fccf83a85fd7b1e500ac495b35c7d0670b84
[ "Unlicense" ]
null
null
null
#include "gtest/gtest.h" #include <append.hpp> #include <vector> using namespace gp; using namespace std; TEST(append, firstEmpty) { const vector<int> result{append(vector<int>{}, vector<int>{1, 2, 3, 4})}; const vector<int> expected{1, 2, 3, 4}; EXPECT_EQ(result, expected); } TEST(append, secondEmpty) { const vector<int> result{append(vector<int>{1, 2, 3}, vector<int>{})}; const vector<int> expected{1, 2, 3}; EXPECT_EQ(result, expected); } TEST(append, appendTest) { const vector<int> result{ append(vector<int>{1, 2, 3}, vector<int>{4, 5, 6})}; const vector<int> expected{1, 2, 3, 4, 5, 6}; EXPECT_EQ(result, expected); }
19.485714
77
0.636364
[ "vector" ]
6917422e3016d69f26279d812437e8ba8a65f920
3,148
cpp
C++
crazyrc/rgb_txt_parser.cpp
mojmir-svoboda/BlackBoxTT
0c87b989827107695538e1bf1266c08b083dda44
[ "MIT" ]
11
2017-06-19T14:21:15.000Z
2020-03-04T06:43:16.000Z
crazyrc/rgb_txt_parser.cpp
mojmir-svoboda/BlackBoxTT
0c87b989827107695538e1bf1266c08b083dda44
[ "MIT" ]
null
null
null
crazyrc/rgb_txt_parser.cpp
mojmir-svoboda/BlackBoxTT
0c87b989827107695538e1bf1266c08b083dda44
[ "MIT" ]
3
2017-07-23T18:08:55.000Z
2019-09-16T16:28:18.000Z
#include "rgb_txt_parser.h" #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <boost/fusion/include/std_pair.hpp> #include <boost/spirit/repository/include/qi_confix.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_stl.hpp> #include <boost/spirit/include/phoenix_object.hpp> //#include <boost/variant/recursive_variant.hpp> #include <boost/foreach.hpp> #include <boost/assert.hpp> #include <boost/config/warning_disable.hpp> using namespace boost::spirit::standard_wide; #include <wtypes.h> #include <iostream> #include <fstream> #include <string> #include <cerrno> #include <tchar.h> #include <string> #include <vector> #include "utils_file.h" namespace qi = boost::spirit::qi; #include "color.h" BOOST_FUSION_ADAPT_STRUCT(Color, (int, r) (int, g) (int, b) (int, a)) namespace rgb_txt { rgb_txt_colors g_colorTable; rgb_txt_colors const & getColorTable () { return g_colorTable; } bool readColorFileToGlobalTable (tstring const & fileName) { if (g_colorTable.empty()) return readColorFileFrom(fileName, g_colorTable); return false; } bool reloadColorFileToGlobalTable (tstring const & fileName) { g_colorTable.clear(); return readColorFileFrom(fileName, g_colorTable); } } #include "rgbtxt_dump.h" namespace rgb_txt { template <typename Iterator> struct Grammar : qi::grammar<Iterator, file_type(), qi::space_type> { qi::rule<Iterator, pair_type(), qi::space_type> pair; qi::rule<Iterator, color_string_type()> color_name; qi::rule<Iterator, Color(), qi::space_type> value_rule; qi::rule<Iterator, file_type(), qi::space_type> file; Grammar () : Grammar::base_type(file) { color_name = *(qi::char_ - qi::eol); //value_rule %= qi::int_[qi::_a = qi::_1] >> qi::int_[qi::_b = qi::_1] >> qi::int_[qi::_val = boost::phoenix::construct<Color>(qi::_a, qi::_b, qi::_1)]; value_rule = qi::int_ >> qi::int_ >> qi::int_ >> qi::attr(0xFF); pair = value_rule >> color_name; file = * ( pair ); } }; bool readColorFileFrom (tstring const & fileName, rgb_txt::file_type & result) { tstring content; if (readFileContent(fileName, content)) { static rgb_txt::Grammar<tstring::iterator> const g; tstring::iterator begin = content.begin(); tstring::iterator end = content.end(); try { bool const r = qi::phrase_parse(begin, end, g, qi::space, result); if (r && begin == end) { //std::cout << result; return true; } else { /*std::cout << "+---- parser stopped here\n"; std::cout << "V\n"; if (std::distance(begin, end) > 120) { tstring rest(begin, begin + 120); std::cout << rest << "\n"; } else { tstring rest(begin, end); std::cout << rest << "\n"; }*/ return false; } } catch (...) { //std::cout << "Parsing failed" << std::endl; return false; } return true; } return false; } }
26.453782
155
0.662961
[ "vector" ]
69177f692dae2f94a1cea8e337cbfb3b664412f8
20,888
inl
C++
thrust/system/cuda/detail/sort.inl
MultithreadCorner/thrust-multi-permutation-iterator
c62bd5c6d8b29921f3759599b2586a9ce0e129a7
[ "Apache-2.0" ]
null
null
null
thrust/system/cuda/detail/sort.inl
MultithreadCorner/thrust-multi-permutation-iterator
c62bd5c6d8b29921f3759599b2586a9ce0e129a7
[ "Apache-2.0" ]
null
null
null
thrust/system/cuda/detail/sort.inl
MultithreadCorner/thrust-multi-permutation-iterator
c62bd5c6d8b29921f3759599b2586a9ce0e129a7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008-2012 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file sort.inl * \brief Inline file for sort.h */ #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/type_traits.h> #include <thrust/system/cuda/detail/detail/stable_merge_sort.h> #include <thrust/system/cuda/detail/detail/stable_primitive_sort.h> #include <thrust/gather.h> #include <thrust/reverse.h> #include <thrust/sequence.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/temporary_array.h> #include <thrust/system/cuda/detail/tag.h> #include <thrust/detail/function.h> #include <thrust/detail/trivial_sequence.h> /* * This file implements the following dispatch procedure for cuda::stable_sort() * and cuda::stable_sort_by_key(). All iterators are assumed to be "trivial * iterators" (i.e. pointer wrappers). The first level inspects the KeyType * and StrictWeakOrdering to determines whether a sort assuming primitive-typed data may be applied. * The second level inspects the KeyType to determine whether keys should * be sorted indirectly (i.e. sorting references to keys instead of keys * themselves). The third level inspects the ValueType to determine whether * the values should be sorted indirectly, again using references instead of * the values themselves. * * The second and third levels convert one sorting problem to another. * The second level converts a sort on T to a sort on integers that index * into an array of type T. Similarly, the third level converts a (key,value) * sort into a (key,index) sort where the indices record the permutation * used to sort the keys. The permuted indices are then used to reorder the * values. In either case, the transformation converts an ill-suited problem * (i.e. sorting with large keys or large values) into a problem more amenable * to the underlying sorting algorithms. * * Summary of the stable_sort() dispatch procedure: * Level 1: * if can_use_primitive_sort<KeyType,StrictWeakOrdering> * stable_primitive_sort() * else * Level2 stable_merge_sort() * * Level2: * if sizeof(KeyType) > 16 * add indirection to keys * stable_merge_sort() * permute keys * else * stable_merge_sort() * * Summary of the stable_sort_by_key() dispatch procedure: * Level 1: * if can_use_primitive_sort<KeyType,StrictWeakOrdering> * stable_primitive_sort_by_key() * else * Level2 stable_merge_sort_by_key() * * Level2: * if sizeof(KeyType) > 16 * add indirection to keys * Level3 stable_merge_sort_by_key() * permute keys * else * Level3 stable_merge_sort_by_key() * * Level3: * if sizeof(ValueType) != 4 * add indirection to values * stable_merge_sort_by_key() * permute values * else * stable_merge_sort_by_key() */ namespace thrust { namespace system { namespace cuda { namespace detail { namespace third_dispatch { // thrid level of the dispatch decision tree template<typename System, typename RandomAccessIterator1, typename RandomAccessIterator2, typename StrictWeakOrdering> void stable_merge_sort_by_key(dispatchable<System> &system, RandomAccessIterator1 keys_first, RandomAccessIterator1 keys_last, RandomAccessIterator2 values_first, StrictWeakOrdering comp, thrust::detail::true_type) { // sizeof(ValueType) != 4, use indirection and permute values typedef typename thrust::iterator_traits<RandomAccessIterator2>::value_type ValueType; thrust::detail::temporary_array<unsigned int, System> permutation(system, keys_last - keys_first); thrust::sequence(system, permutation.begin(), permutation.end()); thrust::system::cuda::detail::detail::stable_merge_sort_by_key (system, keys_first, keys_last, permutation.begin(), comp); RandomAccessIterator2 values_last = values_first + (keys_last - keys_first); thrust::detail::temporary_array<ValueType, System> temp(system, values_first, values_last); thrust::gather(system, permutation.begin(), permutation.end(), temp.begin(), values_first); } template<typename System, typename RandomAccessIterator1, typename RandomAccessIterator2, typename StrictWeakOrdering> void stable_merge_sort_by_key(dispatchable<System> &system, RandomAccessIterator1 keys_first, RandomAccessIterator1 keys_last, RandomAccessIterator2 values_first, StrictWeakOrdering comp, thrust::detail::false_type) { // sizeof(ValueType) == 4, sort values directly thrust::system::cuda::detail::detail::stable_merge_sort_by_key (system, keys_first, keys_last, values_first, comp); } } // end namespace third_dispatch namespace second_dispatch { // second level of the dispatch decision tree // add one level of indirection to the StrictWeakOrdering comp template <typename RandomAccessIterator, typename StrictWeakOrdering> struct indirect_comp { RandomAccessIterator first; thrust::detail::host_device_function< StrictWeakOrdering, bool > comp; indirect_comp(RandomAccessIterator first, StrictWeakOrdering comp) : first(first), comp(comp) {} template <typename IndexType> __host__ __device__ bool operator()(IndexType a, IndexType b) { return comp(*(first + a), *(first + b)); } }; template<typename System, typename RandomAccessIterator, typename StrictWeakOrdering> void stable_merge_sort(dispatchable<System> &system, RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp, thrust::detail::true_type) { // sizeof(KeyType) > 16, sort keys indirectly typedef typename thrust::iterator_traits<RandomAccessIterator>::value_type KeyType; thrust::detail::temporary_array<unsigned int,System> permutation(system, last - first); thrust::sequence(system, permutation.begin(), permutation.end()); thrust::system::cuda::detail::detail::stable_merge_sort (system, permutation.begin(), permutation.end(), indirect_comp<RandomAccessIterator,StrictWeakOrdering>(first, comp)); thrust::detail::temporary_array<KeyType,System> temp(system, first, last); thrust::gather(system, permutation.begin(), permutation.end(), temp.begin(), first); } template<typename System, typename RandomAccessIterator, typename StrictWeakOrdering> void stable_merge_sort(dispatchable<System> &system, RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp, thrust::detail::false_type) { // sizeof(KeyType) <= 16, sort keys directly thrust::system::cuda::detail::detail::stable_merge_sort(system, first, last, comp); } template<typename System, typename RandomAccessIterator1, typename RandomAccessIterator2, typename StrictWeakOrdering> void stable_merge_sort_by_key(dispatchable<System> &system, RandomAccessIterator1 keys_first, RandomAccessIterator1 keys_last, RandomAccessIterator2 values_first, StrictWeakOrdering comp, thrust::detail::true_type) { // sizeof(KeyType) > 16, sort keys indirectly typedef typename thrust::iterator_traits<RandomAccessIterator1>::value_type KeyType; thrust::detail::temporary_array<unsigned int, System> permutation(system, keys_last - keys_first); thrust::sequence(system, permutation.begin(), permutation.end()); // decide whether to sort values indirectly typedef typename thrust::iterator_traits<RandomAccessIterator2>::value_type ValueType; static const bool sort_values_indirectly = sizeof(ValueType) != 4; // XXX WAR unused variable warning (void) sort_values_indirectly; thrust::system::cuda::detail::third_dispatch::stable_merge_sort_by_key (system, permutation.begin(), permutation.end(), values_first, indirect_comp<RandomAccessIterator1,StrictWeakOrdering>(keys_first, comp), thrust::detail::integral_constant<bool, sort_values_indirectly>()); thrust::detail::temporary_array<KeyType,System> temp(system, keys_first, keys_last); thrust::gather(system, permutation.begin(), permutation.end(), temp.begin(), keys_first); } template<typename System, typename RandomAccessIterator1, typename RandomAccessIterator2, typename StrictWeakOrdering> void stable_merge_sort_by_key(dispatchable<System> &system, RandomAccessIterator1 keys_first, RandomAccessIterator1 keys_last, RandomAccessIterator2 values_first, StrictWeakOrdering comp, thrust::detail::false_type) { // sizeof(KeyType) <= 16, sort keys directly // decide whether to sort values indirectly typedef typename thrust::iterator_traits<RandomAccessIterator2>::value_type ValueType; static const bool sort_values_indirectly = sizeof(ValueType) != 4; // XXX WAR unused variable warning (void) sort_values_indirectly; thrust::system::cuda::detail::third_dispatch::stable_merge_sort_by_key (system, keys_first, keys_last, values_first, comp, thrust::detail::integral_constant<bool, sort_values_indirectly>()); } } // end namespace second_dispatch namespace first_dispatch { template<typename KeyType, typename StrictWeakCompare> struct can_use_primitive_sort : thrust::detail::and_< thrust::detail::is_arithmetic<KeyType>, thrust::detail::or_< thrust::detail::is_same<StrictWeakCompare,thrust::less<KeyType> >, thrust::detail::is_same<StrictWeakCompare,thrust::greater<KeyType> > > > {}; template<typename RandomAccessIterator, typename StrictWeakCompare> struct enable_if_primitive_sort : thrust::detail::enable_if< can_use_primitive_sort< typename iterator_value<RandomAccessIterator>::type, StrictWeakCompare >::value > {}; template<typename RandomAccessIterator, typename StrictWeakCompare> struct enable_if_comparison_sort : thrust::detail::disable_if< can_use_primitive_sort< typename iterator_value<RandomAccessIterator>::type, StrictWeakCompare >::value > {}; // first level of the dispatch decision tree template<typename System, typename RandomAccessIterator, typename StrictWeakOrdering> typename enable_if_primitive_sort<RandomAccessIterator,StrictWeakOrdering>::type stable_sort(dispatchable<System> &system, RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp) { // ensure sequence has trivial iterators thrust::detail::trivial_sequence<RandomAccessIterator,System> keys(system, first, last); // CUDA path for thrust::stable_sort with primitive keys // (e.g. int, float, short, etc.) and a less<T> or greater<T> comparison // method is implemented with a primitive sort thrust::system::cuda::detail::detail::stable_primitive_sort(system, keys.begin(), keys.end()); // copy results back, if necessary if(!thrust::detail::is_trivial_iterator<RandomAccessIterator>::value) { thrust::copy(system, keys.begin(), keys.end(), first); } // if comp is greater<T> then reverse the keys typedef typename thrust::iterator_traits<RandomAccessIterator>::value_type KeyType; const static bool reverse = thrust::detail::is_same<StrictWeakOrdering, typename thrust::greater<KeyType> >::value; if(reverse) { thrust::reverse(first, last); } } template<typename System, typename RandomAccessIterator, typename StrictWeakOrdering> typename enable_if_comparison_sort<RandomAccessIterator,StrictWeakOrdering>::type stable_sort(dispatchable<System> &system, RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp) { // decide whether to sort keys indirectly typedef typename thrust::iterator_traits<RandomAccessIterator>::value_type KeyType; static const bool sort_keys_indirectly = sizeof(KeyType) > 16; // XXX WAR unused variable warning (void) sort_keys_indirectly; // XXX magic constant determined by limited empirical testing // TODO more extensive tuning, consider vector types (e.g. int4) // path for thrust::stable_sort with general keys // and comparison methods is implemented with stable_merge_sort thrust::system::cuda::detail::second_dispatch::stable_merge_sort (system, first, last, comp, thrust::detail::integral_constant<bool, sort_keys_indirectly>()); } template<typename System, typename RandomAccessIterator1, typename RandomAccessIterator2, typename StrictWeakOrdering> typename enable_if_primitive_sort<RandomAccessIterator1,StrictWeakOrdering>::type stable_sort_by_key(dispatchable<System> &system, RandomAccessIterator1 keys_first, RandomAccessIterator1 keys_last, RandomAccessIterator2 values_first, StrictWeakOrdering comp) { // path for thrust::stable_sort_by_key with primitive keys // (e.g. int, float, short, etc.) and a less<T> or greater<T> comparison // method is implemented with stable_primitive_sort_by_key // if comp is greater<T> then reverse the keys and values typedef typename thrust::iterator_traits<RandomAccessIterator1>::value_type KeyType; const static bool reverse = thrust::detail::is_same<StrictWeakOrdering, typename thrust::greater<KeyType> >::value; // note, we also have to reverse the (unordered) input to preserve stability if (reverse) { thrust::reverse(system, keys_first, keys_last); thrust::reverse(system, values_first, values_first + (keys_last - keys_first)); } // ensure sequences have trivial iterators thrust::detail::trivial_sequence<RandomAccessIterator1,System> keys(system, keys_first, keys_last); thrust::detail::trivial_sequence<RandomAccessIterator2,System> values(system, values_first, values_first + (keys_last - keys_first)); thrust::system::cuda::detail::detail::stable_primitive_sort_by_key(system, keys.begin(), keys.end(), values.begin()); // copy results back, if necessary if(!thrust::detail::is_trivial_iterator<RandomAccessIterator1>::value) thrust::copy(system, keys.begin(), keys.end(), keys_first); if(!thrust::detail::is_trivial_iterator<RandomAccessIterator2>::value) thrust::copy(system, values.begin(), values.end(), values_first); if (reverse) { thrust::reverse(system, keys_first, keys_last); thrust::reverse(system, values_first, values_first + (keys_last - keys_first)); } } template<typename System, typename RandomAccessIterator1, typename RandomAccessIterator2, typename StrictWeakOrdering> typename enable_if_comparison_sort<RandomAccessIterator1,StrictWeakOrdering>::type stable_sort_by_key(dispatchable<System> &system, RandomAccessIterator1 keys_first, RandomAccessIterator1 keys_last, RandomAccessIterator2 values_first, StrictWeakOrdering comp) { // decide whether to sort keys indirectly typedef typename thrust::iterator_traits<RandomAccessIterator1>::value_type KeyType; static const bool sort_keys_indirectly = sizeof(KeyType) > 16; // XXX WAR unused variable warning (void) sort_keys_indirectly; // XXX magic constant determined by limited empirical testing // TODO more extensive tuning, consider vector types (e.g. int4) // path for thrust::stable_sort with general keys // and comparison methods is implemented with stable_merge_sort thrust::system::cuda::detail::second_dispatch::stable_merge_sort_by_key (system, keys_first, keys_last, values_first, comp, thrust::detail::integral_constant<bool, sort_keys_indirectly>()); } } // end namespace first_dispatch template<typename System, typename RandomAccessIterator, typename StrictWeakOrdering> void stable_sort(dispatchable<System> &system, RandomAccessIterator first, RandomAccessIterator last, StrictWeakOrdering comp) { // we're attempting to launch a kernel, assert we're compiling with nvcc // ======================================================================== // X Note to the user: If you've found this line due to a compiler error, X // X you need to compile your code using nvcc, rather than g++ or cl.exe X // ======================================================================== THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<RandomAccessIterator, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) ); first_dispatch::stable_sort(system, first, last, comp); } template<typename System, typename RandomAccessIterator1, typename RandomAccessIterator2, typename StrictWeakOrdering> void stable_sort_by_key(dispatchable<System> &system, RandomAccessIterator1 keys_first, RandomAccessIterator1 keys_last, RandomAccessIterator2 values_first, StrictWeakOrdering comp) { // we're attempting to launch a kernel, assert we're compiling with nvcc // ======================================================================== // X Note to the user: If you've found this line due to a compiler error, X // X you need to compile your code using nvcc, rather than g++ or cl.exe X // ======================================================================== THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<RandomAccessIterator1, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) ); first_dispatch::stable_sort_by_key(system, keys_first, keys_last, values_first, comp); } } // end namespace detail } // end namespace cuda } // end namespace system } // end namespace thrust
43.157025
155
0.635389
[ "vector" ]
691dbabdcd27bf906d9522825a2f9755e657f32b
2,855
cpp
C++
src/network/emg_data_client.cpp
BiRDLab-UMinho/trignoclient
507351e818b37199aa00aefedb124885dda1ea98
[ "MIT" ]
null
null
null
src/network/emg_data_client.cpp
BiRDLab-UMinho/trignoclient
507351e818b37199aa00aefedb124885dda1ea98
[ "MIT" ]
null
null
null
src/network/emg_data_client.cpp
BiRDLab-UMinho/trignoclient
507351e818b37199aa00aefedb124885dda1ea98
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include "core/sensor.hpp" #include "core/duration.hpp" // trigno::Duration #include "core/frame.hpp" // trigno::Frame #include "network/configuration.hpp" // trigno::network::MultiSensorConfiguration, trigno::network::ConnectionConfiguration #include "network/emg_data_client.hpp" namespace trigno::network { EMGDataClient::EMGDataClient(MultiSensorConfiguration* configuration) : BasicDataClient(ConnectionConfiguration::EMG_DATA_CHANNELS_PER_SENSOR * (sensor::ID::MAX + 1), configuration) { /* ... */ } EMGDataClient::EMGDataClient(MultiSensorConfiguration* configuration, const std::string& address, size_t emg_data_port, const Duration& timeout) : BasicDataClient(ConnectionConfiguration::EMG_DATA_CHANNELS_PER_SENSOR * (sensor::ID::MAX + 1), configuration, address, emg_data_port, timeout) { /* ... */ // no need to connect, BasicDataClient establishes connection on constructor! } void EMGDataClient::connect(const std::string& address, size_t port, const Duration& timeout) { // delegates to base implementation (but with different default arguments!) BasicDataClient::connect(address, port, timeout); } void EMGDataClient::reset() { // call base class reset() implementation BasicDataClient::reset(); // Trigno systems sample all data channels on each port @ same sample rate // therefore only need to check the sample rate for the first EMG channel on the first active sensor for (const auto& sensor : * _configuration) { if (sensor.isActive() && sensor.nEMGChannels()) { _sample_rate = sensor.sampleRate().front(); // first value is assured to be EMG channel! return; } } // throw std::runtime_error("[" + std::string(__func__) + "] No active EMG channels!"); } Frame EMGDataClient::buildFrame(const sensor::List& sensors) const { // intialize empty _frame Frame out; // ensure sensor list has values -> empty list returns empty frame // assert(sensors.size()); // parse only requested values/sensors // @note configuration must be up to date! for (const auto& sensor_id : sensors) { // check if active, skip if not if (!(*_configuration)[sensor_id].isActive()) { continue; } // get start index from configuration auto pos = (*_configuration)[sensor_id].startIndex() - 1; // add sample to frame // @note raw data is parsed by trigno::Sample constructor out.emplace_back(sensor_id, (*_configuration)[sensor_id].nEMGChannels(), &_buffer[pos * sizeof(DataValue)]); // preserve sensor label in output frame out.elements().back().key = _configuration->element(sensor_id).key; } return out; } } // namespace trigno::network
37.565789
148
0.680911
[ "vector" ]
6925b2bbc7f18dc42d7caedd27db5316ba4fa89e
1,219
cpp
C++
code-forces/Educational 84/C.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
1
2020-04-23T00:35:38.000Z
2020-04-23T00:35:38.000Z
code-forces/Educational 84/C.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
code-forces/Educational 84/C.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ENDL '\n' #define deb(u) cout << #u " : " << (u) << ENDL; #define deba(alias, u) cout << alias << ": " << (u) << ENDL; #define debp(u, v) cout << u << " : " << v << ENDL; #define pb push_back #define F first #define S second #define lli long long #define pii pair<int, int> #define pll pair<lli, lli> #define ALL(a) (a).begin(), (a).end() #define FOR(i, a, n) for (int i = (a); i < (n); ++i) #define FORN(i, a, n) for (int i = (a - 1); i >= n; --i) #define IO \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0) using namespace std; int main() { IO; int n, m, k; cin >> n >> m >> k; vector<pii> ini(k), to(k); FOR(i, 0, k) { cin >> ini[i].F >> ini[i].S; } FOR(i, 0, k) { cin >> ini[i].F >> ini[i].S; } int moves = n + m + n * m - 3; cout << moves << ENDL; FOR(i, 1, m) { cout << "L"; } FOR(i, 1, n) { cout << "U"; } FOR(i, 0, n) { if (i != 0) cout << "D"; if (i % 2 == 0) { FOR(i, 1, m) { cout << "R"; } } else { FOR(i, 1, m) { cout << "L"; } } } cout << ENDL; return 0; }
18.469697
60
0.423298
[ "vector" ]
6936f38fe562c8bf0e57a1e773b239222808fdf4
862
cpp
C++
contests/Codeforces Round #700 Div 2/Searching_local_minimum.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
2
2020-08-27T18:21:04.000Z
2020-08-30T13:24:39.000Z
contests/Codeforces Round #700 Div 2/Searching_local_minimum.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
null
null
null
contests/Codeforces Round #700 Div 2/Searching_local_minimum.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
null
null
null
// https://codeforces.com/contest/1480/problem/C #include <bits/stdc++.h> #define trace(x) cerr << #x << ": " << x << endl; #define all(v) v.begin(), v.end() #define int ll typedef long long ll; using namespace std; constexpr int oo = INT_MAX; void solve() { int n; cin >> n; vector<int> arr(n + 1, oo); int left = 1, right = n; int input; while (left < right) { int mid_1 = (left + right) / 2; int mid_2 = mid_1 + 1; cout << "? " << mid_1 << endl; cin >> input; arr[mid_1] = input; cout << "? " << mid_2 << endl; cin >> input; arr[mid_2] = input; if (arr[mid_1] < arr[mid_2]) { right = mid_1; } else { left = mid_2; } } cout << "! " << right << endl; } signed main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int tc = 1; // cin >> tc; while (tc--) { solve(); } return 0; }
14.862069
49
0.549884
[ "vector" ]
693896635ab96ab72e6b643dfd0efc77be38c6f7
432
cpp
C++
aoj/Volume00/0062/solve.cpp
tobyapi/online-judge-solutions
4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c
[ "MIT" ]
null
null
null
aoj/Volume00/0062/solve.cpp
tobyapi/online-judge-solutions
4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c
[ "MIT" ]
null
null
null
aoj/Volume00/0062/solve.cpp
tobyapi/online-judge-solutions
4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main(void){ string s; vector<int>num; while(cin >> s){ num.clear(); for(int i=0;i<10;i++) num.push_back(s[i]-'0'); vector<int>n; for(int i=0;i<9;i++){ for(int j=0;j<num.size()-1;j++){ n.push_back((num[j]+num[j+1])%10); } num=n; n.clear(); } cout << num[0] << endl; } return 0; }
16
38
0.518519
[ "vector" ]
6938bf57566f04ff98f10e34439b10adc951c4be
4,619
cc
C++
Cassie_Example/opt_two_step/gen/opt/J_torque_integral.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/gen/opt/J_torque_integral.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/gen/opt/J_torque_integral.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
/* * Automatically Generated from Mathematica. * Thu 14 Oct 2021 09:51:49 GMT-04:00 */ #ifdef MATLAB_MEX_FILE #include <stdexcept> #include <cmath> #include<math.h> /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ inline double Power(double x, double y) { return pow(x, y); } inline double Sqrt(double x) { return sqrt(x); } inline double Abs(double x) { return fabs(x); } inline double Exp(double x) { return exp(x); } inline double Log(double x) { return log(x); } inline double Sin(double x) { return sin(x); } inline double Cos(double x) { return cos(x); } inline double Tan(double x) { return tan(x); } inline double ArcSin(double x) { return asin(x); } inline double ArcCos(double x) { return acos(x); } inline double ArcTan(double x) { return atan(x); } /* update ArcTan function to use atan2 instead. */ inline double ArcTan(double x, double y) { return atan2(y,x); } inline double Sinh(double x) { return sinh(x); } inline double Cosh(double x) { return cosh(x); } inline double Tanh(double x) { return tanh(x); } const double E = 2.71828182845904523536029; const double Pi = 3.14159265358979323846264; const double Degree = 0.01745329251994329576924; inline double Sec(double x) { return 1/cos(x); } inline double Csc(double x) { return 1/sin(x); } #endif /* * Sub functions */ static void output1(double *p_output1,const double *var1,const double *var2,const double *var3) { double t380; double t391; double t433; double t436; double t437; double t456; double t491; double t501; double t508; double t517; double t540; double t552; double t565; t380 = Power(var2[9],2); t391 = Power(var2[0],2); t433 = Power(var2[1],2); t436 = Power(var2[2],2); t437 = Power(var2[3],2); t456 = Power(var2[4],2); t491 = Power(var2[5],2); t501 = Power(var2[6],2); t508 = Power(var2[7],2); t517 = Power(var2[8],2); t540 = t380 + t391 + t433 + t436 + t437 + t456 + t491 + t501 + t508 + t517; t552 = -1.*var1[0]; t565 = t552 + var1[1]; p_output1[0]=-1.*t540*var3[0]; p_output1[1]=t540*var3[0]; p_output1[2]=2.*t565*var2[0]*var3[0]; p_output1[3]=2.*t565*var2[1]*var3[0]; p_output1[4]=2.*t565*var2[2]*var3[0]; p_output1[5]=2.*t565*var2[3]*var3[0]; p_output1[6]=2.*t565*var2[4]*var3[0]; p_output1[7]=2.*t565*var2[5]*var3[0]; p_output1[8]=2.*t565*var2[6]*var3[0]; p_output1[9]=2.*t565*var2[7]*var3[0]; p_output1[10]=2.*t565*var2[8]*var3[0]; p_output1[11]=2.*t565*var2[9]*var3[0]; } #ifdef MATLAB_MEX_FILE #include "mex.h" /* * Main function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { size_t mrows, ncols; double *var1,*var2,*var3; double *p_output1; /* Check for proper number of arguments. */ if( nrhs != 3) { mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "Three input(s) required (var1,var2,var3)."); } else if( nlhs > 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments."); } /* The input must be a noncomplex double vector or scaler. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || ( !(mrows == 2 && ncols == 1) && !(mrows == 1 && ncols == 2))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong."); } mrows = mxGetM(prhs[1]); ncols = mxGetN(prhs[1]); if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || ( !(mrows == 10 && ncols == 1) && !(mrows == 1 && ncols == 10))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var2 is wrong."); } mrows = mxGetM(prhs[2]); ncols = mxGetN(prhs[2]); if( !mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || ( !(mrows == 1 && ncols == 1) && !(mrows == 1 && ncols == 1))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var3 is wrong."); } /* Assign pointers to each input. */ var1 = mxGetPr(prhs[0]); var2 = mxGetPr(prhs[1]); var3 = mxGetPr(prhs[2]); /* Create matrices for return arguments. */ plhs[0] = mxCreateDoubleMatrix((mwSize) 12, (mwSize) 1, mxREAL); p_output1 = mxGetPr(plhs[0]); /* Call the calculation subroutine. */ output1(p_output1,var1,var2,var3); } #else // MATLAB_MEX_FILE #include "J_torque_integral.hh" namespace LeftStance { void J_torque_integral_raw(double *p_output1, const double *var1,const double *var2,const double *var3) { // Call Subroutines output1(p_output1, var1, var2, var3); } } #endif // MATLAB_MEX_FILE
25.804469
104
0.639316
[ "vector" ]
6939b61c40b76cd88c302c25ea1701bf4f5a3791
17,501
cpp
C++
base/cluster/mgmt/cluscfg/server/ccluscfgcapabilities.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/cluster/mgmt/cluscfg/server/ccluscfgcapabilities.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/cluster/mgmt/cluscfg/server/ccluscfgcapabilities.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000-2001 Microsoft Corporation // // Module Name: // CClusCfgCapabilities.cpp // // Description: // This file contains the definition of the CClusCfgCapabilities class. // // The class CClusCfgCapabilities is the implementations of the // IClusCfgCapabilities interface. // // Maintained By: // Galen Barbee (GalenB) 12-DEC-2000 // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Include Files ////////////////////////////////////////////////////////////////////////////// #include "Pch.h" #include "CClusCfgCapabilities.h" #include <ClusRtl.h> ////////////////////////////////////////////////////////////////////////////// // Constant Definitions ////////////////////////////////////////////////////////////////////////////// DEFINE_THISCLASS( "CClusCfgCapabilities" ); //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgCapabilities class ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgCapabilities::S_HrCreateInstance // // Description: // Create a CClusCfgCapabilities instance. // // Arguments: // ppunkOut - // // Return Values: // Pointer to CClusCfgCapabilities instance. // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CClusCfgCapabilities::S_HrCreateInstance( IUnknown ** ppunkOut ) { TraceFunc( "" ); HRESULT hr = S_OK; CClusCfgCapabilities * pccs = NULL; if ( ppunkOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } // if: pccs = new CClusCfgCapabilities(); if ( pccs == NULL ) { hr = THR( E_OUTOFMEMORY ); goto Cleanup; } // if: error allocating object hr = THR( pccs->HrInit() ); if ( FAILED( hr ) ) { goto Cleanup; } // if: HrInit() failed hr = THR( pccs->TypeSafeQI( IUnknown, ppunkOut ) ); if ( FAILED( hr ) ) { goto Cleanup; } // if: QI failed Cleanup: if ( FAILED( hr ) ) { LogMsg( L"[SRV] CClusCfgCapabilities::S_HrCreateInstance() failed. (hr = %#08x)", hr ); } // if: if ( pccs != NULL ) { pccs->Release(); } // if: HRETURN( hr ); } //*** CClusCfgCapabilities::S_HrCreateInstance ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgCapabilities::S_RegisterCatIDSupport // // Description: // Registers/unregisters this class with the categories that it belongs // to. // // Arguments: // picrIn // Used to register/unregister our CATID support. // // fCreateIn // When true we are registering the server. When false we are // un-registering the server. // // Return Values: // S_OK // Success. // // E_INVALIDARG // The passed in ICatRgister pointer was NULL. // // other HRESULTs // Registration/Unregistration failed. // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CClusCfgCapabilities::S_RegisterCatIDSupport( ICatRegister * picrIn, BOOL fCreateIn ) { TraceFunc( "" ); HRESULT hr = S_OK; CATID rgCatIds[ 1 ]; if ( picrIn == NULL ) { hr = THR( E_INVALIDARG ); goto Cleanup; } // if: rgCatIds[ 0 ] = CATID_ClusCfgCapabilities; if ( fCreateIn ) { hr = THR( picrIn->RegisterClassImplCategories( CLSID_ClusCfgCapabilities, 1, rgCatIds ) ); } // if: Cleanup: HRETURN( hr ); } //*** CClusCfgCapabilities::S_RegisterCatIDSupport ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgCapabilities::CClusCfgCapabilities // // Description: // Constructor of the CClusCfgCapabilities class. This initializes // the m_cRef variable to 1 instead of 0 to account of possible // QueryInterface failure in DllGetClassObject. // // Arguments: // None. // // Return Value: // None. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// CClusCfgCapabilities::CClusCfgCapabilities( void ) : m_cRef( 1 ) , m_lcid( LOCALE_NEUTRAL ) { TraceFunc( "" ); // Increment the count of components in memory so the DLL hosting this // object cannot be unloaded. InterlockedIncrement( &g_cObjects ); Assert( m_picccCallback == NULL ); TraceFuncExit(); } //*** CClusCfgCapabilities::CClusCfgCapabilities ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgCapabilities::~CClusCfgCapabilities // // Description: // Destructor of the CClusCfgCapabilities class. // // Arguments: // None. // // Return Value: // None. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// CClusCfgCapabilities::~CClusCfgCapabilities( void ) { TraceFunc( "" ); if ( m_picccCallback != NULL ) { m_picccCallback->Release(); } // if: // There's going to be one less component in memory. Decrement component count. InterlockedDecrement( &g_cObjects ); TraceFuncExit(); } //*** CClusCfgCapabilities::~CClusCfgCapabilities //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgCapabilities -- IUknkown interface. ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // [IUnknown] // CClusCfgCapabilities::AddRef // // Description: // Increment the reference count of this object by one. // // Arguments: // None. // // Return Value: // The new reference count. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP_( ULONG ) CClusCfgCapabilities::AddRef( void ) { TraceFunc( "[IUnknown]" ); InterlockedIncrement( & m_cRef ); CRETURN( m_cRef ); } //*** CClusCfgCapabilities::AddRef ////////////////////////////////////////////////////////////////////////////// //++ // // [IUnknown] // CClusCfgCapabilities::Release // // Description: // Decrement the reference count of this object by one. // // Arguments: // None. // // Return Value: // The new reference count. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP_( ULONG ) CClusCfgCapabilities::Release( void ) { TraceFunc( "[IUnknown]" ); LONG cRef; cRef = InterlockedDecrement( &m_cRef ); if ( cRef == 0 ) { TraceDo( delete this ); } // if: reference count equal to zero CRETURN( cRef ); } //*** CClusCfgCapabilities::Release ////////////////////////////////////////////////////////////////////////////// //++ // // [IUnknown] // CClusCfgCapabilities::QueryInterface // // Description: // Query this object for the passed in interface. // // Arguments: // riidIn // Id of interface requested. // // ppvOut // Pointer to the requested interface. // // Return Value: // S_OK // If the interface is available on this object. // // E_NOINTERFACE // If the interface is not available. // // E_POINTER // ppvOut was NULL. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgCapabilities::QueryInterface( REFIID riidIn , void ** ppvOut ) { TraceQIFunc( riidIn, ppvOut ); HRESULT hr = S_OK; // // Validate arguments. // Assert( ppvOut != NULL ); if ( ppvOut == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } // // Handle known interfaces. // if ( IsEqualIID( riidIn, IID_IUnknown ) ) { *ppvOut = static_cast< IClusCfgCapabilities * >( this ); } // if: IUnknown else if ( IsEqualIID( riidIn, IID_IClusCfgInitialize ) ) { *ppvOut = TraceInterface( __THISCLASS__, IClusCfgInitialize, this, 0 ); } // else if: IClusCfgInitialize else if ( IsEqualIID( riidIn, IID_IClusCfgCapabilities ) ) { *ppvOut = TraceInterface( __THISCLASS__, IClusCfgCapabilities, this, 0 ); } // else if: IClusCfgCapabilities else { *ppvOut = NULL; hr = E_NOINTERFACE; } // // Add a reference to the interface if successful. // if ( SUCCEEDED( hr ) ) { ((IUnknown *) *ppvOut)->AddRef(); } // if: success Cleanup: QIRETURN_IGNORESTDMARSHALLING( hr, riidIn ); } //*** CClusCfgCapabilities::QueryInterface //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgCapabilities -- IClusCfgInitialize interface. ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // [IClusCfgInitialize] // CClusCfgCapabilities::Initialize // // Description: // Initialize this component. // // Arguments: // IN IUknown * punkCallbackIn // // IN LCID lcidIn // // Return Value: // S_OK // Success // // E_POINTER // The punkCallbackIn param is NULL. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgCapabilities::Initialize( IUnknown * punkCallbackIn, LCID lcidIn ) { TraceFunc( "[IClusCfgInitialize]" ); Assert( m_picccCallback == NULL ); HRESULT hr = S_OK; m_lcid = lcidIn; if ( punkCallbackIn == NULL ) { hr = THR( E_POINTER ); goto Cleanup; } // if: hr = THR( punkCallbackIn->TypeSafeQI( IClusCfgCallback, &m_picccCallback ) ); Cleanup: HRETURN( hr ); } //*** CClusCfgCapabilities::Initialize //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgCapabilities class -- IClusCfgCapabilities interfaces. ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // [IClusCfgCapabilities] // CClusCfgCapabilities::CanNodeBeClustered // // Description: // Can this node be added to a cluster? // // Arguments: // // // Return Value: // S_OK // Node can be clustered. // // S_FALSE // Node cannot be clustered. // // other HRESULTs // The call failed. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CClusCfgCapabilities::CanNodeBeClustered( void ) { TraceFunc( "[IClusCfgCapabilities]" ); HRESULT hr = S_OK; // // Since this only displays a warning there is no need to abort the whole // process if this call fails. // THR( HrCheckForSFM() ); hr = STHR( HrIsOSVersionValid() ); HRETURN( hr ); } //*** CClusCfgCapabilities::CanNodeBeClustered //*************************************************************************// ///////////////////////////////////////////////////////////////////////////// // CClusCfgCapabilities class -- Private Methods. ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgCapabilities::HrInit // // Description: // Initialize this component. // // Arguments: // None. // // Return Value: // S_OK // Success // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CClusCfgCapabilities::HrInit( void ) { TraceFunc( "" ); HRESULT hr = S_OK; // IUnknown Assert( m_cRef == 1 ); HRETURN( hr ); } //*** CClusCfgCapabilities::HrInit ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgCapabilities::HrCheckForSFM // // Description: // Checks for Services for Macintosh (SFM) and displays a warning // in the UI if found. // // Arguments: // None. // // Return Value: // S_OK // Success // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CClusCfgCapabilities::HrCheckForSFM( void ) { TraceFunc( "" ); HRESULT hr = S_OK; BOOL fSFMInstalled = FALSE; DWORD sc; sc = TW32( ClRtlIsServicesForMacintoshInstalled( &fSFMInstalled ) ); if ( sc == ERROR_SUCCESS ) { if ( fSFMInstalled ) { LogMsg( L"[SRV] Services for Macintosh was found on this node." ); hr = S_FALSE; STATUS_REPORT_REF( TASKID_Major_Check_Node_Feasibility , TASKID_Minor_ServicesForMac_Installed , IDS_WARN_SERVICES_FOR_MAC_INSTALLED , IDS_WARN_SERVICES_FOR_MAC_INSTALLED_REF , hr ); } // if: } // if: else { hr = MAKE_HRESULT( 0, FACILITY_WIN32, sc ); STATUS_REPORT_REF( TASKID_Major_Check_Node_Feasibility , TASKID_Minor_ServicesForMac_Installed , IDS_WARN_SERVICES_FOR_MAC_FAILED , IDS_WARN_SERVICES_FOR_MAC_FAILED_REF , hr ); } // else: hr = S_OK; HRETURN( hr ); } //*** CClusCfgCapabilities::HrCheckForSFM ////////////////////////////////////////////////////////////////////////////// //++ // // CClusCfgCapabilities::HrIsOSVersionValid // // Description: // Can this node be added to a cluster? // // Arguments: // None. // // Return Value: // S_OK // Node can be clustered. // // S_FALSE // Node cannot be clustered. // // other HRESULTs // The call failed. // // Remarks: // None. // //-- ////////////////////////////////////////////////////////////////////////////// HRESULT CClusCfgCapabilities::HrIsOSVersionValid( void ) { TraceFunc( "" ); HRESULT hr = S_OK; HRESULT hrSSR; BOOL fRet; BSTR bstrMsg = NULL; // // Get the message to be displayed in the UI for status reports. // hr = THR( HrLoadStringIntoBSTR( g_hInstance, IDS_VALIDATING_NODE_OS_VERSION, &bstrMsg ) ); if ( FAILED( hr ) ) { goto Cleanup; } // if: // // Send the initial status report to be displayed in the UI. // hrSSR = THR( HrSendStatusReport( m_picccCallback , TASKID_Major_Check_Node_Feasibility , TASKID_Minor_Validating_Node_OS_Version , 0 , 1 , 0 , S_OK , bstrMsg ) ); if ( FAILED( hrSSR ) ) { hr = hrSSR; goto Cleanup; } // if: // // Find out if the OS is valid for clustering. // fRet = ClRtlIsOSValid(); if ( ! fRet ) { DWORD sc = TW32( GetLastError() ); hrSSR = HRESULT_FROM_WIN32( sc ); hr = S_FALSE; } // if: else { hrSSR = S_OK; } // else: // // Send the final status report. // hrSSR = THR( HrSendStatusReport( m_picccCallback , TASKID_Major_Check_Node_Feasibility , TASKID_Minor_Validating_Node_OS_Version , 0 , 1 , 1 , hrSSR , bstrMsg ) ); if ( FAILED( hrSSR ) ) { hr = hrSSR; goto Cleanup; } // if: Cleanup: TraceSysFreeString( bstrMsg ); HRETURN( hr ); } //*** CClusCfgCapabilities::HrIsOSVersionValid
23.618084
99
0.427061
[ "object" ]
694d824f6806c461df6493dee545b053c368d5e5
181,979
cpp
C++
fennel/calctest/testCalc.cpp
alexavila150/luciddb
e3125564eb18238677e6efb384b630cab17bb472
[ "Apache-2.0" ]
14
2015-07-21T06:31:22.000Z
2020-05-13T14:18:33.000Z
fennel/calctest/testCalc.cpp
alexavila150/luciddb
e3125564eb18238677e6efb384b630cab17bb472
[ "Apache-2.0" ]
1
2020-05-04T23:08:51.000Z
2020-05-04T23:08:51.000Z
fennel/calctest/testCalc.cpp
alexavila150/luciddb
e3125564eb18238677e6efb384b630cab17bb472
[ "Apache-2.0" ]
22
2015-01-03T14:27:36.000Z
2021-09-14T02:09:13.000Z
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI 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. */ #ifndef __MSVC__ #include "fennel/common/CommonPreamble.h" #include "fennel/tuple/TupleDescriptor.h" #include "fennel/tuple/TupleData.h" #include "fennel/tuple/TupleAccessor.h" #include "fennel/tuple/TuplePrinter.h" #include "fennel/tuple/AttributeAccessor.h" #include "fennel/tuple/StandardTypeDescriptor.h" #include "fennel/common/TraceSource.h" #include "fennel/calculator/CalcCommon.h" // required as we're manipulating instructions #include "fennel/calculator/InstructionCommon.h" #include <boost/test/unit_test_suite.hpp> #include <stdlib.h> #include <stdio.h> #include <string> #include <boost/scoped_array.hpp> #include <limits> using namespace std; using namespace fennel; char* ProgramName; // JR 6/15/07 this construct: //instP = new (Instruction *)[200]; // no longer permitted as of GCC 4.0 - remove parens // so typedef an Instruction * and replace through-out file typedef Instruction *InstructionPtr; void fail(const char* str, int line) { assert(ProgramName); assert(str); printf("%s: unit test failed: |%s| line %d\n", ProgramName, str, line); exit(-1); } void unitTestBool() { printf("=========================================================\n"); printf("=========================================================\n"); printf("=====\n"); printf("===== unitTestBool()\n"); printf("=====\n"); printf("=========================================================\n"); printf("=========================================================\n"); bool isNullable = true; // Can tuple contain nulls? int i, registersize = 125; TupleDescriptor tupleDesc; tupleDesc.clear(); // Build up a description of what we'd like the tuple to look like StandardTypeDescriptorFactory typeFactory; for (i = 0;i < registersize; i++) { StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_BOOL); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); } // Create a tuple accessor from the description // // Note: Must use a NOT_NULL_AND_FIXED accessor when creating a tuple out // of the air like this, otherwise unmarshal() does not know what to do. If // you need a STANDARD type tuple that supports nulls, it has to be built // as a copy. TupleAccessor tupleAccessorFixedLiteral; TupleAccessor tupleAccessorFixedInput; TupleAccessor tupleAccessorFixedOutput; TupleAccessor tupleAccessorFixedLocal; TupleAccessor tupleAccessorFixedStatus; tupleAccessorFixedLiteral.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedInput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedOutput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedLocal.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedStatus.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); // Allocate memory for the tuple boost::scoped_array<FixedBuffer> pTupleBufFixedLiteral( new FixedBuffer[tupleAccessorFixedLiteral.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedInput( new FixedBuffer[tupleAccessorFixedInput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedOutput( new FixedBuffer[tupleAccessorFixedOutput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedLocal( new FixedBuffer[tupleAccessorFixedLocal.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedStatus( new FixedBuffer[tupleAccessorFixedStatus.getMaxByteCount()]); // Link memory to accessor tupleAccessorFixedLiteral.setCurrentTupleBuf( pTupleBufFixedLiteral.get(), false); tupleAccessorFixedInput.setCurrentTupleBuf( pTupleBufFixedInput.get(), false); tupleAccessorFixedOutput.setCurrentTupleBuf( pTupleBufFixedOutput.get(), false); tupleAccessorFixedLocal.setCurrentTupleBuf( pTupleBufFixedLocal.get(), false); tupleAccessorFixedStatus.setCurrentTupleBuf( pTupleBufFixedStatus.get(), false); // Create a vector of TupleDatum objects based on the description we built TupleData tupleDataFixedLiteral(tupleDesc); TupleData tupleDataFixedInput(tupleDesc); TupleData tupleDataFixedOutput(tupleDesc); TupleData tupleDataFixedLocal(tupleDesc); TupleData tupleDataFixedStatus(tupleDesc); // Do something mysterious. Probably binding pointers in the accessor to // items in the TupleData vector tupleAccessorFixedLiteral.unmarshal(tupleDataFixedLiteral); tupleAccessorFixedInput.unmarshal(tupleDataFixedInput); tupleAccessorFixedOutput.unmarshal(tupleDataFixedOutput); tupleAccessorFixedLocal.unmarshal(tupleDataFixedLocal); tupleAccessorFixedStatus.unmarshal(tupleDataFixedStatus); TupleData::iterator itr = tupleDataFixedLiteral.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<bool *>(const_cast<PBuffer>(itr->pData))) = false; } itr = tupleDataFixedInput.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<bool *>(const_cast<PBuffer>(itr->pData))) = false; } itr = tupleDataFixedOutput.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<bool *>(const_cast<PBuffer>(itr->pData))) = false; } itr = tupleDataFixedLocal.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<bool *>(const_cast<PBuffer>(itr->pData))) = false; } // create four nullable tuples to serve as register sets TupleData literal = tupleDataFixedLiteral; TupleData input = tupleDataFixedInput; TupleData output = tupleDataFixedOutput; TupleData local = tupleDataFixedLocal; TupleData status = tupleDataFixedStatus; // null out last element of each type int nullidx = registersize-1; literal[nullidx].pData = NULL; input[nullidx].pData = NULL; output[nullidx].pData = NULL; local[nullidx].pData = NULL; // Print out the nullable tuple TuplePrinter tuplePrinter; tuplePrinter.print(cout, tupleDesc, literal); cout << endl; tuplePrinter.print(cout, tupleDesc, input); cout << endl; tuplePrinter.print(cout, tupleDesc, output); cout << endl; tuplePrinter.print(cout, tupleDesc, local); cout << endl; // set up some nice literals for tests *(reinterpret_cast<bool *>(const_cast<PBuffer>((literal[0].pData)))) = false; *(reinterpret_cast<bool *>(const_cast<PBuffer>((literal[1].pData)))) = true; // predefine register references. a real compiler wouldn't do // something so regular and pre-determined. a compiler would // probably build these on the fly as it built each instruction. RegisterRef<bool> **bInP, **bOutP, **bLoP, **bLiP; bInP = new RegisterRef<bool>*[registersize]; bOutP = new RegisterRef<bool>*[registersize]; bLoP = new RegisterRef<bool>*[registersize]; bLiP = new RegisterRef<bool>*[registersize]; // Set up the Calculator DynamicParamManager dpm; Calculator c(&dpm,0,0,0,0,0,0); c.outputRegisterByReference(false); // set up register references to symbolically point to // their corresponding storage locations -- makes for easy test case // generation. again, a compiler wouldn't do things in quite // this way for (i = 0; i < registersize; i++) { bInP[i] = new RegisterRef<bool>( RegisterReference::EInput, i, STANDARD_TYPE_BOOL); c.appendRegRef(bInP[i]); bOutP[i] = new RegisterRef<bool>( RegisterReference::EOutput, i, STANDARD_TYPE_BOOL); c.appendRegRef(bOutP[i]); bLoP[i] = new RegisterRef<bool>( RegisterReference::ELocal, i, STANDARD_TYPE_BOOL); c.appendRegRef(bLoP[i]); bLiP[i] = new RegisterRef<bool>( RegisterReference::ELiteral, i, STANDARD_TYPE_BOOL); c.appendRegRef(bLiP[i]); } // Set up storage for instructions // a real compiler would probably cons up instructions and insert them // directly into the calculator. keep an array of the instructions at // this level to allow printing of the program after execution, and other // debugging Instruction **instP; instP = new InstructionPtr[200]; int pc = 0, outC = 0; // not instP[pc++] = new BoolNot(bOutP[outC++], bLiP[0]); instP[pc++] = new BoolNot(bOutP[outC++], bLiP[1]); instP[pc++] = new BoolNot(bOutP[outC++], bLiP[nullidx]); // and instP[pc++] = new BoolAnd(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolAnd(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolAnd(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolAnd(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolAnd(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolAnd(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolAnd(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolAnd(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolAnd(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // or instP[pc++] = new BoolOr(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolOr(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolOr(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolOr(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolOr(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolOr(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolOr(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolOr(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolOr(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // move instP[pc++] = new BoolMove(bOutP[outC++], bLiP[0]); instP[pc++] = new BoolMove(bOutP[outC++], bLiP[1]); instP[pc++] = new BoolMove(bOutP[outC++], bLiP[nullidx]); // is instP[pc++] = new BoolIs(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolIs(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolIs(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolIs(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolIs(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolIs(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolIs(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolIs(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolIs(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // isnot instP[pc++] = new BoolIsNot(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolIsNot(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolIsNot(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolIsNot(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolIsNot(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolIsNot(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolIsNot(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolIsNot(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolIsNot(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // equal instP[pc++] = new BoolEqual(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolEqual(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolEqual(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolEqual(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolEqual(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolEqual(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolEqual(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolEqual(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolEqual(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // notequal instP[pc++] = new BoolNotEqual(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolNotEqual(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolNotEqual(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolNotEqual(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolNotEqual(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolNotEqual(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolNotEqual(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolNotEqual(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolNotEqual(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // greater instP[pc++] = new BoolGreater(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolGreater(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolGreater(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolGreater(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolGreater(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolGreater(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolGreater(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolGreater(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolGreater(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // greaterequal instP[pc++] = new BoolGreaterEqual(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolGreaterEqual(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolGreaterEqual(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolGreaterEqual(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolGreaterEqual(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolGreaterEqual(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolGreaterEqual(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolGreaterEqual(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolGreaterEqual(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // less instP[pc++] = new BoolLess(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolLess(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolLess(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolLess(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolLess(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolLess(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolLess(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolLess(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolLess(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // lessequal instP[pc++] = new BoolLessEqual(bOutP[outC++], bLiP[0], bLiP[0]); instP[pc++] = new BoolLessEqual(bOutP[outC++], bLiP[1], bLiP[1]); instP[pc++] = new BoolLessEqual(bOutP[outC++], bLiP[0], bLiP[1]); instP[pc++] = new BoolLessEqual(bOutP[outC++], bLiP[1], bLiP[0]); instP[pc++] = new BoolLessEqual(bOutP[outC++], bLiP[nullidx], bLiP[0]); instP[pc++] = new BoolLessEqual(bOutP[outC++], bLiP[nullidx], bLiP[1]); instP[pc++] = new BoolLessEqual(bOutP[outC++], bLiP[0], bLiP[nullidx]); instP[pc++] = new BoolLessEqual(bOutP[outC++], bLiP[1], bLiP[nullidx]); instP[pc++] = new BoolLessEqual(bOutP[outC++], bLiP[nullidx], bLiP[nullidx]); // isnull instP[pc++] = new BoolIsNull(bOutP[outC++], bLiP[1]); instP[pc++] = new BoolIsNull(bOutP[outC++], bLiP[nullidx]); // isnotnull instP[pc++] = new BoolIsNotNull(bOutP[outC++], bLiP[1]); instP[pc++] = new BoolIsNotNull(bOutP[outC++], bLiP[nullidx]); // tonull instP[pc++] = new BoolToNull(bOutP[outC++]); int lastPC = pc; for (i = 0; i < pc; i++) { c.appendInstruction(instP[i]); } c.bind( RegisterReference::ELiteral, &literal, tupleDesc); c.bind( RegisterReference::EInput, &input, tupleDesc); c.bind( RegisterReference::EOutput, &output, tupleDesc); c.bind( RegisterReference::ELocal, &local, tupleDesc); c.bind( RegisterReference::EStatus, &status, tupleDesc); c.exec(); string out; for (i = 0; i < pc; i++) { instP[i]->describe(out, true); printf("[%2d] %s\n", i, out.c_str()); } if (!c.mWarnings.empty()) { fail("boolwarnings", __LINE__); } // Print out the output tuple tuplePrinter.print(cout, tupleDesc, output); cout << endl; outC = 0; // not if (*(output[outC++].pData) != true) { fail("boolnot1", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolnot2", __LINE__); } if (output[outC++].pData != NULL) { fail("boolnot3", __LINE__); } // and if (*(output[outC++].pData) != false) { fail("booland1", __LINE__); } if (*(output[outC++].pData) != true) { fail("booland2", __LINE__); } if (*(output[outC++].pData) != false) { fail("booland3", __LINE__); } if (*(output[outC++].pData) != false) { fail("booland4", __LINE__); } if (*(output[outC++].pData) != false) { fail("booland5", __LINE__); } if (output[outC++].pData != NULL) { fail("booland6", __LINE__); } if (*(output[outC++].pData) != false) { fail("booland7", __LINE__); } if (output[outC++].pData != NULL) { fail("booland8", __LINE__); } if (output[outC++].pData != NULL) { fail("booland9", __LINE__); } // or if (*(output[outC++].pData) != false) { fail("boolor1", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolor2", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolor3", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolor4", __LINE__); } if (output[outC++].pData != NULL) { fail("boolor5", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolor6", __LINE__); } if (output[outC++].pData != NULL) { fail("boolor7", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolor8", __LINE__); } if (output[outC++].pData != NULL) { fail("boolor9", __LINE__); } // move if (*(output[outC++].pData) != false) { fail("boolmove1", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolmove2", __LINE__); } if (output[outC++].pData != NULL) { fail("boolmove3", __LINE__); } // is if (*(output[outC++].pData) != true) { fail("boolis1", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolis2", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolis3", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolis4", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolis5", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolis6", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolis7", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolis8", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolis9", __LINE__); } // isnot if (*(output[outC++].pData) != false) { fail("boolisnot1", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolisnot2", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolisnot3", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolisnot4", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolisnot5", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolisnot6", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolisnot7", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolisnot8", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolisnot9", __LINE__); } // equal if (*(output[outC++].pData) != true) { fail("boolequal1", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolequal2", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolequal3", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolequal4", __LINE__); } if (output[outC++].pData != NULL) { fail("boolequal5", __LINE__); } if (output[outC++].pData != NULL) { fail("boolequal6", __LINE__); } if (output[outC++].pData != NULL) { fail("boolequal7", __LINE__); } if (output[outC++].pData != NULL) { fail("boolequal8", __LINE__); } if (output[outC++].pData != NULL) { fail("boolequal9", __LINE__); } // notequal if (*(output[outC++].pData) != false) { fail("boolnotequal1", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolnotequal2", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolnotequal3", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolnotequal4", __LINE__); } if (output[outC++].pData != NULL) { fail("boolnotequal5", __LINE__); } if (output[outC++].pData != NULL) { fail("boolnotequal6", __LINE__); } if (output[outC++].pData != NULL) { fail("boolnotequal7", __LINE__); } if (output[outC++].pData != NULL) { fail("boolnotequal8", __LINE__); } if (output[outC++].pData != NULL) { fail("boolnotequal9", __LINE__); } // greater if (*(output[outC++].pData) != false) { fail("boolgreater1", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolgreater2", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolgreater3", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolgreater4", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreater5", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreater6", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreater7", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreater8", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreater9", __LINE__); } // greaterequal if (*(output[outC++].pData) != true) { fail("boolgreaterequal1", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolgreaterequal2", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolgreaterequal3", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolgreaterequal4", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreaterequal5", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreaterequal6", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreaterequal7", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreaterequal8", __LINE__); } if (output[outC++].pData != NULL) { fail("boolgreaterequal9", __LINE__); } // less if (*(output[outC++].pData) != false) { fail("boolless1", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolless2", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolless3", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolless4", __LINE__); } if (output[outC++].pData != NULL) { fail("boolless5", __LINE__); } if (output[outC++].pData != NULL) { fail("boolless6", __LINE__); } if (output[outC++].pData != NULL) { fail("boolless7", __LINE__); } if (output[outC++].pData != NULL) { fail("boolless8", __LINE__); } if (output[outC++].pData != NULL) { fail("boolless9", __LINE__); } // lessequal if (*(output[outC++].pData) != true) { fail("boollessequal1", __LINE__); } if (*(output[outC++].pData) != true) { fail("boollessequal2", __LINE__); } if (*(output[outC++].pData) != true) { fail("boollessequal3", __LINE__); } if (*(output[outC++].pData) != false) { fail("boollessequal4", __LINE__); } if (output[outC++].pData != NULL) { fail("boollessequal5", __LINE__); } if (output[outC++].pData != NULL) { fail("boollessequal6", __LINE__); } if (output[outC++].pData != NULL) { fail("boollessequal7", __LINE__); } if (output[outC++].pData != NULL) { fail("boollessequal8", __LINE__); } if (output[outC++].pData != NULL) { fail("boollessequal9", __LINE__); } // isnull if (*(output[outC++].pData) != false) { fail("boolisnull1", __LINE__); } if (*(output[outC++].pData) != true) { fail("boolisnull1", __LINE__); } // isnotnull if (*(output[outC++].pData) != true) { fail("boolisnotnull1", __LINE__); } if (*(output[outC++].pData) != false) { fail("boolisnotnull1", __LINE__); } // tonull if (output[outC++].pData != NULL) { fail("booltonull1", __LINE__); } cout << "Calculator Warnings: " << c.warnings() << endl; delete [] bInP; delete [] bOutP; delete [] bLoP; delete [] bLiP; for (i = 0; i < lastPC; i++) { delete instP[i]; } delete [] instP; } void unitTestLong() { printf("=========================================================\n"); printf("=========================================================\n"); printf("=====\n"); printf("===== unitTestLong()\n"); printf("=====\n"); printf("=========================================================\n"); printf("=========================================================\n"); bool isNullable = true; // Can tuple contain nulls? int i, registersize = 200; TupleDescriptor tupleDesc; tupleDesc.clear(); // Build up a description of what we'd like the tuple to look like StandardTypeDescriptorFactory typeFactory; for (i = 0;i < registersize; i++) { // longs in first "half" StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_INT_32); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); } for (i = 0;i < registersize; i++) { // booleans in second "half" StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_UINT_8); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); } // Create a tuple accessor from the description // // Note: Must use a NOT_NULL_AND_FIXED accessor when creating a tuple out // of the air like this, otherwise unmarshal() does not know what to do. If // you need a STANDARD type tuple that supports nulls, it has to be built // as a copy. TupleAccessor tupleAccessorFixedLiteral; TupleAccessor tupleAccessorFixedInput; TupleAccessor tupleAccessorFixedOutput; TupleAccessor tupleAccessorFixedLocal; TupleAccessor tupleAccessorFixedStatus; tupleAccessorFixedLiteral.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedInput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedOutput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedLocal.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedStatus.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); // Allocate memory for the tuple boost::scoped_array<FixedBuffer> pTupleBufFixedLiteral( new FixedBuffer[tupleAccessorFixedLiteral.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedInput( new FixedBuffer[tupleAccessorFixedInput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedOutput( new FixedBuffer[tupleAccessorFixedOutput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedLocal( new FixedBuffer[tupleAccessorFixedLocal.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedStatus( new FixedBuffer[tupleAccessorFixedStatus.getMaxByteCount()]); // Link memory to accessor tupleAccessorFixedLiteral.setCurrentTupleBuf( pTupleBufFixedLiteral.get(), false); tupleAccessorFixedInput.setCurrentTupleBuf( pTupleBufFixedInput.get(), false); tupleAccessorFixedOutput.setCurrentTupleBuf( pTupleBufFixedOutput.get(), false); tupleAccessorFixedLocal.setCurrentTupleBuf( pTupleBufFixedLocal.get(), false); tupleAccessorFixedStatus.setCurrentTupleBuf( pTupleBufFixedStatus.get(), false); // Create a vector of TupleDatum objects based on the description we built TupleData tupleDataFixedLiteral(tupleDesc); TupleData tupleDataFixedInput(tupleDesc); TupleData tupleDataFixedOutput(tupleDesc); TupleData tupleDataFixedLocal(tupleDesc); TupleData tupleDataFixedStatus(tupleDesc); // Do something mysterious. Probably binding pointers in the accessor to // items in the TupleData vector tupleAccessorFixedLiteral.unmarshal(tupleDataFixedLiteral); tupleAccessorFixedInput.unmarshal(tupleDataFixedInput); tupleAccessorFixedOutput.unmarshal(tupleDataFixedOutput); tupleAccessorFixedLocal.unmarshal(tupleDataFixedLocal); tupleAccessorFixedStatus.unmarshal(tupleDataFixedStatus); // create four nullable tuples to serve as register sets TupleData literal = tupleDataFixedLiteral; TupleData input = tupleDataFixedInput; TupleData output = tupleDataFixedOutput; TupleData local = tupleDataFixedLocal; TupleData status = tupleDataFixedStatus; TupleData::iterator itr = literal.begin(); for (i = 0; i < registersize; i++, itr++) { // set up some nice literals for tests if (i % 2) { *(reinterpret_cast<int32_t *>(const_cast<PBuffer>(itr->pData))) = i * -1; } else { *(reinterpret_cast<int32_t *>(const_cast<PBuffer>(itr->pData))) = i; } } itr = input.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<int32_t *>(const_cast<PBuffer>(itr->pData))) = -1; } itr = output.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<int32_t *>(const_cast<PBuffer>(itr->pData))) = -1; } itr = local.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<int32_t *>(const_cast<PBuffer>(itr->pData))) = -1; } // set up boolean literals int falseIdx = 0; int trueIdx = 1; *(reinterpret_cast<bool *> (const_cast<PBuffer> (literal[trueIdx + registersize].pData))) = true; *(reinterpret_cast<bool *> (const_cast<PBuffer> (literal[falseIdx + registersize].pData))) = false; // null out last element of each type int nullidx = registersize - 1; literal[nullidx].pData = NULL; input[nullidx].pData = NULL; output[nullidx].pData = NULL; local[nullidx].pData = NULL; // also make a null in the boolean part of the literal set int boolnullidx = (2 * registersize) - 1; literal[boolnullidx].pData = NULL; // Print out the nullable tuple TuplePrinter tuplePrinter; printf("Literals\n"); tuplePrinter.print(cout, tupleDesc, literal); printf("\nInput\n"); tuplePrinter.print(cout, tupleDesc, input); cout << endl; printf("\nOutput\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("\nLocal\n"); tuplePrinter.print(cout, tupleDesc, local); cout << endl; // predefine register references. a real compiler wouldn't do // something so regular and pre-determined. a compiler would // probably build these on the fly as it built each instruction. // predefine register references. a real compiler wouldn't do // something so regular and pre-determined RegisterRef<int32_t> **bInP, **bOutP, **bLoP, **bLiP; RegisterRef<bool> **bOutBoolP, **bLiteralBoolP; bInP = new RegisterRef<int32_t>*[registersize]; bOutP = new RegisterRef<int32_t>*[registersize]; bLoP = new RegisterRef<int32_t>*[registersize]; bLiP = new RegisterRef<int32_t>*[registersize]; bOutBoolP = new RegisterRef<bool>*[registersize]; bLiteralBoolP = new RegisterRef<bool>*[registersize]; // Set up the Calculator DynamicParamManager dpm; Calculator c(&dpm,0,0,0,0,0,0); c.outputRegisterByReference(false); // set up register references to symbolically point to // their corresponding storage locations -- makes for easy test case // generation. again, a compiler wouldn't do things in quite // this way for (i = 0; i < registersize; i++) { bInP[i] = new RegisterRef<int32_t>( RegisterReference::EInput, i, STANDARD_TYPE_INT_32); c.appendRegRef(bInP[i]); bOutP[i] = new RegisterRef<int32_t>( RegisterReference::EOutput, i, STANDARD_TYPE_INT_32); c.appendRegRef(bOutP[i]); bLoP[i] = new RegisterRef<int32_t>( RegisterReference::ELocal, i, STANDARD_TYPE_INT_32); c.appendRegRef(bLoP[i]); bLiP[i] = new RegisterRef<int32_t>( RegisterReference::ELiteral, i, STANDARD_TYPE_INT_32); c.appendRegRef(bLiP[i]); bOutBoolP[i] = new RegisterRef<bool>( RegisterReference::EOutput, i + registersize, STANDARD_TYPE_BOOL); c.appendRegRef(bOutBoolP[i]); bLiteralBoolP[i] = new RegisterRef<bool>( RegisterReference::ELiteral, i + registersize, STANDARD_TYPE_BOOL); c.appendRegRef(bLiteralBoolP[i]); } // Set up storage for instructions // a real compiler would probably cons up instructions and insert them // directly into the calculator. keep an array of the instructions at // this level to allow printing of the program after execution, and other // debugging Instruction **instP; instP = new InstructionPtr[200]; int pc = 0, outC = 0, outBoolC = 0; StandardTypeDescriptorOrdinal isLong = STANDARD_TYPE_INT_32; // add instP[pc++] = new NativeAdd<int32_t>( bOutP[outC++], bLiP[10], bLiP[10], isLong); instP[pc++] = new NativeAdd<int32_t>( bOutP[outC++], bLiP[10], bLiP[9], isLong); instP[pc++] = new NativeAdd<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[9], isLong); instP[pc++] = new NativeAdd<int32_t>( bOutP[outC++], bLiP[10], bLiP[nullidx], isLong); instP[pc++] = new NativeAdd<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[nullidx], isLong); // sub instP[pc++] = new NativeSub<int32_t>( bOutP[outC++], bLiP[10], bLiP[9], isLong); instP[pc++] = new NativeSub<int32_t>( bOutP[outC++], bLiP[10], bLiP[10], isLong); instP[pc++] = new NativeSub<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[10], isLong); instP[pc++] = new NativeSub<int32_t>( bOutP[outC++], bLiP[10], bLiP[nullidx], isLong); instP[pc++] = new NativeSub<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[nullidx], isLong); // mul instP[pc++] = new NativeMul<int32_t>( bOutP[outC++], bLiP[4], bLiP[6], isLong); instP[pc++] = new NativeMul<int32_t>( bOutP[outC++], bLiP[4], bLiP[5], isLong); instP[pc++] = new NativeMul<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[5], isLong); instP[pc++] = new NativeMul<int32_t>( bOutP[outC++], bLiP[4], bLiP[nullidx], isLong); instP[pc++] = new NativeMul<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[nullidx], isLong); // div instP[pc++] = new NativeDiv<int32_t>( bOutP[outC++], bLiP[12], bLiP[4], isLong); instP[pc++] = new NativeDiv<int32_t>( bOutP[outC++], bLiP[12], bLiP[3], isLong); instP[pc++] = new NativeDiv<int32_t>( bOutP[outC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new NativeDiv<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new NativeDiv<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[nullidx], isLong); // div by zero int divbyzero = pc; instP[pc++] = new NativeDiv<int32_t>( bOutP[outC++], bLiP[4], bLiP[0], isLong); // neg instP[pc++] = new NativeNeg<int32_t>( bOutP[outC++], bLiP[3], isLong); instP[pc++] = new NativeNeg<int32_t>( bOutP[outC++], bLiP[6], isLong); instP[pc++] = new NativeNeg<int32_t>( bOutP[outC++], bLiP[nullidx], isLong); // move instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[3], isLong); instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[6], isLong); instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[nullidx], isLong); // mod instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[20], bLiP[4], isLong); instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[20], bLiP[6], isLong); instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[20], bLiP[5], isLong); instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[20], bLiP[7], isLong); instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[19], bLiP[7], isLong); instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[19], bLiP[4], isLong); instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[nullidx], isLong); // mod by zero int modbyzero = pc; instP[pc++] = new IntegralNativeMod<int32_t>( bOutP[outC++], bLiP[3], bLiP[0], isLong); // bitwise and instP[pc++] = new IntegralNativeAnd<int32_t>( bOutP[outC++], bLiP[4], bLiP[4], isLong); instP[pc++] = new IntegralNativeAnd<int32_t>( bOutP[outC++], bLiP[30], bLiP[4], isLong); instP[pc++] = new IntegralNativeAnd<int32_t>( bOutP[outC++], bLiP[30], bLiP[6], isLong); instP[pc++] = new IntegralNativeAnd<int32_t>( bOutP[outC++], bLiP[30], bLiP[32], isLong); instP[pc++] = new IntegralNativeAnd<int32_t>( bOutP[outC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new IntegralNativeAnd<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new IntegralNativeAnd<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[nullidx], isLong); // bitwise or instP[pc++] = new IntegralNativeOr<int32_t>( bOutP[outC++], bLiP[4], bLiP[4], isLong); instP[pc++] = new IntegralNativeOr<int32_t>( bOutP[outC++], bLiP[30], bLiP[64], isLong); instP[pc++] = new IntegralNativeOr<int32_t>( bOutP[outC++], bLiP[30], bLiP[0], isLong); instP[pc++] = new IntegralNativeOr<int32_t>( bOutP[outC++], bLiP[0], bLiP[0], isLong); instP[pc++] = new IntegralNativeOr<int32_t>( bOutP[outC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new IntegralNativeOr<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new IntegralNativeOr<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[nullidx], isLong); // bitwise shift left instP[pc++] = new IntegralNativeShiftLeft<int32_t>( bOutP[outC++], bLiP[4], bLiP[2], isLong); instP[pc++] = new IntegralNativeShiftLeft<int32_t>( bOutP[outC++], bLiP[4], bLiP[0], isLong); instP[pc++] = new IntegralNativeShiftLeft<int32_t>( bOutP[outC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new IntegralNativeShiftLeft<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new IntegralNativeShiftLeft<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[nullidx], isLong); // bitwise shift right instP[pc++] = new IntegralNativeShiftRight<int32_t>( bOutP[outC++], bLiP[4], bLiP[2], isLong); instP[pc++] = new IntegralNativeShiftRight<int32_t>( bOutP[outC++], bLiP[4], bLiP[0], isLong); instP[pc++] = new IntegralNativeShiftRight<int32_t>( bOutP[outC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new IntegralNativeShiftRight<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new IntegralNativeShiftRight<int32_t>( bOutP[outC++], bLiP[nullidx], bLiP[nullidx], isLong); // equal instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[0], bLiP[0], isLong); instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[4], bLiP[4], isLong); instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[9], bLiP[9], isLong); instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[3], bLiP[5], isLong); instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[5], bLiP[3], isLong); instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[6], bLiP[2], isLong); instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[2], bLiP[6], isLong); instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new BoolNativeEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[nullidx], isLong); // notequal instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[0], bLiP[0], isLong); instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[4], bLiP[4], isLong); instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[9], bLiP[9], isLong); instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[3], bLiP[5], isLong); instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[5], bLiP[3], isLong); instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[6], bLiP[2], isLong); instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[2], bLiP[6], isLong); instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new BoolNativeNotEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[nullidx], isLong); // greater instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[0], bLiP[0], isLong); instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[4], bLiP[4], isLong); instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[9], bLiP[9], isLong); instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[3], bLiP[5], isLong); instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[5], bLiP[3], isLong); instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[6], bLiP[2], isLong); instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[2], bLiP[6], isLong); instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new BoolNativeGreater<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[nullidx], isLong); // greaterequal instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[0], bLiP[0], isLong); instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[4], bLiP[4], isLong); instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[9], bLiP[9], isLong); instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[3], bLiP[5], isLong); instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[5], bLiP[3], isLong); instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[6], bLiP[2], isLong); instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[2], bLiP[6], isLong); instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new BoolNativeGreaterEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[nullidx], isLong); // less instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[0], bLiP[0], isLong); instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[4], bLiP[4], isLong); instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[9], bLiP[9], isLong); instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[3], bLiP[5], isLong); instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[5], bLiP[3], isLong); instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[6], bLiP[2], isLong); instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[2], bLiP[6], isLong); instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new BoolNativeLess<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[nullidx], isLong); // lessequal instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[0], bLiP[0], isLong); instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[4], bLiP[4], isLong); instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[9], bLiP[9], isLong); instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[3], bLiP[5], isLong); instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[5], bLiP[3], isLong); instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[6], bLiP[2], isLong); instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[2], bLiP[6], isLong); instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[12], bLiP[nullidx], isLong); instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[3], isLong); instP[pc++] = new BoolNativeLessEqual<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], bLiP[nullidx], isLong); // isnull instP[pc++] = new BoolNativeIsNull<int32_t>( bOutBoolP[outBoolC++], bLiP[12], isLong); instP[pc++] = new BoolNativeIsNull<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], isLong); // isnotnull instP[pc++] = new BoolNativeIsNotNull<int32_t>( bOutBoolP[outBoolC++], bLiP[12], isLong); instP[pc++] = new BoolNativeIsNotNull<int32_t>( bOutBoolP[outBoolC++], bLiP[nullidx], isLong); // tonull instP[pc++] = new NativeToNull<int32_t>( bOutP[outC++], isLong); // jump instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[22], isLong); instP[pc] = new Jump(pc + 2); pc++; instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[12], isLong); // bad flag // jumptrue instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[24], isLong); // jump here good flag instP[pc] = new JumpTrue(pc + 2, bLiteralBoolP[trueIdx]); pc++; // jump over bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[14], isLong); // bad flag instP[pc] = new JumpTrue(pc + 3, bLiteralBoolP[falseIdx]); pc++; // won't jump to bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[26], isLong); // good flag instP[pc] = new Jump(pc + 2); pc++; // jump over bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[18], isLong); // bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[28], isLong); // good flag // jumpfalse instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[34], isLong); // good flag instP[pc] = new JumpFalse(pc + 2, bLiteralBoolP[falseIdx]); pc++; // jump over bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[14], isLong); // bad flag instP[pc] = new JumpFalse(pc + 3, bLiteralBoolP[trueIdx]); pc++; // won't jump to bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[36], isLong); // good flag instP[pc] = new Jump(pc + 2); pc++; // jump over bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[18], isLong); // bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[38], isLong); // good flag // jumpnull instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[44], isLong); // good flag instP[pc] = new JumpNull(pc + 2, bLiteralBoolP[nullidx]); pc++; // jump over bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[14], isLong); // bad flag instP[pc] = new JumpNull(pc + 3, bLiteralBoolP[trueIdx]); pc++; // won't jump to bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[46], isLong); // good flag instP[pc] = new Jump(pc + 2); pc++; // jump over bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[18], isLong); // bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[48], isLong); // good flag // jumpnotnull instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[64], isLong); // good flag instP[pc] = new JumpNotNull(pc + 2, bLiteralBoolP[trueIdx]); pc++; // jump over bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[14], isLong); // bad flag instP[pc] = new JumpNotNull(pc + 3, bLiteralBoolP[nullidx]); pc++; // won't jump to bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[66], isLong); // good flag instP[pc] = new Jump(pc + 2); pc++; // jump over bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[18], isLong); // bad flag instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[68], isLong); // good flag // return instP[pc++] = new NativeMove<int32_t>( bOutP[outC], bLiP[70], isLong); // good flag instP[pc++] = new ReturnInstruction(); instP[pc++] = new NativeMove<int32_t>( bOutP[outC++], bLiP[15], isLong); // bad flag int lastPC = pc; for (i = 0; i < pc; i++) { c.appendInstruction(instP[i]); } c.bind( RegisterReference::ELiteral, &literal, tupleDesc); c.bind( RegisterReference::EInput, &input, tupleDesc); c.bind( RegisterReference::EOutput, &output, tupleDesc); c.bind( RegisterReference::ELocal, &local, tupleDesc); c.bind( RegisterReference::EStatus, &status, tupleDesc); c.exec(); string out; for (i = 0; i < pc; i++) { instP[i]->describe(out, true); printf("[%2d] %s\n", i, out.c_str()); } // Print out the output tuple printf("Output Tuple\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; outC = 0; outBoolC = registersize; // TODO tests to add: Maxint, minint, zeros, negatives, overflow, // underflow, etc // add if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 20) { fail("longadd1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 1) { fail("longadd2", __LINE__); } if (output[outC++].pData != NULL) { fail("longadd3", __LINE__); } if (output[outC++].pData != NULL) { fail("longadd4", __LINE__); } if (output[outC++].pData != NULL) { fail("longadd5", __LINE__); } // sub if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 19) { fail("longsub1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 0) { fail("longsub2", __LINE__); } if (output[outC++].pData != NULL) { fail("longsub3", __LINE__); } if (output[outC++].pData != NULL) { fail("longsub4", __LINE__); } if (output[outC++].pData != NULL) { fail("longsub5", __LINE__); } // mul if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 24) { fail("longmul1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != -20) { fail("longmul2", __LINE__); } if (output[outC++].pData != NULL) { fail("longmul3", __LINE__); } if (output[outC++].pData != NULL) { fail("longmul4", __LINE__); } if (output[outC++].pData != NULL) { fail("longmul5", __LINE__); } // div if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 3) { fail("longdiv1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != -4) { fail("longdiv2", __LINE__); } if (output[outC++].pData != NULL) { fail("longdiv3", __LINE__); } if (output[outC++].pData != NULL) { fail("longdiv4", __LINE__); } if (output[outC++].pData != NULL) { fail("longdiv5", __LINE__); } // div by zero assert(outC == divbyzero); if (output[outC++].pData != NULL) { fail("longdiv6", __LINE__); } deque<CalcMessage>::iterator iter = c.mWarnings.begin(); if (iter->pc != divbyzero) { fail("longdiv by zero failed, pc wrong\n", __LINE__); } string expectederror("22012"); if (expectederror.compare(iter->str)) { fail("longdiv by zero failed string was wrong", __LINE__); } // neg if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 3) { fail("longneg1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != -6) { fail("longneg2", __LINE__); } if (output[outC++].pData != NULL) { fail("longneg3", __LINE__); } // move if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != -3) { fail("longmove1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 6) { fail("longmove2", __LINE__); } if (output[outC++].pData != NULL) { fail("longmove3", __LINE__); } // mod if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 0) { fail("longmod1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 2) { fail("longmod2", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 0) { fail("longmod3", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 6) { fail("longmod4", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != -5) { fail("longmod5", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != -3) { fail("longmod6", __LINE__); } if (output[outC++].pData != NULL) { fail("longmod7", __LINE__); } if (output[outC++].pData != NULL) { fail("longmod8", __LINE__); } if (output[outC++].pData != NULL) { fail("longmod9", __LINE__); } // mod by zero assert(outC == modbyzero); if (output[outC++].pData != NULL) { fail("longmod10", __LINE__); } iter++; if (iter->pc != modbyzero) { fail("longmod by zero failed, pc wrong\n", __LINE__); } expectederror = "22012"; if (expectederror.compare(iter->str)) { fail("longmod by zero failed string was wrong", __LINE__); } // bitwise and if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 4) { fail("longbitand1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 4) { fail("longbitand2", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 6) { fail("longbitand3", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 0) { fail("longbitand4", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitand5", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitand6", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitand7", __LINE__); } // bitwise or if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 4) { fail("longbitor1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 94) { fail("longbitor2", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 30) { fail("longbitor3", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 0) { fail("longbitor4", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitor5", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitor6", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitor7", __LINE__); } // bitwise shift left if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 16) { fail("longbitshiftleft1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 4) { fail("longbitshiftleft2", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitshiftleft5", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitshiftleft6", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitshiftleft7", __LINE__); } // bitwise shift right if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 1) { fail("longbitshiftright1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 4) { fail("longbitshiftright2", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitshiftright5", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitshiftright6", __LINE__); } if (output[outC++].pData != NULL) { fail("longbitshiftright7", __LINE__); } // equal if (*(output[outBoolC++].pData) != true) { fail("longequal1", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longequal2", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longequal3", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longequal4", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longequal5", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longequal6", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longequal7", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longequal8", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longequal9", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longequal10", __LINE__); } // notequal if (*(output[outBoolC++].pData) != false) { fail("longnotequal1", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longnotequal2", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longnotequal3", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longnotequal4", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longnotequal5", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longnotequal6", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longnotequal7", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longnotequal8", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longnotequal9", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longnotequal10", __LINE__); } // greater if (*(output[outBoolC++].pData) != false) { fail("longgreater1", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longgreater2", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longgreater3", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longgreater4", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longgreater5", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longgreater6", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longgreater7", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longgreater8", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longgreater9", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longgreater10", __LINE__); } // greaterequal if (*(output[outBoolC++].pData) != true) { fail("longgreaterequal1", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longgreaterequal2", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longgreaterequal3", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longgreaterequal4", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longgreaterequal5", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longgreaterequal6", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longgreaterequal7", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longgreaterequal8", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longgreaterequal9", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longgreaterequal10", __LINE__); } // less if (*(output[outBoolC++].pData) != false) { fail("longless1", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longless2", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longless3", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longless4", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longless5", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longless6", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longless7", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longless8", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longless9", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longless10", __LINE__); } // lessequal if (*(output[outBoolC++].pData) != true) { fail("longlessequal1", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longlessequal2", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longlessequal3", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longlessequal4", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longlessequal5", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longlessequal6", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longlessequal7", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longlessequal8", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longlessequal9", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("longlessequal10", __LINE__); } // isnull if (*(output[outBoolC++].pData) != false) { fail("longisnull1", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("longisnull2", __LINE__); } // isnotnull if (*(output[outBoolC++].pData) != true) { fail("longisnotnull1", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("longisnotnull2", __LINE__); } // tonull if (output[outC++].pData != NULL) { fail("longtonull1", __LINE__); } // jump if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 22) { fail("longjump1", __LINE__); } // jumptrue if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 24) { fail("longjumptrue1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 26) { fail("longjumptrue2", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 28) { fail("longjumptrue3", __LINE__); } // jumpfalse if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 34) { fail("longjumpfalse1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 36) { fail("longjumpfalse2", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 38) { fail("longjumpfalse3", __LINE__); } // jumpnull if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 44) { fail("longjumpnull1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 46) { fail("longjumpnull2", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 48) { fail("longjumpnull3", __LINE__); } // jumpnotnull if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 64) { fail("longjumpnotnull1", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 66) { fail("longjumpnotnull2", __LINE__); } if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 68) { fail("longjumpnotnull3", __LINE__); } // return if (*(reinterpret_cast<const int32_t *>(output[outC++].pData)) != 70) { fail("longreturn", __LINE__); } cout << "Calculator Warnings: " << c.warnings() << endl; delete [] bInP; delete [] bOutP; delete [] bLoP; delete [] bLiP; delete [] bOutBoolP; delete [] bLiteralBoolP; for (i = 0; i < lastPC; i++) { delete instP[i]; } delete [] instP; } void unitTestFloat() { printf("=========================================================\n"); printf("=========================================================\n"); printf("=====\n"); printf("===== unitTestFloat()\n"); printf("=====\n"); printf("=========================================================\n"); printf("=========================================================\n"); bool isNullable = true; // Can tuple contain nulls? int i, registersize = 200; TupleDescriptor tupleDesc; tupleDesc.clear(); // Build up a description of what we'd like the tuple to look like StandardTypeDescriptorFactory typeFactory; for (i = 0;i < registersize; i++) { // float in first "half" StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_REAL); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); } for (i = 0;i < registersize; i++) { // booleans in second "half" StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_UINT_8); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); } // Create a tuple accessor from the description // // Note: Must use a NOT_NULL_AND_FIXED accessor when creating a tuple out // of the air like this, otherwise unmarshal() does not know what to do. If // you need a STANDARD type tuple that supports nulls, it has to be built // as a copy. TupleAccessor tupleAccessorFixedLiteral; TupleAccessor tupleAccessorFixedInput; TupleAccessor tupleAccessorFixedOutput; TupleAccessor tupleAccessorFixedLocal; TupleAccessor tupleAccessorFixedStatus; tupleAccessorFixedLiteral.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedInput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedOutput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedLocal.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedStatus.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); // Allocate memory for the tuple boost::scoped_array<FixedBuffer> pTupleBufFixedLiteral( new FixedBuffer[tupleAccessorFixedLiteral.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedInput( new FixedBuffer[tupleAccessorFixedInput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedOutput( new FixedBuffer[tupleAccessorFixedOutput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedLocal( new FixedBuffer[tupleAccessorFixedLocal.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedStatus( new FixedBuffer[tupleAccessorFixedStatus.getMaxByteCount()]); // Link memory to accessor tupleAccessorFixedLiteral.setCurrentTupleBuf( pTupleBufFixedLiteral.get(), false); tupleAccessorFixedInput.setCurrentTupleBuf( pTupleBufFixedInput.get(), false); tupleAccessorFixedOutput.setCurrentTupleBuf( pTupleBufFixedOutput.get(), false); tupleAccessorFixedLocal.setCurrentTupleBuf( pTupleBufFixedLocal.get(), false); tupleAccessorFixedStatus.setCurrentTupleBuf( pTupleBufFixedStatus.get(), false); // Create a vector of TupleDatum objects based on the description we built TupleData tupleDataFixedLiteral(tupleDesc); TupleData tupleDataFixedInput(tupleDesc); TupleData tupleDataFixedOutput(tupleDesc); TupleData tupleDataFixedLocal(tupleDesc); TupleData tupleDataFixedStatus(tupleDesc); // Do something mysterious. Probably binding pointers in the accessor to // items in the TupleData vector tupleAccessorFixedLiteral.unmarshal(tupleDataFixedLiteral); tupleAccessorFixedInput.unmarshal(tupleDataFixedInput); tupleAccessorFixedOutput.unmarshal(tupleDataFixedOutput); tupleAccessorFixedLocal.unmarshal(tupleDataFixedLocal); tupleAccessorFixedStatus.unmarshal(tupleDataFixedStatus); TupleData::iterator itr = tupleDataFixedLiteral.begin(); int neg = registersize / 2; for (i = 0; i < registersize; i++, itr++) { // set up some nice literals for tests if (i < neg) { *(reinterpret_cast<float *>(const_cast<PBuffer>(itr->pData))) = (float) i / 2; } else { *(reinterpret_cast<float *>(const_cast<PBuffer>(itr->pData))) = (float) (i - neg) / -2; } } itr = tupleDataFixedInput.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<float *>(const_cast<PBuffer>(itr->pData))) = -1; } itr = tupleDataFixedOutput.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<float *>(const_cast<PBuffer>(itr->pData))) = -1; } itr = tupleDataFixedLocal.begin(); for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<float *>(const_cast<PBuffer>(itr->pData))) = -1; } // set up boolean literals int falseIdx = 0; int trueIdx = 1; *(reinterpret_cast<bool *> (const_cast<PBuffer> (tupleDataFixedLiteral[trueIdx + registersize].pData))) = true; *(reinterpret_cast<bool *> (const_cast<PBuffer> (tupleDataFixedLiteral[falseIdx + registersize].pData))) = false; // Create another TupleData object that will be nullable TupleData literal = tupleDataFixedLiteral; TupleData input = tupleDataFixedInput; TupleData output = tupleDataFixedOutput; TupleData local = tupleDataFixedLocal; TupleData status = tupleDataFixedStatus; // null out last element of each type int nullidx = registersize - 1; literal[nullidx].pData = NULL; input[nullidx].pData = NULL; output[nullidx].pData = NULL; local[nullidx].pData = NULL; // also make a null in the boolean part of the literal set int boolnullidx = (2 * registersize) - 1; literal[boolnullidx].pData = NULL; // Print out the nullable tuple TuplePrinter tuplePrinter; printf("Literals\n"); tuplePrinter.print(cout, tupleDesc, literal); printf("\nInput\n"); tuplePrinter.print(cout, tupleDesc, input); cout << endl; printf("\nOutput\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("\nLocal\n"); tuplePrinter.print(cout, tupleDesc, local); cout << endl; // predefine register references. a real compiler wouldn't do // something so regular and pre-determined. a compiler would // probably build these on the fly as it built each instruction. // predefine register references. a real compiler wouldn't do // something so regular and pre-determined RegisterRef<float> **fInP, **fOutP, **fLoP, **fLiP; RegisterRef<bool> **bOutP; fInP = new RegisterRef<float>*[registersize]; fOutP = new RegisterRef<float>*[registersize]; fLoP = new RegisterRef<float>*[registersize]; fLiP = new RegisterRef<float>*[registersize]; bOutP = new RegisterRef<bool>*[registersize]; // Set up the Calculator DynamicParamManager dpm; Calculator c(&dpm,0,0,0,0,0,0); c.outputRegisterByReference(false); // set up register references to symbolically point to // their corresponding storage locations -- makes for easy test case // generation. again, a compiler wouldn't do things in quite // this way for (i = 0; i < registersize; i++) { fInP[i] = new RegisterRef<float>( RegisterReference::EInput, i, STANDARD_TYPE_REAL); c.appendRegRef(fInP[i]); fOutP[i] = new RegisterRef<float>( RegisterReference::EOutput, i, STANDARD_TYPE_REAL); c.appendRegRef(fOutP[i]); fLoP[i] = new RegisterRef<float>( RegisterReference::ELocal, i, STANDARD_TYPE_REAL); c.appendRegRef(fLoP[i]); fLiP[i] = new RegisterRef<float>( RegisterReference::ELiteral, i, STANDARD_TYPE_REAL); c.appendRegRef(fLiP[i]); bOutP[i] = new RegisterRef<bool>( RegisterReference::EOutput, i + registersize, STANDARD_TYPE_BOOL); c.appendRegRef(bOutP[i]); } // Set up storage for instructions // a real compiler would probably cons up instructions and insert them // directly into the calculator. keep an array of the instructions at // this level to allow printing of the program after execution, and other // debugging Instruction **instP; instP = new InstructionPtr[200]; int pc = 0, outC = 0, outBoolC = 0; StandardTypeDescriptorOrdinal isFloat = STANDARD_TYPE_REAL; // add instP[pc++] = new NativeAdd<float>( fOutP[outC++], fLiP[10], fLiP[10], isFloat); instP[pc++] = new NativeAdd<float>( fOutP[outC++], fLiP[10], fLiP[9], isFloat); instP[pc++] = new NativeAdd<float>( fOutP[outC++], fLiP[0], fLiP[0], isFloat); instP[pc++] = new NativeAdd<float>( fOutP[outC++], fLiP[neg], fLiP[neg], isFloat); // -0 + -0 instP[pc++] = new NativeAdd<float>( fOutP[outC++], fLiP[neg + 1], fLiP[neg + 2], isFloat); instP[pc++] = new NativeAdd<float>( fOutP[outC++], fLiP[nullidx], fLiP[9], isFloat); instP[pc++] = new NativeAdd<float>( fOutP[outC++], fLiP[10], fLiP[nullidx], isFloat); instP[pc++] = new NativeAdd<float>( fOutP[outC++], fLiP[nullidx], fLiP[nullidx], isFloat); // sub instP[pc++] = new NativeSub<float>( fOutP[outC++], fLiP[10], fLiP[9], isFloat); instP[pc++] = new NativeSub<float>( fOutP[outC++], fLiP[10], fLiP[10], isFloat); instP[pc++] = new NativeSub<float>( fOutP[outC++], fLiP[9], fLiP[0], isFloat); instP[pc++] = new NativeSub<float>( fOutP[outC++], fLiP[0], fLiP[0], isFloat); instP[pc++] = new NativeSub<float>( fOutP[outC++], fLiP[neg], fLiP[neg], isFloat); instP[pc++] = new NativeSub<float>( fOutP[outC++], fLiP[neg + 4], fLiP[neg + 1], isFloat); instP[pc++] = new NativeSub<float>( fOutP[outC++], fLiP[nullidx], fLiP[10], isFloat); instP[pc++] = new NativeSub<float>( fOutP[outC++], fLiP[10], fLiP[nullidx], isFloat); instP[pc++] = new NativeSub<float>( fOutP[outC++], fLiP[nullidx], fLiP[nullidx], isFloat); // mul instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[4], fLiP[6], isFloat); instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[5], fLiP[5], isFloat); instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[0], fLiP[0], isFloat); instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[neg], fLiP[neg], isFloat); instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[6], fLiP[neg], isFloat); instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[6], fLiP[0], isFloat); instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[neg + 7], fLiP[2], isFloat); instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[nullidx], fLiP[5], isFloat); instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[4], fLiP[nullidx], isFloat); instP[pc++] = new NativeMul<float>( fOutP[outC++], fLiP[nullidx], fLiP[nullidx], isFloat); // div instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[12], fLiP[4], isFloat); instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[12], fLiP[3], isFloat); instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[0], fLiP[3], isFloat); instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[neg], fLiP[3], isFloat); instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[neg + 9], fLiP[neg + 2], isFloat); instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[neg + 9], fLiP[1], isFloat); instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[12], fLiP[nullidx], isFloat); instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[nullidx], fLiP[3], isFloat); instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[nullidx], fLiP[nullidx], isFloat); // div by zero int divbyzero = pc; instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[4], fLiP[0], isFloat); instP[pc++] = new NativeDiv<float>( fOutP[outC++], fLiP[4], fLiP[neg], isFloat); // neg instP[pc++] = new NativeNeg<float>( fOutP[outC++], fLiP[3], isFloat); instP[pc++] = new NativeNeg<float>( fOutP[outC++], fLiP[neg + 3], isFloat); instP[pc++] = new NativeNeg<float>( fOutP[outC++], fLiP[0], isFloat); instP[pc++] = new NativeNeg<float>( fOutP[outC++], fLiP[neg], isFloat); instP[pc++] = new NativeNeg<float>( fOutP[outC++], fLiP[nullidx], isFloat); // move instP[pc++] = new NativeMove<float>( fOutP[outC++], fLiP[3], isFloat); instP[pc++] = new NativeMove<float>( fOutP[outC++], fLiP[6], isFloat); instP[pc++] = new NativeMove<float>( fOutP[outC++], fLiP[0], isFloat); instP[pc++] = new NativeMove<float>( fOutP[outC++], fLiP[neg], isFloat); instP[pc++] = new NativeMove<float>( fOutP[outC++], fLiP[nullidx], isFloat); // equal instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[0], fLiP[0], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[neg], fLiP[neg], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[4], fLiP[4], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[9], fLiP[9], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[3], fLiP[5], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[5], fLiP[3], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[6], fLiP[2], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[2], fLiP[6], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[neg + 5], fLiP[neg + 5], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[neg + 5], fLiP[neg + 6], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[12], fLiP[nullidx], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[3], isFloat); instP[pc++] = new BoolNativeEqual<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[nullidx], isFloat); // notequal instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[0], fLiP[0], isFloat); instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[4], fLiP[4], isFloat); instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[9], fLiP[9], isFloat); instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[3], fLiP[5], isFloat); instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[5], fLiP[3], isFloat); instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[6], fLiP[2], isFloat); instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[2], fLiP[6], isFloat); instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[12], fLiP[nullidx], isFloat); instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[3], isFloat); instP[pc++] = new BoolNativeNotEqual<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[nullidx], isFloat); // greater instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[0], fLiP[0], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[4], fLiP[4], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[9], fLiP[9], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[3], fLiP[5], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[5], fLiP[3], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[neg + 3], fLiP[neg + 5], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[neg + 5], fLiP[neg + 3], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[neg], fLiP[neg], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[7], fLiP[neg + 7], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[neg + 7], fLiP[7], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[12], fLiP[nullidx], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[3], isFloat); instP[pc++] = new BoolNativeGreater<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[nullidx], isFloat); // greaterequal instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[0], fLiP[0], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[4], fLiP[4], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[9], fLiP[9], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[3], fLiP[5], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[5], fLiP[3], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[neg + 3], fLiP[neg + 5], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[neg + 5], fLiP[neg + 3], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[neg], fLiP[neg], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[7], fLiP[neg + 7], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[neg + 7], fLiP[7], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[neg + 7], fLiP[neg + 7], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[12], fLiP[nullidx], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[3], isFloat); instP[pc++] = new BoolNativeGreaterEqual<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[nullidx], isFloat); // less instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[0], fLiP[0], isFloat); instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[4], fLiP[4], isFloat); instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[9], fLiP[9], isFloat); instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[3], fLiP[5], isFloat); instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[5], fLiP[3], isFloat); instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[neg + 3], fLiP[neg + 5], isFloat); instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[neg + 5], fLiP[neg + 3], isFloat); instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[12], fLiP[nullidx], isFloat); instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[3], isFloat); instP[pc++] = new BoolNativeLess<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[nullidx], isFloat); // lessequal instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[0], fLiP[0], isFloat); instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[4], fLiP[4], isFloat); instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[9], fLiP[9], isFloat); instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[3], fLiP[5], isFloat); instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[5], fLiP[3], isFloat); instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[neg + 3], fLiP[neg + 5], isFloat); instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[neg + 5], fLiP[neg + 3], isFloat); instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[12], fLiP[nullidx], isFloat); instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[3], isFloat); instP[pc++] = new BoolNativeLessEqual<float>( bOutP[outBoolC++], fLiP[nullidx], fLiP[nullidx], isFloat); // isnull instP[pc++] = new BoolNativeIsNull<float>( bOutP[outBoolC++], fLiP[12], isFloat); instP[pc++] = new BoolNativeIsNull<float>( bOutP[outBoolC++], fLiP[nullidx], isFloat); // isnotnull instP[pc++] = new BoolNativeIsNotNull<float>( bOutP[outBoolC++], fLiP[12], isFloat); instP[pc++] = new BoolNativeIsNotNull<float>( bOutP[outBoolC++], fLiP[nullidx], isFloat); // tonull instP[pc++] = new NativeToNull<float>( fOutP[outC++], isFloat); // return instP[pc++] = new NativeMove<float>( fOutP[outC], fLiP[20], isFloat); // good flag instP[pc++] = new ReturnInstruction(); instP[pc++] = new NativeMove<float>( fOutP[outC++], fLiP[10], isFloat); // bad flag int lastPC = pc; for (i = 0; i < pc; i++) { c.appendInstruction(instP[i]); } c.bind( RegisterReference::ELiteral, &literal, tupleDesc); c.bind( RegisterReference::EInput, &input, tupleDesc); c.bind( RegisterReference::EOutput, &output, tupleDesc); c.bind( RegisterReference::ELocal, &local, tupleDesc); c.bind( RegisterReference::EStatus, &status, tupleDesc); c.exec(); string out; for (i = 0; i < pc; i++) { instP[i]->describe(out, true); printf("[%2d] %s\n", i, out.c_str()); } // Print out the output tuple printf("Output Tuple\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; outC = 0; outBoolC = registersize; // TODO tests to add: Maxint, minint, zeros, negatives, overflow, // underflow, etc // add if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 10) { fail("floatadd1", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 9.5) { fail("floatadd2", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatadd3", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatadd4", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != -1.5) { fail("floatadd5", __LINE__); } if (output[outC++].pData != NULL) { fail("floatadd6", __LINE__); } if (output[outC++].pData != NULL) { fail("floatadd7", __LINE__); } if (output[outC++].pData != NULL) { fail("floatadd8", __LINE__); } // sub if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0.5) { fail("floatsub1", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatsub2", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 4.5) { fail("floatsub3", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatsub4", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatsub5", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != -1.5) { fail("floatsub6", __LINE__); } if (output[outC++].pData != NULL) { fail("floatsub7", __LINE__); } if (output[outC++].pData != NULL) { fail("floatsub8", __LINE__); } if (output[outC++].pData != NULL) { fail("floatsub9", __LINE__); } // mul if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 6) { fail("floatmul1", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 6.25) { fail("floatmul2", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatmul3", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatmul4", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatmul5", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatmul6", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != -3.5) { fail("floatmul7", __LINE__); } if (output[outC++].pData != NULL) { fail("floatmul8", __LINE__); } if (output[outC++].pData != NULL) { fail("floatmul9", __LINE__); } if (output[outC++].pData != NULL) { fail("floatmul10", __LINE__); } // div if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 3) { fail("floatdiv1", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 4) { fail("floatdiv2", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatdiv3", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatdiv4", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 4.5) { fail("floatdiv5", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != -9) { fail("floatdiv6", __LINE__); } if (output[outC++].pData != NULL) { fail("floatdiv7", __LINE__); } if (output[outC++].pData != NULL) { fail("floatdiv8", __LINE__); } if (output[outC++].pData != NULL) { fail("floatdiv9", __LINE__); } // div by zero assert(outC == divbyzero); if (output[outC++].pData != NULL) { fail("floatdiv10", __LINE__); } deque<CalcMessage>::iterator iter = c.mWarnings.begin(); if (iter->pc != divbyzero) { fail("floatdiv by zero failed, pc wrong\n", __LINE__); } string expectederror("22012"); if (expectederror.compare(iter->str)) { fail("floatdiv by zero failed string was wrong", __LINE__); } if (output[outC++].pData != NULL) { fail("floatdiv11", __LINE__); } iter++; if (iter->pc != divbyzero + 1) { fail("floatdiv by zero failed, pc wrong\n", __LINE__); } if (expectederror.compare(iter->str)) { fail("floatdiv by zero failed string was wrong", __LINE__); } // neg if (*(reinterpret_cast<const float *>(output[outC++].pData)) != -1.5) { fail("floatneg1", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 1.5) { fail("floatneg2", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatneg3", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatneg4", __LINE__); } if (output[outC++].pData != NULL) { fail("floatneg5", __LINE__); } // move if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 1.5) { fail("floatmove1", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 3) { fail("floatmove2", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatmove3", __LINE__); } if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 0) { fail("floatmove4", __LINE__); } if (output[outC++].pData != NULL) { fail("floatmove5", __LINE__); } // equal if (*(output[outBoolC++].pData) != true) { fail("floatequal1", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatequal2", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatequal3", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatequal4", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatequal5", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatequal6", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatequal7", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatequal8", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatequal9", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatequal10", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatequal11", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatequal12", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatequal13", __LINE__); } // notequal if (*(output[outBoolC++].pData) != false) { fail("floatnotequal1", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatnotequal2", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatnotequal3", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatnotequal4", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatnotequal5", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatnotequal6", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatnotequal7", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatnotequal8", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatnotequal9", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatnotequal10", __LINE__); } // greater if (*(output[outBoolC++].pData) != false) { fail("floatgreater1", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatgreater2", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatgreater3", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatgreater4", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreater5", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreater6", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatgreater7", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatgreater8", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreater9", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatgreater10", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatgreater11", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatgreater12", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatgreater13", __LINE__); } // greaterequal if (*(output[outBoolC++].pData) != true) { fail("floatgreaterequal1", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreaterequal2", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreaterequal3", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatgreaterequal4", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreaterequal5", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreaterequal6", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatgreaterequal7", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreaterequal8", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreaterequal9", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatgreaterequal10", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatgreaterequal11", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatgreaterequal12", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatgreaterequal13", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatgreaterequal14", __LINE__); } // less if (*(output[outBoolC++].pData) != false) { fail("floatless1", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatless2", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatless3", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatless4", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatless5", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatless6", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatless7", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatless8", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatless9", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatless10", __LINE__); } // lessequal if (*(output[outBoolC++].pData) != true) { fail("floatlessequal1", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatlessequal2", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatlessequal3", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatlessequal4", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatlessequal5", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatlessequal6", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatlessequal7", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatlessequal8", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatlessequal9", __LINE__); } if (output[outBoolC++].pData != NULL) { fail("floatlessequal10", __LINE__); } // isnull if (*(output[outBoolC++].pData) != false) { fail("floatisnull1", __LINE__); } if (*(output[outBoolC++].pData) != true) { fail("floatisnull2", __LINE__); } // isnotnull if (*(output[outBoolC++].pData) != true) { fail("floatisnotnull1", __LINE__); } if (*(output[outBoolC++].pData) != false) { fail("floatisnotnull2", __LINE__); } // tonull if (output[outC++].pData != NULL) { fail("floattonull1", __LINE__); } // return if (*(reinterpret_cast<const float *>(output[outC++].pData)) != 10) { fail("floatreturn", __LINE__); } cout << "Calculator Warnings: " << c.warnings() << endl; delete [] fInP; delete [] fOutP; delete [] fLoP; delete [] fLiP; delete [] bOutP; for (i = 0; i < lastPC; i++) { delete instP[i]; } delete [] instP; } void unitTestPointer() { printf("=========================================================\n"); printf("=========================================================\n"); printf("=====\n"); printf("===== unitTestPointer()\n"); printf("=====\n"); printf("=========================================================\n"); printf("=========================================================\n"); bool isNullable = true; // Can tuple contain nulls? int i, registersize = 100; static uint bufferlen = 8; TupleDescriptor tupleDesc; tupleDesc.clear(); // Build up a description of what we'd like the tuple to look like StandardTypeDescriptorFactory typeFactory; int idx = 0; const int pointerIdx = idx; for (i = 0;i < registersize; i++) { // pointers in first "half" StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_VARCHAR); // tell descriptor the size tupleDesc.push_back( TupleAttributeDescriptor( typeDesc, isNullable, bufferlen)); idx++; } const int ulongIdx = idx; for (i = 0;i < registersize; i++) { // unsigned longs in third "half" // will serve as PointerSizeT StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_UINT_32); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); idx++; } const int boolIdx = idx; for (i = 0;i < registersize; i++) { // booleans in fourth "half" StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_UINT_8); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); idx++; } // Create a tuple accessor from the description // // Note: Must use a NOT_NULL_AND_FIXED accessor when creating a tuple out // of the air like this, otherwise unmarshal() does not know what to do. If // you need a STANDARD type tuple that supports nulls, it has to be built // as a copy. TupleAccessor tupleAccessorFixedLiteral; TupleAccessor tupleAccessorFixedInput; TupleAccessor tupleAccessorFixedOutput; TupleAccessor tupleAccessorFixedLocal; TupleAccessor tupleAccessorFixedStatus; tupleAccessorFixedLiteral.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedInput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedOutput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedLocal.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedStatus.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); // Allocate memory for the tuple boost::scoped_array<FixedBuffer> pTupleBufFixedLiteral( new FixedBuffer[tupleAccessorFixedLiteral.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedInput( new FixedBuffer[tupleAccessorFixedInput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedOutput( new FixedBuffer[tupleAccessorFixedOutput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedLocal( new FixedBuffer[tupleAccessorFixedLocal.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedStatus( new FixedBuffer[tupleAccessorFixedStatus.getMaxByteCount()]); // Link memory to accessor tupleAccessorFixedLiteral.setCurrentTupleBuf( pTupleBufFixedLiteral.get(), false); tupleAccessorFixedInput.setCurrentTupleBuf( pTupleBufFixedInput.get(), false); tupleAccessorFixedOutput.setCurrentTupleBuf( pTupleBufFixedOutput.get(), false); tupleAccessorFixedLocal.setCurrentTupleBuf( pTupleBufFixedLocal.get(), false); tupleAccessorFixedStatus.setCurrentTupleBuf( pTupleBufFixedStatus.get(), false); // Create a vector of TupleDatum objects based on the description we built TupleData tupleDataFixedLiteral(tupleDesc); TupleData tupleDataFixedInput(tupleDesc); TupleData tupleDataFixedOutput(tupleDesc); TupleData tupleDataFixedLocal(tupleDesc); TupleData tupleDataFixedStatus(tupleDesc); // Do something mysterious. Probably binding pointers in the accessor to // items in the TupleData vector tupleAccessorFixedLiteral.unmarshal(tupleDataFixedLiteral); tupleAccessorFixedInput.unmarshal(tupleDataFixedInput); tupleAccessorFixedOutput.unmarshal(tupleDataFixedOutput); tupleAccessorFixedLocal.unmarshal(tupleDataFixedLocal); tupleAccessorFixedStatus.unmarshal(tupleDataFixedStatus); // create four nullable tuples to serve as register sets TupleData literal = tupleDataFixedLiteral; TupleData input = tupleDataFixedInput; TupleData output = tupleDataFixedOutput; TupleData local = tupleDataFixedLocal; TupleData status = tupleDataFixedStatus; TupleData::iterator itr; // Set up some useful literals itr = literal.begin(); for (i = 0; i < registersize; i++, itr++) { char num[16]; sprintf(num, "%04d", i); char* ptr = reinterpret_cast<char *>(const_cast<PBuffer>(itr->pData)); memset(ptr, 'C', bufferlen); // VARCHAR is not null terminated memcpy(ptr, num, 4); // copy number, but not null } for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<uint32_t *>(const_cast<PBuffer>(itr->pData))) = i; } for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<bool *>(const_cast<PBuffer>(itr->pData))) = false; } // Put some data other tuples as well itr = input.begin(); for (i = 0; i < registersize; i++, itr++) { char num[16]; sprintf(num, "%04d", i); char *ptr = reinterpret_cast<char *>(const_cast<PBuffer>(itr->pData)); memset(ptr, 'I', bufferlen); // VARCHAR is not null terminated memcpy(ptr, num, 4); // copy number, but not null } for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<uint32_t *>(const_cast<PBuffer>(itr->pData))) = 0; } for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<bool *>(const_cast<PBuffer>(itr->pData))) = false; } itr = output.begin(); for (i = 0; i < registersize; i++, itr++) { char* ptr = reinterpret_cast<char *>(const_cast<PBuffer>(itr->pData)); memset(ptr, 'O', bufferlen); // VARCHAR is not null terminated } for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<uint32_t *>(const_cast<PBuffer>(itr->pData))) = 0; } for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<bool *>(const_cast<PBuffer>(itr->pData))) = false; } itr = local.begin(); for (i = 0; i < registersize; i++, itr++) { char* ptr = reinterpret_cast<char *>(const_cast<PBuffer>(itr->pData)); memset(ptr, 'L', bufferlen); // VARCHAR is not null terminated } for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<uint32_t *>(const_cast<PBuffer>(itr->pData))) = 0; } for (i = 0; i < registersize; i++, itr++) { *(reinterpret_cast<bool *>(const_cast<PBuffer>(itr->pData))) = false; } // set up boolean literals int falseIdx = 0; int trueIdx = 1; *(reinterpret_cast<bool *> (const_cast<PBuffer> (literal[trueIdx + boolIdx].pData))) = true; *(reinterpret_cast<bool *> (const_cast<PBuffer> (literal[falseIdx + boolIdx].pData))) = false; // null out last element of each type int pointerNullIdx = pointerIdx + registersize - 1; int ulongNullIdx = ulongIdx + registersize - 1; int boolNullIdx = boolIdx + registersize - 1; literal[pointerNullIdx].pData = NULL; literal[ulongNullIdx].pData = NULL; literal[boolNullIdx].pData = NULL; literal[pointerNullIdx].cbData = 0; literal[ulongNullIdx].cbData = 0; literal[boolNullIdx].cbData = 0; input[pointerNullIdx].pData = NULL; input[ulongNullIdx].pData = NULL; input[boolNullIdx].pData = NULL; input[pointerNullIdx].cbData = 0; input[ulongNullIdx].cbData = 0; input[boolNullIdx].cbData = 0; output[pointerNullIdx].pData = NULL; output[ulongNullIdx].pData = NULL; output[boolNullIdx].pData = NULL; output[pointerNullIdx].cbData = 0; output[ulongNullIdx].cbData = 0; output[boolNullIdx].cbData = 0; local[pointerNullIdx].pData = NULL; local[ulongNullIdx].pData = NULL; local[boolNullIdx].pData = NULL; local[pointerNullIdx].cbData = 0; local[ulongNullIdx].cbData = 0; local[boolNullIdx].cbData = 0; // Print out the nullable tuple TuplePrinter tuplePrinter; printf("Literals\n"); tuplePrinter.print(cout, tupleDesc, literal); cout << endl; printf("\nInput\n"); tuplePrinter.print(cout, tupleDesc, input); cout << endl; printf("\nOutput\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("\nLocal\n"); tuplePrinter.print(cout, tupleDesc, local); cout << endl; // predefine register references. a real compiler wouldn't do // something so regular and pre-determined. a compiler would // probably build these on the fly as it built each instruction. // predefine register references. a real compiler wouldn't do // something so regular and pre-determined RegisterRef<char *> **cpInP, **cpOutP, **cpLoP, **cpLiP; RegisterRef<PointerOperandT> **lInP, **lOutP, **lLoP, **lLiP; RegisterRef<bool> **bInP, **bOutP, **bLoP, **bLiP; cpInP = new RegisterRef<char *>*[registersize]; cpOutP = new RegisterRef<char *>*[registersize]; cpLoP = new RegisterRef<char *>*[registersize]; cpLiP = new RegisterRef<char *>*[registersize]; lInP = new RegisterRef<PointerOperandT>*[registersize]; lOutP = new RegisterRef<PointerOperandT>*[registersize]; lLoP = new RegisterRef<PointerOperandT>*[registersize]; lLiP = new RegisterRef<PointerOperandT>*[registersize]; bInP = new RegisterRef<bool>*[registersize]; bOutP = new RegisterRef<bool>*[registersize]; bLoP = new RegisterRef<bool>*[registersize]; bLiP = new RegisterRef<bool>*[registersize]; // Set up the Calculator DynamicParamManager dpm; Calculator c(&dpm,0,0,0,0,0,0); c.outputRegisterByReference(false); // set up register references to symbolically point to // their corresponding storage locations -- makes for easy test case // generation. again, a compiler wouldn't do things in quite // this way. for (i = 0; i < registersize; i++) { cpInP[i] = new RegisterRef<char *>( RegisterReference::EInput, pointerIdx + i, STANDARD_TYPE_VARCHAR); c.appendRegRef(cpInP[i]); cpOutP[i] = new RegisterRef<char *>( RegisterReference::EOutput, pointerIdx + i, STANDARD_TYPE_VARCHAR); c.appendRegRef(cpOutP[i]); cpLoP[i] = new RegisterRef<char *>( RegisterReference::ELocal, pointerIdx + i, STANDARD_TYPE_VARCHAR); c.appendRegRef(cpLoP[i]); cpLiP[i] = new RegisterRef<char *>( RegisterReference::ELiteral, pointerIdx + i, STANDARD_TYPE_VARCHAR); c.appendRegRef(cpLiP[i]); lInP[i] = new RegisterRef<PointerOperandT>( RegisterReference::EInput, ulongIdx + i, STANDARD_TYPE_INT_32); c.appendRegRef(lInP[i]); lOutP[i] = new RegisterRef<PointerOperandT>( RegisterReference::EOutput, ulongIdx + i, STANDARD_TYPE_INT_32); c.appendRegRef(lOutP[i]); lLoP[i] = new RegisterRef<PointerOperandT>( RegisterReference::ELocal, ulongIdx + i, STANDARD_TYPE_INT_32); c.appendRegRef(lLoP[i]); lLiP[i] = new RegisterRef<PointerOperandT>( RegisterReference::ELiteral, ulongIdx + i, STANDARD_TYPE_INT_32); c.appendRegRef(lLiP[i]); bInP[i] = new RegisterRef<bool>( RegisterReference::EInput, boolIdx + i, STANDARD_TYPE_BOOL); c.appendRegRef(bInP[i]); bOutP[i] = new RegisterRef<bool>( RegisterReference::EOutput, boolIdx + i, STANDARD_TYPE_BOOL); c.appendRegRef(bOutP[i]); bLoP[i] = new RegisterRef<bool>( RegisterReference::ELocal, boolIdx + i, STANDARD_TYPE_BOOL); c.appendRegRef(bLoP[i]); bLiP[i] = new RegisterRef<bool>( RegisterReference::ELiteral, boolIdx + i, STANDARD_TYPE_BOOL); c.appendRegRef(bLiP[i]); } // Set up storage for instructions // a real compiler would probably cons up instructions and insert them // directly into the calculator. keep an array of the instructions at // this level to allow printing of the program after execution, and other // debugging Instruction **instP; instP = new InstructionPtr[200]; int pc = 0, outCp = 0, outL = 0, outB = 0, localCp = 0; int nullRegister = registersize - 1; StandardTypeDescriptorOrdinal isVC = STANDARD_TYPE_VARCHAR; // add instP[pc++] = new PointerAdd<char *>( cpOutP[0], cpLiP[0], lLiP[0], isVC); // add 0 instP[pc++] = new PointerAdd<char *>( cpOutP[1], cpLiP[1], lLiP[1], isVC); // add 1 instP[pc++] = new PointerAdd<char *>( cpOutP[2], cpLiP[2], lLiP[2], isVC); // add 2 outCp = 3; instP[pc++] = new PointerAdd<char *>( cpOutP[outCp++], cpLiP[nullRegister], lLiP[2], isVC); instP[pc++] = new PointerAdd<char *>( cpOutP[outCp++], cpLiP[0], lLiP[nullRegister], isVC); instP[pc++] = new PointerAdd<char *>( cpOutP[outCp++], cpLiP[nullRegister], lLiP[nullRegister], isVC); // sub // refer to previously added values in output buffer so that // results are always valid (as opposed to pointing before the // legally allocated strings instP[pc++] = new PointerSub<char *>( cpOutP[outCp++], cpLiP[0], lLiP[0], isVC); // sub 0 instP[pc++] = new PointerSub<char *>( cpOutP[outCp++], cpOutP[1], lLiP[1], isVC); // sub 1 instP[pc++] = new PointerSub<char *>( cpOutP[outCp++], cpOutP[2], lLiP[2], isVC); // sub 2 instP[pc++] = new PointerSub<char *>( cpOutP[outCp++], cpLiP[nullRegister], lLiP[2], isVC); instP[pc++] = new PointerSub<char *>( cpOutP[outCp++], cpLiP[0], lLiP[nullRegister], isVC); instP[pc++] = new PointerSub<char *>( cpOutP[outCp++], cpLiP[nullRegister], lLiP[nullRegister], isVC); // move instP[pc++] = new PointerMove<char *>( cpOutP[outCp++], cpLiP[2], isVC); instP[pc++] = new PointerMove<char *>( cpOutP[outCp++], cpLiP[nullRegister], isVC); // move a valid pointer over a null pointer instP[pc++] = new PointerMove<char *>( cpOutP[outCp], cpLiP[nullRegister], isVC); instP[pc++] = new PointerMove<char *>( cpOutP[outCp++], cpLiP[3], isVC); // move a null pointer to a null pointer instP[pc++] = new PointerMove<char *>( cpOutP[outCp], cpLiP[nullRegister], isVC); instP[pc++] = new PointerMove<char *>( cpOutP[outCp++], cpLiP[nullRegister], isVC); // equal instP[pc++] = new BoolPointerEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[0], isVC); instP[pc++] = new BoolPointerEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[1], isVC); instP[pc++] = new BoolPointerEqual<char *>( bOutP[outB++], cpLiP[1], cpLiP[0], isVC); instP[pc++] = new BoolPointerEqual<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[1], isVC); instP[pc++] = new BoolPointerEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[nullRegister], isVC); instP[pc++] = new BoolPointerEqual<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[nullRegister], isVC); // notequal instP[pc++] = new BoolPointerNotEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[0], isVC); instP[pc++] = new BoolPointerNotEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[1], isVC); instP[pc++] = new BoolPointerNotEqual<char *>( bOutP[outB++], cpLiP[1], cpLiP[0], isVC); instP[pc++] = new BoolPointerNotEqual<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[1], isVC); instP[pc++] = new BoolPointerNotEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[nullRegister], isVC); instP[pc++] = new BoolPointerNotEqual<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[nullRegister], isVC); // greater // assume that values allocated later are larger assert(output[pointerIdx].pData < output[pointerIdx + 1].pData); instP[pc++] = new BoolPointerGreater<char *>( bOutP[outB++], cpLiP[0], cpLiP[0], isVC); instP[pc++] = new BoolPointerGreater<char *>( bOutP[outB++], cpLiP[0], cpLiP[1], isVC); instP[pc++] = new BoolPointerGreater<char *>( bOutP[outB++], cpLiP[1], cpLiP[0], isVC); instP[pc++] = new BoolPointerGreater<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[1], isVC); instP[pc++] = new BoolPointerGreater<char *>( bOutP[outB++], cpLiP[0], cpLiP[nullRegister], isVC); instP[pc++] = new BoolPointerGreater<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[nullRegister], isVC); // greaterequal // assume that values allocated later are larger assert(output[pointerIdx].pData < output[pointerIdx + 1].pData); instP[pc++] = new BoolPointerGreaterEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[0], isVC); instP[pc++] = new BoolPointerGreaterEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[1], isVC); instP[pc++] = new BoolPointerGreaterEqual<char *>( bOutP[outB++], cpLiP[1], cpLiP[0], isVC); instP[pc++] = new BoolPointerGreaterEqual<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[1], isVC); instP[pc++] = new BoolPointerGreaterEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[nullRegister], isVC); instP[pc++] = new BoolPointerGreaterEqual<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[nullRegister], isVC); // less // assume that values allocated later are larger assert(output[pointerIdx].pData < output[pointerIdx + 1].pData); instP[pc++] = new BoolPointerLess<char *>( bOutP[outB++], cpLiP[0], cpLiP[0], isVC); instP[pc++] = new BoolPointerLess<char *>( bOutP[outB++], cpLiP[0], cpLiP[1], isVC); instP[pc++] = new BoolPointerLess<char *>( bOutP[outB++], cpLiP[1], cpLiP[0], isVC); instP[pc++] = new BoolPointerLess<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[1], isVC); instP[pc++] = new BoolPointerLess<char *>( bOutP[outB++], cpLiP[0], cpLiP[nullRegister], isVC); instP[pc++] = new BoolPointerLess<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[nullRegister], isVC); // lessequal // assume that values allocated later are larger assert(output[pointerIdx].pData < output[pointerIdx + 1].pData); instP[pc++] = new BoolPointerLessEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[0], isVC); instP[pc++] = new BoolPointerLessEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[1], isVC); instP[pc++] = new BoolPointerLessEqual<char *>( bOutP[outB++], cpLiP[1], cpLiP[0], isVC); instP[pc++] = new BoolPointerLessEqual<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[1], isVC); instP[pc++] = new BoolPointerLessEqual<char *>( bOutP[outB++], cpLiP[0], cpLiP[nullRegister], isVC); instP[pc++] = new BoolPointerLessEqual<char *>( bOutP[outB++], cpLiP[nullRegister], cpLiP[nullRegister], isVC); // isnull instP[pc++] = new BoolPointerIsNull<char *>( bOutP[outB++], cpLiP[0], isVC); instP[pc++] = new BoolPointerIsNull<char *>( bOutP[outB++], cpLiP[nullRegister], isVC); // isnotnull instP[pc++] = new BoolPointerIsNotNull<char *>( bOutP[outB++], cpLiP[0], isVC); instP[pc++] = new BoolPointerIsNotNull<char *>( bOutP[outB++], cpLiP[nullRegister], isVC); // tonull instP[pc++] = new PointerToNull<char *>(cpOutP[outCp++], isVC); // putsize instP[pc++] = new PointerPutSize<char *>(cpOutP[outCp], lLiP[0], isVC); instP[pc++] = new PointerPutSize<char *>(cpOutP[outCp + 1], lLiP[1], isVC); instP[pc++] = new PointerPutSize<char *>(cpOutP[outCp + 2], lLiP[2], isVC); // putsize w/round trip through cached register set instP[pc++] = new PointerPutSize<char *>(cpLoP[localCp], lLiP[0], isVC); // getsize instP[pc++] = new PointerGetSize<char *>( lOutP[outL++], cpOutP[outCp], isVC); instP[pc++] = new PointerGetSize<char *>( lOutP[outL++], cpOutP[outCp + 1], isVC); instP[pc++] = new PointerGetSize<char *>( lOutP[outL++], cpOutP[outCp + 2], isVC); instP[pc++] = new PointerGetSize<char *>( lOutP[outL++], cpLiP[0], isVC); // getsize w/round trip through cached register set instP[pc++] = new PointerGetSize<char *>( lOutP[outL++], cpLoP[localCp], isVC); instP[pc++] = new PointerGetSize<char *>( lOutP[outL++], cpLoP[localCp + 1], isVC); // getmaxsize instP[pc++] = new PointerGetMaxSize<char *>( lOutP[outL++], cpOutP[outCp], isVC); instP[pc++] = new PointerGetMaxSize<char *>( lOutP[outL++], cpLiP[0], isVC); // getmaxsize w/round trip through cached register set instP[pc++] = new PointerGetMaxSize<char *>( lOutP[outL++], cpLoP[localCp], isVC); instP[pc++] = new PointerGetMaxSize<char *>( lOutP[outL++], cpLoP[localCp + 1], isVC); outCp += 3; localCp += 2; instP[pc++] = new ReturnInstruction(); int lastPC = pc; for (i = 0; i < pc; i++) { c.appendInstruction(instP[i]); } c.bind( RegisterReference::ELiteral, &literal, tupleDesc); c.bind( RegisterReference::EInput, &input, tupleDesc); c.bind( RegisterReference::EOutput, &output, tupleDesc); c.bind( RegisterReference::ELocal, &local, tupleDesc); c.bind( RegisterReference::EStatus, &status, tupleDesc); c.exec(); string out; for (i = 0; i < pc; i++) { instP[i]->describe(out, true); printf("[%2d] %s\n", i, out.c_str()); } // Print out the output tuple printf("Output Tuple\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; outCp = 0; // now indexes into output tuple, not outputregisterref outB = boolIdx; // now indexes into output tuple, not outputregisterref outL = ulongIdx; // now indexes into output tuple, not outputregisterref // add if (output[outCp].pData != literal[pointerIdx + 0].pData) { fail("pointeradd1", __LINE__); } if (output[outCp++].cbData != bufferlen - 0) { fail("pointeradd2", __LINE__); } if ((reinterpret_cast<const char *>(output[outCp].pData)) != ((reinterpret_cast<const char *>(literal[pointerIdx + 1].pData)) + *(reinterpret_cast<const int32_t *>(literal[ulongIdx + 1].pData)))) { fail("pointeradd3", __LINE__); } if (output[outCp++].cbData != bufferlen - *(reinterpret_cast<const int32_t *>( literal[ulongIdx + 1].pData))) { fail("pointeradd4", __LINE__); } if ((reinterpret_cast<const char *>(output[outCp].pData)) != ((reinterpret_cast<const char *>(literal[pointerIdx + 2].pData)) + *(reinterpret_cast<const int32_t *>(literal[ulongIdx + 2].pData)))) { fail("pointeradd5", __LINE__); } if (output[outCp++].cbData != bufferlen - *(reinterpret_cast<const int32_t *>( literal[ulongIdx + 2].pData))) { fail("pointeradd6", __LINE__); } if (output[outCp].pData != NULL) { fail("pointeradd7", __LINE__); } if (output[outCp++].cbData != 0) { fail("pointeradd8", __LINE__); } if (output[outCp].pData != NULL) { fail("pointeradd9", __LINE__); } if (output[outCp++].cbData != 0) { fail("pointeradd10", __LINE__); } if (output[outCp].pData != NULL) { fail("pointeradd11", __LINE__); } if (output[outCp++].cbData != 0) { fail("pointeradd12", __LINE__); } // sub if (output[outCp].pData != literal[pointerIdx + 0].pData) { fail("pointersub1", __LINE__); } if (output[outCp++].cbData != bufferlen + 0) { fail("pointersub2", __LINE__); } if ((reinterpret_cast<const char *>(output[outCp].pData)) != ((reinterpret_cast<const char *>(literal[pointerIdx + 1].pData)))) { fail("pointersub3", __LINE__); } if (output[outCp++].cbData != bufferlen) { fail("pointersub4", __LINE__); } if ((reinterpret_cast<const char *>(output[outCp].pData)) != ((reinterpret_cast<const char *>(literal[pointerIdx + 2].pData)))) { fail("pointersub5", __LINE__); } if (output[outCp++].cbData != bufferlen) { fail("pointersub6", __LINE__); } if (output[outCp].pData != NULL) { fail("pointersub7", __LINE__); } if (output[outCp++].cbData != 0) { fail("pointersub8", __LINE__); } if (output[outCp].pData != NULL) { fail("pointersub9", __LINE__); } if (output[outCp++].cbData != 0) { fail("pointersub10", __LINE__); } if (output[outCp].pData != NULL) { fail("pointersub11", __LINE__); } if (output[outCp++].cbData != 0) { fail("pointersub12", __LINE__); } // move if (output[outCp].pData != literal[pointerIdx + 2].pData) { fail("pointermove1", __LINE__); } if (output[outCp++].cbData != bufferlen) { fail("pointermove2", __LINE__); } if (output[outCp].pData != NULL) { fail("pointermove3", __LINE__); } if (output[outCp++].cbData != 0) { fail("pointermove4", __LINE__); } if ((reinterpret_cast<const char *>(output[outCp].pData)) != ((reinterpret_cast<const char *>(literal[pointerIdx + 3].pData)))) { fail("pointermove5", __LINE__); } if (output[outCp++].cbData != bufferlen) { fail("pointermove6", __LINE__); } if (output[outCp].pData != NULL) { fail("pointermove7", __LINE__); } if (output[outCp++].cbData != 0) { fail("pointermove8", __LINE__); } // equal if (*(output[outB++].pData) != true) { fail("pointerequal1", __LINE__); } if (*(output[outB++].pData) != false) { fail("pointerequal2", __LINE__); } if (*(output[outB++].pData) != false) { fail("pointerequal3", __LINE__); } if (output[outB++].pData != NULL) { fail("pointerequal4", __LINE__); } if (output[outB++].pData != NULL) { fail("pointerequal5", __LINE__); } if (output[outB++].pData != NULL) { fail("pointerequal6", __LINE__); } // notequal if (*(output[outB++].pData) != false) { fail("pointernotequal1", __LINE__); } if (*(output[outB++].pData) != true) { fail("pointernotequal2", __LINE__); } if (*(output[outB++].pData) != true) { fail("pointernotequal3", __LINE__); } if (output[outB++].pData != NULL) { fail("pointernotequal4", __LINE__); } if (output[outB++].pData != NULL) { fail("pointernotequal5", __LINE__); } if (output[outB++].pData != NULL) { fail("pointernotequal6", __LINE__); } // greater if (*(output[outB++].pData) != false) { fail("pointergreater1", __LINE__); } if (*(output[outB++].pData) != false) { fail("pointergreater2", __LINE__); } if (*(output[outB++].pData) != true) { fail("pointergreater3", __LINE__); } if (output[outB++].pData != NULL) { fail("pointergreater11", __LINE__); } if (output[outB++].pData != NULL) { fail("pointergreater12", __LINE__); } if (output[outB++].pData != NULL) { fail("pointergreater13", __LINE__); } // greaterequal if (*(output[outB++].pData) != true) { fail("pointergreaterequal1", __LINE__); } if (*(output[outB++].pData) != false) { fail("pointergreaterequal2", __LINE__); } if (*(output[outB++].pData) != true) { fail("pointergreaterequal3", __LINE__); } if (output[outB++].pData != NULL) { fail("pointergreaterequal14", __LINE__); } if (output[outB++].pData != NULL) { fail("pointergreaterequal15", __LINE__); } if (output[outB++].pData != NULL) { fail("pointergreaterequal16", __LINE__); } // less if (*(output[outB++].pData) != false) { fail("pointerless1", __LINE__); } if (*(output[outB++].pData) != true) { fail("pointerless2", __LINE__); } if (*(output[outB++].pData) != false) { fail("pointerless3", __LINE__); } if (output[outB++].pData != NULL) { fail("pointerless4", __LINE__); } if (output[outB++].pData != NULL) { fail("pointerless5", __LINE__); } if (output[outB++].pData != NULL) { fail("pointerless6", __LINE__); } // lessequal if (*(output[outB++].pData) != true) { fail("pointerlessequal1", __LINE__); } if (*(output[outB++].pData) != true) { fail("pointerlessequal2", __LINE__); } if (*(output[outB++].pData) != false) { fail("pointerlessequal3", __LINE__); } if (output[outB++].pData != NULL) { fail("pointerlessequal5", __LINE__); } if (output[outB++].pData != NULL) { fail("pointerlessequal6", __LINE__); } if (output[outB++].pData != NULL) { fail("pointerlessequal7", __LINE__); } // isnull if (*(output[outB++].pData) != false) { fail("pointerisnull1", __LINE__); } if (*(output[outB++].pData) != true) { fail("pointerisnull2", __LINE__); } // isnotnull if (*(output[outB++].pData) != true) { fail("pointerisnotnull1", __LINE__); } if (*(output[outB++].pData) != false) { fail("pointerisnotnull2", __LINE__); } // tonull if (output[outCp].pData != NULL) { fail("pointertonull1", __LINE__); } if (output[outCp++].cbData != 0) { fail("pointertonull2", __LINE__); } // putsize // getsize if (*(output[outL++].pData) != 0) { fail("pointergetsize1", __LINE__); } if (*(output[outL++].pData) != 1) { fail("pointergetsize2", __LINE__); } if (*(output[outL++].pData) != 2) { fail("pointergetsize3", __LINE__); } if (*(output[outL++].pData) != bufferlen) { fail("pointergetsize4", __LINE__); } if (*(output[outL++].pData) != 0) { fail("pointergetsize5", __LINE__); } if (*(output[outL++].pData) != bufferlen) { fail("pointergetsize6", __LINE__); } // getmaxsize if (*(output[outL++].pData) != bufferlen) { fail("pointergetsize7", __LINE__); } if (*(output[outL++].pData) != bufferlen) { fail("pointergetsize8", __LINE__); } if (*(output[outL++].pData) != bufferlen) { fail("pointergetsize9", __LINE__); } if (*(output[outL++].pData) != bufferlen) { fail("pointergetsize10", __LINE__); } cout << "Calculator Warnings: " << c.warnings() << endl; delete [] cpInP; delete [] cpOutP; delete [] cpLoP; delete [] cpLiP; delete [] lInP; delete [] lOutP; delete [] lLoP; delete [] lLiP; delete [] bInP; delete [] bOutP; delete [] bLoP; delete [] bLiP; for (i = 0; i < lastPC; i++) { delete instP[i]; } delete [] instP; } void unitTestWarnings() { printf("=========================================================\n"); printf("=========================================================\n"); printf("=====\n"); printf("===== unitTestWarnings()\n"); printf("=====\n"); printf("=========================================================\n"); printf("=========================================================\n"); bool isNullable = true; // Can tuple contain nulls? int i, registersize = 3; TupleDescriptor tupleDesc; tupleDesc.clear(); // Build up a description of what we'd like the tuple to look like StandardTypeDescriptorFactory typeFactory; int idx = 0; int floatIdx = idx; for (i = 0;i < registersize; i++) { // floats StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_REAL); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); idx++; } // Create a tuple accessor from the description // // Note: Must use a NOT_NULL_AND_FIXED accessor when creating a tuple out // of the air like this, otherwise unmarshal() does not know what to do. If // you need a STANDARD type tuple that supports nulls, it has to be built // as a copy. TupleAccessor tupleAccessorFixedLiteral; TupleAccessor tupleAccessorFixedInput; TupleAccessor tupleAccessorFixedOutput; TupleAccessor tupleAccessorFixedLocal; TupleAccessor tupleAccessorFixedStatus; tupleAccessorFixedLiteral.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedInput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedOutput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedLocal.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedStatus.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); // Allocate memory for the tuple boost::scoped_array<FixedBuffer> pTupleBufFixedLiteral( new FixedBuffer[tupleAccessorFixedLiteral.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedInput( new FixedBuffer[tupleAccessorFixedInput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedOutput( new FixedBuffer[tupleAccessorFixedOutput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedLocal( new FixedBuffer[tupleAccessorFixedLocal.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedStatus( new FixedBuffer[tupleAccessorFixedStatus.getMaxByteCount()]); // Link memory to accessor tupleAccessorFixedLiteral.setCurrentTupleBuf( pTupleBufFixedLiteral.get(), false); tupleAccessorFixedInput.setCurrentTupleBuf( pTupleBufFixedInput.get(), false); tupleAccessorFixedOutput.setCurrentTupleBuf( pTupleBufFixedOutput.get(), false); tupleAccessorFixedLocal.setCurrentTupleBuf( pTupleBufFixedLocal.get(), false); tupleAccessorFixedStatus.setCurrentTupleBuf( pTupleBufFixedStatus.get(), false); // Create a vector of TupleDatum objects based on the description we built TupleData tupleDataFixedLiteral(tupleDesc); TupleData tupleDataFixedInput(tupleDesc); TupleData tupleDataFixedOutput(tupleDesc); TupleData tupleDataFixedLocal(tupleDesc); TupleData tupleDataFixedStatus(tupleDesc); // Do something mysterious. Probably binding pointers in the accessor to // items in the TupleData vector tupleAccessorFixedLiteral.unmarshal(tupleDataFixedLiteral); tupleAccessorFixedInput.unmarshal(tupleDataFixedInput); tupleAccessorFixedOutput.unmarshal(tupleDataFixedOutput); tupleAccessorFixedLocal.unmarshal(tupleDataFixedLocal); tupleAccessorFixedStatus.unmarshal(tupleDataFixedStatus); // create four nullable tuples to serve as register sets TupleData literal = tupleDataFixedLiteral; TupleData input = tupleDataFixedInput; TupleData output = tupleDataFixedOutput; TupleData local = tupleDataFixedLocal; TupleData status = tupleDataFixedStatus; // Set up some useful literals for (i = 0; i < registersize; i++) { *(reinterpret_cast<float *>(const_cast<PBuffer>(literal[i].pData))) = i * 0.5; *(reinterpret_cast<float *>(const_cast<PBuffer>(output[i].pData))) = i * 2 + 1; *(reinterpret_cast<float *>(const_cast<PBuffer>(input[i].pData))) = i * 5.5 + 1; *(reinterpret_cast<float *>(const_cast<PBuffer>(local[i].pData))) = i * 3.3 + 1; } // Print out the nullable tuple TuplePrinter tuplePrinter; printf("Literals\n"); tuplePrinter.print(cout, tupleDesc, literal); cout << endl; printf("\nInput\n"); tuplePrinter.print(cout, tupleDesc, input); cout << endl; printf("\nOutput\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("\nLocal\n"); tuplePrinter.print(cout, tupleDesc, local); cout << endl; // predefine register references. a real compiler wouldn't do // something so regular and pre-determined. a compiler would // probably build these on the fly as it built each instruction. // predefine register references. a real compiler wouldn't do // something so regular and pre-determined RegisterRef<float> **fInP, **fOutP, **fLoP, **fLiP; fInP = new RegisterRef<float>*[registersize]; fOutP = new RegisterRef<float>*[registersize]; fLoP = new RegisterRef<float>*[registersize]; fLiP = new RegisterRef<float>*[registersize]; // Set up the Calculator DynamicParamManager dpm; Calculator c(&dpm,0,0,0,0,0,0); c.outputRegisterByReference(false); // set up register references to symbolically point to // their corresponding storage locations -- makes for easy test case // generation. again, a compiler wouldn't do things in quite // this way. for (i = 0; i < registersize; i++) { fInP[i] = new RegisterRef<float>( RegisterReference::EInput, floatIdx + i, STANDARD_TYPE_REAL); c.appendRegRef(fInP[i]); fOutP[i] = new RegisterRef<float>( RegisterReference::EOutput, floatIdx + i, STANDARD_TYPE_REAL); c.appendRegRef(fOutP[i]); fLoP[i] = new RegisterRef<float>( RegisterReference::ELocal, floatIdx + i, STANDARD_TYPE_REAL); c.appendRegRef(fLoP[i]); fLiP[i] = new RegisterRef<float>( RegisterReference::ELiteral, floatIdx + i, STANDARD_TYPE_REAL); c.appendRegRef(fLiP[i]); } // Set up storage for instructions // a real compiler would probably cons up instructions and insert them // directly into the calculator. keep an array of the instructions at // this level to allow printing of the program after execution, and other // debugging Instruction **instP; instP = new InstructionPtr[200]; int pc = 0, outF = 0; StandardTypeDescriptorOrdinal isFloat = STANDARD_TYPE_REAL; // Force a warning instP[pc++] = new NativeDiv<float>( fOutP[outF++], fLiP[2], fLiP[0], isFloat); int lastPC = pc; for (i = 0; i < pc; i++) { c.appendInstruction(instP[i]); } c.bind( RegisterReference::ELiteral, &literal, tupleDesc); c.bind( RegisterReference::EInput, &input, tupleDesc); c.bind( RegisterReference::EOutput, &output, tupleDesc); c.bind( RegisterReference::ELocal, &local, tupleDesc); c.bind( RegisterReference::EStatus, &status, tupleDesc); c.exec(); string out; for (i = 0; i < pc; i++) { instP[i]->describe(out, true); printf("[%2d] %s\n", i, out.c_str()); } // Print out the output tuple printf("Output Tuple\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; cout << "Calculator Warnings: " << c.warnings() << endl; deque<CalcMessage>::iterator iter = c.mWarnings.begin(); if (iter->pc != 0) { fail("warning:pc", __LINE__); } string expectederror("22012"); if (expectederror.compare(iter->str)) { fail("warning:div by zero failed string wasn't as expected", __LINE__); } string expectedwarningstring("[0]:PC=0 Code=22012 "); cout << "|" << expectedwarningstring << "|" << endl; if (expectedwarningstring.compare(c.warnings())) { fail("warning:warning string wasn't as expected", __LINE__); } // Replace the literal '0' with something benign pc = 0; outF = 0; instP[pc++] = new NativeDiv<float>( fOutP[outF++], fLiP[2], fLiP[2], isFloat); *(reinterpret_cast<float *>(const_cast<PBuffer>(literal[0].pData))) = 2; // Out[0] is now null, due to the div by zero error // Hack output tuple to something re-runable float horriblehack = 88; // JR 6/15.07 - no longer works: // reinterpret_cast<float *>(const_cast<PBuffer>(output[0].pData)) = // &horriblehack; output[0].pData = reinterpret_cast<const uint8_t *>(&horriblehack); printf("Rerunning calculator\n"); c.bind(&input, &output); c.exec(); cout << "Calculator Warnings: " << c.warnings() << endl; if (!c.mWarnings.empty()) { fail("warning:warning deque has data", __LINE__); } if (c.warnings().compare("")) { fail("warning:warning string empty", __LINE__); } delete [] fInP; delete [] fOutP; delete [] fLoP; delete [] fLiP; for (i = 0; i < lastPC; i++) { delete instP[i]; } delete [] instP; } void unitTestPointerCache() { printf("=========================================================\n"); printf("=========================================================\n"); printf("=====\n"); printf("===== unitTestPointerCache()\n"); printf("=====\n"); printf("=========================================================\n"); printf("=========================================================\n"); bool isNullable = true; // Can tuple contain nulls? int i, registersize = 10; TupleDescriptor tupleDesc; tupleDesc.clear(); // Build up a description of what we'd like the tuple to look like StandardTypeDescriptorFactory typeFactory; int idx = 0; int doubleIdx = idx; for (i = 0;i < registersize; i++) { // doubles StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_DOUBLE); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); idx++; } // Create a tuple accessor from the description // // Note: Must use a NOT_NULL_AND_FIXED accessor when creating a tuple out // of the air like this, otherwise unmarshal() does not know what to do. If // you need a STANDARD type tuple that supports nulls, it has to be built // as a copy. TupleAccessor tupleAccessorFixedLiteral; TupleAccessor tupleAccessorFixedInput; TupleAccessor tupleAccessorFixedOutput; TupleAccessor tupleAccessorFixedLocal; TupleAccessor tupleAccessorFixedStatus; tupleAccessorFixedLiteral.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedInput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedOutput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedLocal.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedStatus.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); // Allocate memory for the tuple boost::scoped_array<FixedBuffer> pTupleBufFixedLiteral( new FixedBuffer[tupleAccessorFixedLiteral.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedInput( new FixedBuffer[tupleAccessorFixedInput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedOutput( new FixedBuffer[tupleAccessorFixedOutput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedLocal( new FixedBuffer[tupleAccessorFixedLocal.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedStatus( new FixedBuffer[tupleAccessorFixedStatus.getMaxByteCount()]); // Link memory to accessor tupleAccessorFixedLiteral.setCurrentTupleBuf( pTupleBufFixedLiteral.get(), false); tupleAccessorFixedInput.setCurrentTupleBuf( pTupleBufFixedInput.get(), false); tupleAccessorFixedOutput.setCurrentTupleBuf( pTupleBufFixedOutput.get(), false); tupleAccessorFixedLocal.setCurrentTupleBuf( pTupleBufFixedLocal.get(), false); tupleAccessorFixedStatus.setCurrentTupleBuf( pTupleBufFixedStatus.get(), false); // Create a vector of TupleDatum objects based on the description we built TupleData tupleDataFixedLiteral(tupleDesc); TupleData tupleDataFixedInput(tupleDesc); TupleData tupleDataFixedOutput(tupleDesc); TupleData tupleDataFixedLocal(tupleDesc); TupleData tupleDataFixedStatus(tupleDesc); // Do something mysterious. Probably binding pointers in the accessor to // items in the TupleData vector tupleAccessorFixedLiteral.unmarshal(tupleDataFixedLiteral); tupleAccessorFixedInput.unmarshal(tupleDataFixedInput); tupleAccessorFixedOutput.unmarshal(tupleDataFixedOutput); tupleAccessorFixedLocal.unmarshal(tupleDataFixedLocal); tupleAccessorFixedStatus.unmarshal(tupleDataFixedStatus); // create four nullable tuples to serve as register sets TupleData literal = tupleDataFixedLiteral; TupleData input = tupleDataFixedInput; TupleData output = tupleDataFixedOutput; TupleData local = tupleDataFixedLocal; TupleData status = tupleDataFixedStatus; // Set up some useful literals for (i = 0; i < registersize; i++) { *(reinterpret_cast<double *>(const_cast<PBuffer>(literal[i].pData))) = i * 0.5; *(reinterpret_cast<double *>(const_cast<PBuffer>(output[i].pData))) = i * 2 + 1; *(reinterpret_cast<double *>(const_cast<PBuffer>(input[i].pData))) = i * 5.5 + 1; *(reinterpret_cast<double *>(const_cast<PBuffer>(local[i].pData))) = i * 3.3 + 1; } // Print out the nullable tuple TuplePrinter tuplePrinter; printf("Literals\n"); tuplePrinter.print(cout, tupleDesc, literal); cout << endl; printf("\nInput\n"); tuplePrinter.print(cout, tupleDesc, input); cout << endl; printf("\nOutput\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("\nLocal\n"); tuplePrinter.print(cout, tupleDesc, local); cout << endl; // predefine register references. a real compiler wouldn't do // something so regular and pre-determined. a compiler would // probably build these on the fly as it built each instruction. // predefine register references. a real compiler wouldn't do // something so regular and pre-determined RegisterRef<double> **fInP, **fOutP, **fLoP, **fLiP; fInP = new RegisterRef<double>*[registersize]; fOutP = new RegisterRef<double>*[registersize]; fLoP = new RegisterRef<double>*[registersize]; fLiP = new RegisterRef<double>*[registersize]; // Set up the Calculator DynamicParamManager dpm; Calculator c(&dpm,0,0,0,0,0,0); c.outputRegisterByReference(false); // set up register references to symbolically point to // their corresponding storage locations -- makes for easy test case // generation. again, a compiler wouldn't do things in quite // this way. for (i = 0; i < registersize; i++) { fInP[i] = new RegisterRef<double>( RegisterReference::EInput, doubleIdx + i, STANDARD_TYPE_DOUBLE); c.appendRegRef(fInP[i]); fOutP[i] = new RegisterRef<double>( RegisterReference::EOutput, doubleIdx + i, STANDARD_TYPE_DOUBLE); c.appendRegRef(fOutP[i]); fLoP[i] = new RegisterRef<double>( RegisterReference::ELocal, doubleIdx + i, STANDARD_TYPE_DOUBLE); c.appendRegRef(fLoP[i]); fLiP[i] = new RegisterRef<double>( RegisterReference::ELiteral, doubleIdx + i, STANDARD_TYPE_DOUBLE); c.appendRegRef(fLiP[i]); } // Set up storage for instructions // a real compiler would probably cons up instructions and insert them // directly into the calculator. keep an array of the instructions at // this level to allow printing of the program after execution, and other // debugging Instruction **instP; instP = new InstructionPtr[200]; int pc = 0, outF = 0, liF = 0; StandardTypeDescriptorOrdinal isDouble = STANDARD_TYPE_DOUBLE; // copy some of the literals into the output register for (i = 0; i < (registersize / 2) - 1 ; i++) { instP[pc++] = new NativeMove<double>( fOutP[outF++], fLiP[liF++], isDouble); } // copy some of the locals into the output register for (i = 0; i < (registersize / 2) - 1 ; i++) { instP[pc++] = new NativeMove<double>( fOutP[outF++], fLoP[liF++], isDouble); } int lastPC = pc; for (i = 0; i < pc; i++) { c.appendInstruction(instP[i]); } c.bind( RegisterReference::ELiteral, &literal, tupleDesc); c.bind( RegisterReference::EInput, &input, tupleDesc); c.bind( RegisterReference::EOutput, &output, tupleDesc); c.bind( RegisterReference::ELocal, &local, tupleDesc); c.bind( RegisterReference::EStatus, &status, tupleDesc); c.exec(); string out; for (i = 0; i < pc; i++) { instP[i]->describe(out, true); printf("[%2d] %s\n", i, out.c_str()); } // Print out the output tuple printf("Output Tuple\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; cout << "Calculator Warnings: " << c.warnings() << endl; outF = liF = 0; for (i = 0; i < (registersize / 2) - 1 ; i++) { if (*(reinterpret_cast<double *>( const_cast<PBuffer>(output[outF++].pData))) != (i * 0.5)) { fail("pointercache1", __LINE__); } } for (i = 0; i < (registersize / 2) - 1 ; i++) { double d = outF * 3.3 + 1; if ((*(reinterpret_cast<double *>( const_cast<PBuffer>(output[outF].pData))) - d) > 0.000001) { fail("pointercache2", __LINE__); } ++outF; } // OK, now be mean and yank the literals right out from under // Calculator. The memory is still allocated and available // for the cached pointers. Note that the calculator will have // no reason to reset these pointers as they weren't re-pointed // or set to null for (i = 0; i < registersize; i++) { literal[i].pData = NULL; local[i].pData = NULL; } printf("Rerunning calculator\n"); c.bind(&input, &output); c.exec(); outF = liF = 0; for (i = 0; i < (registersize / 2) - 1 ; i++) { if (*(reinterpret_cast<double *>( const_cast<PBuffer>(output[outF++].pData))) != (i * 0.5)) { fail("pointercache3", __LINE__); } } for (i = 0; i < (registersize / 2) - 1 ; i++) { double d = outF * 3.3 + 1; if ((*(reinterpret_cast<double *>( const_cast<PBuffer>(output[outF].pData))) - d) > 0.000001) { fail("pointercache4", __LINE__); } ++outF; } cout << "Calculator Warnings: " << c.warnings() << endl; delete [] fInP; delete [] fOutP; delete [] fLoP; delete [] fLiP; for (i = 0; i < lastPC; i++) { delete instP[i]; } delete [] instP; } void unitTestNullableLocal() { printf("=========================================================\n"); printf("=========================================================\n"); printf("=====\n"); printf("===== unitTestNullableLocal()\n"); printf("=====\n"); printf("=========================================================\n"); printf("=========================================================\n"); bool isNullable = true; // Can tuple contain nulls? int i, registersize = 10; static int bufferlen = 8; TupleDescriptor tupleDesc; tupleDesc.clear(); // Build up a description of what we'd like the tuple to look like StandardTypeDescriptorFactory typeFactory; int idx = 0; const int pointerIdx = idx; for (i = 0;i < registersize; i++) { // pointers in first "half" StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_VARCHAR); // tell descriptor the size tupleDesc.push_back( TupleAttributeDescriptor( typeDesc, isNullable, bufferlen)); idx++; } const int boolIdx = idx; for (i = 0;i < registersize; i++) { // booleans in second "half" StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_UINT_8); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); idx++; } // Create a tuple accessor from the description // // Note: Must use a NOT_NULL_AND_FIXED accessor when creating a tuple out // of the air like this, otherwise unmarshal() does not know what to do. If // you need a STANDARD type tuple that supports nulls, it has to be built // as a copy. TupleAccessor tupleAccessorFixedLiteral; TupleAccessor tupleAccessorFixedInput; TupleAccessor tupleAccessorFixedOutput; TupleAccessor tupleAccessorFixedLocal; TupleAccessor tupleAccessorFixedStatus; tupleAccessorFixedLiteral.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedInput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedOutput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedLocal.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedStatus.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); // Allocate memory for the tuple boost::scoped_array<FixedBuffer> pTupleBufFixedLiteral( new FixedBuffer[tupleAccessorFixedLiteral.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedInput( new FixedBuffer[tupleAccessorFixedInput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedOutput( new FixedBuffer[tupleAccessorFixedOutput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedLocal( new FixedBuffer[tupleAccessorFixedLocal.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedStatus( new FixedBuffer[tupleAccessorFixedStatus.getMaxByteCount()]); // Link memory to accessor tupleAccessorFixedLiteral.setCurrentTupleBuf( pTupleBufFixedLiteral.get(), false); tupleAccessorFixedInput.setCurrentTupleBuf( pTupleBufFixedInput.get(), false); tupleAccessorFixedOutput.setCurrentTupleBuf( pTupleBufFixedOutput.get(), false); tupleAccessorFixedLocal.setCurrentTupleBuf( pTupleBufFixedLocal.get(), false); tupleAccessorFixedStatus.setCurrentTupleBuf( pTupleBufFixedStatus.get(), false); // Create a vector of TupleDatum objects based on the description we built TupleData tupleDataFixedLiteral(tupleDesc); TupleData tupleDataFixedInput(tupleDesc); TupleData tupleDataFixedOutput(tupleDesc); TupleData tupleDataFixedLocal(tupleDesc); TupleData tupleDataFixedStatus(tupleDesc); // Do something mysterious. Probably binding pointers in the accessor to // items in the TupleData vector tupleAccessorFixedLiteral.unmarshal(tupleDataFixedLiteral); tupleAccessorFixedInput.unmarshal(tupleDataFixedInput); tupleAccessorFixedOutput.unmarshal(tupleDataFixedOutput); tupleAccessorFixedLocal.unmarshal(tupleDataFixedLocal); tupleAccessorFixedStatus.unmarshal(tupleDataFixedStatus); // create four nullable tuples to serve as register sets TupleData literal = tupleDataFixedLiteral; TupleData input = tupleDataFixedInput; TupleData output = tupleDataFixedOutput; TupleData local = tupleDataFixedLocal; TupleData status = tupleDataFixedStatus; // Set up some useful literals for (i = 0; i < registersize; i++) { char num[16]; sprintf(num, "%04d", i); char* ptr = reinterpret_cast<char *>(const_cast<PBuffer>(literal[i].pData)); memset(ptr, 'C', bufferlen); // VARCHAR is not null terminated memcpy(ptr, num, 4); // copy number, but not null // Put some data other tuples as well ptr = reinterpret_cast<char *>(const_cast<PBuffer>(input[i].pData)); memset(ptr, 'I', bufferlen); // VARCHAR is not null terminated memcpy(ptr, num, 4); // copy number, but not null ptr = reinterpret_cast<char *>(const_cast<PBuffer>(output[i].pData)); memset(ptr, 'O', bufferlen); // VARCHAR is not null terminated memcpy(ptr, num, 4); // copy number, but not null ptr = reinterpret_cast<char *>(const_cast<PBuffer>(local[i].pData)); memset(ptr, 'L', bufferlen); // VARCHAR is not null terminated memcpy(ptr, num, 4); // copy number, but not null } int falseIdx = 0; int trueIdx = 1; i = registersize; *(reinterpret_cast<bool *>(const_cast<PBuffer>(literal[i].pData))) = false; for (i++; i < registersize*2; i++) { *(reinterpret_cast<bool *>(const_cast<PBuffer>(literal[i].pData))) = true; } // null out last element of each type int nullidx = registersize-1; literal[nullidx].pData = NULL; input[nullidx].pData = NULL; output[nullidx].pData = NULL; local[nullidx].pData = NULL; // Print out the nullable tuple TuplePrinter tuplePrinter; printf("Literals\n"); tuplePrinter.print(cout, tupleDesc, literal); cout << endl; printf("\nInput\n"); tuplePrinter.print(cout, tupleDesc, input); cout << endl; printf("\nOutput\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("\nLocal\n"); tuplePrinter.print(cout, tupleDesc, local); cout << endl; // predefine register references. a real compiler wouldn't do // something so regular and pre-determined. a compiler would // probably build these on the fly as it built each instruction. // predefine register references. a real compiler wouldn't do // something so regular and pre-determined RegisterRef<char *> **cpInP, **cpOutP, **cpLiP; RegisterRef<bool> **bInP, **bOutP, **bLiP; RegisterRef<char *> **cpLoP; RegisterRef<bool> **bLoP; cpInP = new RegisterRef<char *>*[registersize]; cpOutP = new RegisterRef<char *>*[registersize]; cpLoP = new RegisterRef<char *>*[registersize]; cpLiP = new RegisterRef<char *>*[registersize]; bInP = new RegisterRef<bool>*[registersize]; bOutP = new RegisterRef<bool>*[registersize]; bLoP = new RegisterRef<bool>*[registersize]; bLiP = new RegisterRef<bool>*[registersize]; // Set up the Calculator DynamicParamManager dpm; Calculator c(&dpm,0,0,0,0,0,0); c.outputRegisterByReference(false); // set up register references to symbolically point to // their corresponding storage locations -- makes for easy test case // generation. again, a compiler wouldn't do things in quite // this way. for (i = 0; i < registersize; i++) { cpInP[i] = new RegisterRef<char *>( RegisterReference::EInput, pointerIdx + i, STANDARD_TYPE_VARCHAR); c.appendRegRef(cpInP[i]); cpOutP[i] = new RegisterRef<char *>( RegisterReference::EOutput, pointerIdx + i, STANDARD_TYPE_VARCHAR); c.appendRegRef(cpOutP[i]); cpLoP[i] = new RegisterRef<char *>( RegisterReference::ELocal, pointerIdx + i, STANDARD_TYPE_VARCHAR); c.appendRegRef(cpLoP[i]); cpLiP[i] = new RegisterRef<char *>( RegisterReference::ELiteral, pointerIdx + i, STANDARD_TYPE_VARCHAR); c.appendRegRef(cpLiP[i]); bInP[i] = new RegisterRef<bool>( RegisterReference::EInput, boolIdx + i, STANDARD_TYPE_BOOL); c.appendRegRef(bInP[i]); bOutP[i] = new RegisterRef<bool>( RegisterReference::EOutput, boolIdx + i, STANDARD_TYPE_BOOL); c.appendRegRef(bOutP[i]); bLoP[i] = new RegisterRef<bool>( RegisterReference::ELocal, boolIdx + i, STANDARD_TYPE_BOOL); c.appendRegRef(bLoP[i]); bLiP[i] = new RegisterRef<bool>( RegisterReference::ELiteral, boolIdx + i, STANDARD_TYPE_BOOL); c.appendRegRef(bLiP[i]); } // Set up storage for instructions // a real compiler would probably cons up instructions and insert them // directly into the calculator. keep an array of the instructions at // this level to allow printing of the program after execution, and other // debugging Instruction **instP; instP = new InstructionPtr[200]; int pc = 0, outCp = 0, outB = 0; StandardTypeDescriptorOrdinal isVC = STANDARD_TYPE_VARCHAR; // set success flag to false instP[pc++] = new BoolMove(bOutP[0], bLiP[falseIdx]); // test booleans and thus all natives // check that boolean local register 0 is not null instP[pc++] = new BoolIsNotNull(bLoP[1], bLoP[0]); instP[pc] = new JumpTrue(pc + 2, bLoP[1]); pc++; instP[pc++] = new ReturnInstruction(); // write something into non-null 0 // will cause crash if 0 happened to be null instP[pc++] = new BoolMove(bLoP[0], bLiP[trueIdx]); // set local 0 to null instP[pc++] = new BoolToNull(bLoP[0]); // check local 0 is null instP[pc++] = new BoolIsNull(bLoP[2], bLoP[0]); instP[pc] = new JumpTrue(pc + 2, bLoP[2]); pc++; instP[pc++] = new ReturnInstruction(); // test pointers // check that pointer local register 0 is not null instP[pc++] = new BoolPointerIsNotNull<char *>(bLoP[3], cpLoP[0], isVC); instP[pc] = new JumpTrue(pc + 2, bLoP[3]); pc++; instP[pc++] = new ReturnInstruction(); // copy local 0 to output register, so we can see it instP[pc++] = new PointerMove<char *>(cpOutP[0], cpLoP[0], isVC); // write something into non-null 0 // will cause crash if 0 happened to be null instP[pc++] = new PointerMove<char *>(cpLoP[0], cpLiP[1], isVC); // set local 0 to null instP[pc++] = new PointerToNull<char *>(cpLoP[0], isVC); // copy local 0 to output register, so we can see it instP[pc++] = new PointerMove<char *>(cpOutP[1], cpLoP[0], isVC); // check local 0 is null instP[pc++] = new BoolPointerIsNull<char *>(bLoP[4], cpLoP[0], isVC); instP[pc] = new JumpTrue(pc + 2, bLoP[4]); pc++; instP[pc++] = new ReturnInstruction(); // set success instP[pc++] = new BoolMove(bOutP[0], bLiP[trueIdx]); instP[pc++] = new ReturnInstruction(); int lastPC = pc; for (i = 0; i < pc; i++) { c.appendInstruction(instP[i]); } printf("first run\n"); c.bind( RegisterReference::ELiteral, &literal, tupleDesc); c.bind( RegisterReference::EInput, &input, tupleDesc); c.bind( RegisterReference::EOutput, &output, tupleDesc); c.bind( RegisterReference::ELocal, &local, tupleDesc); c.bind( RegisterReference::EStatus, &status, tupleDesc); c.exec(); printf("after first run\n"); string out; for (i = 0; i < pc; i++) { instP[i]->describe(out, true); printf("[%2d] %s\n", i, out.c_str()); } // Print out the output tuple printf("Output Tuple\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("Local Tuple\n"); tuplePrinter.print(cout, tupleDesc, local); cout << endl; outCp = 0; // now indexes into output tuple, not outputregisterref outB = boolIdx; // now indexs into output tuple, not outputregisterref // check status flag in output if (*(output[boolIdx].pData) != true) { fail("nullablelocal1", __LINE__); } // check that actual pointer was not nulled out if (local[boolIdx].pData == NULL) { fail("nullablelocal2", __LINE__); } // make sure that previously null pointers weren't somehow 'un-nulled' if (literal[nullidx].pData != NULL) { fail("nullablelocal3", __LINE__); } if (input[nullidx].pData != NULL) { fail("nullablelocal4", __LINE__); } if (output[nullidx].pData != NULL) { fail("nullablelocal5", __LINE__); } if (local[nullidx].pData != NULL) { fail("nullablelocal6", __LINE__); } printf("second run\n"); c.bind(&input, &output); c.exec(); printf("after second run\n"); // Print out the output tuple printf("Output Tuple\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("Local Tuple\n"); tuplePrinter.print(cout, tupleDesc, local); cout << endl; // check status flag in output if (*(output[boolIdx].pData) != true) { fail("nullablelocal7", __LINE__); } // check that actual pointer was not nulled out if (local[boolIdx].pData == NULL) { fail("nullablelocal8", __LINE__); } // make sure that previously null pointers weren't somehow 'un-nulled' if (literal[nullidx].pData != NULL) { fail("nullablelocal9", __LINE__); } if (input[nullidx].pData != NULL) { fail("nullablelocal10", __LINE__); } if (output[nullidx].pData != NULL) { fail("nullablelocal11", __LINE__); } if (local[nullidx].pData != NULL) { fail("nullablelocal12", __LINE__); } delete [] cpInP; delete [] cpOutP; delete [] cpLoP; delete [] cpLiP; delete [] bInP; delete [] bOutP; delete [] bLoP; delete [] bLiP; for (i = 0; i < lastPC; i++) { delete instP[i]; } delete [] instP; } void unitTestStatusRegister() { printf("=========================================================\n"); printf("=========================================================\n"); printf("=====\n"); printf("===== unitTestStatusRegister()\n"); printf("=====\n"); printf("=========================================================\n"); printf("=========================================================\n"); bool isNullable = true; // Can tuple contain nulls? int i, registersize = 10; TupleDescriptor tupleDesc; tupleDesc.clear(); // Build up a description of what we'd like the tuple to look like StandardTypeDescriptorFactory typeFactory; int idx = 0; int u_int16Idx = idx; for (i = 0;i < registersize; i++) { // u_int16 (short) StoredTypeDescriptor const &typeDesc = typeFactory.newDataType(STANDARD_TYPE_UINT_16); tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable)); idx++; } // Create a tuple accessor from the description // // Note: Must use a NOT_NULL_AND_FIXED accessor when creating a tuple out // of the air like this, otherwise unmarshal() does not know what to do. If // you need a STANDARD type tuple that supports nulls, it has to be built // as a copy. TupleAccessor tupleAccessorFixedLiteral; TupleAccessor tupleAccessorFixedInput; TupleAccessor tupleAccessorFixedOutput; TupleAccessor tupleAccessorFixedLocal; TupleAccessor tupleAccessorFixedStatus; tupleAccessorFixedLiteral.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedInput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedOutput.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedLocal.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); tupleAccessorFixedStatus.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED); // Allocate memory for the tuple boost::scoped_array<FixedBuffer> pTupleBufFixedLiteral( new FixedBuffer[tupleAccessorFixedLiteral.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedInput( new FixedBuffer[tupleAccessorFixedInput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedOutput( new FixedBuffer[tupleAccessorFixedOutput.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedLocal( new FixedBuffer[tupleAccessorFixedLocal.getMaxByteCount()]); boost::scoped_array<FixedBuffer> pTupleBufFixedStatus( new FixedBuffer[tupleAccessorFixedStatus.getMaxByteCount()]); // Link memory to accessor tupleAccessorFixedLiteral.setCurrentTupleBuf( pTupleBufFixedLiteral.get(), false); tupleAccessorFixedInput.setCurrentTupleBuf( pTupleBufFixedInput.get(), false); tupleAccessorFixedOutput.setCurrentTupleBuf( pTupleBufFixedOutput.get(), false); tupleAccessorFixedLocal.setCurrentTupleBuf( pTupleBufFixedLocal.get(), false); tupleAccessorFixedStatus.setCurrentTupleBuf( pTupleBufFixedStatus.get(), false); // Create a vector of TupleDatum objects based on the description we built TupleData tupleDataFixedLiteral(tupleDesc); TupleData tupleDataFixedInput(tupleDesc); TupleData tupleDataFixedOutput(tupleDesc); TupleData tupleDataFixedLocal(tupleDesc); TupleData tupleDataFixedStatus(tupleDesc); // Do something mysterious. Probably binding pointers in the accessor to // items in the TupleData vector tupleAccessorFixedLiteral.unmarshal(tupleDataFixedLiteral); tupleAccessorFixedInput.unmarshal(tupleDataFixedInput); tupleAccessorFixedOutput.unmarshal(tupleDataFixedOutput); tupleAccessorFixedLocal.unmarshal(tupleDataFixedLocal); tupleAccessorFixedStatus.unmarshal(tupleDataFixedStatus); // create four nullable tuples to serve as register sets TupleData literal = tupleDataFixedLiteral; TupleData input = tupleDataFixedInput; TupleData output = tupleDataFixedOutput; TupleData local = tupleDataFixedLocal; TupleData status = tupleDataFixedStatus; // Set up some useful literals for (i = 0; i < registersize; i++) { *(reinterpret_cast<uint16_t *>(const_cast<PBuffer>(literal[i].pData))) = i; *(reinterpret_cast<uint16_t *>(const_cast<PBuffer>(output[i].pData))) = i * 2 + 1; *(reinterpret_cast<uint16_t *>(const_cast<PBuffer>(input[i].pData))) = i * 5 + 2; *(reinterpret_cast<uint16_t *>(const_cast<PBuffer>(local[i].pData))) = i * 10 + 3; *(reinterpret_cast<uint16_t *>(const_cast<PBuffer>(status[i].pData))) = i * 15 + 4; } // Print out the nullable tuple TuplePrinter tuplePrinter; printf("Literals\n"); tuplePrinter.print(cout, tupleDesc, literal); cout << endl; printf("\nInput\n"); tuplePrinter.print(cout, tupleDesc, input); cout << endl; printf("\nOutput\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("\nLocal\n"); tuplePrinter.print(cout, tupleDesc, local); printf("\nStatus\n"); tuplePrinter.print(cout, tupleDesc, status); cout << endl; // predefine register references. a real compiler wouldn't do // something so regular and pre-determined. a compiler would // probably build these on the fly as it built each instruction. // predefine register references. a real compiler wouldn't do // something so regular and pre-determined RegisterRef<uint16_t> **fInP, **fOutP, **fLoP, **fLiP, **fStP; fInP = new RegisterRef<uint16_t>*[registersize]; fOutP = new RegisterRef<uint16_t>*[registersize]; fLoP = new RegisterRef<uint16_t>*[registersize]; fLiP = new RegisterRef<uint16_t>*[registersize]; fStP = new RegisterRef<uint16_t>*[registersize]; // Set up the Calculator DynamicParamManager dpm; Calculator c(&dpm,0,0,0,0,0,0); c.outputRegisterByReference(false); // set up register references to symbolically point to // their corresponding storage locations -- makes for easy test case // generation. again, a compiler wouldn't do things in quite // this way. for (i = 0; i < registersize; i++) { fInP[i] = new RegisterRef<uint16_t>( RegisterReference::EInput, u_int16Idx + i, STANDARD_TYPE_UINT_16); c.appendRegRef(fInP[i]); fOutP[i] = new RegisterRef<uint16_t>( RegisterReference::EOutput, u_int16Idx + i, STANDARD_TYPE_UINT_16); c.appendRegRef(fOutP[i]); fLoP[i] = new RegisterRef<uint16_t>( RegisterReference::ELocal, u_int16Idx + i, STANDARD_TYPE_UINT_16); c.appendRegRef(fLoP[i]); fLiP[i] = new RegisterRef<uint16_t>( RegisterReference::ELiteral, u_int16Idx + i, STANDARD_TYPE_UINT_16); c.appendRegRef(fLiP[i]); fStP[i] = new RegisterRef<uint16_t>( RegisterReference::EStatus, u_int16Idx + i, STANDARD_TYPE_UINT_16); c.appendRegRef(fStP[i]); } // Set up storage for instructions // a real compiler would probably cons up instructions and insert them // directly into the calculator. keep an array of the instructions at // this level to allow printing of the program after execution, and other // debugging Instruction **instP; instP = new InstructionPtr[200]; int pc = 0, statusS = 0, liS = 0; StandardTypeDescriptorOrdinal isU_Int16 = STANDARD_TYPE_UINT_16; // copy some of the literals into the status register for (i = 0; i < registersize - 1 ; i++) { instP[pc++] = new NativeMove<uint16_t>( fStP[statusS++], fLiP[liS++], isU_Int16); } int lastPC = pc; for (i = 0; i < pc; i++) { c.appendInstruction(instP[i]); } c.bind( RegisterReference::ELiteral, &literal, tupleDesc); c.bind( RegisterReference::EInput, &input, tupleDesc); c.bind( RegisterReference::EOutput, &output, tupleDesc); c.bind( RegisterReference::ELocal, &local, tupleDesc); c.bind( RegisterReference::EStatus, &status, tupleDesc); c.exec(); string out; for (i = 0; i < pc; i++) { instP[i]->describe(out, true); printf("[%2d] %s\n", i, out.c_str()); } // Print out the output tuple printf("Output Tuple\n"); tuplePrinter.print(cout, tupleDesc, output); cout << endl; printf("Status Tuple\n"); tuplePrinter.print(cout, tupleDesc, status); cout << endl; cout << "Calculator Warnings: " << c.warnings() << endl; statusS = liS = 0; for (i = 0; i < registersize - 1 ; i++) { if (*(reinterpret_cast<uint16_t *>( const_cast<PBuffer>(status[statusS++].pData))) != static_cast<uint16_t>(i)) { fail("statusregister1", __LINE__); } } delete [] fInP; delete [] fOutP; delete [] fLoP; delete [] fLiP; delete [] fStP; for (i = 0; i < lastPC; i++) { delete instP[i]; } delete [] instP; } int main(int argc, char* argv[]) { ProgramName = argv[0]; CalcInit::instance(); unitTestBool(); unitTestLong(); unitTestFloat(); unitTestWarnings(); unitTestPointer(); unitTestPointerCache(); unitTestNullableLocal(); unitTestStatusRegister(); printf("all tests passed\n"); exit(0); } boost::unit_test_framework::test_suite *init_unit_test_suite(int,char **) { return NULL; } #else int main(int argc, char *argv[]) { return 0; } #endif // End testCalc.cpp
35.23993
80
0.600218
[ "object", "vector" ]
694d9f2cd65e110bc1d6754996b2a01db5872dbe
1,569
cpp
C++
src/mxml/attributes/AlterSequence.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
18
2016-05-22T00:55:28.000Z
2021-03-29T08:44:23.000Z
src/mxml/attributes/AlterSequence.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
6
2017-05-17T13:20:09.000Z
2018-10-22T20:00:57.000Z
src/mxml/attributes/AlterSequence.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
14
2016-05-12T22:54:34.000Z
2021-10-19T12:43:16.000Z
// Copyright © 2016 Venture Media Labs. // // This file is part of mxml. The full mxml copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "AlterSequence.h" #include <mxml/dom/Measure.h> #include <mxml/dom/Part.h> #include <algorithm> #include <iterator> namespace mxml { void AlterSequence::addFromNote(std::size_t partIndex, std::size_t measureIndex, const dom::Note& note) { if (!note.pitch) return; Item item; item.index = indexFromNote(note); item.value = note.pitch->alter(); _items.push_back(item); } int AlterSequence::find(const Index& index, int defaultAlter) const { Item modelItem; modelItem.index = index; // Only note alters on the same measure should be considered auto range = std::equal_range(_items.begin(), _items.end(), modelItem, [=](const Item& item1, const Item& item2) { return item1.index.time.measureIndex < item2.index.time.measureIndex; }); // Find the last alter with a time before index auto rbegin = std::reverse_iterator<std::vector<Item>::const_iterator>(range.second); auto rend = std::reverse_iterator<std::vector<Item>::const_iterator>(range.first); auto it = std::find_if(rbegin, rend, [=](const Item& item) { return item.index.line == modelItem.index.line && item.index.time.time < modelItem.index.time.time; }); if (it == rend) return defaultAlter; return it->value; } } // namespace mxml
31.38
118
0.692161
[ "vector" ]
69530653e466cc45cdefdf6b3662a80cb1df330f
603
cpp
C++
src/Generator.cpp
JaredDyreson/BetterScheduler
311d9f4b958dcbd8fcc129abca647f7efd7d3c12
[ "MIT" ]
null
null
null
src/Generator.cpp
JaredDyreson/BetterScheduler
311d9f4b958dcbd8fcc129abca647f7efd7d3c12
[ "MIT" ]
null
null
null
src/Generator.cpp
JaredDyreson/BetterScheduler
311d9f4b958dcbd8fcc129abca647f7efd7d3c12
[ "MIT" ]
null
null
null
#include "../includes/Generator.hpp" #include "../includes/dataclasses/OrderTicket.hpp" Generator::Generator() {} OrderTicket Generator::dispense() { /* * Once we give the contents of our OrderTicket * we no longer want the information persist */ return this->currentTicket; //OrderTicket returnTicket = this->currentTicket; //// FIXME: we need some way to clear this object after dispensing //return returnTicket; } bool Generator::is_empty() const{ return true; // this should probably check if this->container is a nullptr but I want to actively avoid a use after free here }
30.15
127
0.729685
[ "object" ]
6966723e67c361052f9ed0960ca13d2de034df30
3,666
cpp
C++
examples/cpp/parameters_cpp/parameters_service_cpp.cpp
asorbini/rticonnextdds-ros2-adapter
a8073e5bcd3ccd5cabf7bc6b73aff3a90d1116c8
[ "Apache-2.0" ]
null
null
null
examples/cpp/parameters_cpp/parameters_service_cpp.cpp
asorbini/rticonnextdds-ros2-adapter
a8073e5bcd3ccd5cabf7bc6b73aff3a90d1116c8
[ "Apache-2.0" ]
null
null
null
examples/cpp/parameters_cpp/parameters_service_cpp.cpp
asorbini/rticonnextdds-ros2-adapter
a8073e5bcd3ccd5cabf7bc6b73aff3a90d1116c8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2022 Real-Time Innovations, Inc. (RTI) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include <thread> #include <chrono> #include <rti/request/Replier.hpp> #include "rticonnextdds_ros2_adapter/rticonnextdds_ros2_adapter_cpp.hpp" #include "Parameters.hpp" #include "ParametersPlugin.hpp" using namespace std::chrono_literals; int main(int argc, char **argv) { (void)argc; (void)argv; static const char * const topic_name_req = "rq/foo/list_parametersRequest"; static const char * const topic_name_rep = "rr/foo/list_parametersReply"; dds::domain::DomainParticipant participant(0); assert(nullptr != participant); dds::sub::Subscriber subscriber = dds::sub::Subscriber(participant); assert(nullptr != subscriber); dds::pub::Publisher publisher = dds::pub::Publisher(participant); assert(nullptr != publisher); dds::pub::qos::DataWriterQos dw_qos; publisher->default_writer_qos(dw_qos); rti::core::policy::Property dw_props; dw_props.set( { "dds.data_writer.history.memory_manager.fast_pool.pool_buffer_max_size", "1024" }, false); dw_qos << dw_props; dds::sub::qos::DataReaderQos dr_qos; subscriber->default_datareader_qos(dr_qos); rti::core::policy::Property dr_props; dr_props.set( { "dds.data_reader.history.memory_manager.fast_pool.pool_buffer_max_size", "1024" }, false); dr_qos << dr_props; rti::request::ReplierParams rep_params(participant); rep_params.request_topic_name(topic_name_req); rep_params.reply_topic_name(topic_name_rep); rep_params.datawriter_qos(dw_qos); rep_params.datareader_qos(dr_qos); rep_params.publisher(publisher); rep_params.subscriber(subscriber); rti::request::Replier< rcl_interfaces::srv::dds_::ListParameters_Request_, rcl_interfaces::srv::dds_::ListParameters_Response_> replier(rep_params); rcl_interfaces::srv::dds_::ListParameters_Response_ response; response.result().names().resize(3); response.result().names()[0] = "foo"; response.result().names()[1] = "bar"; response.result().names()[2] = "baz"; // Create a ROS 2 graph object, then register a ROS 2 node // and associate it with the DomainParticipant. // Let the graph inspect the participant and automatically // detect endpoints which follow the ROS 2 naming conventions. rti::ros2::GraphProperties g_props; g_props.graph_participant = participant; rti::ros2::Graph graph(g_props); auto node_handle = graph.register_local_node("params_service"); assert(rti::ros2::GraphNodeHandle_INVALID != node_handle); graph.inspect_local_node(node_handle); while (true) { std::cout << "Waiting for requests..." << std::endl; dds::sub::LoanedSamples<rcl_interfaces::srv::dds_::ListParameters_Request_> requests = replier.receive_requests(dds::core::Duration::from_secs(10)); for (const auto& request : requests) { if (!request.info().valid()) { std::cout << "Received invalid request\n"; continue; } std::cout << "Received request!" << std::endl; replier.send_reply(response, request.info()); } } return 0; }
32.157895
79
0.721768
[ "object" ]
696910738db8648749172dfc36ce9045127dc33e
3,819
cpp
C++
SimulationEngineLib/universe/UniverseImpl.cpp
KevinMcGin/Simulation
f1dbed05d6024274f6a69e0679f529feaae1e26e
[ "MIT" ]
4
2021-12-11T17:59:07.000Z
2021-12-24T11:08:55.000Z
SimulationEngineLib/universe/UniverseImpl.cpp
KevinMcGin/Simulation
f1dbed05d6024274f6a69e0679f529feaae1e26e
[ "MIT" ]
121
2021-12-11T09:20:47.000Z
2022-03-13T18:36:48.000Z
SimulationEngineLib/universe/UniverseImpl.cpp
KevinMcGin/Simulation
f1dbed05d6024274f6a69e0679f529feaae1e26e
[ "MIT" ]
null
null
null
#include "universe/UniverseImpl.h" #include "util/Timing.h" #include "particle/helper/ParticlesHelper.h" #include <cmath> #include <iostream> #include <map> UniverseImpl::UniverseImpl( std::vector<std::shared_ptr<Law>> laws, std::shared_ptr<SimulationInput> input, std::shared_ptr<SimulationOutput> output, unsigned int deltaTime, unsigned long endTime, Usage useGpu ) : Universe(input->input(), laws, output, deltaTime, endTime, useGpu) { if(this->useGpu == TRUE) { gpuDataController = new GpuDataController(); } } UniverseImpl::~UniverseImpl() = default; void UniverseImpl::run() { std::cout << "Simulation running" << std::endl; std::cout << particles.size() << " particles" << std::endl; std::cout << "Frames: " << endTime << std::endl; universeTiming.timingTotal.setTime(); output->output(particles, 0); universeTiming.progress = -1; int lawsRan = 0; bool particleDeleted = false; universeTiming.timingSections.setTime(); if(useGpu == TRUE) { gpuDataController->putParticlesOnDevice(particles, true); updateSectionsTiming("Data to GPU"); } for (unsigned long i = 0; i < endTime; i += deltaTime) { if(useGpu == TRUE) { if(particleDeleted) { gpuDataController->putParticlesOnDevice(particles); updateSectionsTiming("Data to GPU"); } } particleDeleted = false; for (const auto& l : laws) { if(useGpu == TRUE) { l->gpuLaw->run(gpuDataController->get_td_par(), gpuDataController->getParticleCount()); } else { l->cpuLaw->run(particles); } updateSectionsTiming(l->gpuLaw->getClassName()); printPercentComplete(++lawsRan); updateSectionsTiming("Printing"); } if(useGpu == TRUE) { gpuDataController->getParticlesFromDevice(particles); updateSectionsTiming("Data from GPU"); particleDeleted = ParticlesHelper::removeDeletedParticles(particles); updateSectionsTiming("Deletions"); } output->output(particles, i + 1); updateSectionsTiming("Data to JSON"); } printPercentComplete(lawsRan, true); printSectionsTiming(); std::cout << std::endl << "Simulation complete" << std::endl; } void UniverseImpl::printPercentComplete(int lawsRan, bool force) { float accurary = 1000.f; float fractionPassed = (lawsRan/(float)laws.size()) / endTime; universeTiming.progress = (100 * fractionPassed * accurary) / accurary; float elapsedSeconds = universeTiming.timingTotal.getTimeSeconds(); if(force || elapsedSeconds - universeTiming.lastPrintedSeconds > universeTiming.maxTimeBetweenPrints) { universeTiming.lastPrintedSeconds = elapsedSeconds; float remainingPercent = 100 - universeTiming.progress; float timeRemaining = remainingPercent * ((elapsedSeconds-universeTiming.lastEstimatedSeconds) / (universeTiming.progress-universeTiming.lastEstimatedProgress)); std::cout << "\r" << "passed: " << universeTiming.progress << "% " << Timing::getTimeWithUnit(elapsedSeconds) << ", " "remaining: " << remainingPercent << "% " << Timing::getTimeWithUnit(timeRemaining) << " " << std::flush; } if(elapsedSeconds - universeTiming.lastEstimatedSeconds > universeTiming.maxTimeBetweenEstimates) { universeTiming.lastEstimatedSeconds = elapsedSeconds; universeTiming.lastEstimatedProgress = universeTiming.progress; } } void UniverseImpl::updateSectionsTiming(std::string name) { if(universeTiming.progresses.find(name) == universeTiming.progresses.end()) { universeTiming.progresses[name] = 0; } universeTiming.progresses[name] += universeTiming.timingSections.getTimeSeconds(); universeTiming.timingSections.setTime(); } void UniverseImpl::printSectionsTiming() { std::string sections = ""; for (auto const& it : universeTiming.progresses) { sections += it.first + ": " + Timing::getTimeWithUnit(it.second) + ", "; } std::cout << std::endl << sections << std::endl; }
36.028302
163
0.722964
[ "vector" ]
69727e0d6d18b24a6ae9362dd53bc9e163969ebe
2,020
cpp
C++
solutions/longest-consecutive-sequence/solution.cpp
locker/leetcode
bf34a697de47aaf32823224d054f9a45613ce180
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
solutions/longest-consecutive-sequence/solution.cpp
locker/leetcode
bf34a697de47aaf32823224d054f9a45613ce180
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
solutions/longest-consecutive-sequence/solution.cpp
locker/leetcode
bf34a697de47aaf32823224d054f9a45613ce180
[ "BSD-2-Clause-FreeBSD" ]
1
2019-08-30T06:53:23.000Z
2019-08-30T06:53:23.000Z
#include <algorithm> #include <iostream> #include <unordered_map> #include <vector> using namespace std; template<typename T> ostream& operator<<(ostream& out, const vector<T>& v) { out << '['; for (auto it = v.begin(); it != v.end(); ++it) { if (it != v.begin()) out << ','; out << *it; } out << ']'; return out; } class Solution { public: int longestConsecutive(const vector<int>& nums) { if (nums.empty()) return 0; // // Map: k => v, k belongs to nums. // // Depending on the sign of v, [k, k+v] or [k+v, k] // is a consecutive sequence. // // Initialized with one-number sequences for each // given number. // unordered_map<int, int> seqs; for (auto x: nums) seqs.emplace(x, 0); // // Do another pass over the array and merge adjacent // sequences, keeping track of the longest consecutive // sequence length. // int max_seq = 1; for (auto x: nums) { auto end1 = seqs.find(x); if (end1 == seqs.end() || end1->second > 0) { // The value has already been merged into // some sequence. continue; } auto begin2 = seqs.find(x + 1); if (begin2 == seqs.end()) { // No adjacent sequence. continue; } auto begin1 = (end1->second == 0 ? end1 : seqs.find(end1->first + end1->second)); auto end2 = (begin2->second == 0 ? begin2 : seqs.find(begin2->first + begin2->second)); int len = begin1->second + begin2->second + 1; begin1->second = len; end2->second = -len; if (begin1 != end1) seqs.erase(end1); if (begin2 != end2) seqs.erase(begin2); max_seq = max(max_seq, len + 1); } return max_seq; } }; int main() { vector<int> input[] = { {}, // 0 {1}, // 1 {1, 2}, // 2 {2, 4, 1}, // 2 {2, 4, 3, 6}, // 3 {8, 3, 9, 5, 4, 7, 1}, // 3 {100, 4, 200, 1, 2, 3}, // 4 {3, 4, 100, 5, 101, 102, 6, 50, 60, 51}, // 4 }; Solution solution; for (const auto& nums: input) { cout << nums << " => " << solution.longestConsecutive(nums) << endl; } return 0; }
21.489362
56
0.558911
[ "vector" ]
697c4d181fe92e6399dd1963265e0fa2a0a9a276
25,953
hpp
C++
include/hil/hil.hpp
Ruin0x11/microhil
c67013600dd2c4e1dbffe174bc2ceaa6925d707a
[ "MIT" ]
null
null
null
include/hil/hil.hpp
Ruin0x11/microhil
c67013600dd2c4e1dbffe174bc2ceaa6925d707a
[ "MIT" ]
null
null
null
include/hil/hil.hpp
Ruin0x11/microhil
c67013600dd2c4e1dbffe174bc2ceaa6925d707a
[ "MIT" ]
null
null
null
#ifndef MICROHIL_H_ #define MICROHIL_H_ #include <fstream> #include <iostream> #include <istream> #include <iterator> #include <sstream> #include <vector> #include <string> #include <cassert> namespace hil { class Value; struct FunctionCall { FunctionCall(std::string& v) : name(v) {} FunctionCall(const char* v) : name(v) {} FunctionCall(const FunctionCall& other) { name = other.name; args = other.args; } ~FunctionCall() = default; std::string name; std::vector<Value> args; }; namespace internal { template<typename T> struct call_traits_value { typedef T return_type; }; template<typename T> struct call_traits_ref { typedef const T& return_type; }; } // namespace internal template<typename T> struct call_traits; template<> struct call_traits<bool> : public internal::call_traits_value<bool> {}; template<> struct call_traits<int> : public internal::call_traits_value<int> {}; template<> struct call_traits<int64_t> : public internal::call_traits_value<int64_t> {}; template<> struct call_traits<std::string> : public internal::call_traits_ref<std::string> {}; template<> struct call_traits<FunctionCall> : public internal::call_traits_ref<FunctionCall> {}; // A value is returned for std::vector<T>. Not reference. // This is because a fresh vector is made. template<typename T> struct call_traits<std::vector<T>> : public internal::call_traits_value<std::vector<T>> {}; class Value { public: enum Type { NULL_TYPE, BOOL_TYPE, INT_TYPE, IDENT_TYPE, FUNCTION_TYPE, }; Value() : type_(NULL_TYPE), null_(nullptr) {} Value(bool v) : type_(BOOL_TYPE), bool_(v) {} Value(int v) : type_(INT_TYPE), int_(v) {} Value(int64_t v) : type_(INT_TYPE), int_(v) {} Value(const std::string& v) : type_(IDENT_TYPE), string_(new std::string(v)) {} Value(const char* v) : type_(IDENT_TYPE), string_(new std::string(v)) {} Value(const FunctionCall& v) : type_(FUNCTION_TYPE), func_(new FunctionCall(v)) {} Value(std::string&& v) : type_(IDENT_TYPE), string_(new std::string(std::move(v))) {} Value(FunctionCall&& v) : type_(FUNCTION_TYPE), func_(new FunctionCall(std::move(v))) {} Value(const Value& v); Value(Value&& v) noexcept; Value& operator=(const Value& v); Value& operator=(Value&& v) noexcept; Value(const void* v) = delete; ~Value(); Type type() const { return type_; } bool valid() const { return type_ != NULL_TYPE; } template<typename T> bool is() const; template<typename T> typename call_traits<T>::return_type as() const; private: static const char* typeToString(Type); template<typename T> void assureType() const; Value* ensureValue(const std::string& key); template<typename T> struct ValueConverter; Type type_; union { void* null_; bool bool_; int64_t int_; std::string* string_; FunctionCall* func_; }; template<typename T> friend struct ValueConverter; }; class Context { public: bool valid() const { for (auto&& value : hilParts) { if (!value.valid()) return false; } return true; }; std::vector<std::string> textParts; std::vector<Value> hilParts; }; // parse() returns ParseResult. struct ParseResult { ParseResult(hil::Context v, std::string er) : context(std::move(v)), errorReason(std::move(er)) {} bool valid() const { return context.valid(); } hil::Context context; std::string errorReason; }; // Parses from std::istream. ParseResult parse(std::istream&); // Parses a file. ParseResult parseFile(const std::string& filename); namespace internal { enum class TokenType { // Special tokens ILLEGAL, END_OF_FILE, COMMENT, IDENT, // literals NUMBER, // 12345 FLOAT, // 123.45 BOOL, // true,false STRING, // "abc" HIL, // "${foo(bar)}" HEREDOC, // <<FOO\nbar\nFOO LBRACK, // [ LPAREN, // ( LBRACE, // { COMMA, // , PERIOD, // . RBRACK, // ] RPAREN, // ) RBRACE, // } }; class Token { public: explicit Token(TokenType type) : type_(type) {} Token(TokenType type, const std::string& v) : type_(type), str_value_(v) {} Token(TokenType type, bool v) : type_(type), int_value_(v) {} Token(TokenType type, std::int64_t v) : type_(type), int_value_(v) {} Token(TokenType type, double v) : type_(type), double_value_(v) {} TokenType type() const { return type_; } const std::string& strValue() const { return str_value_; } bool boolValue() const { return int_value_ != 0; } std::int64_t intValue() const { return int_value_; } double doubleValue() const { return double_value_; } private: TokenType type_; std::string str_value_; std::int64_t int_value_; double double_value_; }; class Lexer { public: explicit Lexer(std::istream& is) : is_(is), lineNo_(1), columnNo_(0) {} Token nextToken(bool); int lineNo() const { return lineNo_; } int columnNo() const { return columnNo_; } // Skips if UTF8BOM is found. // Returns true if success. Returns false if intermediate state is left. bool skipUTF8BOM(); bool consume(char c); private: bool current(char* c); void next(); Token nextValueToken(); Token nextNumber(bool leadingDot, bool leadingSub); void skipUntilNewLine(); Token nextString(); Token nextHereDoc(); std::istream& is_; int lineNo_; int columnNo_; }; class Parser { public: explicit Parser(std::istream& is) : lexer_(is), token_(TokenType::ILLEGAL) { lexer_.skipUTF8BOM(); nextToken(false); } // Parses. If failed, value should be invalid value. // You can get the error by calling errorReason(). Context parse(); const std::string& errorReason(); private: const Token& token() const { return token_; } void nextToken(bool isInHil) { token_ = lexer_.nextToken(isInHil); } bool consume(char c) { return lexer_.consume(c); } int columnNo() { return lexer_.columnNo(); } void skipForKey(); void skipForValue(); bool consumeForKey(TokenType); bool consumeForValue(TokenType); bool consumeEOLorEOFForKey(); bool parseText(std::string&); bool parseHil(Value&); bool parseFunction(Value&, std::string); void addError(const std::string& reason); bool unindentHeredoc(const std::string& heredoc, std::string& out); Lexer lexer_; Token token_; std::string errorReason_; }; } // namespace internal // ---------------------------------------------------------------------- // Implementations inline ParseResult parse(std::istream& is) { if (!is) { return ParseResult(hil::Context(), "stream is in bad state. file does not exist?"); } internal::Parser parser(is); hil::Context v = parser.parse(); if (v.valid()) return ParseResult(std::move(v), std::string()); return ParseResult(std::move(v), std::move(parser.errorReason())); } inline ParseResult parseFile(const std::string& filename) { std::ifstream ifs(filename); if (!ifs) { return ParseResult(hil::Context(), std::string("could not open file: ") + filename); } return parse(ifs); } inline std::string format(std::stringstream& ss) { return ss.str(); } template<typename T, typename... Args> std::string format(std::stringstream& ss, T&& t, Args&&... args) { ss << std::forward<T>(t); return format(ss, std::forward<Args>(args)...); } template<typename... Args> #if defined(_MSC_VER) __declspec(noreturn) #else [[noreturn]] #endif void failwith(Args&&... args) { std::stringstream ss; throw std::runtime_error(format(ss, std::forward<Args>(args)...)); } namespace internal { inline std::string removeDelimiter(const std::string& s) { std::string r; for (char c : s) { if (c == '_') continue; r += c; } return r; } inline std::string unescape(const std::string& codepoint) { std::uint32_t x; std::uint8_t buf[8]; std::stringstream ss(codepoint); ss >> std::hex >> x; if (x <= 0x7FUL) { // 0xxxxxxx buf[0] = 0x00 | ((x >> 0) & 0x7F); buf[1] = '\0'; } else if (x <= 0x7FFUL) { // 110yyyyx 10xxxxxx buf[0] = 0xC0 | ((x >> 6) & 0xDF); buf[1] = 0x80 | ((x >> 0) & 0xBF); buf[2] = '\0'; } else if (x <= 0xFFFFUL) { // 1110yyyy 10yxxxxx 10xxxxxx buf[0] = 0xE0 | ((x >> 12) & 0xEF); buf[1] = 0x80 | ((x >> 6) & 0xBF); buf[2] = 0x80 | ((x >> 0) & 0xBF); buf[3] = '\0'; } else if (x <= 0x10FFFFUL) { // 11110yyy 10yyxxxx 10xxxxxx 10xxxxxx buf[0] = 0xF0 | ((x >> 18) & 0xF7); buf[1] = 0x80 | ((x >> 12) & 0xBF); buf[2] = 0x80 | ((x >> 6) & 0xBF); buf[3] = 0x80 | ((x >> 0) & 0xBF); buf[4] = '\0'; } else { buf[0] = '\0'; } return reinterpret_cast<char*>(buf); } // Returns true if |s| is integer. // [+-]?\d+(_\d+)* inline bool isInteger(const std::string& s) { if (s.empty()) return false; std::string::size_type p = 0; if (s[p] == '+' || s[p] == '-') ++p; while (p < s.size() && '0' <= s[p] && s[p] <= '9') { ++p; if (p < s.size() && s[p] == '_') { ++p; if (!(p < s.size() && '0' <= s[p] && s[p] <= '9')) return false; } } return p == s.size(); } // Returns true if |s| is double. // [+-]? (\d+(_\d+)*)? (\.\d+(_\d+)*)? ([eE] [+-]? \d+(_\d+)*)? // 1----------- 2------------- 3---------------------- // 2 or (1 and 3) should exist. inline bool isDouble(const std::string& s) { if (s.empty()) return false; std::string::size_type p = 0; if (s[p] == '+' || s[p] == '-') ++p; bool ok = false; while (p < s.size() && '0' <= s[p] && s[p] <= '9') { ++p; ok = true; if (p < s.size() && s[p] == '_') { ++p; if (!(p < s.size() && '0' <= s[p] && s[p] <= '9')) return false; } } if (p < s.size() && s[p] == '.') ++p; while (p < s.size() && '0' <= s[p] && s[p] <= '9') { ++p; ok = true; if (p < s.size() && s[p] == '_') { ++p; if (!(p < s.size() && '0' <= s[p] && s[p] <= '9')) return false; } } if (!ok) return false; ok = false; if (p < s.size() && (s[p] == 'e' || s[p] == 'E')) { ++p; if (p < s.size() && (s[p] == '+' || s[p] == '-')) ++p; while (p < s.size() && '0' <= s[p] && s[p] <= '9') { ++p; ok = true; if (p < s.size() && s[p] == '_') { ++p; if (!(p < s.size() && '0' <= s[p] && s[p] <= '9')) return false; } } if (!ok) return false; } return p == s.size(); } // static inline std::string escapeString(const std::string& s) { std::stringstream ss; for (size_t i = 0; i < s.size(); ++i) { switch (s[i]) { case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; case '\"': ss << "\\\""; break; case '\'': ss << "\\\'"; break; case '\\': ss << "\\\\"; break; default: ss << s[i]; break; } } return ss.str(); } } // namespace internal // ---------------------------------------------------------------------- // Lexer namespace internal { inline bool Lexer::skipUTF8BOM() { // Check [EF, BB, BF] int x1 = is_.peek(); if (x1 != 0xEF) { // When the first byte is not 0xEF, it's not UTF8 BOM. // Just return true. return true; } is_.get(); int x2 = is_.get(); if (x2 != 0xBB) { is_.clear(); is_.seekg(0); return false; } int x3 = is_.get(); if (x3 != 0xBF) { is_.clear(); is_.seekg(0); return false; } return true; } inline bool Lexer::current(char* c) { int x = is_.peek(); if (x == EOF) return false; *c = static_cast<char>(x); return true; } inline void Lexer::next() { int x = is_.get(); if (x == '\n') { columnNo_ = 0; ++lineNo_; } else { ++columnNo_; } } inline bool Lexer::consume(char c) { char x; if (!current(&x)) return false; if (x != c) return false; next(); return true; } inline void Lexer::skipUntilNewLine() { char c; while (current(&c)) { if (c == '\n') return; next(); } } inline Token Lexer::nextString() { std::string s; char c; bool dollar = false; while (current(&c)) { next(); if (dollar) { if (c == '{') return Token(TokenType::STRING, s); else s += "$"; } dollar = false; if (c == '$') { dollar = true; } if (c == '\\') { if (!current(&c)) return Token(TokenType::ILLEGAL, std::string("string has unknown escape sequence")); next(); switch (c) { case 't': c = '\t'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 'x': case 'u': case 'U': { int size = 0; if (c == 'x') { size = 2; } else if (c == 'u') { size = 4; } else if (c == 'U') { size = 8; } std::string codepoint; for (int i = 0; i < size; ++i) { if (current(&c) && (('0' <= c && c <= '9') || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f'))) { codepoint += c; next(); } else { return Token(TokenType::ILLEGAL, std::string("string has unknown escape sequence")); } } s += unescape(codepoint); continue; } case '"': c = '"'; break; case '\'': c = '\''; break; case '\\': c = '\\'; break; case '\n': return Token(TokenType::ILLEGAL, std::string("literal not terminated")); default: return Token(TokenType::ILLEGAL, std::string("string has unknown escape sequence")); } } else if (c == '\n') { return Token(TokenType::ILLEGAL, std::string("found newline while parsing non-HIL string literal")); } else if (c == '"') { return Token(TokenType::ILLEGAL, std::string("found double quotes while parsing non-HIL string literal")); } if (!dollar) s += c; } return Token(TokenType::STRING, s); } inline bool isValidIdentChar(char c) { return isalpha(static_cast<unsigned char>(c)) || isdigit(static_cast<unsigned char>(c)) || c == '_' || c == '-' || c == '.' || c == ':' || c == '/'; } inline Token Lexer::nextValueToken() { std::string s; char c; if (current(&c) && (isalpha(static_cast<unsigned char>(c)) || c == '_')) { s += c; next(); while (current(&c) && isValidIdentChar(c)) { s += c; next(); } if (s == "true") { return Token(TokenType::BOOL, true); } if (s == "false") { return Token(TokenType::BOOL, false); } return Token(TokenType::IDENT, s); } return nextNumber(false, false); } inline Token Lexer::nextNumber(bool leadingDot, bool leadingSub) { std::string s; char c; if (leadingDot) { s += '.'; } if (leadingSub) { s += '-'; } while (current(&c) && (('0' <= c && c <= '9') || c == '.' || c == 'e' || c == 'E' || c == 'T' || c == 'Z' || c == '_' || c == ':' || c == '-' || c == '+')) { next(); s += c; } if (isInteger(s)) { std::stringstream ss(removeDelimiter(s)); std::int64_t x; ss >> x; return Token(TokenType::NUMBER, x); } if (isDouble(s)) { std::stringstream ss(removeDelimiter(s)); double d; ss >> d; return Token(TokenType::FLOAT, d); } return Token(TokenType::ILLEGAL, std::string("Invalid token")); } inline bool isWhitespace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } inline Token Lexer::nextToken(bool isInHil) { char c; while (current(&c)) { if (!isInHil) { return nextString(); } if (isInHil && isWhitespace(c)) { next(); continue; } switch (c) { case '{': next(); return Token(TokenType::LBRACE, "{"); case '}': next(); return Token(TokenType::RBRACE, "}"); case '(': next(); return Token(TokenType::LPAREN, "("); case ')': next(); return Token(TokenType::RPAREN, ")"); case '[': next(); return Token(TokenType::LBRACK, "["); case ']': next(); return Token(TokenType::RBRACK, "]"); case ',': next(); return Token(TokenType::COMMA, ","); case '.': next(); return Token(TokenType::COMMA, "."); default: return nextValueToken(); } } return Token(TokenType::END_OF_FILE); } } // namespace internal inline const char* Value::typeToString(Value::Type type) { switch (type) { case NULL_TYPE: return "null"; case BOOL_TYPE: return "bool"; case INT_TYPE: return "int"; case IDENT_TYPE: return "string"; case FUNCTION_TYPE: return "function call"; default: return "unknown"; } } inline Value::Value(const Value& v) : type_(v.type_) { switch (v.type_) { case NULL_TYPE: null_ = v.null_; break; case BOOL_TYPE: bool_ = v.bool_; break; case INT_TYPE: int_ = v.int_; break; case IDENT_TYPE: string_ = new std::string(*v.string_); break; case FUNCTION_TYPE: func_ = new FunctionCall(*v.func_); break; default: assert(false); type_ = NULL_TYPE; null_ = nullptr; } } inline Value::Value(Value&& v) noexcept : type_(v.type_) { switch (v.type_) { case NULL_TYPE: null_ = v.null_; break; case BOOL_TYPE: bool_ = v.bool_; break; case INT_TYPE: int_ = v.int_; break; case IDENT_TYPE: string_ = v.string_; break; case FUNCTION_TYPE: func_ = v.func_; break; default: assert(false); type_ = NULL_TYPE; null_ = nullptr; } v.type_ = NULL_TYPE; v.null_ = nullptr; } inline Value& Value::operator=(const Value& v) { if (this == &v) return *this; this->~Value(); type_ = v.type_; switch (v.type_) { case NULL_TYPE: null_ = v.null_; break; case BOOL_TYPE: bool_ = v.bool_; break; case INT_TYPE: int_ = v.int_; break; case IDENT_TYPE: string_ = new std::string(*v.string_); break; case FUNCTION_TYPE: func_ = new FunctionCall(*v.func_); break; default: assert(false); type_ = NULL_TYPE; null_ = nullptr; } return *this; } inline Value& Value::operator=(Value&& v) noexcept { if (this == &v) return *this; this->~Value(); type_ = v.type_; switch (v.type_) { case NULL_TYPE: null_ = v.null_; break; case BOOL_TYPE: bool_ = v.bool_; break; case INT_TYPE: int_ = v.int_; break; case IDENT_TYPE: string_ = v.string_; break; case FUNCTION_TYPE: func_ = v.func_; break; default: assert(false); type_ = NULL_TYPE; null_ = nullptr; } v.type_ = NULL_TYPE; v.null_ = nullptr; return *this; } inline Value::~Value() { switch (type_) { case IDENT_TYPE: delete string_; break; case FUNCTION_TYPE: delete func_; break; default: break; } } template<> struct Value::ValueConverter<bool> { bool is(const Value& v) { return v.type() == Value::BOOL_TYPE; } bool to(const Value& v) { v.assureType<bool>(); return v.bool_; } }; template<> struct Value::ValueConverter<int64_t> { bool is(const Value& v) { return v.type() == Value::INT_TYPE; } int64_t to(const Value& v) { v.assureType<int64_t>(); return v.int_; } }; template<> struct Value::ValueConverter<int> { bool is(const Value& v) { return v.type() == Value::INT_TYPE; } int to(const Value& v) { v.assureType<int>(); return static_cast<int>(v.int_); } }; template<> struct Value::ValueConverter<std::string> { bool is(const Value& v) { return v.type() == Value::IDENT_TYPE; } const std::string& to(const Value& v) { v.assureType<std::string>(); return *v.string_; } }; template<> struct Value::ValueConverter<FunctionCall> { bool is(const Value& v) { return v.type() == Value::FUNCTION_TYPE; } const FunctionCall& to(const Value& v) { v.assureType<FunctionCall>(); return *v.func_; } }; namespace internal { template<typename T> inline const char* type_name(); template<> inline const char* type_name<bool>() { return "bool"; } template<> inline const char* type_name<int>() { return "int"; } template<> inline const char* type_name<int64_t>() { return "int64_t"; } template<> inline const char* type_name<std::string>() { return "string"; } template<> inline const char* type_name<hil::FunctionCall>() { return "function call"; } } // namespace internal template<typename T> inline void Value::assureType() const { if (!is<T>()) failwith("type error: this value is ", typeToString(type_), " but ", internal::type_name<T>(), " was requested"); } template<typename T> inline bool Value::is() const { return ValueConverter<T>().is(*this); } template<typename T> inline typename call_traits<T>::return_type Value::as() const { return ValueConverter<T>().to(*this); } // ---------------------------------------------------------------------- // Parser namespace internal { inline void Parser::addError(const std::string& reason) { std::stringstream ss; ss << "Error:" << lexer_.lineNo() << ":" << lexer_.columnNo() << ": " << reason << "\n"; errorReason_ += ss.str(); } inline const std::string& Parser::errorReason() { return errorReason_; } inline Context Parser::parse() { Context context; std::string text; while (true) { if (!parseText(text)) { if (errorReason().size() > 0) { context.textParts.clear(); context.hilParts.clear(); return context; } break; } nextToken(true); if (token().type() == TokenType::END_OF_FILE) break; context.textParts.emplace_back(std::move(text)); Value v; if (!parseHil(v)) { addError("failed to parse HIL"); break; } context.hilParts.emplace_back(std::move(v)); if (token().type() != TokenType::RBRACE) { addError("expected closing brace"); break; } nextToken(false); } context.textParts.emplace_back(std::move(text)); return context; } inline bool Parser::parseText(std::string& text) { if (token().type() == TokenType::END_OF_FILE) { return false; } else if (token().type() == TokenType::STRING) { text = token().strValue(); return true; } addError("could not parse text"); return true; } inline bool Parser::parseHil(Value& currentValue) { switch (token().type()) { case TokenType::RBRACE: addError("no value within braces"); return false; case TokenType::IDENT: { std::string ident = token().strValue(); nextToken(true); if (token().type() == TokenType::LPAREN) { if(!parseFunction(currentValue, ident)) return false; else return true; } else if (token().type() == TokenType::RBRACE) { currentValue = ident; return true; } else { addError("error parsing ident"); return false; } } default: addError("unsupported value"); return false; } } inline bool Parser::parseFunction(Value& currentValue, std::string ident) { FunctionCall func(ident); while(true) { nextToken(true); switch(token().type()) { case TokenType::RPAREN: currentValue = func; nextToken(true); return true; case TokenType::COMMA: break; case TokenType::IDENT: func.args.emplace_back(std::move(token().strValue())); break; case TokenType::BOOL: func.args.emplace_back(token().boolValue()); break; case TokenType::NUMBER: func.args.emplace_back(token().intValue()); break; default: addError("error parsing function arguments: " + func.name); } } addError("error parsing function arguments: " + func.name); return false; } } // namespace internal } // namespace hil #endif // MICROHIL_H_
24.27783
152
0.520287
[ "vector" ]
6985372e07a767f3ac9a9db481d244007a673ba1
727
cpp
C++
Codeforces/Practice/A12.cpp
MayThirtyOne/DS-Algo
12d2d02612fc59c877dcc05f42add5a7f5c88337
[ "MIT" ]
null
null
null
Codeforces/Practice/A12.cpp
MayThirtyOne/DS-Algo
12d2d02612fc59c877dcc05f42add5a7f5c88337
[ "MIT" ]
null
null
null
Codeforces/Practice/A12.cpp
MayThirtyOne/DS-Algo
12d2d02612fc59c877dcc05f42add5a7f5c88337
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long int using namespace std; void solve() { int n; cin>>n; vector<int> v(n); for(int i=0;i<n;i++){ cin>>v[i]; } sort(v.begin(),v.end()); bool flag=false; for(int i=1;i<v.size();i++){ if(abs(v[i]-v[i-1]>1)){ flag=true; break; } } if(flag) cout<<"NO"<<endl; else cout<<"YES"<<endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("error.txt", "w", stderr); #endif int t = 1; /*is Single Test case?*/ cin >> t; while (t--) { solve(); } cerr << "Total Time Taken : " << (float)clock() / CLOCKS_PER_SEC << " Seconds!" << endl; return 0; }
12.754386
93
0.52132
[ "vector" ]
698d73a8ec31bf1ba28fd776579cd45abd87d222
9,011
cpp
C++
mplapack/reference/Rlasd3.cpp
Ndersam/mplapack
f2ef54d7ce95e4028d3f101a901c75d18d3f1327
[ "BSD-3-Clause-Open-MPI" ]
26
2019-03-20T04:06:03.000Z
2022-03-02T10:21:01.000Z
mplapack/reference/Rlasd3.cpp
Ndersam/mplapack
f2ef54d7ce95e4028d3f101a901c75d18d3f1327
[ "BSD-3-Clause-Open-MPI" ]
5
2019-03-04T03:32:41.000Z
2021-12-01T07:47:25.000Z
mplapack/reference/Rlasd3.cpp
Ndersam/mplapack
f2ef54d7ce95e4028d3f101a901c75d18d3f1327
[ "BSD-3-Clause-Open-MPI" ]
5
2019-03-09T17:50:26.000Z
2022-03-10T19:46:20.000Z
/* * Copyright (c) 2008-2021 * Nakata, Maho * 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 AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include <mpblas.h> #include <mplapack.h> inline REAL Rlamc3(REAL a, REAL b) { REAL c = a + b; return c; } void Rlasd3(INTEGER const nl, INTEGER const nr, INTEGER const sqre, INTEGER const k, REAL *d, REAL *q, INTEGER const ldq, REAL *dsigma, REAL *u, INTEGER const ldu, REAL *u2, INTEGER const ldu2, REAL *vt, INTEGER const ldvt, REAL *vt2, INTEGER const ldvt2, INTEGER *idxc, INTEGER *ctot, REAL *z, INTEGER &info) { INTEGER n = 0; INTEGER m = 0; INTEGER nlp1 = 0; INTEGER nlp2 = 0; const REAL zero = 0.0; INTEGER i = 0; REAL rho = 0.0; const REAL one = 1.0; INTEGER j = 0; const REAL negone = -1.0; REAL temp = 0.0; INTEGER jc = 0; INTEGER ktemp = 0; INTEGER ctemp = 0; INTEGER nrp1 = 0; // // Test the input parameters. // info = 0; // if (nl < 1) { info = -1; } else if (nr < 1) { info = -2; } else if ((sqre != 1) && (sqre != 0)) { info = -3; } // n = nl + nr + 1; m = n + sqre; nlp1 = nl + 1; nlp2 = nl + 2; // if ((k < 1) || (k > n)) { info = -4; } else if (ldq < k) { info = -7; } else if (ldu < n) { info = -10; } else if (ldu2 < n) { info = -12; } else if (ldvt < m) { info = -14; } else if (ldvt2 < m) { info = -16; } if (info != 0) { Mxerbla("Rlasd3", -info); return; } // // Quick return if possible // if (k == 1) { d[1 - 1] = abs(z[1 - 1]); Rcopy(m, &vt2[(1 - 1)], ldvt2, &vt[(1 - 1)], ldvt); if (z[1 - 1] > zero) { Rcopy(n, &u2[(1 - 1)], 1, &u[(1 - 1)], 1); } else { for (i = 1; i <= n; i = i + 1) { u[(i - 1)] = -u2[(i - 1)]; } } return; } // // Modify values DSIGMA(i) to make sure all DSIGMA(i)-DSIGMA(j) can // be computed with high relative accuracy (barring over/underflow). // This is a problem on machines without a guard digit in // add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). // The following code replaces DSIGMA(I) by 2*DSIGMA(I)-DSIGMA(I), // which on any of these machines zeros out the bottommost // bit of DSIGMA(I) if it is 1; this makes the subsequent // subtractions DSIGMA(I)-DSIGMA(J) unproblematic when cancellation // occurs. On binary machines with a guard digit (almost all // machines) it does not change DSIGMA(I) at all. On hexadecimal // and decimal machines with a guard digit, it slightly // changes the bottommost bits of DSIGMA(I). It does not account // for hexadecimal or decimal machines without guard digits // (we know of none). We use a subroutine call to compute // 2*DSIGMA(I) to prevent optimizing compilers from eliminating // this code. // for (i = 1; i <= k; i = i + 1) { dsigma[i - 1] = Rlamc3(dsigma[i - 1], dsigma[i - 1]) - dsigma[i - 1]; } // // Keep a copy of Z. // Rcopy(k, z, 1, q, 1); // // Normalize Z. // rho = Rnrm2(k, z, 1); Rlascl("G", 0, 0, rho, one, k, 1, z, k, info); rho = rho * rho; // // Find the new singular values. // for (j = 1; j <= k; j = j + 1) { Rlasd4(k, j, dsigma, z, &u[(j - 1) * ldu], rho, d[j - 1], &vt[(j - 1) * ldvt], info); // // If the zero finder fails, report the convergence failure. // if (info != 0) { return; } } // // Compute updated Z. // for (i = 1; i <= k; i = i + 1) { z[i - 1] = u[(i - 1) + (k - 1) * ldu] * vt[(i - 1) + (k - 1) * ldvt]; for (j = 1; j <= i - 1; j = j + 1) { z[i - 1] = z[i - 1] * (u[(i - 1) + (j - 1) * ldu] * vt[(i - 1) + (j - 1) * ldvt] / (dsigma[i - 1] - dsigma[j - 1]) / (dsigma[i - 1] + dsigma[j - 1])); } for (j = i; j <= k - 1; j = j + 1) { z[i - 1] = z[i - 1] * (u[(i - 1) + (j - 1) * ldu] * vt[(i - 1) + (j - 1) * ldvt] / (dsigma[i - 1] - dsigma[(j + 1) - 1]) / (dsigma[i - 1] + dsigma[(j + 1) - 1])); } z[i - 1] = sign(sqrt(abs(z[i - 1])), q[(i - 1)]); } // // Compute left singular vectors of the modified diagonal matrix, // and store related information for the right singular vectors. // for (i = 1; i <= k; i = i + 1) { vt[(i - 1) * ldvt] = z[1 - 1] / u[(i - 1) * ldu] / vt[(i - 1) * ldvt]; u[(i - 1) * ldu] = negone; for (j = 2; j <= k; j = j + 1) { vt[(j - 1) + (i - 1) * ldvt] = z[j - 1] / u[(j - 1) + (i - 1) * ldu] / vt[(j - 1) + (i - 1) * ldvt]; u[(j - 1) + (i - 1) * ldu] = dsigma[j - 1] * vt[(j - 1) + (i - 1) * ldvt]; } temp = Rnrm2(k, &u[(i - 1) * ldu], (INTEGER)1); q[(i - 1) * ldq] = u[(i - 1) * ldu] / temp; for (j = 2; j <= k; j = j + 1) { jc = idxc[j - 1]; q[(j - 1) + (i - 1) * ldq] = u[(jc - 1) + (i - 1) * ldu] / temp; } } // // Update the left singular vector matrix. // if (k == 2) { Rgemm("N", "N", n, k, k, one, u2, ldu2, q, ldq, zero, u, ldu); goto statement_100; } if (ctot[1 - 1] > 0) { Rgemm("N", "N", nl, k, ctot[1 - 1], one, &u2[(2 - 1) * ldu2], ldu2, &q[(2 - 1)], ldq, zero, &u[(1 - 1)], ldu); if (ctot[3 - 1] > 0) { ktemp = 2 + ctot[1 - 1] + ctot[2 - 1]; Rgemm("N", "N", nl, k, ctot[3 - 1], one, &u2[(ktemp - 1) * ldu2], ldu2, &q[(ktemp - 1)], ldq, one, &u[(1 - 1)], ldu); } } else if (ctot[3 - 1] > 0) { ktemp = 2 + ctot[1 - 1] + ctot[2 - 1]; Rgemm("N", "N", nl, k, ctot[3 - 1], one, &u2[(ktemp - 1) * ldu2], ldu2, &q[(ktemp - 1)], ldq, zero, &u[(1 - 1)], ldu); } else { Rlacpy("F", nl, k, u2, ldu2, u, ldu); } Rcopy(k, &q[(1 - 1)], ldq, &u[(nlp1 - 1)], ldu); ktemp = 2 + ctot[1 - 1]; ctemp = ctot[2 - 1] + ctot[3 - 1]; Rgemm("N", "N", nr, k, ctemp, one, &u2[(nlp2 - 1) + (ktemp - 1) * ldu2], ldu2, &q[(ktemp - 1)], ldq, zero, &u[(nlp2 - 1)], ldu); // // Generate the right singular vectors. // statement_100: for (i = 1; i <= k; i = i + 1) { temp = Rnrm2(k, &vt[(i - 1) * ldvt], 1); q[(i - 1)] = vt[(i - 1) * ldvt] / temp; for (j = 2; j <= k; j = j + 1) { jc = idxc[j - 1]; q[(i - 1) + (j - 1) * ldq] = vt[(jc - 1) + (i - 1) * ldvt] / temp; } } // // Update the right singular vector matrix. // if (k == 2) { Rgemm("N", "N", k, m, k, one, q, ldq, vt2, ldvt2, zero, vt, ldvt); return; } ktemp = 1 + ctot[1 - 1]; Rgemm("N", "N", k, nlp1, ktemp, one, &q[(1 - 1)], ldq, &vt2[(1 - 1)], ldvt2, zero, &vt[(1 - 1)], ldvt); ktemp = 2 + ctot[1 - 1] + ctot[2 - 1]; if (ktemp <= ldvt2) { Rgemm("N", "N", k, nlp1, ctot[3 - 1], one, &q[(ktemp - 1) * ldq], ldq, &vt2[(ktemp - 1)], ldvt2, one, &vt[(1 - 1)], ldvt); } // ktemp = ctot[1 - 1] + 1; nrp1 = nr + sqre; if (ktemp > 1) { for (i = 1; i <= k; i = i + 1) { q[(i - 1) + (ktemp - 1) * ldq] = q[(i - 1)]; } for (i = nlp2; i <= m; i = i + 1) { vt2[(ktemp - 1) + (i - 1) * ldvt2] = vt2[(i - 1) * ldvt2]; } } ctemp = 1 + ctot[2 - 1] + ctot[3 - 1]; Rgemm("N", "N", k, nrp1, ctemp, one, &q[(ktemp - 1) * ldq], ldq, &vt2[(ktemp - 1) + (nlp2 - 1) * ldvt2], ldvt2, zero, &vt[(nlp2 - 1) * ldvt], ldvt); // // End of Rlasd3 // }
37.235537
311
0.478082
[ "vector" ]
7e38aab80826c8d3add57042996037c890e928e8
12,305
cpp
C++
sgviewer/sgviewerDoc.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
3
2019-04-20T10:16:36.000Z
2021-03-21T19:51:38.000Z
sgviewer/sgviewerDoc.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
null
null
null
sgviewer/sgviewerDoc.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
2
2020-04-18T20:04:24.000Z
2021-09-19T05:07:41.000Z
#include "stdafx.h" #include "sgviewer.h" #include "sgviewerDoc.h" #include "createCube.h" #include <io/File.h> #include <io/DirectoryInputStreamArchive.h> #include <sg/Mesh.h> #include <sg/Texture.h> #include <sg/LineList.h> #include <sg/Scene.h> #include <sg/Model.h> #include <sg/TriangleList.h> #include <sg/VertexFormat.h> #include <sg/VertexLock.h> #include <sg/Material.h> #include <sg/DirectLight.h> #include <sg/PointLight.h> #include <sg/ShadowVolume.h> #include <sg/ShadowShader.h> #include <sgu/MeshUtil.h> #include <sgu/ShadowUtil.h> #include <sgu/SceneFile.h> #include <sgu/CameraUtil.h> #include <sgu/ModelFileCache.h> #include <pix/Color.h> #include <lang/Math.h> #include <lang/Debug.h> #include <lang/Throwable.h> #include <direct.h> #include "config.h" //----------------------------------------------------------------------------- // Light name used to detect shadow volume scenes static const String SHADOW_KEYLIGHT_NAME = "Light1"; //----------------------------------------------------------------------------- using namespace io; using namespace sg; using namespace sgu; using namespace pix; using namespace lang; using namespace util; using namespace math; //----------------------------------------------------------------------------- IMPLEMENT_DYNCREATE(CSgviewerDoc, CDocument) BEGIN_MESSAGE_MAP(CSgviewerDoc, CDocument) //{{AFX_MSG_MAP(CSgviewerDoc) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() //----------------------------------------------------------------------------- CSgviewerDoc::CSgviewerDoc() : cameras( Allocator<P(Camera)>(__FILE__,__LINE__) ) { scene = 0; camera = 0; } CSgviewerDoc::~CSgviewerDoc() { } BOOL CSgviewerDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // clear old scene = 0; camera = 0; // creat new scene P(Scene) root = new Scene; scene = root.ptr(); root->setName( "scene" ); root->setAmbientColor( Color(40,40,40) ); // create scene objects P(DirectLight) lt = new DirectLight; lt->setName( SHADOW_KEYLIGHT_NAME ); lt->linkTo( scene ); lt->setPosition( Vector3(2,2,-1) ); lt->lookAt( scene ); P(LineList) axisp = new LineList( 3, LineList::LINES_3D ); {VertexLock<LineList> lineLock( axisp, LineList::LOCK_WRITE ); axisp->addLine( Vector3(0,0,0), Vector3(1,0,0), Color(255,255,0) ); axisp->addLine( Vector3(0,0,0), Vector3(0,1,0), Color(0,255,0) ); axisp->addLine( Vector3(0,0,0), Vector3(0,0,1), Color(0,0,255) );} P(Mesh) axis = new Mesh; axis->addPrimitive( axisp ); axis->setName( "axis" ); axis->linkTo( scene ); const float shadowLength = 50.f; P(Material) cubemat = new Material; cubemat->setDiffuseColor( Colorf(0,1,0) ); cube1dim = Vector3( 1,1,1 ) * .5f; P(Model) cubep = createCube( cube1dim*2.f ); cubemat->setVertexFormat( cubep->vertexFormat() ); cubep->setShader( cubemat ); P(Mesh) mesh = new Mesh; cube1 = mesh; mesh->setName( "cube1" ); mesh->linkTo( scene ); mesh->setPosition( Vector3(0,5,0) ); mesh->setRotation( mesh->transform().rotation() * 1.24f ); mesh->addPrimitive( cubep ); mesh->addPrimitive( new ShadowVolume( cubep, mesh->worldTransform().inverse().rotation() * lt->worldDirection(), shadowLength ) ); cubemat = new Material; cubemat->setDiffuseColor( Colorf(0,0,1) ); cube2dim = Vector3( 2, 2.5f, 3.f ) * .5f; cubep = createCube( cube2dim*2.f ); cubemat->setVertexFormat( cubep->vertexFormat() ); cubep->setShader( cubemat ); mesh = new Mesh; cube2 = mesh; mesh->setName( "cube2" ); mesh->linkTo( scene ); mesh->setPosition( Vector3(0,2,0) ); mesh->addPrimitive( cubep ); mesh->addPrimitive( new ShadowVolume( cubep, mesh->worldTransform().inverse().rotation() * lt->worldDirection(), shadowLength ) ); P(Mesh) floor = new Mesh; floor->setName( "floor" ); floor->linkTo( scene ); P(Model) floorp = createCube( Vector3(1000.f, 0.1f, 1000.f) ); floor->addPrimitive( floorp ); floor->setPosition( Vector3(0,-1.1f,0) ); P(Material) floormat = new Material; floormat->setDiffuseColor( Colorf(1,0,0) ); floormat->setVertexFormat( floorp->vertexFormat() ); floorp->setShader( floormat ); P(Camera) cam = new Camera; cam->setHorizontalFov( Math::toRadians(90.f) ); cam->setName( "cam" ); cam->setPosition( Vector3(1,6,-5) ); cam->linkTo( scene ); cam->lookAt( mesh ); prepareDoc(); //CSgviewerApp::getApp().setPropPathToCwd(); return TRUE; } void CSgviewerDoc::Serialize(CArchive& ar) { CSgviewerApp::getApp().setPause( true ); if (ar.IsStoring()) { // TODO: add storing code here } else { try { CFile* file = ar.GetFile(); if ( file ) { Texture::flushTextures(); CString pathstr = file->GetFilePath(); String path = (const char*)pathstr; String dir = File(path).getParent(); P(DirectoryInputStreamArchive) arch = new DirectoryInputStreamArchive; arch->addPath( dir ); P(ModelFileCache) modelcache = new ModelFileCache( arch ); P(SceneFile) sf = new SceneFile( path, modelcache, arch ); modelcache->clear(); scene = sf->scene(); name = path; cube1 = cube2 = 0; prepareDoc(); } } catch ( Throwable& e ) { char buf[1000]; e.getMessage().format().getBytes( buf, sizeof(buf), "ASCII-7" ); if ( CSgviewerApp::getApp().m_pMainWnd ) CSgviewerApp::getApp().m_pMainWnd->MessageBox( buf, "Error - sgviewer", MB_OK|MB_ICONERROR|MB_SYSTEMMODAL ); else MessageBox( 0, buf, "Error - sgviewer", MB_OK|MB_ICONERROR|MB_SYSTEMMODAL ); } } CSgviewerApp::getApp().setPause( false ); } void CSgviewerDoc::prepareDoc() { CSgviewerApp& app = CSgviewerApp::getApp(); // split large meshes /*for ( Node* node = scene ; node ; node = node->nextInHierarchy() ) { Mesh* mesh = dynamic_cast<Mesh*>( node ); if ( mesh ) MeshUtil::splitModels( mesh, app.splitPrimitivePolygons(), app.splitPrimitiveSize() ); }*/ // collect cameras camera = 0; cameras.clear(); P(Camera) flyCam = new Camera; flyCam->setName( "fly" ); flyCam->linkTo( scene ); cameras.add( flyCam ); for ( Node* node = scene ; node ; node = node->nextInHierarchy() ) { Camera* cam = dynamic_cast<Camera*>( node ); if ( cam ) cameras.add( cam ); } camera = cameras.size()-1; // set fly camera parameters Camera* curCam = cameras[camera]; curCam->setState( 0 ); flyCam->setHorizontalFov( curCam->horizontalFov() ); // find 'keylight' to be used as key light bool hasLight = false; Light* keylt = 0; for ( Node* node = scene ; node ; node = node->nextInHierarchy() ) { Light* lt0 = dynamic_cast<Light*>( node ); if ( lt0 ) { hasLight = true; if ( lt0 && lt0->name() == SHADOW_KEYLIGHT_NAME ) { keylt = lt0; break; } } } // is there a keylight in the scene? if ( keylt ) { P(Shader) shadowShader = new ShadowShader; // set shadow volume shaders ShadowUtil::setShadowVolumeShaders( scene, shadowShader ); // create shadow filler P(Primitive) fillgeom = ShadowUtil::createShadowFiller( Color(0,0,0,80), 4000, 4000 ); P(Mesh) fillmesh = new Mesh; fillmesh->addPrimitive( fillgeom ); fillmesh->setName( "ShadowFiller" ); fillmesh->linkTo( scene ); } // add default light if none defaultLight = 0; if ( !hasLight ) { defaultLight = new PointLight; defaultLight->setName( SHADOW_KEYLIGHT_NAME ); defaultLight->linkTo( scene ); } // replace lightmap materials with lightmap shader /*for ( Node* node = scene ; node ; node = node->nextInHierarchy() ) { Mesh* mesh = dynamic_cast<Mesh*>( node ); if ( mesh ) { for ( int i = 0 ; i < mesh->primitives() ; ++i ) { P(Primitive) prim = mesh->getPrimitive(i); P(Material) mat = dynamic_cast<Material*>( prim->shader() ); if ( mat && !mat->lighting() && mat->isTextureLayerEnabled(0) && mat->isTextureLayerEnabled(1) && !mat->isTextureLayerEnabled(2) && mat->sourceBlend() == Material::BLEND_ONE && mat->destinationBlend() == Material::BLEND_ZERO ) { Material::TextureArgument arg1, arg2; Material::TextureOperation op; mat->getTextureColorCombine( 0, &arg1, &op, &arg2 ); if ( arg1 == Material::TA_TEXTURE && arg2 == Material::TA_DIFFUSE && op == Material::TOP_MODULATE ) { mat->getTextureColorCombine( 1, &arg1, &op, &arg2 ); if ( arg1 == Material::TA_TEXTURE && arg2 == Material::TA_CURRENT && op == Material::TOP_MODULATE ) { Debug::println( "Replacing lightmap material {0} with shader", mat->name() ); P(BaseTexture) dif = mat->getTexture(0); P(BaseTexture) lmap = mat->getTexture(1); P(Shader) fx = app.lightmapShader->clone(); fx->setVertexFormat( prim->vertexFormat() ); fx->setTexture( "tDiffuse", dif ); fx->setTexture( "tLightMap", lmap ); prim->setShader( fx ); } } } } } }*/ // load objects to rendering device /*for ( Node* node = scene ; node ; node = node->nextInHierarchy() ) { Mesh* mesh = dynamic_cast<Mesh*>( node ); if ( mesh ) { for ( int i = 0 ; i < mesh->primitives() ; ++i ) { Primitive* prim = mesh->getPrimitive(i); prim->load(); } } }*/ } #ifdef _DEBUG void CSgviewerDoc::AssertValid() const { CDocument::AssertValid(); } void CSgviewerDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG Camera* CSgviewerDoc::activeCamera() const { if ( camera >= 0 && camera < cameras.size() ) return cameras[camera]; else return 0; } void CSgviewerDoc::selectNextCamera() { if ( camera >= 0 && camera < cameras.size() ) camera = (camera+1) % cameras.size(); } void CSgviewerDoc::selectFlyCamera() { camera = 0; } sg::Camera* CSgviewerDoc::flyCamera() const { if ( camera >= 0 && camera < cameras.size() ) return cameras.firstElement(); else return 0; } sg::Node* CSgviewerDoc::pickNode( float x, float y, float* distance ) { if ( scene ) { Camera* cam = cameras[camera]; float dx = ( Math::tan( cam->horizontalFov() / 2.f ) * cam->front() * x ); float dy = ( Math::tan( cam->verticalFov() / 2.f ) * cam->front() * y ); Vector3 wtarget = ( cam->worldTransform().translation() + cam->worldTransform().rotation().getColumn(0) * dx + cam->worldTransform().rotation().getColumn(1) * dy + cam->worldTransform().rotation().getColumn(2) * cam->front() ); Vector3 wpos = cam->worldTransform().translation(); Vector3 wdir = (wtarget - wpos).normalize(); Node* node = CameraUtil::pick( scene, wpos, wdir, distance ); if ( node ) { OutputDebugString( "Picked " ); char str[256]; node->name().getBytes( str, sizeof(str), "ASCII-7" ); OutputDebugString( str ); OutputDebugString( "\n" ); } return node; } return 0; } void CSgviewerDoc::dragNode( float dx, float dy, float dz, sg::Node* node, float dist ) { if ( scene ) { Camera* cam = cameras[camera]; float s = dist / cam->front(); float w = 2.f * Math::tan( cam->horizontalFov() / 2.f ) * cam->front(); float h = 2.f * Math::tan( cam->verticalFov() / 2.f ) * cam->front(); float dvx = w * dx * s; float dvy = h * dy * s; float dvz = Math::sqrt(w*w+h*h) * dz * s; Vector3 wdelta = cam->worldTransform().rotation().getColumn(0) * dvx + cam->worldTransform().rotation().getColumn(1) * dvy + cam->worldTransform().rotation().getColumn(2) * dvz; Vector3 nodeDelta = node->parent()->worldTransform().inverse().rotate( wdelta ); node->setPosition( node->transform().translation() + nodeDelta ); } } void CSgviewerDoc::dragNodeRotate( float dx, float dy, sg::Node* node ) { if ( scene ) { Camera* cam = cameras[camera]; float xang = dy*3.14f; float yang = -dx*3.14f; Matrix3x3 xrot( Vector3(1,0,0), xang ); Matrix3x3 yrot( Vector3(0,1,0), yang ); Matrix3x3 rot = yrot * xrot; node->setRotation( node->transform().rotation() * rot ); } }
27.839367
136
0.613328
[ "mesh", "model", "transform" ]
7e3cee1782bc5705df5ef2780549cf7189a2f43a
4,919
cpp
C++
application/dialogs/LoginDialog.cpp
StephenGss/Polycraft-Launcher
d70f6729dba876e0252b075dcfd4c9caa45113b2
[ "Apache-2.0" ]
3
2020-10-08T19:55:33.000Z
2021-11-28T04:02:39.000Z
application/dialogs/LoginDialog.cpp
StephenGss/Polycraft-Launcher
d70f6729dba876e0252b075dcfd4c9caa45113b2
[ "Apache-2.0" ]
null
null
null
application/dialogs/LoginDialog.cpp
StephenGss/Polycraft-Launcher
d70f6729dba876e0252b075dcfd4c9caa45113b2
[ "Apache-2.0" ]
null
null
null
/* Copyright 2013-2018 PolycraftLauncher Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "LoginDialog.h" #include "ui_LoginDialog.h" #include "minecraft/auth/YggdrasilTask.h" #include <QtWidgets/QPushButton> LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent), ui(new Ui::LoginDialog) { ui->setupUi(this); ui->progressBar->setVisible(false); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); } LoginDialog::~LoginDialog() { delete ui; } // Stage 1.1: User interaction + test for Polycraft account void LoginDialog::accept() { setUserInputsEnabled(false); ui->progressBar->setVisible(true); // check for special Polycraft logins manager = new QNetworkAccessManager(this); QUrl url(BuildConfig.PCW_VERSION_URL + "/portal/exp_account/"); //QUrl url("http://10.163.43.159:8000/portal/exp_account/"); QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); QUrlQuery params; params.addQueryItem("token", "DpBmRTBBp7P4X0Pn6qmM6NEhkbweM3R3O1k5N2mJAHCMrgwVjKqw5NRjgmTHOeqM"); params.addQueryItem("polycraft_user_name", ui->userTextBox->text()); params.addQueryItem("polycraft_pass", ui->passTextBox->text()); // etc QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(checkForPolycraftAccount(QNetworkReply *))); manager->post(request, params.query().toUtf8()); } // Stage 1.2: Minecraft account auth void LoginDialog::accept2() { // Setup the login task and start it m_account = MojangAccount::createFromUsername(ui->userTextBox->text()); m_loginTask = m_account->login(nullptr, ui->passTextBox->text()); connect(m_loginTask.get(), &Task::failed, this, &LoginDialog::onTaskFailed); connect(m_loginTask.get(), &Task::succeeded, this, &LoginDialog::onTaskSucceeded); connect(m_loginTask.get(), &Task::status, this, &LoginDialog::onTaskStatus); connect(m_loginTask.get(), &Task::progress, this, &LoginDialog::onTaskProgress); m_loginTask->start(); } void LoginDialog::checkForPolycraftAccount(QNetworkReply *reply){ if(reply->error() == QNetworkReply::NoError){ QString strReply = (QString)reply->readAll(); //parse json qDebug() << "Response:" << strReply; QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8()); QJsonObject jsonObj = jsonResponse.object(); //qDebug() << "email:" << jsonObj["email"].toString(); //qDebug() << "minecraft_pass:" << jsonObj["minecraft_pass"].toString(); ui->userTextBox->setText(jsonObj["email"].toString()); ui->passTextBox->setText(jsonObj["minecraft_pass"].toString()); } accept2(); } void LoginDialog::setUserInputsEnabled(bool enable) { ui->userTextBox->setEnabled(enable); ui->passTextBox->setEnabled(enable); ui->buttonBox->setEnabled(enable); } // Enable the OK button only when both textboxes contain something. void LoginDialog::on_userTextBox_textEdited(const QString &newText) { ui->buttonBox->button(QDialogButtonBox::Ok) ->setEnabled(!newText.isEmpty() && !ui->passTextBox->text().isEmpty()); } void LoginDialog::on_passTextBox_textEdited(const QString &newText) { ui->buttonBox->button(QDialogButtonBox::Ok) ->setEnabled(!newText.isEmpty() && !ui->userTextBox->text().isEmpty()); } void LoginDialog::onTaskFailed(const QString &reason) { // Set message ui->label->setText("<span style='color:red'>" + reason + "</span>"); // Re-enable user-interaction setUserInputsEnabled(true); ui->progressBar->setVisible(false); } void LoginDialog::onTaskSucceeded() { QDialog::accept(); } void LoginDialog::onTaskStatus(const QString &status) { ui->label->setText(status); } void LoginDialog::onTaskProgress(qint64 current, qint64 total) { ui->progressBar->setMaximum(total); ui->progressBar->setValue(current); } // Public interface MojangAccountPtr LoginDialog::newAccount(QWidget *parent, QString msg) { LoginDialog dlg(parent); dlg.ui->label->setText(msg); if (dlg.exec() == QDialog::Accepted) { return dlg.m_account; } return 0; }
32.361842
120
0.705021
[ "object" ]
7e403f911c7dad162a9ccd1bf56c12e5d7ac5c85
2,144
hpp
C++
src/utils.hpp
berkonat/AtomNeighbors
1ce0785c327c8c96309af6715e4804f589941262
[ "MIT" ]
null
null
null
src/utils.hpp
berkonat/AtomNeighbors
1ce0785c327c8c96309af6715e4804f589941262
[ "MIT" ]
null
null
null
src/utils.hpp
berkonat/AtomNeighbors
1ce0785c327c8c96309af6715e4804f589941262
[ "MIT" ]
null
null
null
#include <vector> #include <string> std::vector<double> read_radius(std::string fname); std::vector<double> read_xyz(std::string fname, std::vector<double>* box_lengths); template<typename T> std::vector<T> vecslice(std::vector<T> const &A, int start, int step); template<typename T> std::vector<T> vecslice(std::vector<T> const &A, int start, int step, int stride); template<typename T1, typename T2> std::vector<T1> gemv(std::vector<T1> const &A, std::vector<T2> const &x); template<typename T1, typename T2> std::vector<T1> gemv(std::vector<T1> const &A, std::vector<T2> const &B, int ncolA, int* axis = NULL); template<typename T> double norm(std::vector<T> const &u); template<typename T> std::vector<double> norm(std::vector<T> const &A, int ncolA, int* axis = NULL); template<typename T1, typename T2> std::vector<T1> vsub(std::vector<T1> const &u, T2 const &v); template<typename T1, typename T2> std::vector<T1> vsub(std::vector<T1> const &u, std::vector<T2> const &v); template<typename T1, typename T2> std::vector<T1> vsub(std::vector<T1> const &A, std::vector<T2> const &v, int ncolA); template<typename T1, typename T2> std::vector<T1> vadd(std::vector<T1> const &u, T2 const &v); template<typename T1, typename T2> std::vector<T1> vadd(std::vector<T1> const &u, std::vector<T2> const &v); template<typename T1, typename T2> std::vector<T1> vadd(std::vector<T1> const &A, std::vector<T2> const &v, int ncolA); template<typename T1, typename T2> std::vector<T1> vmul(std::vector<T1> const &u, std::vector<T2> const &v); template<typename T1, typename T2> std::vector<T1> vmul(std::vector<T1> const &A, std::vector<T2> const &v, int ncolA); template<typename T1, typename T2> std::vector<T1> vmul(std::vector<T1> const &u, T2 const &v); template<typename T1, typename T2> std::vector<T1> vdiv(std::vector<T1> const &u, std::vector<T2> const &v); template<typename T1, typename T2> std::vector<T1> vdiv(std::vector<T1> const &u, T2 const v); template<typename T1, typename T2> std::vector<T1> vdiv(std::vector<T1> const &A, std::vector<T2> const &v, int ncolA);
33.5
84
0.688899
[ "vector" ]
7e48d9a1deba060c47e4d999509fcc5f75d891f1
34,609
cpp
C++
OVP/D3D9Client/D3D9Effect.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
null
null
null
OVP/D3D9Client/D3D9Effect.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
null
null
null
OVP/D3D9Client/D3D9Effect.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
null
null
null
// =========================================================================================== // D3D9Effect.cpp // Part of the ORBITER VISUALISATION PROJECT (OVP) // Dual licensed under GPL v3 and LGPL v3 // Copyright (C) 2011 - 2016 Jarmo Nikkanen // =========================================================================================== #include "D3D9Effect.h" #include "Log.h" #include "Scene.h" #include "D3D9Surface.h" #include "D3D9Config.h" #include "Mesh.h" #include "VectorHelpers.h" D3D9Client * D3D9Effect::gc = 0; ID3DXEffect * D3D9Effect::FX = 0; LPDIRECT3DVERTEXBUFFER9 D3D9Effect::VB = 0; D3DXVECTOR4 D3D9Effect::atm_color; // Earth glow color D3D9MatExt D3D9Effect::mfdmat; D3D9MatExt D3D9Effect::defmat; D3D9MatExt D3D9Effect::night_mat; D3D9MatExt D3D9Effect::emissive_mat; // Some general rendering techniques D3DXHANDLE D3D9Effect::ePanelTech = 0; // Used to draw a new style 2D panel D3DXHANDLE D3D9Effect::ePanelTechB = 0; // Used to draw a new style 2D panel D3DXHANDLE D3D9Effect::eVesselTech = 0; // Vessel exterior, surface bases. D3DXHANDLE D3D9Effect::eBBTech = 0; // Bounding Box Tech D3DXHANDLE D3D9Effect::eTBBTech = 0; D3DXHANDLE D3D9Effect::eBSTech = 0; // Bounding Sphere Tech D3DXHANDLE D3D9Effect::eSimple = 0; D3DXHANDLE D3D9Effect::eBaseShadowTech = 0; // Used to draw transparent surface without texture D3DXHANDLE D3D9Effect::eBeaconArrayTech = 0; D3DXHANDLE D3D9Effect::eExhaust = 0; // Render engine exhaust texture D3DXHANDLE D3D9Effect::eSpotTech = 0; // Vessel beacons D3DXHANDLE D3D9Effect::eBaseTile = 0; D3DXHANDLE D3D9Effect::eRingTech = 0; // Planet rings technique D3DXHANDLE D3D9Effect::eRingTech2 = 0; // Planet rings technique D3DXHANDLE D3D9Effect::eShadowTech = 0; // Vessel ground shadows D3DXHANDLE D3D9Effect::eArrowTech = 0; // (Grapple point) arrows D3DXHANDLE D3D9Effect::eAxisTech = 0; D3DXHANDLE D3D9Effect::eSimpMesh = 0; D3DXHANDLE D3D9Effect::eGeometry = 0; // Planet Rendering techniques D3DXHANDLE D3D9Effect::ePlanetTile = 0; D3DXHANDLE D3D9Effect::eCloudTech = 0; D3DXHANDLE D3D9Effect::eCloudShadow = 0; D3DXHANDLE D3D9Effect::eSkyDomeTech = 0; D3DXHANDLE D3D9Effect::eHazeTech = 0; // Particle effect texhniques D3DXHANDLE D3D9Effect::eDiffuseTech = 0; D3DXHANDLE D3D9Effect::eEmissiveTech = 0; D3DXHANDLE D3D9Effect::eVP = 0; // Combined View & Projection Matrix D3DXHANDLE D3D9Effect::eW = 0; // World matrix D3DXHANDLE D3D9Effect::eLVP = 0; // Light view projection D3DXHANDLE D3D9Effect::eGT = 0; // Mesh group transformation matrix D3DXHANDLE D3D9Effect::eMat = 0; // Material D3DXHANDLE D3D9Effect::eWater = 0; // Water D3DXHANDLE D3D9Effect::eMtrl = 0; D3DXHANDLE D3D9Effect::eTune = 0; D3DXHANDLE D3D9Effect::eSun = 0; D3DXHANDLE D3D9Effect::eNight = 0; D3DXHANDLE D3D9Effect::eLights = 0; // Additional light sources D3DXHANDLE D3D9Effect::eTex0 = 0; // Primary texture D3DXHANDLE D3D9Effect::eTex1 = 0; // Secondary texture D3DXHANDLE D3D9Effect::eTex3 = 0; // Tertiary texture D3DXHANDLE D3D9Effect::eSpecMap = 0; D3DXHANDLE D3D9Effect::eEmisMap = 0; D3DXHANDLE D3D9Effect::eEnvMapA = 0; D3DXHANDLE D3D9Effect::eEnvMapB = 0; D3DXHANDLE D3D9Effect::eReflMap = 0; D3DXHANDLE D3D9Effect::eRghnMap = 0; D3DXHANDLE D3D9Effect::eMetlMap = 0; D3DXHANDLE D3D9Effect::eHeatMap = 0; D3DXHANDLE D3D9Effect::eShadowMap = 0; D3DXHANDLE D3D9Effect::eTranslMap = 0; D3DXHANDLE D3D9Effect::eTransmMap = 0; D3DXHANDLE D3D9Effect::eIrradMap = 0; D3DXHANDLE D3D9Effect::eSpecularMode = 0; D3DXHANDLE D3D9Effect::eHazeMode = 0; D3DXHANDLE D3D9Effect::eColor = 0; // Auxiliary color input D3DXHANDLE D3D9Effect::eFogColor = 0; // Fog color input D3DXHANDLE D3D9Effect::eTexOff = 0; // Surface tile texture offsets D3DXHANDLE D3D9Effect::eTime = 0; // FLOAT Simulation elapsed time D3DXHANDLE D3D9Effect::eMix = 0; // FLOAT Auxiliary factor/multiplier D3DXHANDLE D3D9Effect::eFogDensity = 0; // D3DXHANDLE D3D9Effect::ePointScale = 0; D3DXHANDLE D3D9Effect::eSHD = 0; D3DXHANDLE D3D9Effect::eAtmColor = 0; D3DXHANDLE D3D9Effect::eProxySize = 0; D3DXHANDLE D3D9Effect::eMtrlAlpha = 0; D3DXHANDLE D3D9Effect::eKernel = 0; // Shader Flow Controls D3DXHANDLE D3D9Effect::eFlow = 0; D3DXHANDLE D3D9Effect::eModAlpha = 0; // BOOL if true multiply material alpha with texture alpha D3DXHANDLE D3D9Effect::eFullyLit = 0; // BOOL D3DXHANDLE D3D9Effect::eTextured = 0; // BOOL D3DXHANDLE D3D9Effect::eFresnel = 0; // BOOL D3DXHANDLE D3D9Effect::eSwitch = 0; // BOOL D3DXHANDLE D3D9Effect::eRghnSw = 0; D3DXHANDLE D3D9Effect::eShadowToggle = 0; // BOOL D3DXHANDLE D3D9Effect::eEnvMapEnable = 0; // BOOL D3DXHANDLE D3D9Effect::eInSpace = 0; // BOOL D3DXHANDLE D3D9Effect::eNoColor = 0; // BOOL D3DXHANDLE D3D9Effect::eLightsEnabled = 0; // BOOL D3DXHANDLE D3D9Effect::eTuneEnabled = 0; // BOOL D3DXHANDLE D3D9Effect::eBaseBuilding = 0; // -------------------------------------------------------------- D3DXHANDLE D3D9Effect::eExposure = 0; D3DXHANDLE D3D9Effect::eCameraPos = 0; D3DXHANDLE D3D9Effect::eNorth = 0; D3DXHANDLE D3D9Effect::eEast = 0; D3DXHANDLE D3D9Effect::eDistScale = 0; D3DXHANDLE D3D9Effect::eRadius = 0; D3DXHANDLE D3D9Effect::eAttennuate = 0; D3DXHANDLE D3D9Effect::eInScatter = 0; D3DXHANDLE D3D9Effect::eInvProxySize = 0; D3DXHANDLE D3D9Effect::eGlowConst = 0; // -------------------------------------------------------------- D3DXHANDLE D3D9Effect::eGlobalAmb = 0; D3DXHANDLE D3D9Effect::eSunAppRad = 0; D3DXHANDLE D3D9Effect::eAmbient0 = 0; D3DXHANDLE D3D9Effect::eDispersion = 0; LPDIRECT3DDEVICE9 D3D9Effect::pDev = 0; static D3DMATERIAL9 _emissive_mat = { {0,0,0,1}, {0,0,0,1}, {0,0,0,1}, {1,1,1,1}, 0.0 }; static D3DMATERIAL9 _defmat = { {1,1,1,1}, {1,1,1,1}, {0,0,0,1}, {0,0,0,1},10.0f }; static D3DMATERIAL9 _mfdmat = { {1,1,1,1}, {1,1,1,1}, {0,0,0,1}, {1,1,1,1},10.0f }; static D3DMATERIAL9 _night_mat = { {1,1,1,1}, {0,0,0,1}, {0,0,0,1}, {1,1,1,1},10.0f }; static WORD billboard_idx[6] = {0,1,2, 3,2,1}; static NTVERTEX billboard_vtx[4] = { {0,-1, 1, -1,0,0, 0,0}, {0, 1, 1, -1,0,0, 0,1}, {0,-1,-1, -1,0,0, 1,0}, {0, 1,-1, -1,0,0, 1,1} }; static WORD exhaust_idx[12] = {0,1,2, 3,2,1, 4,5,6, 7,6,5}; NTVERTEX exhaust_vtx[8] = { {0,0,0, 0,0,0, 0.24f,0}, {0,0,0, 0,0,0, 0.24f,1}, {0,0,0, 0,0,0, 0.01f,0}, {0,0,0, 0,0,0, 0.01f,1}, {0,0,0, 0,0,0, 0.50390625f, 0.00390625f}, {0,0,0, 0,0,0, 0.99609375f, 0.00390625f}, {0,0,0, 0,0,0, 0.50390625f, 0.49609375f}, {0,0,0, 0,0,0, 0.99609375f, 0.49609375f} }; // TotalWeight = 21.337518, Count = 27, x - balance = -0.145075, y - balance = -0.012734 /* static D3DXVECTOR3 shadow_kernel[27] = { { -0.2607f, -0.9643f, 0.9995f }, { -0.7879f, -0.5824f, 0.9898f }, { -0.3796f, -0.6389f, 0.8620f }, { -0.1287f, -0.6631f, 0.8219f }, { 0.4393f, -0.6945f, 0.9065f }, { -0.5448f, -0.4505f, 0.8408f }, { -0.2330f, -0.3496f, 0.6482f }, { -0.1185f, -0.2572f, 0.5322f }, { 0.4340f, -0.4138f, 0.7744f }, { 0.6976f, -0.4110f, 0.8998f }, { -0.5738f, 0.0418f, 0.7585f }, { -0.3732f, -0.1313f, 0.6290f }, { -0.1242f, 0.0847f, 0.3877f }, { 0.4157f, 0.0066f, 0.6448f }, { 0.7117f, 0.0726f, 0.8458f }, { 0.8990f, 0.0801f, 0.9500f }, { -0.8740f, 0.2448f, 0.9527f }, { -0.5545f, 0.3910f, 0.8237f }, { -0.3458f, 0.3380f, 0.6954f }, { -0.1168f, 0.2083f, 0.4887f }, { 0.2998f, 0.4449f, 0.7325f }, { 0.5572f, 0.2251f, 0.7752f }, { -0.2250f, 0.5790f, 0.7882f }, { 0.0300f, 0.5853f, 0.7656f }, { 0.3031f, 0.6734f, 0.8594f }, { 0.7652f, 0.6273f, 0.9947f }, { -0.0571f, 0.9407f, 0.9708f } }; */ static D3DXVECTOR3 shadow_kernel[27] = { { -0.0000f, 0.0000f, 1.0000f }, { 0.1915f, 0.0188f, 1.0000f }, { 0.0558f, -0.2664f, 1.0000f }, { -0.2608f, -0.2076f, 1.0000f }, { -0.0706f, 0.3784f, 1.0000f }, { 0.3207f, -0.2869f, 1.0000f }, { -0.2438f, -0.4035f, 1.0000f }, { -0.4869f, -0.1488f, 1.0000f }, { -0.3108f, 0.4468f, 1.0000f }, { 0.4330f, 0.3819f, 1.0000f }, { -0.4208f, -0.4396f, 1.0000f }, { -0.6056f, -0.2017f, 1.0000f }, { -0.0612f, 0.6638f, 1.0000f }, { 0.6489f, -0.2457f, 1.0000f }, { 0.1850f, -0.6959f, 1.0000f }, { -0.7254f, 0.1711f, 1.0000f }, { -0.3309f, 0.6950f, 1.0000f }, { 0.6890f, -0.3937f, 1.0000f }, { -0.5610f, -0.5933f, 1.0000f }, { -0.7326f, -0.4086f, 1.0000f }, { -0.2997f, 0.8068f, 1.0000f }, { 0.8774f, -0.0892f, 1.0000f }, { -0.1133f, -0.8955f, 1.0000f }, { -0.9205f, -0.0673f, 1.0000f }, { 0.4487f, 0.8292f, 1.0000f }, { 0.7320f, 0.6245f, 1.0000f }, { 0.6067f, -0.7713f, 1.0000f } }; // =========================================================================================== // D3D9Effect::D3D9Effect() : d3d9id('D3D9') { } // =========================================================================================== // D3D9Effect::~D3D9Effect() { } // =========================================================================================== // void D3D9Effect::GlobalExit() { LogAlw("====== D3D9Effect Global Exit ======="); SAFE_RELEASE(FX); SAFE_RELEASE(VB); } // =========================================================================================== // void D3D9Effect::ShutDown() { if (!FX) return; FX->SetTexture(eTex0, NULL); FX->SetTexture(eTex1, NULL); FX->SetTexture(eTex3, NULL); FX->SetTexture(eSpecMap, NULL); FX->SetTexture(eEmisMap, NULL); } // =========================================================================================== // void D3D9Effect::D3D9TechInit(D3D9Client *_gc, LPDIRECT3DDEVICE9 _pDev, const char *folder) { char name[256]; pDev = _pDev; gc = _gc; gc->OutputLoadStatus("D3D9Client.fx",1); LogAlw("Starting to initialize D3D9Client.fx a rendering technique..."); // Create the Effect from a .fx file. ID3DXBuffer* errors = 0; D3DXMACRO macro[18]; memset(&macro, 0, 16*sizeof(D3DXMACRO)); sprintf_s(name,256,"Modules/D3D9Client/D3D9Client.fx"); if (Config->ShadowMapMode == 0) Config->ShadowFilter = -1; // ------------------------------------------------------------------------------ macro[0].Name = "ANISOTROPY_MACRO"; macro[0].Definition = new char[32]; sprintf_s((char*)macro[0].Definition,32,"%d",max(2,Config->Anisotrophy)); // ------------------------------------------------------------------------------ macro[1].Name = "LMODE"; macro[1].Definition = new char[32]; sprintf_s((char*)macro[1].Definition, 32, "%d", Config->LightConfig); // ------------------------------------------------------------------------------ macro[2].Name = "MAX_LIGHTS"; macro[2].Definition = new char[32]; sprintf_s((char*)macro[2].Definition, 32, "%d", Config->MaxLights()); // ------------------------------------------------------------------------------ macro[3].Name = "SHDMAP"; macro[3].Definition = new char[32]; sprintf_s((char*)macro[3].Definition, 32, "%d", Config->ShadowFilter + 1); // ------------------------------------------------------------------------------ macro[4].Name = "KERNEL_SIZE"; macro[4].Definition = new char[32]; if (Config->ShadowFilter >= 3) sprintf_s((char*)macro[4].Definition, 32, "%d", 35); else sprintf_s((char*)macro[4].Definition, 32, "%d", 27); // ------------------------------------------------------------------------------ macro[5].Name = "KERNEL_WEIGHT"; macro[5].Definition = new char[32]; if (Config->ShadowFilter >= 3) sprintf_s((char*)macro[5].Definition, 32, "%f", 0.0285f); else sprintf_s((char*)macro[5].Definition, 32, "%f", 1.0f / 27.0f); // 0.04634f); // ------------------------------------------------------------------------------ int m = 6; if (Config->EnableGlass) macro[m++].Name = "_GLASS"; if (Config->EnableMeshDbg) macro[m++].Name = "_DEBUG"; if (Config->EnvMapMode) macro[m++].Name = "_ENVMAP"; if (Config->PostProcess == PP_DEFAULT) macro[m++].Name = "_LIGHTGLOW"; HR(D3DXCreateEffectFromFileA(pDev, name, macro, 0, D3DXSHADER_NO_PRESHADER|D3DXSHADER_PREFER_FLOW_CONTROL, 0, &FX, &errors)); delete []macro[0].Definition; delete []macro[1].Definition; delete []macro[2].Definition; delete []macro[3].Definition; delete []macro[4].Definition; delete []macro[5].Definition; macro[0].Definition = NULL; macro[1].Definition = NULL; macro[2].Definition = NULL; macro[3].Definition = NULL; macro[4].Definition = NULL; macro[5].Definition = NULL; if (errors) { LogErr("Effect Error: %s",(char*)errors->GetBufferPointer()); MessageBoxA(0, (char*)errors->GetBufferPointer(), "D3D9Client.fx Error", 0); FatalAppExitA(0,"Critical error has occured. See Orbiter.log for details"); } if (FX==0) { LogErr("Failed to create an Effect (%s)",name); return; } if (Config->ShaderDebug) { LPD3DXBUFFER pBuffer = NULL; if (D3DXDisassembleEffect(FX, true, &pBuffer) == S_OK) { FILE *fp = NULL; if (!fopen_s(&fp, "D9D9Effect_asm.html", "w")) { fwrite(pBuffer->GetBufferPointer(), 1, pBuffer->GetBufferSize(), fp); fclose(fp); } pBuffer->Release(); } } // Techniques -------------------------------------------------------------- eHazeTech = FX->GetTechniqueByName("HazeTech"); ePlanetTile = FX->GetTechniqueByName("PlanetTech"); eBaseTile = FX->GetTechniqueByName("BaseTileTech"); eSimple = FX->GetTechniqueByName("SimpleTech"); eBBTech = FX->GetTechniqueByName("BoundingBoxTech"); eTBBTech = FX->GetTechniqueByName("TileBoxTech"); eBSTech = FX->GetTechniqueByName("BoundingSphereTech"); eRingTech = FX->GetTechniqueByName("RingTech"); eRingTech2 = FX->GetTechniqueByName("RingTech2"); eExhaust = FX->GetTechniqueByName("ExhaustTech"); eSpotTech = FX->GetTechniqueByName("SpotTech"); eShadowTech = FX->GetTechniqueByName("ShadowTech"); ePanelTech = FX->GetTechniqueByName("PanelTech"); ePanelTechB = FX->GetTechniqueByName("PanelTechB"); eCloudTech = FX->GetTechniqueByName("PlanetCloudTech"); eCloudShadow = FX->GetTechniqueByName("PlanetCloudShadowTech"); eSkyDomeTech = FX->GetTechniqueByName("SkyDomeTech"); eArrowTech = FX->GetTechniqueByName("ArrowTech"); eAxisTech = FX->GetTechniqueByName("AxisTech"); eSimpMesh = FX->GetTechniqueByName("SimplifiedTech"); eGeometry = FX->GetTechniqueByName("GeometryTech"); eVesselTech = FX->GetTechniqueByName("VesselTech"); eBaseShadowTech = FX->GetTechniqueByName("BaseShadowTech"); eBeaconArrayTech = FX->GetTechniqueByName("BeaconArrayTech"); eDiffuseTech = FX->GetTechniqueByName("ParticleDiffuseTech"); eEmissiveTech = FX->GetTechniqueByName("ParticleEmissiveTech"); // Flow Control Booleans ----------------------------------------------- eModAlpha = FX->GetParameterByName(0,"gModAlpha"); eFullyLit = FX->GetParameterByName(0,"gFullyLit"); eFlow = FX->GetParameterByName(0,"gCfg"); eShadowToggle = FX->GetParameterByName(0,"gShadowsEnabled"); eEnvMapEnable = FX->GetParameterByName(0,"gEnvMapEnable"); eTextured = FX->GetParameterByName(0,"gTextured"); eFresnel = FX->GetParameterByName(0,"gFresnel"); eSwitch = FX->GetParameterByName(0,"gPBRSw"); eRghnSw = FX->GetParameterByName(0,"gRghnSw"); eInSpace = FX->GetParameterByName(0,"gInSpace"); eNoColor = FX->GetParameterByName(0,"gNoColor"); eLightsEnabled = FX->GetParameterByName(0,"gLightsEnabled"); eTuneEnabled = FX->GetParameterByName(0,"gTuneEnabled"); eBaseBuilding = FX->GetParameterByName(0,"gBaseBuilding"); // General parameters -------------------------------------------------- eSpecularMode = FX->GetParameterByName(0,"gSpecMode"); eLights = FX->GetParameterByName(0,"gLights"); eColor = FX->GetParameterByName(0,"gColor"); eDistScale = FX->GetParameterByName(0,"gDistScale"); eProxySize = FX->GetParameterByName(0,"gProxySize"); eTexOff = FX->GetParameterByName(0,"gTexOff"); eRadius = FX->GetParameterByName(0,"gRadius"); eCameraPos = FX->GetParameterByName(0,"gCameraPos"); eNorth = FX->GetParameterByName(0,"gNorth"); eEast = FX->GetParameterByName(0,"gEast"); ePointScale = FX->GetParameterByName(0,"gPointScale"); eMix = FX->GetParameterByName(0,"gMix"); eTime = FX->GetParameterByName(0,"gTime"); eMtrlAlpha = FX->GetParameterByName(0,"gMtrlAlpha"); eGlowConst = FX->GetParameterByName(0,"gGlowConst"); eSHD = FX->GetParameterByName(0,"gSHD"); eKernel = FX->GetParameterByName(0,"kernel"); // ---------------------------------------------------------------------- eVP = FX->GetParameterByName(0,"gVP"); eW = FX->GetParameterByName(0,"gW"); eLVP = FX->GetParameterByName(0,"gLVP"); eGT = FX->GetParameterByName(0,"gGrpT"); // ---------------------------------------------------------------------- eSun = FX->GetParameterByName(0,"gSun"); eMat = FX->GetParameterByName(0,"gMat"); eWater = FX->GetParameterByName(0,"gWater"); eMtrl = FX->GetParameterByName(0,"gMtrl"); eTune = FX->GetParameterByName(0,"gTune"); // ---------------------------------------------------------------------- eTex0 = FX->GetParameterByName(0,"gTex0"); eTex1 = FX->GetParameterByName(0,"gTex1"); eTex3 = FX->GetParameterByName(0,"gTex3"); eSpecMap = FX->GetParameterByName(0,"gSpecMap"); eEmisMap = FX->GetParameterByName(0,"gEmisMap"); eEnvMapA = FX->GetParameterByName(0,"gEnvMapA"); eEnvMapB = FX->GetParameterByName(0,"gEnvMapB"); eReflMap = FX->GetParameterByName(0,"gReflMap"); eRghnMap = FX->GetParameterByName(0,"gRghnMap"); eMetlMap = FX->GetParameterByName(0,"gMetlMap"); eHeatMap = FX->GetParameterByName(0,"gHeatMap"); eShadowMap = FX->GetParameterByName(0,"gShadowMap"); eTranslMap = FX->GetParameterByName(0, "gTranslMap"); eTransmMap = FX->GetParameterByName(0, "gTransmMap"); eIrradMap = FX->GetParameterByName(0,"gIrradianceMap"); // Atmosphere ----------------------------------------------------------- eGlobalAmb = FX->GetParameterByName(0,"gGlobalAmb"); eSunAppRad = FX->GetParameterByName(0,"gSunAppRad"); eAmbient0 = FX->GetParameterByName(0,"gAmbient0"); eDispersion = FX->GetParameterByName(0,"gDispersion"); eFogDensity = FX->GetParameterByName(0,"gFogDensity"); eAttennuate = FX->GetParameterByName(0,"gAttennuate"); eInScatter = FX->GetParameterByName(0,"gInScatter"); eInvProxySize = FX->GetParameterByName(0,"gInvProxySize"); eFogColor = FX->GetParameterByName(0,"gFogColor"); eAtmColor = FX->GetParameterByName(0,"gAtmColor"); eHazeMode = FX->GetParameterByName(0,"gHazeMode"); eNight = FX->GetParameterByName(0, "gNightTime"); // Initialize default values -------------------------------------- // FX->SetInt(eHazeMode, 0); FX->SetBool(eInSpace, false); FX->SetVector(eAttennuate, &D3DXVECTOR4(1,1,1,1)); FX->SetVector(eInScatter, &D3DXVECTOR4(0,0,0,0)); FX->SetVector(eColor, &D3DXVECTOR4(0, 0, 0, 0)); //if (Config->ShadowFilter>=3) FX->SetValue(eKernel, &shadow_kernel2, sizeof(shadow_kernel2)); FX->SetValue(eKernel, &shadow_kernel, sizeof(shadow_kernel)); CreateMatExt(&_mfdmat, &mfdmat); CreateMatExt(&_defmat, &defmat); CreateMatExt(&_night_mat, &night_mat); CreateMatExt(&_emissive_mat, &emissive_mat); // Create a Circle Mesh -------------------------------------------- // if (!VB) { HR(pDev->CreateVertexBuffer(256 * sizeof(D3DXVECTOR3), 0, 0, D3DPOOL_DEFAULT, &VB, NULL)); D3DXVECTOR3 *pVert; if (VB->Lock(0, 0, (void **)&pVert, 0) == S_OK) { float angle = 0.0f, step = float(PI2) / 255.0f; pVert[0] = D3DXVECTOR3(0, 0, 0); for (int i = 1; i < 256; i++) { pVert[i].x = 0; pVert[i].y = cos(angle); pVert[i].z = sin(angle); angle += step; } VB->Unlock(); } else LogErr("Failed to Lock vertex buffer"); } } void D3D9Effect::SetViewProjMatrix(LPD3DXMATRIX pVP) { FX->SetMatrix(eVP, pVP); } void D3D9Effect::UpdateEffectCamera(OBJHANDLE hPlanet) { if (!hPlanet) return; VECTOR3 cam, pla, sun; OBJHANDLE hSun = oapiGetGbodyByIndex(0); // generalise later cam = gc->GetScene()->GetCameraGPos(); oapiGetGlobalPos(hPlanet, &pla); oapiGetGlobalPos(hSun, &sun); double len = length(cam - pla); double rad = oapiGetSize(hPlanet); sun = unit(sun - cam); // Vector pointing to sun from camera cam = unit(cam - pla); // Vector pointing to cam from planet DWORD width, height; oapiGetViewportSize(&width, &height); // BUG: Custom Camera may have different view size float radlimit = float(rad) + 1.0f; float rho0 = 1.0f; atm_color = D3DXVECTOR4(0.5f, 0.5f, 0.5f, 1.0f); const ATMCONST *atm = oapiGetPlanetAtmConstants(hPlanet); VESSEL *hVessel = oapiGetFocusInterface(); OBJHANDLE hGRef = hVessel->GetGravityRef(); MATRIX3 grot; oapiGetRotationMatrix(hGRef, &grot); VECTOR3 polaraxis = mul(grot, _V(0, 1, 0)); VECTOR3 east = unit(crossp(polaraxis, cam)); VECTOR3 north = unit(crossp(cam, east)); if (hVessel==NULL) { LogErr("hVessel = NULL in UpdateEffectCamera()"); return; } if (atm) { radlimit = float(atm->radlimit); atm_color = D3DXVEC4(atm->color0, 1.0f); rho0 = float(atm->rho0); } float av = (atm_color.x + atm_color.y + atm_color.z) * 0.3333333f; float fc = 1.5f; float alt = 1.0f - pow(float(hVessel->GetAtmDensity()/rho0), 0.2f); atm_color += D3DXVECTOR4(av,av,av,1.0)*fc; atm_color *= 1.0f/(fc+1.0f); atm_color *= float(Config->PlanetGlow) * alt; float ap = gc->GetScene()->GetCameraAperture(); float rl = float(rad/len); float proxy_size = asin(min(1.0f, rl)) + float(40.0*PI/180.0); if (rl>1e-3) atm_color *= pow(rl, 1.5f); else atm_color = D3DXVECTOR4(0,0,0,1); FX->SetValue(eEast, &D3DXVEC(east), sizeof(D3DXVECTOR3)); FX->SetValue(eNorth, &D3DXVEC(north), sizeof(D3DXVECTOR3)); FX->SetValue(eCameraPos, &D3DXVEC(cam), sizeof(D3DXVECTOR3)); FX->SetVector(eRadius, &D3DXVECTOR4((float)rad, radlimit, (float)len, (float)(len-rad))); FX->SetFloat(ePointScale, 0.5f*float(height)/tan(ap)); FX->SetFloat(eProxySize, cos(proxy_size)); FX->SetFloat(eInvProxySize, 1.0f/(1.0f-cos(proxy_size))); FX->SetFloat(eGlowConst, saturate(float(dotp(cam, sun)))); } // =========================================================================================== // void D3D9Effect::EnablePlanetGlow(bool bEnabled) { if (bEnabled) FX->SetVector(eAtmColor, &atm_color); else FX->SetVector(eAtmColor, &D3DXVECTOR4(0,0,0,0)); } // =========================================================================================== // void D3D9Effect::InitLegacyAtmosphere(OBJHANDLE hPlanet, float GlobalAmbient) { VECTOR3 GS, GP; OBJHANDLE hS = oapiGetGbodyByIndex(0); // the central star oapiGetGlobalPos (hS, &GS); // sun position oapiGetGlobalPos (hPlanet, &GP); // planet position float rs = (float)(oapiGetSize(hS) / length(GS-GP)); const ATMCONST *atm = (oapiGetObjectType(hPlanet)==OBJTP_PLANET ? oapiGetPlanetAtmConstants (hPlanet) : NULL); FX->SetFloat(eGlobalAmb, GlobalAmbient); FX->SetFloat(eSunAppRad, rs); if (atm) { FX->SetFloat(eAmbient0, float(min(0.7, log1p(atm->rho0)*0.4))); FX->SetFloat(eDispersion, float(max(0.02, min(0.9, log1p(atm->rho0))))); } else { FX->SetFloat(eAmbient0, 0.0f); FX->SetFloat(eDispersion, 0.0f); } } // =========================================================================================== // void D3D9Effect::Render2DPanel(const MESHGROUP *mg, const SURFHANDLE pTex, const LPD3DXMATRIX pW, float alpha, float scale, bool additive) { UINT numPasses = 0; if (SURFACE(pTex)->IsPowerOfTwo() || (!gc->IsLimited())) FX->SetTechnique(ePanelTech); // ANISOTROPIC filter else FX->SetTechnique(ePanelTechB); // POINT filter (for non-pow2 conditional) HR(FX->SetMatrix(eW, pW)); if (pTex) FX->SetTexture(eTex0, SURFACE(pTex)->GetTexture()); else FX->SetTexture(eTex0, NULL); HR(FX->SetFloat(eMix, alpha)); HR(FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE)); HR(FX->BeginPass(0)); if (additive) pDev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); else pDev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); pDev->SetVertexDeclaration(pNTVertexDecl); pDev->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, mg->nVtx, mg->nIdx/3, mg->Idx, D3DFMT_INDEX16, mg->Vtx, sizeof(NTVERTEX)); HR(FX->EndPass()); HR(FX->End()); } // =========================================================================================== // void D3D9Effect::RenderReEntry(const SURFHANDLE pTex, const LPD3DXVECTOR3 vPosA, const LPD3DXVECTOR3 vPosB, const LPD3DXVECTOR3 vDir, float alpha_a, float alpha_b, float size) { static WORD ReentryIdx[6] = {0,1,2, 3,2,1}; static NTVERTEX ReentryVtxB[4] = { {0,-1,-1, 0,0,0, 0.51f, 0.01f}, {0,-1, 1, 0,0,0, 0.99f, 0.01f}, {0, 1,-1, 0,0,0, 0.51f, 0.49f}, {0, 1, 1, 0,0,0, 0.99f, 0.49f} }; float x = 4.5f + sin(fmod(float(oapiGetSimTime())*60.0f, 6.283185f)) * 0.5f; NTVERTEX ReentryVtxA[4] = { {0, 1, 1, 0,0,0, 0.49f, 0.01f}, {0, 1,-x, 0,0,0, 0.49f, 0.99f}, {0,-1, 1, 0,0,0, 0.01f, 0.01f}, {0,-1,-x, 0,0,0, 0.01f, 0.99f}, }; UINT numPasses = 0; D3DXMATRIX WA, WB; D3DXVECTOR3 vCam; D3DXVec3Normalize(&vCam, vPosA); D3DMAT_CreateX_Billboard(&vCam, vPosB, size*(0.8f+x*0.02f), &WB); D3DMAT_CreateX_Billboard(&vCam, vPosA, vDir, size, size, &WA); pDev->SetVertexDeclaration(pNTVertexDecl); FX->SetTechnique(eExhaust); FX->SetTexture(eTex0, SURFACE(pTex)->GetTexture()); FX->SetFloat(eMix, alpha_b); FX->SetMatrix(eW, &WB); FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE); FX->BeginPass(0); pDev->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, 4, 2, &ReentryIdx, D3DFMT_INDEX16, &ReentryVtxB, sizeof(NTVERTEX)); FX->SetFloat(eMix, alpha_a); FX->SetMatrix(eW, &WA); FX->CommitChanges(); pDev->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, 4, 2, &ReentryIdx, D3DFMT_INDEX16, &ReentryVtxA, sizeof(NTVERTEX)); FX->EndPass(); FX->End(); } // =========================================================================================== // This is a special rendering routine used to render beacons // void D3D9Effect::RenderSpot(float alpha, const LPD3DXCOLOR pColor, const LPD3DXMATRIX pW, SURFHANDLE pTex) { UINT numPasses = 0; HR(pDev->SetVertexDeclaration(pNTVertexDecl)); HR(FX->SetTechnique(eSpotTech)); HR(FX->SetFloat(eMix, alpha)); HR(FX->SetValue(eColor, pColor, sizeof(D3DXCOLOR))); HR(FX->SetMatrix(eW, pW)); HR(FX->SetTexture(eTex0, SURFACE(pTex)->GetTexture())); HR(FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE)); HR(FX->BeginPass(0)); HR(pDev->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, 4, 2, billboard_idx, D3DFMT_INDEX16, billboard_vtx, sizeof(NTVERTEX))); HR(FX->EndPass()); HR(FX->End()); } // =========================================================================================== // Used by Render Star only // void D3D9Effect::RenderBillboard(const LPD3DXMATRIX pW, SURFHANDLE pTex) { UINT numPasses = 0; HR(pDev->SetVertexDeclaration(pNTVertexDecl)); HR(FX->SetTechnique(eSimple)); HR(FX->SetMatrix(eW, pW)); HR(FX->SetTexture(eTex0, SURFACE(pTex)->GetTexture())); HR(FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE)); HR(FX->BeginPass(0)); HR(pDev->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, 4, 2, billboard_idx, D3DFMT_INDEX16, billboard_vtx, sizeof(NTVERTEX))); HR(FX->EndPass()); HR(FX->End()); } // =========================================================================================== // This is a special rendering routine used to render engine exhaust // void D3D9Effect::RenderExhaust(const LPD3DXMATRIX pW, VECTOR3 &cdir, EXHAUSTSPEC *es, SURFHANDLE def) { SURFHANDLE pTex = SURFACE(es->tex); if (!pTex) pTex = def; double alpha = *es->level; if (es->modulate) alpha *= ((1.0 - es->modulate)+(double)rand()* es->modulate/(double)RAND_MAX); VECTOR3 edir = -(*es->ldir); VECTOR3 ref = (*es->lpos) - (*es->ldir)*es->lofs; const float flarescale = 7.0; VECTOR3 sdir = crossp(cdir, edir); normalise(sdir); VECTOR3 tdir = crossp(cdir, sdir); normalise(tdir); float rx = (float)ref.x; float ry = (float)ref.y; float rz = (float)ref.z; float sx = (float)(sdir.x*es->wsize); float sy = (float)(sdir.y*es->wsize); float sz = (float)(sdir.z*es->wsize); float ex = (float)(edir.x*es->lsize); float ey = (float)(edir.y*es->lsize); float ez = (float)(edir.z*es->lsize); exhaust_vtx[1].x = (exhaust_vtx[0].x = rx + sx) + ex; exhaust_vtx[1].y = (exhaust_vtx[0].y = ry + sy) + ey; exhaust_vtx[1].z = (exhaust_vtx[0].z = rz + sz) + ez; exhaust_vtx[3].x = (exhaust_vtx[2].x = rx - sx) + ex; exhaust_vtx[3].y = (exhaust_vtx[2].y = ry - sy) + ey; exhaust_vtx[3].z = (exhaust_vtx[2].z = rz - sz) + ez; double wscale = es->wsize; wscale *= flarescale, sx *= flarescale, sy *= flarescale, sz *= flarescale; float tx = (float)(tdir.x*wscale); float ty = (float)(tdir.y*wscale); float tz = (float)(tdir.z*wscale); exhaust_vtx[4].x = rx - sx + tx; exhaust_vtx[5].x = rx + sx + tx; exhaust_vtx[4].y = ry - sy + ty; exhaust_vtx[5].y = ry + sy + ty; exhaust_vtx[4].z = rz - sz + tz; exhaust_vtx[5].z = rz + sz + tz; exhaust_vtx[6].x = rx - sx - tx; exhaust_vtx[7].x = rx + sx - tx; exhaust_vtx[6].y = ry - sy - ty; exhaust_vtx[7].y = ry + sy - ty; exhaust_vtx[6].z = rz - sz - tz; exhaust_vtx[7].z = rz + sz - tz; UINT numPasses = 0; HR(pDev->SetVertexDeclaration(pNTVertexDecl)); HR(FX->SetTechnique(eExhaust)); HR(FX->SetFloat(eMix, float(alpha))); HR(FX->SetMatrix(eW, pW)); HR(FX->SetTexture(eTex0, SURFACE(pTex)->GetTexture())); HR(FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE)); HR(FX->BeginPass(0)); HR(pDev->DrawIndexedPrimitiveUP(D3DPT_TRIANGLELIST, 0, 8, 4, exhaust_idx, D3DFMT_INDEX16, exhaust_vtx, sizeof(NTVERTEX))); HR(FX->EndPass()); HR(FX->End()); } void D3D9Effect::RenderBoundingBox(const LPD3DXMATRIX pW, const LPD3DXMATRIX pGT, const D3DXVECTOR4 *bmin, const D3DXVECTOR4 *bmax, const LPD3DXVECTOR4 color) { D3DXMATRIX ident; D3DXMatrixIdentity(&ident); static D3DVECTOR poly[10] = { {0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 0, 0}, {0, 0, 1}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1} }; static D3DVECTOR list[6] = { {1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1} }; pDev->SetVertexDeclaration(pPositionDecl); FX->SetMatrix(eW, pW); FX->SetMatrix(eGT, pGT); FX->SetVector(eAttennuate, bmin); FX->SetVector(eInScatter, bmax); FX->SetVector(eColor, color); FX->SetTechnique(eBBTech); UINT numPasses = 0; FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE); FX->BeginPass(0); pDev->DrawPrimitiveUP(D3DPT_LINESTRIP, 9, &poly, sizeof(D3DVECTOR)); pDev->DrawPrimitiveUP(D3DPT_LINELIST, 3, &list, sizeof(D3DVECTOR)); FX->EndPass(); FX->End(); } void D3D9Effect::RenderTileBoundingBox(const LPD3DXMATRIX pW, VECTOR4 *pVtx, const LPD3DXVECTOR4 color) { D3DXVECTOR3 poly[8]; for (int i=0;i<8;i++) poly[i] = D3DXVEC(pVtx[i]); WORD idc1[10] = { 0, 1, 3, 2, 0, 4, 5, 7, 6, 4 }; WORD idc2[6] = { 1, 5, 3, 7, 2, 6}; pDev->SetVertexDeclaration(pPositionDecl); FX->SetMatrix(eW, pW); FX->SetVector(eColor, color); FX->SetTechnique(eTBBTech); UINT numPasses = 0; FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE); FX->BeginPass(0); pDev->DrawIndexedPrimitiveUP(D3DPT_LINESTRIP, 0, 8, 9, &idc1, D3DFMT_INDEX16, &poly, sizeof(D3DXVECTOR3)); pDev->DrawIndexedPrimitiveUP(D3DPT_LINELIST, 0, 8, 3, &idc2, D3DFMT_INDEX16, &poly, sizeof(D3DXVECTOR3)); FX->EndPass(); FX->End(); } void D3D9Effect::RenderLines(const D3DXVECTOR3 *pVtx, const WORD *pIdx, int nVtx, int nIdx, const D3DXMATRIX *pW, DWORD color) { UINT numPasses = 0; pDev->SetVertexDeclaration(pPositionDecl); FX->SetMatrix(eW, pW); FX->SetVector(eColor, (const D3DXVECTOR4 *)&D3DXCOLOR(color)); FX->SetTechnique(eTBBTech); FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE); FX->BeginPass(0); pDev->DrawIndexedPrimitiveUP(D3DPT_LINELIST, 0, nVtx, nIdx/2, pIdx, D3DFMT_INDEX16, pVtx, sizeof(D3DXVECTOR3)); FX->EndPass(); FX->End(); } void D3D9Effect::RenderBoundingSphere(const LPD3DXMATRIX pW, const LPD3DXMATRIX pGT, const D3DXVECTOR4 *bs, const LPD3DXVECTOR4 color) { D3DXMATRIX mW; D3DXVECTOR3 vCam; D3DXVECTOR3 vPos; D3DXVec3TransformCoord(&vPos, &D3DXVECTOR3(bs->x, bs->y, bs->z), pW); D3DXVec3Normalize(&vCam, &vPos); D3DMAT_CreateX_Billboard(&vCam, &vPos, bs->w, &mW); pDev->SetVertexDeclaration(pPositionDecl); FX->SetMatrix(eW, &mW); FX->SetVector(eColor, color); FX->SetTechnique(eBSTech); UINT numPasses = 0; FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE); FX->BeginPass(0); pDev->SetStreamSource(0, VB, 0, sizeof(D3DXVECTOR3)); pDev->DrawPrimitive(D3DPT_LINESTRIP, 0, 255); FX->EndPass(); FX->End(); } // =========================================================================================== // This is a special rendering routine used to render (grapple point) arrows // void D3D9Effect::RenderArrow(OBJHANDLE hObj, const VECTOR3 *ofs, const VECTOR3 *dir, const VECTOR3 *rot, float size, const D3DXCOLOR *pColor) { static D3DVECTOR arrow[18] = { // Head (front- & back-face) {0.0, 0.0, 0.0}, {0.0,-1.0, 1.0}, {0.0, 1.0, 1.0}, {0.0, 0.0, 0.0}, {0.0, 1.0, 1.0}, {0.0,-1.0, 1.0}, // Body first triangle (front- & back-face) {0.0,-0.5, 1.0}, {0.0,-0.5, 2.0}, {0.0, 0.5, 2.0}, {0.0,-0.5, 1.0}, {0.0, 0.5, 2.0}, {0.0,-0.5, 2.0}, // Body second triangle (front- & back-face) {0.0,-0.5, 1.0}, {0.0, 0.5, 2.0}, {0.0, 0.5, 1.0}, {0.0,-0.5, 1.0}, {0.0, 0.5, 1.0}, {0.0, 0.5, 2.0} }; MATRIX3 grot; D3DXMATRIX W; VECTOR3 camp, gpos; oapiGetRotationMatrix(hObj, &grot); oapiGetGlobalPos(hObj, &gpos); camp = gc->GetScene()->GetCameraGPos(); VECTOR3 pos = gpos - camp; if (ofs) pos += mul (grot, *ofs); VECTOR3 z = mul (grot, unit(*dir)) * size; VECTOR3 y = mul (grot, unit(*rot)) * size; VECTOR3 x = mul (grot, unit(crossp(*dir, *rot))) * size; D3DXMatrixIdentity(&W); W._11 = float(x.x); W._12 = float(x.y); W._13 = float(x.z); W._21 = float(y.x); W._22 = float(y.y); W._23 = float(y.z); W._31 = float(z.x); W._32 = float(z.y); W._33 = float(z.z); W._41 = float(pos.x); W._42 = float(pos.y); W._43 = float(pos.z); UINT numPasses = 0; HR(pDev->SetVertexDeclaration(pPositionDecl)); // Position only vertex decleration HR(FX->SetTechnique(eArrowTech)); // Use arrow shader HR(FX->SetValue(eColor, pColor, sizeof(D3DXCOLOR))); // Setup arrow color HR(FX->SetMatrix(eW, &W)); HR(FX->Begin(&numPasses, D3DXFX_DONOTSAVESTATE)); HR(FX->BeginPass(0)); HR(pDev->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 6, &arrow, sizeof(D3DVECTOR))); // Draw 6 triangles un-indexed HR(FX->EndPass()); HR(FX->End()); }
34.131164
175
0.623884
[ "mesh", "render", "vector" ]
7e4e1f4daa994038d01188dd661b4e7b6b7ff843
2,813
hpp
C++
auth.hpp
xen0napp/example
81374f3cd6773af7860802d6819e71c1949212e1
[ "MIT" ]
null
null
null
auth.hpp
xen0napp/example
81374f3cd6773af7860802d6819e71c1949212e1
[ "MIT" ]
null
null
null
auth.hpp
xen0napp/example
81374f3cd6773af7860802d6819e71c1949212e1
[ "MIT" ]
1
2021-06-03T21:11:25.000Z
2021-06-03T21:11:25.000Z
/* Copyright (c) 2021-2022 [xen0n.app] 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. */ #pragma once #include <Windows.h> #include <string> #include <vector> namespace xen0n { typedef int package; class response { private: std::string message_str; bool status; std::string session; std::string uuid; public: /** * Initialize a response instance. * @param message The message returned by server * @param status The status provided by server (boolean) * @param session Encrypted session token provided by server. * @param uuid Application UUID provided by the authenticate function. */ response(std::string message, bool status, std::string session, std::string uuid); public: std::string expiry; std::string app; xen0n::package package; /** * Returns the message provided by server. * @return A string containing server-response. */ std::string message(); /** * Check if the authentication suceeded. * @return A boolean containing status of request. */ bool succeeded(); /** * Stream data from the server. * @return Container who contains bytes of streamed data. */ std::vector<uint8_t> stream(); }; class auth { private: std::string uuid; std::wstring endpoint = L"https://xen0n.app/api/"; /** * Get's hardware identifier in xen0n.app's format. * @return Returns a base64 encoded string containing serials and other unique identifiers. */ std::string get_hardware(); public: /** * Initialize an authentication instance. * @param uuid Universal identifier for the application you want to auth for. */ auth(std::string uuid); public: /** * Update endpoint used for middleman servers. * @param new_endpoint Link to your middleman server * @return Current instance of auth */ xen0n::auth with_endpoint(std::string new_endpoint); /** * Authenticate license key with xen0n.app. * * @param license License key provided by the user. * @param attempts Attempts if the authentication fails on server or client. * @return Returns an instance of xen0n::response* provided by the server. */ xen0n::response* authenticate(std::string license, int attempts = 1); }; }
26.790476
93
0.693921
[ "vector" ]
7e4ebfec36bc4440dd970b98066110b6990880a4
9,483
cpp
C++
examples/GPIO/autoDrive.cpp
shawandshaw/rpi
bbe139f8cb51cde28d244f12b4da310ddbba1fc1
[ "MIT" ]
null
null
null
examples/GPIO/autoDrive.cpp
shawandshaw/rpi
bbe139f8cb51cde28d244f12b4da310ddbba1fc1
[ "MIT" ]
null
null
null
examples/GPIO/autoDrive.cpp
shawandshaw/rpi
bbe139f8cb51cde28d244f12b4da310ddbba1fc1
[ "MIT" ]
1
2018-10-18T03:10:53.000Z
2018-10-18T03:10:53.000Z
#include <iostream> #include <stdlib.h> #include <vector> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #include <signal.h> #include <termios.h> #include <unistd.h> #include "GPIOlib.h" #define PI 3.1415926 //Uncomment this line at run-time to skip GUI rendering //#define _DEBUG using namespace cv; using namespace std; using namespace GPIO; void on_exit(void) { stopLeft(); stopRight(); } void signal_crash_handler(int sig) { on_exit(); exit(-1); } void signal_exit_handler(int sig) { exit(0); } const string CAM_PATH = "/dev/video0"; const string MAIN_WINDOW_NAME = "Processed Image"; const string CANNY_WINDOW_NAME = "Canny"; const string THRESHOLD_WINDOW_NAME = "Threshold"; const string DILATE_WINDOW_NAME = "Dilate"; const string ERODE_WINDOW_NAME = "Erode"; const string ROTATED_WINDOW_NAME = "Rotated"; const int CANNY_LOWER_BOUND = 50; const int CANNY_UPPER_BOUND = 250; const int HOUGH_THRESHOLD = 100; const int K = 10; struct test_line { float rho; float angle; }; test_line test_lines[20]; test_line result_lines[4]; void lineCluster(); int main() { init(); atexit(on_exit); signal(SIGTERM, signal_exit_handler); signal(SIGINT, signal_exit_handler); // ignore SIGPIPE signal(SIGPIPE, SIG_IGN); signal(SIGBUS, signal_crash_handler); // 总线错误 signal(SIGSEGV, signal_crash_handler); // SIGSEGV,非法内存访问 signal(SIGFPE, signal_crash_handler); // SIGFPE,数学相关的异常,如被0除,浮点溢出,等等 signal(SIGABRT, signal_crash_handler); int speed = 10; int abs_speed = 10; int direction = FORWARD; int angle = 0; turnTo(angle); controlLeft(FORWARD, abs_speed); controlRight(FORWARD, abs_speed); VideoCapture capture(CAM_PATH); //If this fails, try to open as a video camera, through the use of an integer param if (!capture.isOpened()) { capture.open(atoi(CAM_PATH.c_str())); } double dWidth = capture.get(CV_CAP_PROP_FRAME_WIDTH); //the width of frames of the video double dHeight = capture.get(CV_CAP_PROP_FRAME_HEIGHT); //the height of frames of the video clog << "Frame Size: " << dWidth << "x" << dHeight << endl; Mat image; while (true) { capture >> image; if (image.empty()) break; //Set the ROI for the image Rect roi(0, image.rows / 3, image.cols, image.rows / 3); Mat imgROI = image(roi); cvtColor(imgROI, imgROI, COLOR_BGR2GRAY); //二值化 Mat result_thre = imgROI; //threshold(imgROI, result_thre,150, 255, CV_THRESH_BINARY); #ifdef _DEBUG imshow(THRESHOLD_WINDOW_NAME, result_thre); #endif //膨胀 Mat result_dilate; Mat element = getStructuringElement(MORPH_RECT, Size(5, 5)); dilate(result_thre, result_dilate, element); #ifdef _DEBUG //imshow(DILATE_WINDOW_NAME, result_dilate); #endif //腐蚀 Mat result_erode; erode(result_dilate, result_erode, element); #ifdef _DEBUG //imshow(ERODE_WINDOW_NAME, result_erode); #endif //Canny algorithm(边缘检测) Mat contours; Canny(result_erode, contours, CANNY_LOWER_BOUND, CANNY_UPPER_BOUND); #ifdef _DEBUG //imshow(CANNY_WINDOW_NAME, contours); #endif vector<Vec2f> lines; HoughLines(contours, lines, 1, PI / 180, HOUGH_THRESHOLD); Mat result1(imgROI.size(), CV_8U, Scalar(255)); //imgROI.copyTo(result); float maxRad = -2 * PI; float minRad = 2 * PI; //myself int lines_num = 0; //Draw the lines and judge the slope for (vector<Vec2f>::const_iterator it = lines.begin(); it != lines.end(); ++it) { float rho = (*it)[0]; //First element is distance rho float theta = (*it)[1]; //Second element is angle theta //myself test_lines[lines_num].rho = rho; test_lines[lines_num].angle = theta * 180 / CV_PI; lines_num++; //Filter to remove vertical and horizontal lines, //and atan(0.09) equals about 5 degrees. if ((theta > 0.09 && theta < 1.48) || (theta > 1.62 && theta < 3.05)) { if (theta > maxRad) maxRad = theta; if (theta < minRad) minRad = theta; } } //myself test_lines[lines_num].rho = 0; test_lines[lines_num].angle = 404; lineCluster(); /*clog << "OUT1:"; for (int i = 0; i < 20 && test_lines[i].angle != 404;i++) { clog << "Line: (" << test_lines[i].rho << "," << test_lines[i].angle << ")\n"; } clog << "OUT2:";*/ for (int i = 0; i < 4 && result_lines[i].angle != 404; i++) { //clog << "Line: (" << result_lines[i].rho << "," << result_lines[i].angle << ")\n"; float theta = result_lines[i].angle * CV_PI / 180; float rho = result_lines[i].rho; //point of intersection of the line with first row Point pt1(rho / cos(theta), 0); //point of intersection of the line with last row Point pt2((rho - result1.rows * sin(theta)) / cos(theta), result1.rows); //Draw a line line(result1, pt1, pt2, Scalar(0, 255, 255), 3, CV_AA); } //透视变换 vector<Point> not_a_rect_shape; not_a_rect_shape.push_back(Point(image.cols * 0.4, 0)); not_a_rect_shape.push_back(Point(image.cols * 0.6, 0)); not_a_rect_shape.push_back(Point(0, image.rows / 3)); not_a_rect_shape.push_back(Point(image.cols, image.rows / 3)); Point2f src_vertices[4]; src_vertices[0] = not_a_rect_shape[0]; src_vertices[1] = not_a_rect_shape[1]; src_vertices[2] = not_a_rect_shape[2]; src_vertices[3] = not_a_rect_shape[3]; Point2f dst_vertices[4]; dst_vertices[0] = Point(0, 0); dst_vertices[1] = Point(image.cols, 0); dst_vertices[2] = Point(0, image.rows / 3); dst_vertices[3] = Point(image.cols, image.rows / 3); Mat warpMatrix = getPerspectiveTransform(src_vertices, dst_vertices); Mat result_rotated; warpPerspective(result1, result_rotated, warpMatrix, result_rotated.size(), INTER_LINEAR, BORDER_CONSTANT); #ifdef _DEBUG imshow(ROTATED_WINDOW_NAME, result_rotated); #endif //Canny algorithm(边缘检测) Canny(result_rotated, contours, CANNY_LOWER_BOUND, CANNY_UPPER_BOUND); HoughLines(contours, lines, 1, PI / 180, HOUGH_THRESHOLD); Mat result2(imgROI.size(), CV_8U, Scalar(255)); lines_num = 0; //Draw the lines and judge the slope for (vector<Vec2f>::const_iterator it = lines.begin(); it != lines.end(); ++it) { float rho = (*it)[0]; //First element is distance rho float theta = (*it)[1]; //Second element is angle theta //myself test_lines[lines_num].rho = rho; test_lines[lines_num].angle = theta * 180 / CV_PI; lines_num++; //Filter to remove vertical and horizontal lines, //and atan(0.09) equals about 5 degrees. if ((theta > 0.09 && theta < 1.48) || (theta > 1.62 && theta < 3.05)) { if (theta > maxRad) maxRad = theta; if (theta < minRad) minRad = theta; } } //myself test_lines[lines_num].rho = 0; test_lines[lines_num].angle = 404; lineCluster(); /*clog << "OUT1:"; for (int i = 0; i < 20 && test_lines[i].angle != 404; i++) { clog << "Line: (" << test_lines[i].rho << "," << test_lines[i].angle << ")\n"; } clog << "OUT2:";*/ for (int i = 0; i < 4 && result_lines[i].angle != 404; i++) { //clog << "Line: (" << result_lines[i].rho << "," << result_lines[i].angle << ")\n"; float theta = result_lines[i].angle * CV_PI / 180; float rho = result_lines[i].rho; //point of intersection of the line with first row Point pt1(rho / cos(theta), 0); //point of intersection of the line with last row Point pt2((rho - result1.rows * sin(theta)) / cos(theta), result1.rows); //Draw a line line(result2, pt1, pt2, Scalar(0, 255, 255), 3, CV_AA); } float result_angle; result_angle = 404; if (result_lines[0].angle != 404) { if (result_lines[0].angle < 90) { result_angle = result_lines[0].angle; } else if (result_lines[0].angle > 90) { result_angle = result_lines[0].angle - 180; } } else { result_angle = 0; } clog << "Angle:" << result_angle << "\n"; if(result_angle>-90&&result_angle<90){ angle=-result_angle; turnTo(angle); } #ifdef _DEBUG stringstream overlayedText; //overlayedText << "Lines: " << i; putText(result1, overlayedText.str(), Point(10, result1.rows - 10), 2, 0.8, Scalar(0, 0, 255), 0); imshow(MAIN_WINDOW_NAME, result1); imshow("result2", result2); #endif lines.clear(); waitKey(1); } return 0; } void lineCluster() { int tempNum[3] = {0, 0, 0}; int result_lines_num = 0; for (int i = 0; test_lines[i].rho != -1 && result_lines_num < 3; i++) { int inArray = 0; if (result_lines_num == 0) { result_lines[0] = test_lines[0]; tempNum[0]++; result_lines_num++; continue; } for (int j = 0; j < result_lines_num; j++) { float angleDiff = (test_lines[i].angle - result_lines[j].angle) * (test_lines[i].angle - result_lines[j].angle); float rhoDiff = (test_lines[i].rho - result_lines[j].rho) * (test_lines[i].rho - result_lines[j].rho); if (angleDiff < 150 && rhoDiff < 150) { result_lines[j].angle = (result_lines[j].angle * tempNum[j] + test_lines[i].angle) / (tempNum[j] + 1); result_lines[j].rho = (result_lines[j].rho * tempNum[j] + test_lines[i].rho) / (tempNum[j] + 1); tempNum[j]++; inArray = 1; break; } } //clog << "inArray:"<<inArray<<"\n"; if (inArray == 0) { result_lines[result_lines_num] = test_lines[i]; tempNum[result_lines_num] = 1; result_lines_num++; } } result_lines[result_lines_num].rho = 0; result_lines[result_lines_num].angle = 404; /*clog << "IN:\n"; clog << "num:"<< result_lines_num<<"\n"; for (int i = 0; i<result_lines_num;i++) { clog << "Line: (" << result_lines[i].rho << "," << result_lines[i].angle << ")\n"; }*/ }
27.25
115
0.65918
[ "vector" ]
7e561f588390d5672037e9582fd2df0905706c3c
6,450
cpp
C++
example/wiki/graph/KokkosGraph_wiki_coloring.cpp
trmcnealy/kokkos-kernels
a952807dc29948b9eb1ae8486f553c23ad7e7806
[ "BSD-3-Clause" ]
null
null
null
example/wiki/graph/KokkosGraph_wiki_coloring.cpp
trmcnealy/kokkos-kernels
a952807dc29948b9eb1ae8486f553c23ad7e7806
[ "BSD-3-Clause" ]
null
null
null
example/wiki/graph/KokkosGraph_wiki_coloring.cpp
trmcnealy/kokkos-kernels
a952807dc29948b9eb1ae8486f553c23ad7e7806
[ "BSD-3-Clause" ]
null
null
null
#include <vector> #include <cstdio> #include <cmath> #include <sstream> #include "Kokkos_Core.hpp" #include "KokkosKernels_default_types.hpp" #include "KokkosKernels_Handle.hpp" #include "KokkosGraph_Distance1Color.hpp" #include "KokkosGraph_Distance2Color.hpp" //Greedy Graph Coloring // -Generate the graph for a rectangular grid, with a 9-point stencil // (each vertex is adjacent to the 8 vertices around it within 1 grid square) // -Run Distance-1 coloring (usual coloring: adjacent vertices must have different colors) // -Print out the colors of each vertex in a grid // -Run Distance-2 coloring, and print out the colors // -Different constraint: two vertices separated by a path of length 1 OR 2 // must have different colors) using Ordinal = default_lno_t; using Offset = default_size_type; using Layout = default_layout; using ExecSpace = Kokkos::DefaultExecutionSpace; using DeviceSpace = typename ExecSpace::memory_space; using Kokkos::HostSpace; using RowmapType = Kokkos::View<Offset*, DeviceSpace>; using ColindsType = Kokkos::View<Ordinal*, DeviceSpace>; using Handle = KokkosKernels::Experimental:: KokkosKernelsHandle<Offset, Ordinal, default_scalar, ExecSpace, DeviceSpace, DeviceSpace>; namespace ColoringDemo { constexpr Ordinal gridX = 15; constexpr Ordinal gridY = 25; constexpr Ordinal numVertices = gridX * gridY; //Helper to get the vertex ID given grid coordinates Ordinal getVertexID(Ordinal x, Ordinal y) { return y * gridX + x; } //Inverse of getVertexID void getVertexPos(Ordinal vert, Ordinal& x, Ordinal& y) { x = vert % gridX; y = vert / gridX; } //Helper to print out colors in the shape of the grid template<typename ColorView> void printColoring(ColorView colors, Ordinal numColors) { //Read colors on host auto colorsHost = Kokkos::create_mirror_view_and_copy(HostSpace(), colors); int numDigits = ceil(log10(numColors + 1)); //Print out the grid, with columns aligned and at least one space between numbers std::ostringstream numFmtStream; numFmtStream << '%' << numDigits + 1 << 'd'; std::string numFmt = numFmtStream.str(); for(Ordinal y = 0; y < gridY; y++) { for(Ordinal x = 0; x < gridX; x++) { Ordinal vertex = getVertexID(x, y); int color = colorsHost(vertex); printf(numFmt.c_str(), color); } putchar('\n'); } } //Build the graph on host, allocate these views on device and copy the graph to them. //Both rowmapDevice and colindsDevice are output parameters and should default-initialized (empty) on input. void generate9pt(RowmapType& rowmapDevice, ColindsType& colindsDevice) { //Generate the graph on host (use std::vector to not need to know //how many entries ahead of time) std::vector<Offset> rowmap(numVertices + 1); std::vector<Ordinal> colinds; rowmap[0] = 0; for(Ordinal vert = 0; vert < numVertices; vert++) { Ordinal x, y; getVertexPos(vert, x, y); //Loop over the neighbors in a 3x3 region for(Ordinal ny = y - 1; ny <= y + 1; ny++) { for(Ordinal nx = x - 1; nx <= x + 1; nx++) { //exclude the edge to self if(nx == x && ny == y) continue; //exclude vertices that would be outside the grid if(nx < 0 || nx >= gridX || ny < 0 || ny >= gridY) continue; //add the neighbor to colinds, forming an edge colinds.push_back(getVertexID(nx, ny)); } } //mark where the current row ends rowmap[vert + 1] = colinds.size(); } Offset numEdges = colinds.size(); //Now that the graph is formed, copy rowmap and colinds to Kokkos::Views in device memory //The nonowning host views just alias the std::vectors. Kokkos::View<Offset*, HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>> rowmapHost(rowmap.data(), numVertices + 1); Kokkos::View<Ordinal*, HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>> colindsHost(colinds.data(), numEdges); //Allocate owning views on device with the correct size. rowmapDevice = RowmapType("Rowmap", numVertices + 1); colindsDevice = ColindsType("Colinds", numEdges); //Copy the graph from host to device Kokkos::deep_copy(rowmapDevice, rowmapHost); Kokkos::deep_copy(colindsDevice, colindsHost); } } int main(int argc, char* argv[]) { Kokkos::initialize(); { using ColoringDemo::numVertices; RowmapType rowmapDevice; ColindsType colindsDevice; //Step 1: Generate the graph on host, allocate space on device, and copy. //See function "generate9pt" below. ColoringDemo::generate9pt(rowmapDevice, colindsDevice); //Step 2: Create handle and run distance-1 coloring. { Handle handle; //Use the default algorithm (chosen based on ExecSpace) handle.create_graph_coloring_handle(KokkosGraph::COLORING_DEFAULT); //Run coloring (graph is square and symmetric) KokkosGraph::Experimental::graph_color(&handle, numVertices, numVertices, rowmapDevice, colindsDevice); //Get the colors array, and the number of colors used from the handle. auto colors = handle.get_graph_coloring_handle()->get_vertex_colors(); Ordinal numColors = handle.get_graph_coloring_handle()->get_num_colors(); printf("9-pt stencil: Distance-1 Colors (used %d):\n", (int) numColors); ColoringDemo::printColoring(colors, numColors); putchar('\n'); //Clean up handle.destroy_graph_coloring_handle(); } //Step 3: Create handle and run distance-2 coloring. { Handle handle; //Use the default algorithm (chosen based on ExecSpace) handle.create_distance2_graph_coloring_handle(KokkosGraph::COLORING_D2_DEFAULT); //Run coloring KokkosGraph::Experimental::graph_color_distance2(&handle, numVertices, rowmapDevice, colindsDevice); //Get the colors array, and the number of colors used from the handle. auto colors = handle.get_distance2_graph_coloring_handle()->get_vertex_colors(); Ordinal numColors = handle.get_distance2_graph_coloring_handle()->get_num_colors(); printf("9-pt stencil: Distance-2 Colors (used %d):\n", (int) numColors); ColoringDemo::printColoring(colors, numColors); putchar('\n'); //Clean up handle.destroy_distance2_graph_coloring_handle(); } } Kokkos::finalize(); return 0; }
39.090909
121
0.687752
[ "shape", "vector" ]
7e582d66e6ec1f58b22b8a33be6c50542a907b85
262
cpp
C++
acmicpc.net/13129.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
4
2016-04-15T07:54:39.000Z
2021-01-11T09:02:16.000Z
acmicpc.net/13129.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
null
null
null
acmicpc.net/13129.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <functional> #include <vector> #include <queue> using namespace std; int main() { int A, B, N; cin >> A >> B >> N; for (int i = 1; i <= N; i++) { cout << A * N + B * i << " "; } cout << endl; return 0; }
16.375
31
0.545802
[ "vector" ]
7e612d60bce50419b7dbec60af00e4a303a1fda2
1,058
cpp
C++
Online-Judges/CodeForces/900/320A.Magic_Numbers.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
3
2021-06-15T01:19:23.000Z
2022-03-16T18:23:53.000Z
Online-Judges/CodeForces/900/320A.Magic_Numbers.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
Online-Judges/CodeForces/900/320A.Magic_Numbers.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; //typedef typedef long long int lli; typedef long double ld; //define #define endn "\n" #define faststdio ios_base::sync_with_stdio(false); #define fastcincout cin.tie(NULL); cout.tie(NULL); #define fastio faststdio fastcincout #define tc(sl) int T; cin >>T; while (T--) {sl;} #define vec vector //functions template <typename T> inline void print_vector(vector<T> &vac) { for (int ele:vac) cout <<ele <<" "; cout <<"\n";} // Solve void test(void) { string nums; cin >>nums; for (int i = 0; i < nums.size(); ) { if (nums[i] == '1' && nums[i+1] == '4' && nums[i+2] == '4') { i += 3; } else if (nums[i] == '1' && nums[i+1] == '4') { i += 2; } else if (nums[i] == '1') { i++; } else { cout <<"NO" <<endn; return; } } cout <<"YES" <<endn; } int main(void) { fastio; test(); return 0; } // Solved By: shihab4t // Wednesday, June 16, 2021 | 01:26:33 AM (+06)
21.591837
69
0.516068
[ "vector" ]
7e72bd0d4024cca7f77e96cbefc6607498fc32f3
11,281
cpp
C++
src/fmd.cpp
softmaterialslab/nanoconfinement-cpmd
0e59ba29c5f411bd67dc6d3b7daf6c3e76b42b0a
[ "BSD-3-Clause" ]
null
null
null
src/fmd.cpp
softmaterialslab/nanoconfinement-cpmd
0e59ba29c5f411bd67dc6d3b7daf6c3e76b42b0a
[ "BSD-3-Clause" ]
null
null
null
src/fmd.cpp
softmaterialslab/nanoconfinement-cpmd
0e59ba29c5f411bd67dc6d3b7daf6c3e76b42b0a
[ "BSD-3-Clause" ]
null
null
null
// This is fictitious molecular dynamics // This program is used to estimate the correct w(k)'s on the interface #include "fmd.h" void fmd(vector<PARTICLE> &ion, INTERFACE &box, CONTROL &fmdremote, CONTROL &cpmdremote) { // Part I : Initialize for (unsigned int k = 0; k < box.leftplane.size(); k++) { box.leftplane[k].mu = fmdremote.fakemass * box.leftplane[k].a * box.leftplane[k].a; // Assign mass to the fake degree // s[k].w = 0.0; // Initialize fake degree value (unconstrained) box.leftplane[k].vw = 0.0; // Initialize fake degree velocity (unconstrained) } for (unsigned int k = 0; k < box.rightplane.size(); k++) { box.rightplane[k].mu = fmdremote.fakemass * box.rightplane[k].a * box.rightplane[k].a; // Assign mass to the fake degree // s[k].w = 0.0; // Initialize fake degree value (unconstrained) box.rightplane[k].vw = 0.0; // Initialize fake degree velocity (unconstrained) } /* long double sigma = constraint( ion, box); for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].w = box.leftplane[k].w - sigma / ( box.leftplane[k].a *( box.leftplane.size()+box.rightplane.size()) ); // Force to satisfy constraint for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].w = box.rightplane[k].w - sigma / (box.rightplane[k].a *( box.leftplane.size()+box.rightplane.size()) ); // Satisfy constraint long double sigmadot = dotconstraint(box); for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].vw = box.leftplane[k].vw - sigmadot / ( box.leftplane[k].a * ( box.leftplane.size()+box.rightplane.size())); // Force to atisfy time derivative of the constraint for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].vw =box.rightplane[k].vw - sigmadot / (box.rightplane[k].a * ( box.leftplane.size()+box.rightplane.size())); // Satisfy time derivative of the constraint */ long double sigma_left = constraint_left(ion, box); for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].w = box.leftplane[k].w - sigma_left / (box.leftplane[k].a * (box.leftplane.size())); // Force to satisfy constraint long double sigma_right = constraint_right(ion, box); for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].w = box.rightplane[k].w - sigma_right / (box.rightplane[k].a * (box.rightplane.size())); // Satisfy constraint long double sigmadot_left = dotconstraint_left(box); for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].vw = box.leftplane[k].vw - sigmadot_left / (box.leftplane[k].a * (box.leftplane.size())); // Force to atisfy time derivative of the constraint long double sigmadot_right = dotconstraint_right(box); for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].vw = box.rightplane[k].vw - sigmadot_right / (box.rightplane[k].a * (box.rightplane.size())); // Satisfy time derivative of the constraint compute_force_fake_dof(ion, box, 'n'); // Compute initial force long double kinetic_energy = 0.0; kinetic_energy = fake_kinetic_energy(box); // Compute initial kinetic energy double potential_energy = energy_functional(ion, box); // Compute initial potential energy if (world.rank() == 0) cout << "potential energy : " << potential_energy << endl; fmdremote.annealfreq = 10; fmdremote.hiteqm = 100; fmdremote.freq = 10; // Output fmd essentials if (world.rank() == 0) { cout << "\n"; cout << "F M D" << " at " << fmdremote.verify << endl; cout << "Mass assigned to the fake degrees " << box.leftplane[0].mu << endl; cout << "Total induced charge on the interface " << box.total_induced_charge() << endl; cout << "Constraint is (zero if satisfied) " << constraint(ion, box) << endl; cout << "Time derivative of the constraint is " << dotconstraint(box) << endl; cout << "Initial force on fake degree at vertex 0 at left interface " << box.leftplane[0].fw << endl; cout << "Initial force on fake degree at vertex 0 at right interface" << box.rightplane[0].fw << endl; cout << "Initial fake kinetic energy " << kinetic_energy << endl; cout << "Inital potential energy " << potential_energy << endl; cout << "Initial total energy " << kinetic_energy + potential_energy << endl; cout << "Time step " << fmdremote.timestep << endl; cout << "Number of steps " << fmdremote.steps << endl; } // create fmd output files /* ofstream fmdv, fmde, fmdtic; char data[200]; sprintf(data, "outfiles_windows/fmdv_%.06d.dat", fmdremote.verify); fmdv.open(data); sprintf(data, "outfiles_windows/fmde_%.06d.dat", fmdremote.verify); fmde.open(data); sprintf(data, "outfiles_windows/fmdtic_%.06d.dat", fmdremote.verify); fmdtic.open(data); */ //cout << "Time step " << fmdremote.timestep << endl; double average_total_induced_charge = 0.0; // initialize useful averages double average_total_induced_charge_left = 0.0; // initialize useful averages double average_total_induced_charge_right = 0.0; // initialize useful averages for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].wmean = 0; for (unsigned int l = 0; l < box.rightplane.size(); l++) box.rightplane[l].wmean = 0; int samples = 0; // number of samples fmdremote.extra_compute = 1000; // new addition, if one wants to have longer fmd since the startind density is not coming out right //cout << "extra_compute " << fmdremote.extra_compute << endl; // PART II : Propagate /*.......................................Fictitious molecular dynamics.......................................*/ for (int num = 1; num <= fmdremote.steps; num++) { // if (num % 50 == 0) cout << "what step is this " << num << endl; // cout << num <<endl; // fmdv << num << " " << box.leftplane[0].w << " " << box.rightplane[0].w << " " << box.leftplane[0].fw << " " << box.rightplane[0].fw << " " << box.leftplane[0].vw << " " << box.rightplane[0].vw <<endl; // total induced charge // fmdtic << num << " " << box.total_induced_charge_left() << " " << box.total_induced_charge_right() << endl; // INTEGRATOR //! begins for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].update_velocity(fmdremote.timestep); // update velocity half time step for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].update_velocity(fmdremote.timestep); // update velocity half time step for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].update_position(fmdremote.timestep); // update position full time step for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].update_position(fmdremote.timestep); // update position full time step //SHAKE_left(ion, box, fmdremote); // shake to ensure constraint //SHAKE_right(ion, box, fmdremote); // shake to ensure constraint compute_force_fake_dof(ion, box, 'n'); // calculate forces using the new positions for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].update_velocity(fmdremote.timestep); // update velocity half time step for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].update_velocity(fmdremote.timestep); // update velocity half time step //RATTLE_left(box); // rattle to ensure time derivative of the constraint //RATTLE_right(box); // rattle to ensure time derivative of the constraint //! ends // anneal (only if necessary) if (fmdremote.anneal == 'y' && num >= fmdremote.hiteqm && num % fmdremote.annealfreq == 0) { for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].vw = 0.9 * box.leftplane[k].vw; for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].vw = 0.9 * box.rightplane[k].vw; } // sample collection for averages if (num > fmdremote.hiteqm && (num % fmdremote.freq) == 0) { samples = samples + 1; for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].wmean += box.leftplane[k].w; for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].wmean += box.rightplane[k].w; average_total_induced_charge += box.total_induced_charge(); average_total_induced_charge_left += box.total_induced_charge_left(); average_total_induced_charge_right += box.total_induced_charge_right(); } /* // additional computations (turn off for faster simulations) if (num % fmdremote.extra_compute == 0) { kinetic_energy =0.0; kinetic_energy = fake_kinetic_energy(box); // Compute kinetic energy double potential_energy = energy_functional(ion, box); double extended_energy = kinetic_energy + potential_energy; fmde << num << " " << extended_energy << " " << kinetic_energy << " " << potential_energy << endl; } */ } /*.................................................fmd ends..................................................*/ // Part III: Compute averages for (unsigned int k = 0; k < box.leftplane.size(); k++) box.leftplane[k].wmean /= samples; // average induced charge at each vertex for (unsigned int k = 0; k < box.rightplane.size(); k++) box.rightplane[k].wmean /= samples; // average induced charge at each vertex average_total_induced_charge /= samples; // average total induced charge average_total_induced_charge_left /= samples; // average total induced charge average_total_induced_charge_right /= samples; // average total induced charge if (world.rank() == 0) { cout << "Number of samples used to estimate induced charges " << samples << endl; cout << "Total induced charge on average " << average_total_induced_charge << endl; cout << "Total induced charge leftplane on average " << average_total_induced_charge_left << endl; cout << "Total induced charge rightplane on average " << average_total_induced_charge_right << endl; } return; }
58.755208
214
0.582041
[ "vector" ]
7e7641f53c3d6555c449c26318021c2a977d07db
11,781
cpp
C++
camera/hal/mediatek/mtkcam/utils/imgbuf/ImageBufferHeap.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
camera/hal/mediatek/mtkcam/utils/imgbuf/ImageBufferHeap.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
camera/hal/mediatek/mtkcam/utils/imgbuf/ImageBufferHeap.cpp
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
/* * Copyright (C) 2019 MediaTek Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "MtkCam/Cam1Heap" // #include "BaseImageBufferHeap.h" #include <mtkcam/utils/imgbuf/ImageBufferHeap.h> #include <memory> #include <vector> #include <inttypes.h> // using NSCam::NSImageBufferHeap::BaseImageBufferHeap; // /****************************************************************************** * ******************************************************************************/ #define GET_BUF_VA(plane, va, index) (plane >= (index + 1)) ? va : 0 #define GET_BUF_ID(plane, memID, index) (plane >= (index + 1)) ? memID : 0 /****************************************************************************** * Image Buffer Heap (Camera1). ******************************************************************************/ class ImageBufferHeapImpl : public NSCam::ImageBufferHeap, public NSCam::NSImageBufferHeap::BaseImageBufferHeap { //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Interface. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public: //// Creation. static std::shared_ptr<ImageBufferHeapImpl> create( char const* szCallerName, ImageBufferHeapImpl::ImgParam_t const& rImgParam, NSCam::PortBufInfo_v1 const& rPortBufInfo, MBOOL const enableLog = MTRUE); //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // BaseImageBufferHeap Interface. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ protected: //// virtual char const* impGetMagicName() const { return magicName(); } virtual HeapInfoVect_t const& impGetHeapInfo() const { return mvHeapInfo; } virtual MBOOL impInit(BufInfoVect_t const& rvBufInfo); virtual MBOOL impUninit(); virtual MBOOL impReconfig(BufInfoVect_t const& rvBufInfo) { return MFALSE; } public: //// virtual MBOOL impLockBuf(char const* szCallerName, MINT usage, BufInfoVect_t const& rvBufInfo); virtual MBOOL impUnlockBuf(char const* szCallerName, MINT usage, BufInfoVect_t const& rvBufInfo); //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Implementations. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ protected: //// virtual MBOOL doMapPhyAddr(char const* szCallerName, HeapInfo const& rHeapInfo, BufInfo const& rBufInfo); virtual MBOOL doUnmapPhyAddr(char const* szCallerName, HeapInfo const& rHeapInfo, BufInfo const& rBufInfo); //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Instantiation. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public: //// Destructor/Constructors. /** * Disallowed to directly delete a raw pointer. */ virtual ~ImageBufferHeapImpl(); ImageBufferHeapImpl(char const* szCallerName, ImageBufferHeapImpl::ImgParam_t const& rImgParam, NSCam::PortBufInfo_v1 const& rPortBufInfo); //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Data Members. //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ protected: //// Info to Allocate. size_t mBufStridesInBytesToAlloc[3]; // buffer strides in bytes. protected: //// Info of Allocated Result. NSCam::PortBufInfo_v1 mPortBufInfo; // HeapInfoVect_t mvHeapInfo; // BufInfoVect_t mvBufInfo; // }; /****************************************************************************** * ******************************************************************************/ std::shared_ptr<NSCam::ImageBufferHeap> NSCam::ImageBufferHeap::create( char const* szCallerName, ImageBufferHeapImpl::ImgParam_t const& rImgParam, NSCam::PortBufInfo_v1 const& rPortBufInfo, MBOOL const enableLog) { return ImageBufferHeapImpl::create(szCallerName, rImgParam, rPortBufInfo, enableLog); } /****************************************************************************** * ******************************************************************************/ std::shared_ptr<ImageBufferHeapImpl> ImageBufferHeapImpl::create( char const* szCallerName, ImageBufferHeapImpl::ImgParam_t const& rImgParam, NSCam::PortBufInfo_v1 const& rPortBufInfo, MBOOL const enableLog) { MUINT const planeCount = NSCam::Utils::Format::queryPlaneCount(rImgParam.imgFormat); CAM_LOGD("format %#x, planeCount %d", rImgParam.imgFormat, planeCount); // std::shared_ptr<ImageBufferHeapImpl> pHeap = std::make_shared<ImageBufferHeapImpl>(szCallerName, rImgParam, rPortBufInfo); if (!pHeap) { CAM_LOGE("Fail to new"); return NULL; } // if (!pHeap->onCreate(std::dynamic_pointer_cast<BaseImageBufferHeap>(pHeap), rImgParam.imgSize, rImgParam.imgFormat, rImgParam.bufSize, enableLog)) { CAM_LOGE("onCreate"); // delete pHeap; return NULL; } // return pHeap; } /****************************************************************************** * ******************************************************************************/ ImageBufferHeapImpl::ImageBufferHeapImpl( char const* szCallerName, ImageBufferHeapImpl::ImgParam_t const& rImgParam, NSCam::PortBufInfo_v1 const& rPortBufInfo) : BaseImageBufferHeap(szCallerName), mPortBufInfo(rPortBufInfo) { ::memcpy(mBufStridesInBytesToAlloc, rImgParam.bufStridesInBytes, sizeof(mBufStridesInBytesToAlloc)); } ImageBufferHeapImpl::~ImageBufferHeapImpl() { impUninit(); } /****************************************************************************** * ******************************************************************************/ MBOOL ImageBufferHeapImpl::impInit(BufInfoVect_t const& rvBufInfo) { MBOOL ret = MFALSE; MUINT32 planesSizeInBytes = 0; // for calculating n-plane va // MY_LOGD_IF(getLogCond(), "continuos(%d) plane(%zu), memID(0x%x/0x%x/0x%x), va(0x%" PRIxPTR "/0x%" PRIxPTR "/0x%" PRIxPTR ")", mPortBufInfo.continuos, getPlaneCount(), GET_BUF_ID(getPlaneCount(), mPortBufInfo.memID[0], 0), (mPortBufInfo.continuos) ? 0 : GET_BUF_ID(getPlaneCount(), mPortBufInfo.memID[1], 1), (mPortBufInfo.continuos) ? 0 : GET_BUF_ID(getPlaneCount(), mPortBufInfo.memID[2], 2), GET_BUF_VA(getPlaneCount(), mPortBufInfo.virtAddr[0], 0), (mPortBufInfo.continuos) ? 0 : GET_BUF_VA(getPlaneCount(), mPortBufInfo.virtAddr[1], 1), (mPortBufInfo.continuos) ? 0 : GET_BUF_VA(getPlaneCount(), mPortBufInfo.virtAddr[2], 2)); mvHeapInfo.reserve(getPlaneCount()); mvBufInfo.reserve(getPlaneCount()); for (MUINT32 i = 0; i < getPlaneCount(); i++) { if (!helpCheckBufStrides(i, mBufStridesInBytesToAlloc[i])) { goto lbExit; } // { std::shared_ptr<HeapInfo> pHeapInfo = std::make_shared<HeapInfo>(); mvHeapInfo.push_back(pHeapInfo); pHeapInfo->heapID = (MTRUE == mPortBufInfo.continuos) ? mPortBufInfo.memID[0] : mPortBufInfo.memID[i]; // std::shared_ptr<BufInfo> pBufInfo = std::make_shared<BufInfo>(); mvBufInfo.push_back(pBufInfo); pBufInfo->stridesInBytes = mBufStridesInBytesToAlloc[i]; pBufInfo->sizeInBytes = helpQueryBufSizeInBytes(i, mBufStridesInBytesToAlloc[i]); pBufInfo->va = (MTRUE == mPortBufInfo.continuos) ? mPortBufInfo.virtAddr[0] + planesSizeInBytes : mPortBufInfo.virtAddr[i]; // planesSizeInBytes += pBufInfo->sizeInBytes; // rvBufInfo[i]->stridesInBytes = pBufInfo->stridesInBytes; rvBufInfo[i]->sizeInBytes = pBufInfo->sizeInBytes; } } // ret = MTRUE; lbExit: return ret; } /****************************************************************************** * ******************************************************************************/ MBOOL ImageBufferHeapImpl::impUninit() { // return MTRUE; } /****************************************************************************** * ******************************************************************************/ MBOOL ImageBufferHeapImpl::impLockBuf(char const* szCallerName, MINT usage, BufInfoVect_t const& rvBufInfo) { MBOOL ret = MFALSE; // for (MUINT32 i = 0; i < rvBufInfo.size(); i++) { std::shared_ptr<HeapInfo> pHeapInfo = mvHeapInfo[i]; std::shared_ptr<BufInfo> pBufInfo = rvBufInfo[i]; // // SW Access. pBufInfo->va = (0 != (usage & NSCam::eBUFFER_USAGE_SW_MASK)) ? mvBufInfo[i]->va : 0; } // ret = MTRUE; if (!ret) { impUnlockBuf(szCallerName, usage, rvBufInfo); } return ret; } /****************************************************************************** * ******************************************************************************/ MBOOL ImageBufferHeapImpl::impUnlockBuf(char const* szCallerName, MINT usage, BufInfoVect_t const& rvBufInfo) { // for (MUINT32 i = 0; i < rvBufInfo.size(); i++) { std::shared_ptr<HeapInfo> pHeapInfo = mvHeapInfo[i]; std::shared_ptr<BufInfo> pBufInfo = rvBufInfo[i]; // // HW Access. if (0 != (usage & NSCam::eBUFFER_USAGE_HW_MASK)) { if (0 != pBufInfo->pa) { doUnmapPhyAddr(szCallerName, *pHeapInfo, *pBufInfo); pBufInfo->pa = 0; } else { MY_LOGD("%s@ skip PA=0 at %d-th plane", szCallerName, i); } } // // SW Access. if (0 != (usage & NSCam::eBUFFER_USAGE_SW_MASK)) { if (0 != pBufInfo->va) { pBufInfo->va = 0; } else { MY_LOGD("%s@ skip VA=0 at %d-th plane", szCallerName, i); } } } // return MTRUE; } /****************************************************************************** * ******************************************************************************/ MBOOL ImageBufferHeapImpl::doMapPhyAddr(char const* szCallerName, HeapInfo const& rHeapInfo, BufInfo const& rBufInfo) { return MFALSE; } /****************************************************************************** * ******************************************************************************/ MBOOL ImageBufferHeapImpl::doUnmapPhyAddr(char const* szCallerName, HeapInfo const& rHeapInfo, BufInfo const& rBufInfo) { return MFALSE; }
37.519108
80
0.47984
[ "vector" ]
7e764bca0bd2eba9d988b7daf04af00c8ab9b745
12,846
cpp
C++
tests/Basic/BlockchainSynchronizer/main.cpp
CASH2-js/cash2
17d5582ec41149567fcad12ba58c392fab502097
[ "BSD-3-Clause" ]
null
null
null
tests/Basic/BlockchainSynchronizer/main.cpp
CASH2-js/cash2
17d5582ec41149567fcad12ba58c392fab502097
[ "BSD-3-Clause" ]
null
null
null
tests/Basic/BlockchainSynchronizer/main.cpp
CASH2-js/cash2
17d5582ec41149567fcad12ba58c392fab502097
[ "BSD-3-Clause" ]
1
2020-05-13T19:39:58.000Z
2020-05-13T19:39:58.000Z
// Copyright (c) 2018-2020 The Cash2 developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "gtest/gtest.h" #include "helperFunctions.h" #include "Transfers/BlockchainSynchronizer.h" #include "CryptoNoteCore/CryptoNoteTools.h" #include "CryptoNoteCore/Currency.h" #include "Logging/ConsoleLogger.h" #include "CryptoNoteCore/Transaction.cpp" #include <random> #include <iostream> using namespace CryptoNote; /* My Notes class BlockchainSynchronizer { public BlockchainSynchronizer() ~BlockchainSynchronizer() addConsumer() removeConsumer() getConsumerState() getConsumerKnownBlocks() addUnconfirmedTransaction() removeUnconfirmedTransaction() start() stop() save() load() localBlockchainUpdated() lastKnownBlockHeightUpdated() poolChanged() private typedef std::map<IBlockchainConsumer*, std::shared_ptr<SynchronizationState>> ConsumersMap ConsumersMap m_consumers INode& m_node const Crypto::Hash m_genesisBlockHash Crypto::Hash lastBlockId State m_currentState State m_futureState std::unique_ptr<std::thread> workingThread std::list<std::pair<const ITransactionReader*, std::promise<std::error_code>>> m_addTransactionTasks std::list<std::pair<const Crypto::Hash*, std::promise<void>>> m_removeTransactionTasks mutable std::mutex m_consumersMutex mutable std::mutex m_stateMutex std::condition_variable m_hasWork } */ class Node : public CryptoNote::INode { public: virtual bool addObserver(CryptoNote::INodeObserver* observer) override { return true; }; virtual bool removeObserver(CryptoNote::INodeObserver* observer) override { return true; }; virtual void init(const CryptoNote::INode::Callback& callback) override {callback(std::error_code());}; virtual bool shutdown() override { return true; }; virtual size_t getPeerCount() const override { return 0; }; virtual uint32_t getLastLocalBlockHeight() const override { return 0; }; virtual uint32_t getLastKnownBlockHeight() const override { return 0; }; virtual uint32_t getLocalBlockCount() const override { return 0; }; virtual uint32_t getKnownBlockCount() const override { return 0; }; virtual uint64_t getLastLocalBlockTimestamp() const override { return 0; } virtual void getNewBlocks(std::vector<Crypto::Hash>&& knownBlockIds, std::vector<CryptoNote::block_complete_entry>& newBlocks, uint32_t& height, const Callback& callback) override { callback(std::error_code()); }; virtual void relayTransaction(const CryptoNote::Transaction& transaction, const Callback& callback) override { callback(std::error_code()); }; virtual void getRandomOutsByAmounts(std::vector<uint64_t>&& amounts, uint64_t outsCount, std::vector<CryptoNote::CORE_RPC_COMMAND_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount>& result, const Callback& callback) override { callback(std::error_code()); }; virtual void getTransactionOutsGlobalIndexes(const Crypto::Hash& transactionHash, std::vector<uint32_t>& outsGlobalIndexes, const Callback& callback) override { callback(std::error_code()); }; virtual void getPoolSymmetricDifference(std::vector<Crypto::Hash>&& known_pool_tx_ids, Crypto::Hash known_block_id, bool& is_bc_actual, std::vector<std::unique_ptr<CryptoNote::ITransactionReader>>& new_txs, std::vector<Crypto::Hash>& deleted_tx_ids, const Callback& callback) override { is_bc_actual = true; callback(std::error_code()); }; virtual void queryBlocks(std::vector<Crypto::Hash>&& knownBlockIds, uint64_t timestamp, std::vector<CryptoNote::BlockShortEntry>& newBlocks, uint32_t& startHeight, const Callback& callback) override { callback(std::error_code()); }; virtual void getBlocks(const std::vector<uint32_t>& blockHeights, std::vector<std::vector<CryptoNote::BlockDetails>>& blocks, const Callback& callback) override { callback(std::error_code()); }; virtual void getBlocks(const std::vector<Crypto::Hash>& blockHashes, std::vector<CryptoNote::BlockDetails>& blocks, const Callback& callback) override { callback(std::error_code()); }; virtual void getBlocks(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t blocksNumberLimit, std::vector<CryptoNote::BlockDetails>& blocks, uint32_t& blocksNumberWithinTimestamps, const Callback& callback) override { callback(std::error_code()); }; virtual void getTransactions(const std::vector<Crypto::Hash>& transactionHashes, std::vector<CryptoNote::TransactionDetails>& transactions, const Callback& callback) override { callback(std::error_code()); }; virtual void getTransactionsByPaymentId(const Crypto::Hash& paymentId, std::vector<CryptoNote::TransactionDetails>& transactions, const Callback& callback) override { callback(std::error_code()); }; virtual void getPoolTransactions(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t transactionsNumberLimit, std::vector<CryptoNote::TransactionDetails>& transactions, uint64_t& transactionsNumberWithinTimestamps, const Callback& callback) override { callback(std::error_code()); }; virtual void isSynchronized(bool& syncStatus, const Callback& callback) override { callback(std::error_code()); }; virtual void getMultisignatureOutputByGlobalIndex(uint64_t amount, uint32_t gindex, CryptoNote::MultisignatureOutput& out, const Callback& callback) override { callback(std::error_code()); } void updateObservers(); Tools::ObserverManager<CryptoNote::INodeObserver> observerManager; }; class BlockchainConsumer : public IBlockchainConsumer { public: BlockchainConsumer(const Crypto::Hash& genesisBlockHash) { m_blockchain.push_back(genesisBlockHash); } void addPoolTransaction(const Crypto::Hash& hash) { m_pool.emplace(hash); } virtual SynchronizationStart getSyncStart() override { SynchronizationStart start = { 0, 0 }; return start; } virtual void addObserver(IBlockchainConsumerObserver* observer) override { } virtual void removeObserver(IBlockchainConsumerObserver* observer) override { } virtual void onBlockchainDetach(uint32_t height) override { assert(height < m_blockchain.size()); m_blockchain.resize(height); } virtual bool onNewBlocks(const CompleteBlock* blocks, uint32_t startHeight, uint32_t count) override { while (count--) { m_blockchain.push_back(blocks->blockHash); ++blocks; } return true; } const std::vector<Crypto::Hash>& getBlockchain() const { return m_blockchain; } virtual const std::unordered_set<Crypto::Hash>& getKnownPoolTxIds() const override { return m_pool; } virtual std::error_code onPoolUpdated(const std::vector<std::unique_ptr<ITransactionReader>>& addedTransactions, const std::vector<Crypto::Hash>& deletedTransactions) override { for (const auto& tx: addedTransactions) { m_pool.emplace(tx->getTransactionHash()); } for (auto& hash : deletedTransactions) { m_pool.erase(hash); } return std::error_code(); } std::error_code addUnconfirmedTransaction(const ITransactionReader& /*transaction*/) override { throw std::runtime_error("Not implemented"); } void removeUnconfirmedTransaction(const Crypto::Hash& /*transactionHash*/) override { throw std::runtime_error("Not implemented"); } private: std::unordered_set<Crypto::Hash> m_pool; std::vector<Crypto::Hash> m_blockchain; }; // constructor() TEST(BlockchainSynchronizer, 1) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer(node, genesisBlockHash); } // addConsumer() TEST(BlockchainSynchronizer, 2) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); BlockchainConsumer consumer(genesisBlockHash); blockchainSynchronizer.addConsumer(&consumer); } // removeConsumer() TEST(BlockchainSynchronizer, 3) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); BlockchainConsumer consumer(genesisBlockHash); blockchainSynchronizer.addConsumer(&consumer); ASSERT_TRUE(blockchainSynchronizer.removeConsumer(&consumer)); } // getConsumerState() TEST(BlockchainSynchronizer, 4) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); BlockchainConsumer consumer(genesisBlockHash); blockchainSynchronizer.addConsumer(&consumer); ASSERT_NO_THROW(blockchainSynchronizer.getConsumerState(&consumer)); } // getConsumerKnownBlocks() TEST(BlockchainSynchronizer, 5) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); BlockchainConsumer consumer(genesisBlockHash); blockchainSynchronizer.addConsumer(&consumer); std::vector<Crypto::Hash> blockHashes = blockchainSynchronizer.getConsumerKnownBlocks(consumer); ASSERT_EQ(1, blockHashes.size()); } // addUnconfirmedTransaction() TEST(BlockchainSynchronizer, 6) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); // add consumer BlockchainConsumer consumer(genesisBlockHash); blockchainSynchronizer.addConsumer(&consumer); // start blockchain synchronizer blockchainSynchronizer.start(); // add unconfirmed transaction Transaction transaction = getRandTransaction(); TransactionImpl transactionImpl(transaction); ASSERT_NO_THROW(blockchainSynchronizer.addUnconfirmedTransaction(transactionImpl)); } // removeUnconfirmedTransaction() TEST(BlockchainSynchronizer, 7) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); // add consumer BlockchainConsumer consumer(genesisBlockHash); blockchainSynchronizer.addConsumer(&consumer); // start blockchain synchronizer blockchainSynchronizer.start(); // add unconfirmed transaction Transaction transaction = getRandTransaction(); TransactionImpl transactionImpl(transaction); ASSERT_NO_THROW(blockchainSynchronizer.addUnconfirmedTransaction(transactionImpl)); Crypto::Hash transactionHash = getObjectHash(transaction); ASSERT_NO_THROW(blockchainSynchronizer.removeUnconfirmedTransaction(transactionHash)); } // start() TEST(BlockchainSynchronizer, 8) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); // add consumer BlockchainConsumer consumer(genesisBlockHash); blockchainSynchronizer.addConsumer(&consumer); // start blockchain synchronizer ASSERT_NO_THROW(blockchainSynchronizer.start()); } // stop() TEST(BlockchainSynchronizer, 9) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); // add consumer BlockchainConsumer consumer(genesisBlockHash); blockchainSynchronizer.addConsumer(&consumer); // start blockchain synchronizer ASSERT_NO_THROW(blockchainSynchronizer.start()); // stop blockchain synchronizer ASSERT_NO_THROW(blockchainSynchronizer.stop()); } // save() TEST(BlockchainSynchronizer, 10) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); // save blockchain synchronizer std::stringstream ss; ASSERT_NO_THROW(blockchainSynchronizer.save(ss)); } // load() TEST(BlockchainSynchronizer, 11) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); // save blockchain synchronizer std::stringstream ss; ASSERT_NO_THROW(blockchainSynchronizer.save(ss)); // load blockchain synchronizer blockchainSynchronizer.load(ss); } // localBlockchainUpdated() TEST(BlockchainSynchronizer, 12) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); uint32_t height = getRandUint32_t(); blockchainSynchronizer.localBlockchainUpdated(height); } // lastKnownBlockHeightUpdated() TEST(BlockchainSynchronizer, 13) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); uint32_t height = getRandUint32_t(); blockchainSynchronizer.lastKnownBlockHeightUpdated(height); } // poolChanged() TEST(BlockchainSynchronizer, 14) { Node node; Crypto::Hash genesisBlockHash = getRandHash(); BlockchainSynchronizer blockchainSynchronizer(node, genesisBlockHash); ASSERT_NO_THROW(blockchainSynchronizer.poolChanged()); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
34.907609
290
0.778219
[ "vector" ]
7e7cf7edf5cc7a098b3e313bc880af959431c061
10,441
cpp
C++
src/statement.cpp
holodnii/Mython-Interpreter
e06aa9fca3646c1d0ebadbe03fa6c0e34af97546
[ "MIT" ]
null
null
null
src/statement.cpp
holodnii/Mython-Interpreter
e06aa9fca3646c1d0ebadbe03fa6c0e34af97546
[ "MIT" ]
null
null
null
src/statement.cpp
holodnii/Mython-Interpreter
e06aa9fca3646c1d0ebadbe03fa6c0e34af97546
[ "MIT" ]
null
null
null
#include "statement.h" #include <iostream> #include <sstream> #include <utility> using namespace std; namespace ast{ using runtime::Closure; using runtime::Context; using runtime::ObjectHolder; namespace{ const string ADD_METHOD = "__add__"s; const string INIT_METHOD = "__init__"s; } VariableValue::VariableValue(const std::string& var_name) { dotted_ids_.push_back(var_name); } VariableValue::VariableValue(std::vector<std::string> dotted_ids) : dotted_ids_(std::move(dotted_ids)){ } ObjectHolder VariableValue::Execute(Closure& closure, [[maybe_unused]] Context& context){ auto found_object = closure.find(dotted_ids_.front()); if (found_object == closure.end()){ throw std::runtime_error("Not find variable"); } for (size_t i = 1; i < dotted_ids_.size(); ++i){ auto instance = found_object->second.TryAs<runtime::ClassInstance>(); Closure& fields = instance->Fields(); found_object = fields.find(dotted_ids_[i]); if (found_object == fields.end()) { throw std::runtime_error("Not find variable"); } } if (dotted_ids_.size() == 1){ return found_object->second; } return found_object->second; } Assignment::Assignment(std::string var_name, std::unique_ptr<Statement> rv) : var_name_(std::move(var_name)) , rv_(std::move(rv)) {} ObjectHolder Assignment::Execute(Closure& closure, Context& context){ auto found_object = closure.find(var_name_); if (found_object != closure.end()) { return found_object->second = rv_->Execute(closure, context); } auto [new_var, _] = closure.emplace(var_name_, rv_->Execute(closure, context)); return new_var->second; } FieldAssignment::FieldAssignment(VariableValue object, std::string field_name, std::unique_ptr<Statement> rv) : object_(std::move(object)) , field_name_(std::move(field_name)) , rv_(std::move(rv)) {} ObjectHolder FieldAssignment::Execute(Closure& closure, Context& context){ auto ex = object_.Execute(closure, context); auto instance = ex.TryAs<runtime::ClassInstance>(); Closure& fields = instance->Fields(); auto found_field = fields.find(field_name_); if (found_field != fields.end()) { return found_field->second = rv_->Execute(closure, context); } auto [new_field, _] = fields.emplace(field_name_, rv_->Execute(closure, context)); return new_field->second; } Print::Print(unique_ptr<Statement> argument) : args_() { args_.push_back(std::move(argument)); } Print::Print(vector<unique_ptr<Statement>> args) : args_(std::move(args)) {} unique_ptr<Print> Print::Variable(const std::string& name){ auto value = make_unique<VariableValue>(name); return make_unique<Print>(std::move(value)); } ObjectHolder Print::Execute(Closure& closure, Context& context){ ostream& out = context.GetOutputStream(); if (args_.empty()){ out << '\n'; return {}; } for (size_t i = 0; i < args_.size() - 1; ++i){ auto obj = args_[i]->Execute(closure, context); if (obj){ obj->Print(out, context); }else{ out << "None"s; } out << ' '; } auto obj = args_.back()->Execute(closure, context); if (obj){ obj->Print(out, context); }else{ out << "None"s; } out << '\n'; return {}; } ObjectHolder Stringify::Execute(Closure& closure, Context& context){ stringstream strm; auto obj = argument_->Execute(closure, context); if (obj){ obj->Print(strm, context); }else{ strm << "None"; } return runtime::ObjectHolder::Own(runtime::String(strm.str())); } MethodCall::MethodCall(std::unique_ptr<Statement> object, std::string method, std::vector<std::unique_ptr<Statement>> args) : object_(std::move(object)) , method_(std::move(method)) , args_(std::move(args)){ } ObjectHolder MethodCall::Execute(Closure& closure, Context& context){ auto obj = object_->Execute(closure, context); auto instance = obj.TryAs<runtime::ClassInstance>(); vector<ObjectHolder> actual_args; for (const auto& arg : args_){ auto temp_obj = arg->Execute(closure, context); actual_args.push_back(temp_obj); } return instance->Call(method_, actual_args, context); } ObjectHolder Add::Execute(Closure& closure, Context& context){ auto lhs = lhs_->Execute(closure, context); auto rhs = rhs_->Execute(closure, context); auto lhs_number = lhs.TryAs<runtime::Number>(); auto rhs_number = rhs.TryAs<runtime::Number>(); if (lhs_number != nullptr && rhs_number != nullptr){ int number = lhs_number->GetValue() + rhs_number->GetValue(); return runtime::ObjectHolder::Own(runtime::Number{number}); } auto lhs_string = lhs.TryAs<runtime::String>(); auto rhs_string = rhs.TryAs<runtime::String>(); if (lhs_string != nullptr && rhs_string != nullptr){ string str = lhs_string->GetValue() + rhs_string->GetValue(); return runtime::ObjectHolder::Own(runtime::String{std::move(str)}); } auto lhs_instance = lhs.TryAs<runtime::ClassInstance>(); if (lhs_instance != nullptr && lhs_instance->HasMethod(ADD_METHOD, 1)){ std::vector<ObjectHolder> actual_args = { rhs }; return lhs_instance->Call(ADD_METHOD, actual_args, context); } throw std::runtime_error("No __add__ method"s); } ObjectHolder Sub::Execute(Closure& closure, Context& context){ auto lhs = lhs_->Execute(closure, context); auto rhs = rhs_->Execute(closure, context); auto lhs_number = lhs.TryAs<runtime::Number>(); auto rhs_number = rhs.TryAs<runtime::Number>(); if (lhs_number != nullptr && rhs_number != nullptr){ int number = lhs_number->GetValue() - rhs_number->GetValue(); return runtime::ObjectHolder::Own(runtime::Number{number}); } throw std::runtime_error("lhs or rhs not Number"s); } ObjectHolder Mult::Execute(Closure& closure, Context& context){ auto lhs = lhs_->Execute(closure, context); auto rhs = rhs_->Execute(closure, context); auto lhs_number = lhs.TryAs<runtime::Number>(); auto rhs_number = rhs.TryAs<runtime::Number>(); if (lhs_number != nullptr && rhs_number != nullptr){ int number = lhs_number->GetValue() * rhs_number->GetValue(); return runtime::ObjectHolder::Own(runtime::Number{number}); } throw std::runtime_error("lhs or rhs not Number"s); } ObjectHolder Div::Execute(Closure& closure, Context& context){ auto lhs = lhs_->Execute(closure, context); auto rhs = rhs_->Execute(closure, context); auto lhs_number = lhs.TryAs<runtime::Number>(); auto rhs_number = rhs.TryAs<runtime::Number>(); if (lhs_number != nullptr && rhs_number != nullptr){ if (rhs_number->GetValue() == 0){ throw std::runtime_error("Division by zero"s); } int number = lhs_number->GetValue() / rhs_number->GetValue(); return runtime::ObjectHolder::Own(runtime::Number{number}); } throw std::runtime_error("lhs or rhs not Number"s); } ObjectHolder Or::Execute(Closure& closure, Context& context){ auto lhs = lhs_->Execute(closure, context); auto rhs = rhs_->Execute(closure, context); bool result = (runtime::IsTrue(lhs) || runtime::IsTrue(rhs)); return runtime::ObjectHolder::Own(runtime::Bool{result}); } ObjectHolder And::Execute(Closure& closure, Context& context){ auto lhs = lhs_->Execute(closure, context); auto rhs = rhs_->Execute(closure, context); bool result = (runtime::IsTrue(lhs) && runtime::IsTrue(rhs)); return runtime::ObjectHolder::Own(runtime::Bool{result}); } ObjectHolder Not::Execute(Closure& closure, Context& context){ auto arg = argument_->Execute(closure, context); bool result = !runtime::IsTrue(arg); return runtime::ObjectHolder::Own(runtime::Bool{result}); } ObjectHolder Compound::Execute(Closure& closure, Context& context){ for (const auto& stmt : statements_) { stmt->Execute(closure, context); } return {}; } MethodBody::MethodBody(std::unique_ptr<Statement>&& body) : body_(std::move(body)) {} ObjectHolder MethodBody::Execute(Closure& closure, Context& context){ try{ body_->Execute(closure, context); return runtime::ObjectHolder::None(); }catch(runtime::ObjectHolder& obj) { return obj; } } ObjectHolder Return::Execute(Closure& closure, Context& context){ throw statement_->Execute(closure, context); } ClassDefinition::ClassDefinition(ObjectHolder cls) : cls_(std::move(cls)) {} ObjectHolder ClassDefinition::Execute(Closure& closure, [[maybe_unused]] Context& context){ const auto obj_cls = cls_.TryAs<const runtime::Class>(); std::string name = obj_cls->GetName(); const auto [it, _] = closure.emplace(name, cls_); return it->second; } IfElse::IfElse(std::unique_ptr<Statement> condition, std::unique_ptr<Statement> if_body, std::unique_ptr<Statement> else_body) : condition_(std::move(condition)) , if_body_(std::move(if_body)) , else_body_(std::move(else_body)) {} ObjectHolder IfElse::Execute(Closure& closure, Context& context){ if (runtime::IsTrue(condition_->Execute(closure, context))){ return if_body_->Execute(closure, context); }else if (else_body_ != nullptr){ return else_body_->Execute(closure, context); }else{ return ObjectHolder::None(); } } Comparison::Comparison(Comparator cmp, unique_ptr<Statement> lhs, unique_ptr<Statement> rhs) : BinaryOperation(std::move(lhs), std::move(rhs)) , cmp_(std::move(cmp)) {} ObjectHolder Comparison::Execute(Closure& closure, Context& context){ auto lhs = lhs_->Execute(closure, context); auto rhs = rhs_->Execute(closure, context); bool result = cmp_(lhs, rhs, context); return runtime::ObjectHolder::Own(runtime::Bool{result}); } NewInstance::NewInstance(const runtime::Class& cls) : instance_(cls) {} NewInstance::NewInstance(const runtime::Class& cls, std::vector<std::unique_ptr<Statement>> args) : instance_(cls) , args_(std::move(args)) {} ObjectHolder NewInstance::Execute(Closure& closure, Context& context){ std::vector<ObjectHolder> actual_args; for (const auto& arg : args_){ actual_args.push_back(arg->Execute(closure, context)); } if (instance_.HasMethod(INIT_METHOD, actual_args.size())){ instance_.Call(INIT_METHOD, actual_args, context); } return ObjectHolder::Share(instance_); } }
31.074405
99
0.674456
[ "object", "vector" ]
7e8018ac3b074fe72a178dbc3aa00edeac9e3dd9
711
cpp
C++
nonrepeatingnumberwhileothernumbersrepeatktimes.cpp
procheta1999/dsaonechallenge
b89608f473c6dc164eeb33107563dd1b1e2e05c9
[ "MIT" ]
null
null
null
nonrepeatingnumberwhileothernumbersrepeatktimes.cpp
procheta1999/dsaonechallenge
b89608f473c6dc164eeb33107563dd1b1e2e05c9
[ "MIT" ]
null
null
null
nonrepeatingnumberwhileothernumbersrepeatktimes.cpp
procheta1999/dsaonechallenge
b89608f473c6dc164eeb33107563dd1b1e2e05c9
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int k; cin>>k; int num=0; vector<int> arr; vector<int> arr32(32,0); for(int i=0;i<n;i++) { int el; int x=0; cin>>el; arr.push_back(el); while(el) { if((el&1)==1) { arr32[x]++; } el=el>>1; x++; } } for(int i=0;i<arr32.size();i++) { arr32[i]=arr32[i]%k; } for(int i=0;i<arr32.size();i++) { if(arr32[i]==1) { num=num+pow(2,i); } } cout<<num<<endl; return 0; }
16.159091
38
0.367089
[ "vector" ]
7e89b56b05ef8ff6ec4e75bd8a1b1f101b5cdc7a
6,270
hxx
C++
src/mdtrec.hxx
re-Isearch/re-Isearch
f2a2012c1814b0940a6004b6186a5e6896c1135a
[ "BSD-4-Clause-UC", "Apache-2.0" ]
2
2022-02-05T17:48:29.000Z
2022-02-06T15:25:04.000Z
src/mdtrec.hxx
re-Isearch/re-Isearch
f2a2012c1814b0940a6004b6186a5e6896c1135a
[ "BSD-4-Clause-UC", "Apache-2.0" ]
null
null
null
src/mdtrec.hxx
re-Isearch/re-Isearch
f2a2012c1814b0940a6004b6186a5e6896c1135a
[ "BSD-4-Clause-UC", "Apache-2.0" ]
1
2022-03-30T20:14:00.000Z
2022-03-30T20:14:00.000Z
/* Copyright (c) 2020-21 Project re-Isearch and its contributors: See CONTRIBUTORS. It is made available and licensed under the Apache 2.0 license: see LICENSE */ /************************************************************************ ************************************************************************/ /*@@@ File: mdtrec.hxx Version: 1.00 Description: Class MDTREC - Multiple Document Table Record @@@*/ #ifndef MDTREC_HXX #define MDTREC_HXX #include "date.hxx" #include "pathname.hxx" #include "lang-codes.hxx" #include "mdthashtable.hxx" class MDT; class MDTREC { friend class MDT; friend class KEYREC; public: MDTREC(MDT *Mdt= NULL); MDTREC(const MDTREC& OtherMdtRec); MDTREC& operator=(const MDTREC& OtherMdtRec); void SetCategory(const _ib_category_t newCategory) { Category = newCategory; } _ib_category_t GetCategory() const { return Category; } void SetPriority(const _ib_priority_t newPriority) { Priority = newPriority; } _ib_priority_t GetPriority() const { return Priority; } GDT_BOOLEAN SetKey(const STRING& NewKey); STRING GetKey() const { return STRING().Assign (Key, DocumentKeySize);} STRING& GetKey(PSTRING Buffer) const { return Buffer->Assign (Key, DocumentKeySize);} void SetDocumentType(const DOCTYPE_ID &NewDoctypeId); void SetDocumentType(const STRING& NewDocumentType); DOCTYPE_ID GetDocumentType() const { DOCTYPE_ID Doctype; Doctype.Name.Assign (DocumentType, DocumentTypeSize); Doctype.Id = Property & 0x7F; return Doctype; } INT GetDocumentType(STRING *Buffer) const { if (Buffer) Buffer->Assign (DocumentType, DocumentTypeSize); return Property & 0x7F; } void SetPath(const STRING& NewPath); STRING GetPath() const; STRING& GetPath(STRING *Buffer) const { return *Buffer = GetPath(); } void SetFileName(const STRING& NewFileName); STRING GetFileName() const; STRING& GetFileName(STRING *Buffer) const { return *Buffer = GetFileName(); } void SetFullFileName(const STRING& NewFullPath); STRING GetFullFileName() const { return GetPath() + GetFileName(); } void SetOrigPath(const STRING& NewPathName); STRING GetOrigPath() const; void SetOrigFileName(const STRING& NewFileName); STRING GetOrigFileName() const; void SetOrigFullFileName(const STRING& NewFullPath); STRING GetOrigFullFileName() const { return GetOrigPath() + GetOrigFileName(); } STRING& GetFullFileName(STRING *Buffer) const { return *Buffer = GetFullFileName(); } PATHNAME GetPathname() const; PATHNAME GetOrigPathname() const; void SetPathname (const PATHNAME& Pathname); void SetOrigPathname (const PATHNAME& Pathname); void SetGlobalFileStart(const GPTYPE NewStart) { GlobalFileStart = NewStart; } GPTYPE GetGlobalFileStart() const { return GlobalFileStart; }; // For index import MDTREC& operator+=(const GPTYPE Offset) { IncrementStart(Offset); return *this;} void IncrementStart(GPTYPE x) { GlobalFileStart += x;} #if 0 void SetGlobalFileEnd(const GPTYPE NewEnd) { GlobalFileEnd = NewEnd; } GPTYPE GetGlobalFileEnd() const { return GlobalFileEnd; }; #endif // This gives us the record (document length) off_t GetLength() const { return LocalRecordEnd - LocalRecordStart; } void SetLocalRecordStart(const UINT4 NewStart) { LocalRecordStart = NewStart; } UINT4 GetLocalRecordStart() const { return LocalRecordStart; } void SetLocalRecordEnd(const UINT4 NewEnd) { LocalRecordEnd = NewEnd; } UINT4 GetLocalRecordEnd() const { return LocalRecordEnd; } void SetLocale(const LOCALE& NewLocale) { Locale = NewLocale; } LOCALE GetLocale() const { return Locale; } // We store the dates as a pair of 4-byte ints // Generic Date void SetDate(const SRCH_DATE& NewDate) { Date = NewDate; } SRCH_DATE GetDate() const { return Date; } // Modified Date void SetDateModified(const SRCH_DATE& NewDate) { if ((DateModified = NewDate).Ok() && Date.IsNotSet()) Date = DateModified; } SRCH_DATE GetDateModified() const { return DateModified; } // Date Created void SetDateCreated(const SRCH_DATE& NewDate) { if ((DateCreated = NewDate).Ok() && Date.IsNotSet()) Date = DateCreated; } SRCH_DATE GetDateCreated() const { return DateCreated; } // Date Expires void SetDateExpires(const SRCH_DATE& NewDate) { DateExpires = NewDate; } SRCH_DATE GetDateExpires() const { return DateExpires; } // Time To Live int TTL() const; int TTL(const SRCH_DATE& Now) const; void SetDeleted(const GDT_BOOLEAN Flag); GDT_BOOLEAN GetDeleted() const; void FlipBytes(); // In the structure read/write.. GDT_BOOLEAN Write(FILE *fp, INT Index = 0) const; GDT_BOOLEAN Read(FILE *fp, INT Index = 0); SRCH_DATE GetDate(FILE *fp, INT Index=0) const; // Is the MDT Index deleted? GDT_BOOLEAN IsDeleted(FILE *fp, INT Index); STRING Dump() const; friend ostream& operator<<(ostream& os, const MDTREC& mdtrec); void SetHashTable (MDTHASHTABLE *newHashTable) { HashTable = newHashTable; } ~MDTREC(); private: SRCH_DATE Date; // Date of Record (Must be first element!) /* This is an object we write so the types need to be well defined */ CHR Key[DocumentKeySize]; CHR DocumentType[DocumentTypeSize]; GPTYPE pathNameID; GPTYPE fileNameID; GPTYPE origpathNameID; GPTYPE origfileNameID; MDTHASHTABLE *HashTable; GPTYPE GlobalFileStart; UINT4 LocalRecordStart; UINT4 LocalRecordEnd; LOCALE Locale; _ib_category_t Category; _ib_priority_t Priority; SRCH_DATE DateModified; SRCH_DATE DateCreated; SRCH_DATE DateExpires; BYTE Property; // This MUST be the last element! }; typedef MDTREC* PMDTREC; // Common Functions inline void Write(const MDTREC& Mdtrec, PFILE Fp) { Mdtrec.Write(Fp); } inline GDT_BOOLEAN Read(PMDTREC MdtrecPtr, PFILE Fp) { return MdtrecPtr->Read(Fp); } #endif
29.857143
90
0.662679
[ "object" ]
7e90343c7c1d85f25d4d30b6e250d67df4c7eb84
1,066
cpp
C++
src/process.cpp
LucasSabbatini/udacity_cpp_system_monitor_project
537c25bdcd7e4199b2aefefff94bb833471bbe09
[ "MIT" ]
null
null
null
src/process.cpp
LucasSabbatini/udacity_cpp_system_monitor_project
537c25bdcd7e4199b2aefefff94bb833471bbe09
[ "MIT" ]
null
null
null
src/process.cpp
LucasSabbatini/udacity_cpp_system_monitor_project
537c25bdcd7e4199b2aefefff94bb833471bbe09
[ "MIT" ]
null
null
null
#include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include "process.h" #include "linux_parser.h" using std::string; using std::to_string; using std::vector; Process::Process(int pid) : _pid(pid) { _user = LinuxParser::User(_pid); _command = LinuxParser::Command(_pid); } float Process::CpuUtilization() { long int uptime = LinuxParser::UpTime(); vector<string> stat_data = LinuxParser::ParseStat(_pid); int utime = std::stoi(stat_data[0]); int stime = std::stoi(stat_data[1]); int starttime = std::stoi(stat_data[4]); float total_time = utime + stime; long int process_uptime = uptime - (starttime/sysconf(_SC_CLK_TCK)); // total time (active+ idle) float cpu_utilization = 100 * ((total_time/sysconf(_SC_CLK_TCK))/process_uptime); return cpu_utilization; } string Process::Ram() { return LinuxParser::Ram(_pid); } long int Process::UpTime() { return LinuxParser::UpTime(_pid); } #include <iostream> bool Process::operator<(Process a) { return this->CpuUtilization() > a.CpuUtilization(); }
27.333333
99
0.712946
[ "vector" ]
7ea79d685cc789654f41f3e7294c4a3fa7ccb57c
707
cpp
C++
239.cpp
ducthienbui97/Random-leetcode
209cbf537319875735b5dea876103f13eecef6d1
[ "MIT" ]
null
null
null
239.cpp
ducthienbui97/Random-leetcode
209cbf537319875735b5dea876103f13eecef6d1
[ "MIT" ]
null
null
null
239.cpp
ducthienbui97/Random-leetcode
209cbf537319875735b5dea876103f13eecef6d1
[ "MIT" ]
null
null
null
// Leetcode 239. Sliding Window Maximum class Solution { public: deque<int> slide; void insert(vector<int>&nums, int idx){ while(!slide.empty() && nums[slide.back()] < nums[idx]) slide.pop_back(); slide.push_back(idx); } void check(int k){ while(!slide.empty() && slide.back() - slide.front() >= k) slide.pop_front(); } vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> ans; for(int i = 0; i < nums.size(); i++){ insert(nums, i); check(k); if(i >= k - 1 && !slide.empty()) ans.push_back(nums[slide.front()]); } return ans; } };
28.28
66
0.506365
[ "vector" ]
7ea92b2d550fee9170668487f96dbe4c217650f6
6,409
cpp
C++
src/application/tools/app_report_settings_loader.cpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
177
2020-08-24T19:20:35.000Z
2022-03-27T01:58:04.000Z
src/application/tools/app_report_settings_loader.cpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
15
2020-08-30T17:59:42.000Z
2022-01-12T11:14:10.000Z
src/application/tools/app_report_settings_loader.cpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
11
2020-09-17T23:31:10.000Z
2022-03-04T13:15:21.000Z
#include "application/tools/app_report_settings_loader.hpp" #include "application/exceptions/app_incorrect_thousands_separator_impl.hpp" #include "application/tools/app_configuration_file.hpp" #include "application/tools/app_parser_arg_wrapper.hpp" #include "reporter/api/rp_factory.hpp" #include "reporter/api/rp_settings.hpp" #include "exception/ih/exc_internal_error.hpp" #include <memory> #include <vector> //------------------------------------------------------------------------------ namespace application { //------------------------------------------------------------------------------ ReportSettingsLoader::ReportSettingsLoader( reporter::Factory & _reporterFactory ) : m_reporterFactory{ _reporterFactory } { } //------------------------------------------------------------------------------ ReportSettingsLoader::SettingsPtr ReportSettingsLoader::load( const ParserArgWrapper & _arguments, const ConfigurationFile * _configurationFile ) { auto settingsPtr = createSettings(); INTERNAL_CHECK_WARRING( settingsPtr ); if( !settingsPtr ) { return nullptr; } reporter::Settings & settings = *settingsPtr; const auto maxFiles = loadMaxFilesCount( _arguments, _configurationFile ); const auto maxDetails = loadMaxDetailsCount( _arguments, _configurationFile ); const bool showStdFiles = loadShowStdFiles( _arguments, _configurationFile ); const bool showOnlyStdFiles = loadShowOnlyStdHeaders( _arguments, _configurationFile ); const bool showDetails = loadShowDetails( _arguments, _configurationFile ); const char separator = loadThousandsSeparator( _arguments, _configurationFile ); settings.setMaxFilesCount( maxFiles ); settings.setMaxDetailsCount( maxDetails ); settings.setThousandsSeparator( separator ); settings.setShowStdFiles( showStdFiles ); settings.setShowOnlyStdHeaders( showOnlyStdFiles ); settings.setShowDetails( showDetails ); if( showOnlyStdFiles ) settings.setShowStdFiles( true ); return settingsPtr; } //------------------------------------------------------------------------------ ReportSettingsLoader::ReporterKinds ReportSettingsLoader::loadReports( const ParserArgWrapper & _arguments, const ConfigurationFile * _configurationFile ) { if( auto reportsOpt = _arguments.getReporterKinds(); reportsOpt ) { return *reportsOpt; } if( _configurationFile != nullptr ) { if( auto kindOpt = _configurationFile->getReporterKinds(); kindOpt ) { return *kindOpt; } } return _arguments.getDefaultReporterKinds(); } //------------------------------------------------------------------------------ ReportSettingsLoader::SettingsPtr ReportSettingsLoader::createSettings() { return m_reporterFactory.createSettings(); } //------------------------------------------------------------------------------ ReportSettingsLoader::CountType ReportSettingsLoader::loadMaxFilesCount( const ParserArgWrapper & _arguments, const ConfigurationFile * _configurationFile ) { return getValue( _arguments, &ParserArgWrapper::getReportLimit, &ParserArgWrapper::getDefaultReportLimit, _configurationFile, &ConfigurationFile::getReportLimit ); } //------------------------------------------------------------------------------ ReportSettingsLoader::CountType ReportSettingsLoader::loadMaxDetailsCount( const ParserArgWrapper & _arguments, const ConfigurationFile * _configurationFile ) { return getValue( _arguments, &ParserArgWrapper::getReportDetailsLimit, &ParserArgWrapper::getDefaultReportDetailsLimit, _configurationFile, &ConfigurationFile::getReportDetailsLimit ); } //------------------------------------------------------------------------------ bool ReportSettingsLoader::loadShowStdFiles( const ParserArgWrapper & _arguments, const ConfigurationFile * _configurationFile ) { return getValue( _arguments, &ParserArgWrapper::getShowStdFile, &ParserArgWrapper::getDefaultShowStdFile, _configurationFile, &ConfigurationFile::getShowStdFiles ); } //------------------------------------------------------------------------------ bool ReportSettingsLoader::loadShowOnlyStdHeaders( const ParserArgWrapper & _arguments, const ConfigurationFile * _configurationFile ) { return getValue( _arguments, &ParserArgWrapper::getShowOnlyStdHeaders, &ParserArgWrapper::getDefaultShowOnlyStdHeaders, _configurationFile, &ConfigurationFile::getShowOnlyStdFiles ); } //------------------------------------------------------------------------------ bool ReportSettingsLoader::loadShowDetails( const ParserArgWrapper & _arguments, const ConfigurationFile * _configurationFile ) { return getValue( _arguments, &ParserArgWrapper::getShowDetails, &ParserArgWrapper::getDefaultShowDetails, _configurationFile, &ConfigurationFile::getShowDetails ); } //------------------------------------------------------------------------------ char ReportSettingsLoader::loadThousandsSeparator( const ParserArgWrapper & _arguments, const ConfigurationFile * _configurationFile ) { std::string result = getValue( _arguments, &ParserArgWrapper::getThousandsSeparator, &ParserArgWrapper::getDefaultThousandsSeparator, _configurationFile, &ConfigurationFile::getThousandsSeparator ); checkThousandsSeparator( result ); return result.at( 0 ); } //------------------------------------------------------------------------------ template< typename _ValueType > _ValueType ReportSettingsLoader::getValue( const ParserArgWrapper & _arguments, std::optional< _ValueType > ( ParserArgWrapper::*_getValueFromArg )() const, _ValueType ( ParserArgWrapper::*_getDefaultValueFromArg )() const, const ConfigurationFile * _configurationFile, std::optional< _ValueType > ( ConfigurationFile::*_getValueFromFile )() const ) { if( auto valueFromArgOpt = ( _arguments.*_getValueFromArg )(); valueFromArgOpt ) { return *valueFromArgOpt; } if( _configurationFile ) { auto valueFromFileOpt = ( *_configurationFile.*_getValueFromFile )(); if( valueFromFileOpt ) { return *valueFromFileOpt; } } return ( _arguments.*_getDefaultValueFromArg )(); } //------------------------------------------------------------------------------ void ReportSettingsLoader::checkThousandsSeparator( const std::string & _separator ) { if( _separator.size() != 1 ) throw IncorrectThousandsSeparatorImpl( _separator ); } //------------------------------------------------------------------------------ }
30.374408
80
0.655328
[ "vector" ]
7eaced5ee3cb996c2a2bc8fb4c94c5833b8370bb
747
cpp
C++
leetcode/5554.cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
107
2019-10-25T07:46:59.000Z
2022-03-29T11:10:56.000Z
leetcode/5554.cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
1
2021-08-13T05:42:27.000Z
2021-08-13T05:42:27.000Z
leetcode/5554.cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
18
2020-12-09T14:24:22.000Z
2022-03-30T06:56:01.000Z
// https://leetcode.com/contest/weekly-contest-213/problems/check-array-formation-through-concatenation/ #include <bits/stdc++.h> using namespace std; // Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]] class Solution { public: bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) { for (auto p : pieces) { auto i = find(arr.begin(), arr.end(), p[0]) - arr.begin(); auto j = find(arr.begin(), arr.end(), p[p.size() - 1]) - arr.begin(); if (i == arr.size() || j == arr.size()) return false; if (i > j) return false; for (int c = i; c <= j; c++) { if (arr[c] != p[c - i]) return false; } } return true; } };
37.35
104
0.515395
[ "vector" ]
9d1909344b710b9cb00d5f3fa441a54721af43b4
27,012
hpp
C++
SDK/PUBG_PhysXVehicles_classes.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
7
2019-03-06T11:04:52.000Z
2019-07-10T20:00:51.000Z
SDK/PUBG_PhysXVehicles_classes.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
null
null
null
SDK/PUBG_PhysXVehicles_classes.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
10
2019-03-06T11:53:46.000Z
2021-02-18T14:01:11.000Z
#pragma once // PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_PhysXVehicles_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class PhysXVehicles.WheeledVehicle // 0x0010 (0x0450 - 0x0440) class AWheeledVehicle : public APawn { public: class USkeletalMeshComponent* Mesh; // 0x0440(0x0008) (Edit, BlueprintVisible, ExportObject, BlueprintReadOnly, ZeroConstructor, DisableEditOnInstance, EditConst, InstancedReference, IsPlainOldData) class UWheeledVehicleMovementComponent* VehicleMovement; // 0x0448(0x0008) (Edit, BlueprintVisible, ExportObject, BlueprintReadOnly, ZeroConstructor, DisableEditOnInstance, EditConst, InstancedReference, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class PhysXVehicles.WheeledVehicle"); return ptr; } }; // Class PhysXVehicles.VehicleAnimInstance // 0x0568 (0x0900 - 0x0398) class UVehicleAnimInstance : public UAnimInstance { public: unsigned char UnknownData00[0x548]; // 0x0398(0x0548) MISSED OFFSET class UWheeledVehicleMovementComponent* WheeledVehicleMovementComponent; // 0x08E0(0x0008) (ExportObject, ZeroConstructor, Transient, InstancedReference, IsPlainOldData) bool bUseSupsensionInterpolation; // 0x08E8(0x0001) (Edit, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x3]; // 0x08E9(0x0003) MISSED OFFSET float VehicleSuspensionInterpSpeed_ContactUpwards; // 0x08EC(0x0004) (Edit, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float VehicleSuspensionInterpSpeed_Contact; // 0x08F0(0x0004) (Edit, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float VehicleSuspensionInterpSpeed_NoContact; // 0x08F4(0x0004) (Edit, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData02[0x8]; // 0x08F8(0x0008) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class PhysXVehicles.VehicleAnimInstance"); return ptr; } class AWheeledVehicle* GetVehicle(); }; // Class PhysXVehicles.WheeledVehicleMovementComponent // 0x0190 (0x0410 - 0x0280) class UWheeledVehicleMovementComponent : public UPawnMovementComponent { public: unsigned char bDeprecatedSpringOffsetMode : 1; // 0x0280(0x0001) (Edit) unsigned char UnknownData00[0x7]; // 0x0281(0x0007) MISSED OFFSET TArray<bool> TirePunctured; // 0x0288(0x0010) (Net, ZeroConstructor, Transient) TArray<struct FWheelSetup> WheelSetups; // 0x0298(0x0010) (Edit, ZeroConstructor) TArray<struct FVehicleAntiRollbarSetup> AntirollSetups; // 0x02A8(0x0010) (Edit, ZeroConstructor) float Mass; // 0x02B8(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float DragCoefficient; // 0x02BC(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float ChassisWidth; // 0x02C0(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float ChassisHeight; // 0x02C4(0x0004) (Edit, ZeroConstructor, IsPlainOldData) bool bReverseAsBrake; // 0x02C8(0x0001) (Edit, ZeroConstructor, IsPlainOldData) unsigned char UnknownData01[0x3]; // 0x02C9(0x0003) MISSED OFFSET float DragArea; // 0x02CC(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float EstimatedMaxEngineSpeed; // 0x02D0(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float MaxEngineRPM; // 0x02D4(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float DebugDragMagnitude; // 0x02D8(0x0004) (ZeroConstructor, Transient, IsPlainOldData) struct FVector InertiaTensorScale; // 0x02DC(0x000C) (Edit, IsPlainOldData) float MinNormalizedTireLoad; // 0x02E8(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float MinNormalizedTireLoadFiltered; // 0x02EC(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float MaxNormalizedTireLoad; // 0x02F0(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float MaxNormalizedTireLoadFiltered; // 0x02F4(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float ThresholdLongitudinalSpeed; // 0x02F8(0x0004) (Edit, ZeroConstructor, IsPlainOldData) int LowForwardSpeedSubStepCount; // 0x02FC(0x0004) (Edit, ZeroConstructor, IsPlainOldData) int HighForwardSpeedSubStepCount; // 0x0300(0x0004) (Edit, ZeroConstructor, IsPlainOldData) unsigned char UnknownData02[0x4]; // 0x0304(0x0004) MISSED OFFSET TArray<class UVehicleWheel*> Wheels; // 0x0308(0x0010) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Transient, DuplicateTransient) unsigned char UnknownData03[0x18]; // 0x0318(0x0018) MISSED OFFSET unsigned char bUseRVOAvoidance : 1; // 0x0330(0x0001) (Edit, BlueprintVisible) unsigned char UnknownData04[0x3]; // 0x0331(0x0003) MISSED OFFSET float RVOAvoidanceRadius; // 0x0334(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float RVOAvoidanceHeight; // 0x0338(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float AvoidanceConsiderationRadius; // 0x033C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float RVOSteeringStep; // 0x0340(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float RVOThrottleStep; // 0x0344(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) int AvoidanceUID; // 0x0348(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, EditConst, IsPlainOldData) struct FNavAvoidanceMask AvoidanceGroup; // 0x034C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, IsPlainOldData) struct FNavAvoidanceMask GroupsToAvoid; // 0x0350(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, IsPlainOldData) struct FNavAvoidanceMask GroupsToIgnore; // 0x0354(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, IsPlainOldData) float AvoidanceWeight; // 0x0358(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData) struct FVector PendingLaunchVelocity; // 0x035C(0x000C) (IsPlainOldData) unsigned char UnknownData05[0x4]; // 0x0368(0x0004) MISSED OFFSET struct FReplicatedVehicleState ReplicatedState; // 0x036C(0x0014) (Net, Transient, IsPlainOldData) unsigned char UnknownData06[0x4]; // 0x0380(0x0004) MISSED OFFSET float RawSteeringInput; // 0x0384(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float RawThrottleInput; // 0x0388(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float RawBrakeInput; // 0x038C(0x0004) (ZeroConstructor, Transient, IsPlainOldData) unsigned char bRawHandbrakeInput : 1; // 0x0390(0x0001) (Transient) unsigned char bRawGearUpInput : 1; // 0x0390(0x0001) (Transient) unsigned char bRawGearDownInput : 1; // 0x0390(0x0001) (Transient) unsigned char UnknownData07[0x3]; // 0x0391(0x0003) MISSED OFFSET float LastForwardInput; // 0x0394(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float LastRightInput; // 0x0398(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float LastHandbrakeInput; // 0x039C(0x0004) (ZeroConstructor, Transient, IsPlainOldData) int LastGear; // 0x03A0(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float SteeringInput; // 0x03A4(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float ThrottleInput; // 0x03A8(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float BrakeInput; // 0x03AC(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float HandbrakeInput; // 0x03B0(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float IdleBrakeInput; // 0x03B4(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float StopThreshold; // 0x03B8(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float WrongDirectionThreshold; // 0x03BC(0x0004) (Edit, ZeroConstructor, IsPlainOldData) struct FVehicleInputRate ThrottleInputRate; // 0x03C0(0x0008) (Edit) struct FVehicleInputRate BrakeInputRate; // 0x03C8(0x0008) (Edit) struct FVehicleInputRate HandbrakeInputRate; // 0x03D0(0x0008) (Edit) struct FVehicleInputRate SteeringInputRate; // 0x03D8(0x0008) (Edit) unsigned char bWasAvoidanceUpdated : 1; // 0x03E0(0x0001) (Transient) unsigned char UnknownData08[0x2F]; // 0x03E1(0x002F) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class PhysXVehicles.WheeledVehicleMovementComponent"); return ptr; } void SetUseAutoGears(bool bUseAuto); void SetThrottleInput(float* Throttle); void SetTargetGear(int* GearNum, bool* bImmediate); void SetSteeringInput(float* Steering); void SetHandbrakeInput(bool bNewHandbrake); void SetGroupsToIgnoreMask(struct FNavAvoidanceMask* GroupMask); void SetGroupsToIgnore(int* GroupFlags); void SetGroupsToAvoidMask(struct FNavAvoidanceMask* GroupMask); void SetGroupsToAvoid(int* GroupFlags); void SetGearUp(bool bNewGearUp); void SetGearDown(bool bNewGearDown); void SetBrakeInput(float* Brake); void SetAvoidanceGroupMask(struct FNavAvoidanceMask* GroupMask); void SetAvoidanceGroup(int* GroupFlags); void SetAvoidanceEnabled(bool bEnable); void ServerUpdateState(float* InSteeringInput, float* InThrottleInput, float* InBrakeInput, float* InHandbrakeInput, int* CurrentGear, uint32_t* Checksum); void OnRep_TirePunctured(TArray<bool>* LastTirePunctured); bool GetUseAutoGears(); int GetTargetGear(); float GetForwardSpeed(); float GetEngineRotationSpeed(); float GetEngineMaxRotationSpeed(); int GetCurrentGear(); }; // Class PhysXVehicles.WheeledVehicleMovementComponent4W // 0x0160 (0x0570 - 0x0410) class UWheeledVehicleMovementComponent4W : public UWheeledVehicleMovementComponent { public: unsigned char UnknownData00[0x88]; // 0x0410(0x0088) MISSED OFFSET struct FVehicleDifferential4WData DifferentialSetup; // 0x0498(0x001C) (Edit) unsigned char UnknownData01[0x4]; // 0x04B4(0x0004) MISSED OFFSET struct FVehicleTransmissionData TransmissionSetup; // 0x04B8(0x0030) (Edit) struct FRuntimeFloatCurve SteeringCurve; // 0x04E8(0x0078) (Edit) float AckermannAccuracy; // 0x0560(0x0004) (Edit, ZeroConstructor, IsPlainOldData) unsigned char UnknownData02[0xC]; // 0x0564(0x000C) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class PhysXVehicles.WheeledVehicleMovementComponent4W"); return ptr; } }; // Class PhysXVehicles.VehicleWheel // 0x00F8 (0x0128 - 0x0030) class UVehicleWheel : public UObject { public: class UStaticMesh* CollisionMesh; // 0x0030(0x0008) (Edit, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool bDontCreateShape; // 0x0038(0x0001) (Edit, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool bAutoAdjustCollisionSize; // 0x0039(0x0001) (Edit, ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x2]; // 0x003A(0x0002) MISSED OFFSET struct FVector Offset; // 0x003C(0x000C) (Edit, IsPlainOldData) float ShapeRadius; // 0x0048(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float ShapeWidth; // 0x004C(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float Mass; // 0x0050(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float DampingRate; // 0x0054(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float SteerAngle; // 0x0058(0x0004) (Edit, ZeroConstructor, IsPlainOldData) bool bAffectedByHandbrake; // 0x005C(0x0001) (Edit, ZeroConstructor, IsPlainOldData) unsigned char UnknownData01[0x3]; // 0x005D(0x0003) MISSED OFFSET class UTireType* TireType; // 0x0060(0x0008) (ZeroConstructor, IsPlainOldData) class UTireConfig* TireConfig; // 0x0068(0x0008) (Edit, ZeroConstructor, IsPlainOldData) float LatStiffMaxLoad; // 0x0070(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float LatStiffValue; // 0x0074(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float LongStiffValue; // 0x0078(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float SuspensionForceOffset; // 0x007C(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float SuspensionForceOffsetX; // 0x0080(0x0004) (Edit, ZeroConstructor, IsPlainOldData) struct FVector SuspensionTravelDir; // 0x0084(0x000C) (Edit, IsPlainOldData) struct FVector TireForceOffset; // 0x0090(0x000C) (Edit, IsPlainOldData) float SuspensionMaxRaise; // 0x009C(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float SuspensionMaxDrop; // 0x00A0(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float SuspensionNaturalFrequency; // 0x00A4(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float SuspensionDampingRatio; // 0x00A8(0x0004) (Edit, ZeroConstructor, IsPlainOldData) struct FWheelDetailedConfig WheelDetailedConfig; // 0x00AC(0x0014) (Edit) float MaxBrakeTorque; // 0x00C0(0x0004) (Edit, ZeroConstructor, IsPlainOldData) float MaxHandBrakeTorque; // 0x00C4(0x0004) (Edit, ZeroConstructor, IsPlainOldData) TEnumAsByte<ECollisionChannel> QueryChannel; // 0x00C8(0x0001) (Edit, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData02[0x7]; // 0x00C9(0x0007) MISSED OFFSET class UWheeledVehicleMovementComponent* VehicleSim; // 0x00D0(0x0008) (ExportObject, ZeroConstructor, Transient, InstancedReference, IsPlainOldData) int WheelIndex; // 0x00D8(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float DebugLongSlip; // 0x00DC(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float DebugLatSlip; // 0x00E0(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float DebugNormalizedTireLoad; // 0x00E4(0x0004) (ZeroConstructor, Transient, IsPlainOldData) unsigned char UnknownData03[0x4]; // 0x00E8(0x0004) MISSED OFFSET float DebugWheelTorque; // 0x00EC(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float DebugLongForce; // 0x00F0(0x0004) (ZeroConstructor, Transient, IsPlainOldData) float DebugLatForce; // 0x00F4(0x0004) (ZeroConstructor, Transient, IsPlainOldData) struct FVector Location; // 0x00F8(0x000C) (Transient, IsPlainOldData) struct FVector OldLocation; // 0x0104(0x000C) (Transient, IsPlainOldData) struct FVector Velocity; // 0x0110(0x000C) (Transient, IsPlainOldData) float RealWheelRotationSpeed; // 0x011C(0x0004) (ZeroConstructor, Transient, IsPlainOldData) unsigned char UnknownData04[0x8]; // 0x0120(0x0008) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class PhysXVehicles.VehicleWheel"); return ptr; } bool IsInAir(); float GetSuspensionOffset(); float GetSteerAngle(); float GetRotationAngle(); float GetLongitudinalSlip(); float GetLateralSlip(); }; // Class PhysXVehicles.TireConfig // 0x0050 (0x0088 - 0x0038) class UTireConfig : public UDataAsset { public: float FrictionScale; // 0x0038(0x0004) (Edit, ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x003C(0x0004) MISSED OFFSET TArray<struct FTireConfigMaterialFriction> TireFrictionScales; // 0x0040(0x0010) (Edit, ZeroConstructor) unsigned char UnknownData01[0x8]; // 0x0050(0x0008) MISSED OFFSET struct FTireConfigFrictionVsSlipGraph FrictionVsSlipConfig; // 0x0058(0x0028) (Edit) bool bOverrideCamberStiffness; // 0x0080(0x0001) (Edit, ZeroConstructor, IsPlainOldData) unsigned char UnknownData02[0x3]; // 0x0081(0x0003) MISSED OFFSET float CamberStiffnessOverride; // 0x0084(0x0004) (Edit, ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class PhysXVehicles.TireConfig"); return ptr; } }; // Class PhysXVehicles.SimpleWheeledVehicleMovementComponent // 0x0000 (0x0410 - 0x0410) class USimpleWheeledVehicleMovementComponent : public UWheeledVehicleMovementComponent { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class PhysXVehicles.SimpleWheeledVehicleMovementComponent"); return ptr; } void SetUseAutoGears(bool bUseAuto); void SetThrottleInput(float* Throttle); void SetTargetGear(int* GearNum, bool* bImmediate); void SetSteeringInput(float* Steering); void SetHandbrakeInput(bool bNewHandbrake); void SetGroupsToIgnoreMask(struct FNavAvoidanceMask* GroupMask); void SetGroupsToIgnore(int* GroupFlags); void SetGroupsToAvoidMask(struct FNavAvoidanceMask* GroupMask); void SetGroupsToAvoid(int* GroupFlags); void SetGearUp(bool bNewGearUp); void SetGearDown(bool bNewGearDown); void SetBrakeInput(float* Brake); void SetAvoidanceGroupMask(struct FNavAvoidanceMask* GroupMask); void SetAvoidanceGroup(int* GroupFlags); void SetAvoidanceEnabled(bool bEnable); void ServerUpdateState(float* InSteeringInput, float* InThrottleInput, float* InBrakeInput, float* InHandbrakeInput, int* CurrentGear, uint32_t* Checksum); void OnRep_TirePunctured(TArray<bool>* LastTirePunctured); bool GetUseAutoGears(); int GetTargetGear(); float GetForwardSpeed(); float GetEngineRotationSpeed(); float GetEngineMaxRotationSpeed(); int GetCurrentGear(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
84.677116
272
0.485303
[ "mesh" ]
9d19d06093ed16e4704792209399eb4f12191782
2,608
cpp
C++
Computer Vision/KL.cpp
yashgandhijee2018/Applications-of-C-
7c030f9bf7b748aa8227b987db0b398f6d500b96
[ "MIT" ]
null
null
null
Computer Vision/KL.cpp
yashgandhijee2018/Applications-of-C-
7c030f9bf7b748aa8227b987db0b398f6d500b96
[ "MIT" ]
null
null
null
Computer Vision/KL.cpp
yashgandhijee2018/Applications-of-C-
7c030f9bf7b748aa8227b987db0b398f6d500b96
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define mod 1000000007 #define small INT_MIN #define large INT_MAX #define inl long long #define ll long long #define ld long double #define lli long long int #define rep(i,n) for(ll i=0;i<n;i++) #define f(i,a,b) for(ll i=(ll)a;i<(ll)b;i++) #define rep2(i,j,n) rep(i,n) rep(j,n) #define pb push_back #define mp make_pair #define ff first #define ss second #define pii pair<int,int> #define pll pair<ll,ll> #define vi vector<int> #define vl vector<ll> #define vpi vector<pii> #define vpl vector<pll> #define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); using namespace std; class matrix { public: ll dim=2; ld M[2][2]; void find_covar_matrix(pll px,ld col,ld row) { ld c=(ld)px.ff-col; ld r=(ld)px.ss-row; M[0][0]=c*c; M[0][1]=c*r; M[1][0]=r*c; M[1][1]=r*r; } void print_covar_matrix() { rep(i,dim) { rep(j,dim)cout<<setw(10)<<setprecision(4)<<M[i][j]; cout<<endl; } } }; void fun() { cout<<"\nDimensions:"; ll n;cin>>n; ll img[n][n]; ll sum_row=0,sum_col=0; ld avg_row,avg_col; cout<<"\nEnter Image:\n"; vector<pll> v; rep2(i,j,n) { cin>>img[i][j]; if(img[i][j]!=0) { v.pb({j,n-i-1}); sum_row+=n-i-1; sum_col+=j; } } avg_row=(ld)sum_row/(ld)n; avg_col=(ld)sum_col/(ld)n; cout<<"\nAverage matrix: { "<<avg_col<<" , "<<avg_row<<" }\n"; ll total_on_pixels=v.size(); cout<<total_on_pixels; cout<<"\nDark Pixels:\n"; rep(i,total_on_pixels)cout<<"("<<v[i].ff<<","<<v[i].ss<<") "; matrix* arr[total_on_pixels*10]; ld covar_matrix[2][2]={}; rep(i,total_on_pixels) { matrix m; arr[i]=&m; (*arr[i]).find_covar_matrix(v[i],avg_col,avg_row); cout<<"\nCovar matrix "<<i<<":\n"; (*arr[i]).print_covar_matrix(); fflush(stdin); rep2(j,k,2) { covar_matrix[i][j]=covar_matrix[i][j]+(abs)((*arr[i]).M[i][j]); } } rep2(i,j,2)covar_matrix[i][j]/=(ld)n; cout<<"\nFinal Covariance Matrix:\n"; rep(i,2) { rep(j,2)cout<<setw(10)<<setprecision(4)<<covar_matrix[i][j]; cout<<endl; } } int main() { ll t;cin>>t; while(t--) { fun();cout<<endl; } return 0; }
22.101695
77
0.488113
[ "vector" ]
9d1b0b6b825a25ccc3c051602ae9dc3a5b338aa0
10,191
cpp
C++
src/audio/sndlistener.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/audio/sndlistener.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/audio/sndlistener.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file sndlistener.cpp * @brief Implementation of SndListener.h * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2003-04-11 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/audio/precompiled.h" #include "o3d/audio/sndlistener.h" #include "o3d/audio/audiotype.h" #include "o3d/audio/audio.h" #include "o3d/audio/audiorenderer.h" #include "o3d/engine/primitive/primitivemanager.h" #include "o3d/engine/context.h" #include "o3d/engine/matrix.h" #include "o3d/engine/scene/scene.h" #include "o3d/engine/hierarchy/hierarchytree.h" #include "o3d/engine/object/camera.h" using namespace o3d; O3D_IMPLEMENT_DYNAMIC_CLASS1(SndListener, AUDIO_SND_LISTENER, SceneObject) // Get the drawing type UInt32 SndListener::getDrawType() const { return Scene::DRAW_SND_LISTENER; } SndListener::SndListener(BaseObject *parent) : SceneObject(parent), m_gain(1.f), m_velocity(0.f,0.f,0.f), m_orientationAt(0.f,0.f,-1.f), m_orientationUp(0.f,1.f,0.f), m_modifiermodel(False), m_modifiedEAX(False), m_oldGain(-1.f) { setDrawable(True); setUpdatable(True); setGenericEnv(); } SndListener::~SndListener() { } // set to generic default environment void SndListener::setGenericEnv() { // set the generic EAX environment settings // there are here for none EAX availability for the compatibilities with EAX availability // and for the serialization #ifdef O3D_EFX m_EAX.dwEnvironment = EAX_ENVIRONMENT_GENERIC; m_EAX.dwFlags = EAXLISTENERFLAGS_DECAYTIMESCALE | EAXLISTENERFLAGS_REFLECTIONSSCALE | EAXLISTENERFLAGS_REFLECTIONSDELAYSCALE | EAXLISTENERFLAGS_REVERBSCALE | EAXLISTENERFLAGS_REVERBDELAYSCALE | EAXLISTENERFLAGS_DECAYHFLIMIT; m_EAX.flAirAbsorptionHF = EAXLISTENER_DEFAULTAIRABSORPTIONHF; m_EAX.flDecayHFRatio = EAXLISTENER_DEFAULTDECAYHFRATIO; m_EAX.flDecayTime = EAXLISTENER_DEFAULTDECAYTIME; m_EAX.flEnvironmentDiffusion = EAXLISTENER_DEFAULTENVIRONMENTDIFFUSION; m_EAX.flEnvironmentSize = EAXLISTENER_DEFAULTENVIRONMENTSIZE; m_EAX.flReflectionsDelay = EAXLISTENER_DEFAULTREFLECTIONSDELAY; m_EAX.flReverbDelay = EAXLISTENER_DEFAULTREVERBDELAY; m_EAX.flRoomRolloffFactor = EAXLISTENER_DEFAULTROOMROLLOFFFACTOR; m_EAX.lReflections = EAXLISTENER_DEFAULTREFLECTIONS; m_EAX.lReverb = EAXLISTENER_DEFAULTREVERB; m_EAX.lRoom = EAXLISTENER_DEFAULTROOM; m_EAX.lRoomHF = EAXLISTENER_DEFAULTROOMHF; #else m_EAX.dwEnvironment = 0; m_EAX.dwFlags = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20; m_EAX.flAirAbsorptionHF = -5.0f; m_EAX.flDecayHFRatio = 0.83f; m_EAX.flDecayTime = 1.49f; m_EAX.flEnvironmentDiffusion = 1.0f; m_EAX.flEnvironmentSize = 7.5f; m_EAX.flReflectionsDelay = 0.007f; m_EAX.flReverbDelay = 0.011f; m_EAX.flRoomRolloffFactor = 0.0f; m_EAX.lReflections = -2602; m_EAX.lReverb = 200; m_EAX.lRoom = -1000; m_EAX.lRoomHF = -100; #endif m_modifiermodel = True; m_modifiedEAX = True; } // set an environment model void SndListener::setEnvModel(O3DEAX_EnvModel envmodel) { if (envmodel < EAX_EnvironnementCount) { if (envmodel != (Int32)m_EAX.dwEnvironment) { m_EAX.dwEnvironment = envmodel; m_modifiermodel = m_modifiedEAX = True; } } else { O3D_ERROR(E_InvalidParameter("envmodel")); } } // update the absolute position of the listener void SndListener::update() { O3D_ASSERT(m_node); clearUpdated(); if (m_node && m_node->hasUpdated()) { m_orientationUp = m_node->getAbsoluteMatrix().getY(); m_orientationAt = -m_node->getAbsoluteMatrix().getZ(); setUpdated(); } } // setup OpenAL parameters void SndListener::put() { if (hasUpdated()) { if (m_node) alListenerfv(AL_POSITION, m_node->getAbsoluteMatrix().getTranslationPtr()); alListenerfv(AL_VELOCITY, m_velocity.getData()); Float tmp[6]; tmp[0] = m_orientationAt[X]; tmp[1] = m_orientationAt[Y]; tmp[2] = m_orientationAt[Z]; tmp[3] = m_orientationUp[X]; tmp[4] = m_orientationUp[Y]; tmp[5] = m_orientationUp[Z]; alListenerfv(AL_ORIENTATION, tmp); alListenerf(AL_GAIN, m_gain); } #ifdef O3D_EFX // put EAX listener settings if (m_modifiedEAX && getScene()->getAudio()->renderer()->isEAX()) { if (m_modifiermodel) { unsigned long EAXVal = m_EAX.dwEnvironment; alEAXSet(&DSPROPSETID_EAX_ListenerProperties,DSPROPERTY_EAXLISTENER_ENVIRONMENT,0,&EAXVal, sizeof(unsigned long)); } else { Bool undo = False; if (m_EAX.dwEnvironment == EAX_Personalised) { m_EAX.dwEnvironment = EAX_Generic; undo = True; } alEAXSet(&DSPROPSETID_EAX_ListenerProperties,DSPROPERTY_EAXLISTENER_ALLPARAMETERS,0,&m_EAX, sizeof(EAXLISTENERPROPERTIES)); if (undo) m_EAX.dwEnvironment = EAX_Personalised; } // commit deferred setting to EAX //alEAXSet(&DSPROPSETID_EAX20_ListenerProperties, // DSPROPERTY_EAXLISTENER_COMMITDEFERREDSETTINGS,0,nullptr,0); // get all settings (useful for know value when there is size scale flag active) alEAXGet(&DSPROPSETID_EAX_ListenerProperties,DSPROPERTY_EAXLISTENER_ALLPARAMETERS,0,&m_EAX, sizeof(EAXLISTENERPROPERTIES)); } #endif } // Setup the modelview matrix to OpenGL void SndListener::setUpModelView() { O3D_ASSERT(getScene()->getActiveCamera() != nullptr); if (m_node) getScene()->getContext()->modelView().set( getScene()->getActiveCamera()->getModelviewMatrix() * m_node->getAbsoluteMatrix()); else getScene()->getContext()->modelView().set(getScene()->getActiveCamera()->getModelviewMatrix()); } // draw a symbolic representation of a listener void SndListener::draw(const DrawInfo &drawInfo) { if (!getActivity() || !getVisibility()) { return; } if ((drawInfo.pass == DrawInfo::AMBIENT_PASS/*SymbolicPass*/) && getScene()->getDrawObject(Scene::DRAW_SND_LISTENER)) { // if it is m_IsVisible draw its symbolic setUpModelView(); PrimitiveAccess primitive = getScene()->getPrimitiveManager()->access(drawInfo); if (getScene()->getDrawObject(Scene::DRAW_LOCAL_AXIS)) { primitive->drawLocalAxis(); } primitive->setColor(1.0f,0.0f,1.0f); primitive->draw(PrimitiveManager::WIRE_CUBE1, Vector3(3.0f,1.0f,1.0f)); } } // These flags determine what properties are affected by environment size // set/get flags state #ifndef O3D_EFX #define EAXLISTENERFLAGS_DECAYTIMESCALE 0x00000001 #define EAXLISTENERFLAGS_REFLECTIONSSCALE 0x00000002 #define EAXLISTENERFLAGS_REFLECTIONSDELAYSCALE 0x00000004 #define EAXLISTENERFLAGS_REVERBSCALE 0x00000008 #define EAXLISTENERFLAGS_REVERBDELAYSCALE 0x00000010 #define EAXLISTENERFLAGS_DECAYHFLIMIT 0x00000020 #endif // !O3D_EFX void SndListener::setEnvSizeFlag(O3DEAX_EnvSizeFlags flag,Bool b) { switch (flag) { case EAX_DecayTime: if (b) m_EAX.dwFlags |= EAXLISTENERFLAGS_DECAYTIMESCALE; else m_EAX.dwFlags &= m_EAX.dwFlags ^ EAXLISTENERFLAGS_DECAYTIMESCALE; break; case EAX_Reflection: if (b) m_EAX.dwFlags |= EAXLISTENERFLAGS_REFLECTIONSSCALE; else m_EAX.dwFlags &= m_EAX.dwFlags ^ EAXLISTENERFLAGS_REFLECTIONSSCALE; break; case EAX_ReflectionDelay: if (b) m_EAX.dwFlags |= EAXLISTENERFLAGS_REFLECTIONSDELAYSCALE; else m_EAX.dwFlags &= m_EAX.dwFlags ^ EAXLISTENERFLAGS_REFLECTIONSDELAYSCALE; break; case EAX_Reverb: if (b) m_EAX.dwFlags |= EAXLISTENERFLAGS_REVERBSCALE; else m_EAX.dwFlags &= m_EAX.dwFlags ^ EAXLISTENERFLAGS_REVERBSCALE; break; case EAX_ReverbDelay: if (b) m_EAX.dwFlags |= EAXLISTENERFLAGS_REVERBDELAYSCALE; else m_EAX.dwFlags &= m_EAX.dwFlags ^ EAXLISTENERFLAGS_REVERBDELAYSCALE; break; case EAX_DecayLimit: if (b) m_EAX.dwFlags |= EAXLISTENERFLAGS_DECAYHFLIMIT; else m_EAX.dwFlags &= m_EAX.dwFlags ^ EAXLISTENERFLAGS_DECAYHFLIMIT; break; default: O3D_ERROR(E_InvalidParameter("flag")); return; } m_modifiedEAX = True; m_EAX.dwEnvironment = (Int32)EAX_Personalised; } Bool SndListener::getEnvSizeFlag(O3DEAX_EnvSizeFlags flag)const { switch (flag) { case EAX_DecayTime: return m_EAX.dwFlags & EAXLISTENERFLAGS_DECAYTIMESCALE; case EAX_Reflection: return m_EAX.dwFlags & EAXLISTENERFLAGS_REFLECTIONSSCALE; case EAX_ReflectionDelay: return m_EAX.dwFlags & EAXLISTENERFLAGS_REFLECTIONSDELAYSCALE; case EAX_Reverb: return m_EAX.dwFlags & EAXLISTENERFLAGS_REVERBSCALE; case EAX_ReverbDelay: return m_EAX.dwFlags & EAXLISTENERFLAGS_REVERBDELAYSCALE; case EAX_DecayLimit: return m_EAX.dwFlags & EAXLISTENERFLAGS_DECAYHFLIMIT; default: O3D_ERROR(E_InvalidParameter("flag")); return False; } } // serialization Bool SndListener::writeToFile(OutStream &os) { SceneObject::writeToFile(os); os << m_gain << m_velocity; if (((Audio*)getScene()->getAudio())->getActiveListener() == this) os << True; // EAX settings os << (UInt32)m_EAX.dwEnvironment << (UInt32)m_EAX.dwFlags << m_EAX.flAirAbsorptionHF << m_EAX.flDecayHFRatio << m_EAX.flDecayTime << m_EAX.flEnvironmentDiffusion << m_EAX.flEnvironmentSize << m_EAX.flReflectionsDelay << m_EAX.flReverbDelay << m_EAX.flRoomRolloffFactor << (Int32)m_EAX.lReflections << (Int32)m_EAX.lReverb << (Int32)m_EAX.lRoom << (Int32)m_EAX.lRoomHF; return True; } Bool SndListener::readFromFile(InStream &is) { SceneObject::readFromFile(is); is >> m_gain >> m_velocity; Bool current; is >> current; if (current) ((Audio*)getScene()->getAudio())->setActiveListener(this); // eax settings UInt32 uintulong; Int32 intlong; is >> uintulong; m_EAX.dwEnvironment = (UInt32)uintulong; is >> uintulong; m_EAX.dwFlags = (UInt32)uintulong; is >> m_EAX.flAirAbsorptionHF >> m_EAX.flDecayHFRatio >> m_EAX.flDecayTime >> m_EAX.flEnvironmentDiffusion >> m_EAX.flEnvironmentSize >> m_EAX.flReflectionsDelay >> m_EAX.flReverbDelay >> m_EAX.flRoomRolloffFactor; is >> intlong; m_EAX.lReflections = (Int32)intlong; is >> intlong; m_EAX.lReverb = (Int32)intlong; is >> intlong; m_EAX.lRoom = (Int32)intlong; is >> intlong; m_EAX.lRoomHF = (Int32)intlong; m_modifiedEAX = True; if (m_EAX.dwEnvironment != EAX_Personalised) m_modifiermodel = True; return True; } void SndListener::postImportPass() { }
27.103723
123
0.744382
[ "object", "model" ]
9d1d8ad4577f96cb3f3bab59ccf0c0e3d3cd5f7b
6,435
cpp
C++
Assignments/Final_Project/src2/main.cpp
CaoSY/PittCompMethods
853c36676df140eecd249bd9905eb9fa704f1585
[ "MIT" ]
null
null
null
Assignments/Final_Project/src2/main.cpp
CaoSY/PittCompMethods
853c36676df140eecd249bd9905eb9fa704f1585
[ "MIT" ]
null
null
null
Assignments/Final_Project/src2/main.cpp
CaoSY/PittCompMethods
853c36676df140eecd249bd9905eb9fa704f1585
[ "MIT" ]
null
null
null
#include <charmonia.h> #include <visual.h> #include <iostream> #include <string> #include <vector> #include <iomanip> #include <algorithm> #include <memory> #include <sstream> #include <QApplication> #include <QToolBar> #include <QAction> #include <QTextEdit> #include <QFont> #include <QatPlotWidgets/MultipleViewWindow.h> #include <QatPlotWidgets/MultipleViewWidget.h> #include <QatPlotWidgets/CustomRangeDivider.h> #include <QatPlotting/PlotProfile.h> #include <QatPlotting/PlotStream.h> #include <QatPlotting/PlotText.h> typedef std::unique_ptr<PlotFunction1D> PF1D_Ptr; typedef std::unique_ptr<PlotProfile> PP_Ptr; typedef std::unique_ptr<MultipleViewWidget> MVW_Ptr; typedef std::unique_ptr<PlotText> PT_Ptr; bool JPCOrder(const Charmonia::State& a, const Charmonia::State& b) { return a.JPC < b.JPC; } int main(int argc, char **argv) { const double rMax = 15; const int matrixSize = 500; const double halfWidth = 0.25; std::vector<Charmonia::State> states = { {1, 0, 0, 0, 2983.4, "0-+", "ηc(1S)"}, {1, 0, 1, 1, 3096.9, "1--", "J/ψ(1S)"}, {2, 0, 0, 0, 3639.2, "0-+", "ηc(2S)"}, {2, 0, 1, 1, 3686.10, "1--", "ψ(2S)"}, {1, 2, 1, 1, 3770, "1--", "ψ(3770)"}, {3, 0, 1, 1, 4040, "1--", "ψ(4040)"}, {2, 2, 1, 1, 4160, "1--", "ψ(4160)"}, {1, 1, 1, 0, 3414.75, "0++", "χc0(1P)"}, {1, 1, 1, 1, 3510.66, "1++", "χc1(1P)"}, {1, 1, 1, 2, 3556.20, "2++", "χc2(1P)"}, {1, 1, 0, 1, 3525.38, "1+-", "hc(1P)"}, {2, 1, 1, 0, 3860, "0++", "χc0(2P)"}, {2, 1, 1, 1, 3871.69, "1++", "χc1(2P)"}, {2, 1, 1, 0, 3927.20, "2++", "χc2(2P)"}, {1, 2, 1, 2, 3822.2, "2--", "ψ(3823)"}, {4, 0, 1, 1, 4421, "1--", "ψ(4415)"}, }; std::vector<Charmonia> charmStates; for (size_t i = 0; i < states.size(); i++) { charmStates.push_back(Charmonia(states[i], matrixSize, rMax)); } for (size_t i = 0; i < charmStates.size(); i++) { std::cout << "(N,L,S,J)=(" << states[i].N << "," << states[i].L << "," << states[i].S << "," << states[i].J << ",) " << "mass=" << std::setprecision(5) << std::setw(7) << charmStates[i].Mass() << "MeV, " << "fs=" << std::setprecision(5) << std::setw(7) << charmStates[i].fsCorrection() << "MeV, " << "err=" << std::setprecision(5) << std::setw(7) << std::abs(charmStates[i].Mass() - states[i].mass) << "MeV" << std::endl; } QApplication app(argc, argv); MultipleViewWindow window; QToolBar *toolBar=window.addToolBar("Tools"); QAction *quitAction=toolBar->addAction("Quit"); quitAction->setShortcut(QKeySequence("q")); QObject::connect(quitAction, SIGNAL(triggered()), &app, SLOT(quit())); std::vector<std::string> rowLabels = {"0-+", "1--", "1+-", "0++", "1++", "2++", "2--"}; CustomRangeDivider xDivider; QTextEdit edit; PlotStream xStream(&edit); xStream << PlotStream::Size(24) << PlotStream::Family("Times New Roman") << "J" << PlotStream::Super() << "PC" << PlotStream::Normal() << "=" << PlotStream::EndP(); xDivider.add(-0.5, edit.document()->clone()); for (size_t i = 0; i < rowLabels.size(); i++) { xStream << PlotStream::Clear() << rowLabels[i].substr(0,1) << PlotStream::Super() << rowLabels[i].substr(1,2) << PlotStream::Normal() << PlotStream::EndP(); xDivider.add(i, edit.document()->clone()); } std::vector<PF1D_Ptr> experLevels; std::vector<PT_Ptr> stateTexts; for (size_t i = 0; i < states.size(); i++) { size_t rowNum = std::find(rowLabels.begin(), rowLabels.end(), states[i].JPC) - rowLabels.begin(); if (rowNum < rowLabels.size()) { experLevels.push_back(PF1D_Ptr(plotBar(rowNum, states[i].mass, halfWidth))); { PlotFunction1D::Properties prop; prop.pen.setStyle(Qt::DashLine); prop.pen.setWidth(2); experLevels.back()->setProperties(prop); } stateTexts.push_back(PT_Ptr(new PlotText(rowNum+halfWidth, states[i].mass+50, states[i].name))); stateTexts.back()->setFont(QFont("Times New Roman", 14)); } } PlotView *levelView = createPlotView("Levels", "", "Mass/GeV", PRectF(-0.5, rowLabels.size(), 2800, 4500)); for (size_t i = 0; i < states.size(); i++) { levelView->add(experLevels[i].get()); levelView->add(stateTexts[i].get()); } levelView->setXRangeDivider(&xDivider); window.add(levelView, "Levels"); PlotProfile compLevels; for (size_t i = 0; i < charmStates.size(); i++) { size_t rowNum = std::find(rowLabels.begin(), rowLabels.end(), charmStates[i].JPC()) - rowLabels.begin(); if (rowNum < rowLabels.size()) { compLevels.addPoint(rowNum, charmStates[i].Mass()); } } { PlotProfile::Properties prop; prop.pen.setColor(Qt::red); prop.pen.setWidth(8); prop.symbolSize = 8; compLevels.setProperties(prop); } levelView->add(&compLevels); std::vector<MVW_Ptr> curveList; for (size_t i = 0; i < charmStates.size(); i++) { curveList.push_back(MVW_Ptr(new MultipleViewWidget())); PlotFunction1D *psiCurve = plotCurve(charmStates[i].Psi(), charmStates[i].R()); PlotFunction1D *vCurve = plotCurve(charmStates[i].Potential(), charmStates[i].R()); PlotFunction1D::Properties prop; prop.pen.setWidth(2); psiCurve->setProperties(prop); vCurve->setProperties(prop); std::ostringstream label; label << "N=" << states[i].N << "/L=" << states[i].L << "/S=" << states[i].S << "/J=" << states[i].J; PlotView *psiView = createPlotView(label.str(), "r/GeV^-1", "psi", PRectF(0, rMax, -1, 1)); psiView->add(psiCurve); PlotView *vView = createPlotView(label.str(), "r/GeV^-1", "V", PRectF(0, rMax, -10, 10)); vView->add(vCurve); curveList.back()->add(psiView, "Psi"); curveList.back()->add(vView, "Potential"); window.add(curveList.back().get(), label.str()); } levelView->save("levels.png"); window.show(); app.exec(); return 0; }
35.163934
126
0.548096
[ "vector" ]
9d1fab32358ed5ddf1a60ef7b052e66c8ad0ea57
803
cpp
C++
jmedia/filter/filter_buffersink.cpp
paopaol/jmedia
9aa083b107892a2c8c80b150523229155978f013
[ "MIT" ]
2
2020-05-11T08:45:00.000Z
2021-12-15T01:25:06.000Z
jmedia/filter/filter_buffersink.cpp
paopaol/jmedia
9aa083b107892a2c8c80b150523229155978f013
[ "MIT" ]
null
null
null
jmedia/filter/filter_buffersink.cpp
paopaol/jmedia
9aa083b107892a2c8c80b150523229155978f013
[ "MIT" ]
1
2021-01-11T09:28:33.000Z
2021-01-11T09:28:33.000Z
#include "filter_buffersink.h" extern "C"{ #include <libavfilter/buffersrc.h> #include <libavutil/channel_layout.h> #include <libavutil/opt.h> } #include <assert.h> namespace JMedia{ FilterBuffersink::FilterBuffersink(FilterGraph *filter_graph, const std::string &name): Filter(name) { m_filter = (AVFilter *)avfilter_get_by_name("buffersink"); m_filter_ctx = avfilter_graph_alloc_filter(filter_graph->getAVFilterGraph(), m_filter, name.c_str()); } int FilterBuffersink::set_pix_fmts(const std::vector<AVPixelFormat> pix_fmts) { assert(m_filter_ctx != NULL); int e = av_opt_set_int_list(m_filter_ctx, "pix_fmts", &pix_fmts[0], AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN); if (e != 0) { m_error.set_error(e); } return e; } }
25.09375
110
0.694894
[ "vector" ]
9d20e306f7e54cf72e271198c243ad788213574f
2,930
cpp
C++
experimental/Pomdog.Experimental/Skeletal2D/AnimationSystem.cpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Skeletal2D/AnimationSystem.cpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Skeletal2D/AnimationSystem.cpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #include "AnimationSystem.hpp" #include "AnimationClip.hpp" #include "AnimationState.hpp" #include "JointIndex.hpp" #include "Skeleton.hpp" #include "SkeletonPose.hpp" #include "SkeletonHelper.hpp" #include "Pomdog/Math/Matrix4x4.hpp" #include "Pomdog/Utility/Assert.hpp" #include <vector> #include <algorithm> namespace Pomdog { namespace { class SkeletonAnimationContext { public: std::shared_ptr<Pomdog::AnimationState> AnimationState; std::shared_ptr<Pomdog::Skeleton const> Skeleton; std::shared_ptr<Pomdog::SkeletonPose> SkeletonPose; }; } // unnamed namespace // MARK: - AnimationSystem::Impl class class AnimationSystem::Impl { public: std::vector<SkeletonAnimationContext> skeletonAnimations; public: void Add(std::shared_ptr<AnimationState> const& state, std::shared_ptr<Skeleton const> const& skeleton, std::shared_ptr<SkeletonPose> const& skeletonPose); void Remove(std::shared_ptr<AnimationState> const& state); void Update(GameClock const& clock); }; void AnimationSystem::Impl::Add(std::shared_ptr<AnimationState> const& state, std::shared_ptr<Skeleton const> const& skeleton, std::shared_ptr<SkeletonPose> const& skeletonPose) { skeletonAnimations.push_back({state, skeleton, skeletonPose}); } void AnimationSystem::Impl::Remove(std::shared_ptr<AnimationState> const& state) { skeletonAnimations.erase(std::remove_if(std::begin(skeletonAnimations), std::end(skeletonAnimations), [&state](SkeletonAnimationContext const& context){ return context.AnimationState == state; }), std::end(skeletonAnimations)); } void AnimationSystem::Impl::Update(GameClock const& clock) { for (auto & animationContext: skeletonAnimations) { // (1) Update time: auto & state = *animationContext.AnimationState; state.Update(clock.GetFrameDuration()); // (2) Pose extraction: auto & clip = state.Clip(); auto & skeleton = *animationContext.Skeleton; auto & skeletonPose = *animationContext.SkeletonPose; clip->Apply(state.Time(), skeleton, skeletonPose); // (3) Pose blending: ///@todo Not implemented } } // MARK: - AnimationSystem class AnimationSystem::AnimationSystem() : impl(std::make_unique<Impl>()) { } AnimationSystem::~AnimationSystem() = default; void AnimationSystem::Update(GameClock const& clock) { POMDOG_ASSERT(impl); impl->Update(clock); } void AnimationSystem::Add(std::shared_ptr<AnimationState> const& state, std::shared_ptr<Skeleton const> const& skeleton, std::shared_ptr<SkeletonPose> const& skeletonPose) { POMDOG_ASSERT(impl); impl->Add(state, skeleton, skeletonPose); } void AnimationSystem::Remove(std::shared_ptr<AnimationState> const& state) { POMDOG_ASSERT(impl); impl->Remove(state); } } // namespace Pomdog
27.383178
105
0.717406
[ "vector" ]
9d2408ca66028523f7cd39b1326a33164212fa36
12,791
cc
C++
lib/debugger_utils/jobs.cc
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
[ "BSD-3-Clause" ]
null
null
null
lib/debugger_utils/jobs.cc
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
[ "BSD-3-Clause" ]
null
null
null
lib/debugger_utils/jobs.cc
PowerOlive/garnet
16b5b38b765195699f41ccb6684cc58dd3512793
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "garnet/lib/debugger_utils/jobs.h" #include <inttypes.h> #include <stdlib.h> #include <list> #include <lib/zx/job.h> #include <lib/zx/process.h> #include <lib/zx/thread.h> #include <zircon/syscalls.h> #include "garnet/lib/debugger_utils/util.h" #include "lib/fxl/logging.h" #include "lib/fxl/macros.h" #include "lib/fxl/strings/string_printf.h" namespace debugger_utils { struct WalkContext { JobTreeJobCallback* job_callback; JobTreeProcessCallback* process_callback; JobTreeThreadCallback* thread_callback; }; // When reallocating koid buffer because we were too small add this much extra // on top of what the kernel says is currently needed. static const size_t kNumExtraKoids = 10; class KoidTable { public: explicit KoidTable() : koids_(&initial_buf_[0]), size_(0), capacity_(kNumInitialKoids) {} ~KoidTable() { if (koids_ != &initial_buf_[0]) { delete[] koids_; } } size_t size() const { return size_; } size_t capacity() const { return capacity_; } zx_koid_t* data() const { return koids_; } bool empty() const { return size_ == 0; } size_t CapacityInBytes() const { return capacity() * sizeof(zx_koid_t); } zx_koid_t Get(size_t index) const { FXL_DCHECK(index < size_); return koids_[index]; } // If this fails then we just continue to use the current capacity. void TryReserve(size_t new_capacity) { auto new_buf = malloc(new_capacity * sizeof(zx_koid_t)); if (new_buf) { if (koids_ != &initial_buf_[0]) { free(koids_); } koids_ = reinterpret_cast<zx_koid_t*>(new_buf); capacity_ = new_capacity; } } void SetSize(size_t size) { FXL_DCHECK(size <= capacity_); size_ = size; } private: // Allocate space for this many koids within the object, it can live on the // stack. Only if we need more than this do we use the heap. // Note that for jobs, due to potentially deep nesting, this object should // always be allocated in the heap. static constexpr size_t kNumInitialKoids = 32; zx_koid_t initial_buf_[kNumInitialKoids]; // A pointer to |initial_buf_| or a heap-allocated object. zx_koid_t* koids_; // The number of entries in |koids_|. size_t size_; // The amount of koids available in |koids_|. size_t capacity_; FXL_DISALLOW_COPY_ASSIGN_AND_MOVE(KoidTable); }; // A stack of job koid tables, to avoid recursion. // Jobs aren't normally nested *that* deep, but we can't assume that of course. class JobKoidTableStackEntry { public: explicit JobKoidTableStackEntry(zx::job job, zx_handle_t job_h, zx_koid_t jid, int depth, std::unique_ptr<KoidTable> subjob_koids) : job_(std::move(job)), job_h_(job_h), jid_(jid), depth_(depth), subjob_koids_(std::move(subjob_koids)), current_subjob_index_(0) {} zx_handle_t job_h() const { return job_h_; } zx_koid_t jid() const { return jid_; } int depth() const { return depth_; } bool empty() const { return current_subjob_index_ == subjob_koids_->size(); } zx_koid_t PopNext() { FXL_DCHECK(!empty()); auto koid = subjob_koids_->Get(current_subjob_index_); ++current_subjob_index_; return koid; } private: // The only use of this member is to automagically free the handle when // the object is destructed. In the case of the top job this object is // not valid. zx::job job_; // This is the handle of the job to use. zx_handle_t job_h_; zx_koid_t jid_; int depth_; std::unique_ptr<KoidTable> subjob_koids_; size_t current_subjob_index_; FXL_DISALLOW_COPY_ASSIGN_AND_MOVE(JobKoidTableStackEntry); }; using JobKoidTableStack = std::list<JobKoidTableStackEntry>; static zx_status_t GetChild(zx_handle_t parent_h, zx_koid_t parent_koid, zx_koid_t koid, zx_handle_t* out_task_h) { auto status = zx_object_get_child(parent_h, koid, ZX_RIGHT_SAME_RIGHTS, out_task_h); if (status != ZX_OK) { // The task could have terminated in the interim. if (status == ZX_ERR_NOT_FOUND) { FXL_VLOG(1) << fxl::StringPrintf( "zx_object_get_child(%" PRIu64 ", %" PRIu64 ", ...) failed: %s\n", parent_koid, koid, ZxErrorString(status).c_str()); } else { FXL_LOG(ERROR) << fxl::StringPrintf( "zx_object_get_child(%" PRIu64 ", %" PRIu64 ", ...) failed: %s\n", parent_koid, koid, ZxErrorString(status).c_str()); } } return status; } static zx_status_t FetchChildren(zx_handle_t parent_h, zx_koid_t parent_koid, int children_kind, const char* kind_name, KoidTable* out_koids) { size_t actual = 0; size_t avail = 0; zx_status_t status; // This is inherently racy, but we retry once with a bit of slop to try to // get a complete list. for (int pass = 0; pass < 2; ++pass) { if (actual < avail) { out_koids->TryReserve(avail + kNumExtraKoids); } status = zx_object_get_info(parent_h, children_kind, out_koids->data(), out_koids->CapacityInBytes(), &actual, &avail); if (status != ZX_OK) { FXL_LOG(ERROR) << fxl::StringPrintf( "zx_object_get_info(%" PRIu64 ", %s, ...) failed: %s\n", parent_koid, kind_name, ZxErrorString(status).c_str()); return status; } if (actual == avail) { break; } } // If we're still too small at least warn the user. if (actual < avail) { FXL_LOG(WARNING) << fxl::StringPrintf("zx_object_get_info(%" PRIu64 ", %s, ...)" " truncated results, got %zu/%zu\n", parent_koid, kind_name, actual, avail); } out_koids->SetSize(actual); return ZX_OK; } static zx_status_t DoThreads(const WalkContext* ctx, zx_handle_t process_h, zx_koid_t pid, int depth) { FXL_DCHECK(ctx->thread_callback); KoidTable koids; auto status = FetchChildren(process_h, pid, ZX_INFO_PROCESS_THREADS, "ZX_INFO_PROCESS_THREADS", &koids); if (status != ZX_OK) { return status; } for (size_t i = 0; i < koids.size(); ++i) { zx_handle_t thread_h; zx_koid_t tid = koids.Get(i); status = GetChild(process_h, pid, tid, &thread_h); if (status != ZX_OK) { continue; } zx::thread thread(thread_h); status = (*ctx->thread_callback)(&thread, tid, pid, depth); if (status != ZX_OK) { return status; } // There's nothing special we need to do here if the callback took // ownership of the handle. } return ZX_OK; } static zx_status_t DoProcesses(const WalkContext* ctx, zx_handle_t job_h, zx_koid_t jid, int depth) { KoidTable koids; auto status = FetchChildren(job_h, jid, ZX_INFO_JOB_PROCESSES, "ZX_INFO_JOB_PROCESSES", &koids); if (status != ZX_OK) { return status; } for (size_t i = 0; i < koids.size(); ++i) { zx_handle_t process_h; zx_koid_t pid = koids.Get(i); status = GetChild(job_h, jid, pid, &process_h); if (status != ZX_OK) { continue; } zx::process process(process_h); if (ctx->process_callback) { status = (*ctx->process_callback)(&process, pid, jid, depth); if (status != ZX_OK) { return status; } } // If the callback took ownership of the process handle we can still scan // the threads using |child|. The callback is required to not close the // process handle until WalkJobTree() returns. if (ctx->thread_callback) { status = DoThreads(ctx, process_h, pid, depth + 1); if (status != ZX_OK) { return status; } } } return ZX_OK; } // This function is bi-modal: It handles both the top job and all subjobs. // When processing the top job |job| is nullptr, otherwise it is a pointer // to the subjob's object. |job_h| is the handle of the job. In the case of // subjobs it is |job.get()|. static zx_status_t DoJob(JobKoidTableStack* stack, const WalkContext* ctx, zx::job* job, zx_handle_t job_h, zx_koid_t jid, zx_koid_t parent_jid, int depth) { zx_status_t status; if (job) { // Things are a bit tricky here as |job_callback| could take ownership of // the job, but we still need to call DoProcesses(). FXL_DCHECK(job->get() == job_h); if (ctx->job_callback) { status = (*ctx->job_callback)(job, jid, parent_jid, depth); if (status != ZX_OK) { return status; } } } if (ctx->process_callback || ctx->thread_callback) { status = DoProcesses(ctx, job_h, jid, depth + 1); if (status != ZX_OK) { return status; } } auto subjob_koids = std::unique_ptr<KoidTable>(new KoidTable()); status = FetchChildren(job_h, jid, ZX_INFO_JOB_CHILDREN, "ZX_INFO_JOB_CHILDREN", subjob_koids.get()); if (status != ZX_OK) { return status; } if (!subjob_koids->empty()) { if (job) { stack->emplace_front(std::move(*job), job_h, jid, depth + 1, std::move(subjob_koids)); } else { stack->emplace_front(zx::job(), job_h, jid, depth + 1, std::move(subjob_koids)); } } return ZX_OK; } static zx_status_t WalkJobTreeInternal(JobKoidTableStack* stack, const WalkContext* ctx) { while (!stack->empty()) { auto& stack_entry = stack->front(); if (stack_entry.empty()) { stack->pop_front(); } else { auto parent_job_h = stack_entry.job_h(); auto parent_jid = stack_entry.jid(); auto depth = stack_entry.depth(); auto jid = stack_entry.PopNext(); zx_handle_t job_h; auto status = GetChild(parent_job_h, parent_jid, jid, &job_h); if (status != ZX_OK) { return status; } zx::job job(job_h); status = DoJob(stack, ctx, &job, job_h, jid, parent_jid, depth); if (status != ZX_OK) { return status; } } } return ZX_OK; } zx_status_t WalkJobTree(const zx::job& job, JobTreeJobCallback* job_callback, JobTreeProcessCallback* process_callback, JobTreeThreadCallback* thread_callback) { FXL_DCHECK(job.is_valid()); zx_info_handle_basic_t info; auto status = zx_object_get_info(job.get(), ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); if (status != ZX_OK) { FXL_LOG(ERROR) << fxl::StringPrintf( "zx_object_get_info(search_job, ZX_INFO_HANDLE_BASIC, ...) failed: " "%s\n", ZxErrorString(status).c_str()); return status; } auto jid = info.koid; auto parent_jid = info.related_koid; WalkContext ctx; ctx.job_callback = job_callback; ctx.process_callback = process_callback; ctx.thread_callback = thread_callback; JobKoidTableStack stack; status = DoJob(&stack, &ctx, nullptr, job.get(), jid, parent_jid, 0); if (status != ZX_OK) { return status; } return WalkJobTreeInternal(&stack, &ctx); } zx::process FindProcess(const zx::job& job, zx_koid_t pid) { zx::process process; JobTreeProcessCallback find_process_callback = [&](zx::process* task, zx_koid_t koid, zx_koid_t parent_koid, int depth) -> zx_status_t { if (koid == pid) { process.reset(task->release()); return ZX_ERR_STOP; } return ZX_OK; }; // There's no real need to check the result here. WalkJobTree(job, nullptr, &find_process_callback, nullptr); return process; } zx::process FindProcess(zx_handle_t job_h, zx_koid_t pid) { zx::job job(job_h); auto result = FindProcess(job, pid); // Don't close |job_h| when we return. auto released_handle __UNUSED = job.release(); return result; } // The default job is not ours to own so we need to make a copy. // This is a simple wrapper to do that. zx::job GetDefaultJob() { auto job = zx_job_default(); if (job == ZX_HANDLE_INVALID) { FXL_VLOG(1) << "no default job"; return zx::job(); } zx_handle_t dupe_h; auto status = zx_handle_duplicate(job, ZX_RIGHT_SAME_RIGHTS, &dupe_h); if (status != ZX_OK) { FXL_LOG(ERROR) << "unable to create dupe of default job: " << ZxErrorString(status); return zx::job(); } return zx::job(dupe_h); } } // namespace debugger_utils
30.382423
79
0.628958
[ "object" ]
9d2937491a8ebdb060e5203c0b437008969269e8
658
cpp
C++
examples.legacy/critical_point_tracking_2d/main1.cpp
robertu94/ftk
96c53ec21b795bb596908910b0b6d379f3dca157
[ "MIT" ]
null
null
null
examples.legacy/critical_point_tracking_2d/main1.cpp
robertu94/ftk
96c53ec21b795bb596908910b0b6d379f3dca157
[ "MIT" ]
null
null
null
examples.legacy/critical_point_tracking_2d/main1.cpp
robertu94/ftk
96c53ec21b795bb596908910b0b6d379f3dca157
[ "MIT" ]
null
null
null
#include <ftk/filters/critical_point_tracker_2d_regular.hh> #include <ftk/ndarray/synthetic.hh> #include <ftk/ndarray/grad.hh> #if FTK_HAVE_VTK #include <ftk/geometry/points2vtk.hh> #endif const int DW = 256, DH = 256, DT = 10; int main(int argc, char **argv) { diy::mpi::environment env; auto scalar = ftk::synthetic_woven_2Dt<double>(DW, DH, DT); ftk::critical_point_tracker_2d_regular tracker; tracker.set_input_scalar_field(scalar); // tracker.set_type_filter(ftk::CRITICAL_POINT_2D_MAXIMUM); tracker.update(); #if FTK_HAVE_VTK auto polydata = tracker.get_results_vtk(); ftk::write_vtp("asdf1.vtp", polydata); #endif return 0; }
22.689655
61
0.743161
[ "geometry" ]
9d2b5975f1c3a5e0e765651733da9edaf870635a
482
cpp
C++
Day1(Arrays)/287.FindtheDuplicateNumber.cpp
rishusingh022/30-Days-of-Code
021fa9ab5fca81912ea97853746a49ffd011e249
[ "MIT" ]
null
null
null
Day1(Arrays)/287.FindtheDuplicateNumber.cpp
rishusingh022/30-Days-of-Code
021fa9ab5fca81912ea97853746a49ffd011e249
[ "MIT" ]
null
null
null
Day1(Arrays)/287.FindtheDuplicateNumber.cpp
rishusingh022/30-Days-of-Code
021fa9ab5fca81912ea97853746a49ffd011e249
[ "MIT" ]
null
null
null
//space complexity jada hai bas class Solution { public: int findDuplicate(vector<int>& nums) { int n=nums.size(); vector<int> frequency(n); for(int i=0;i<n;i++){ frequency[nums[i]]++; } int result=0; for(int i=0;i<n;i++){ if(frequency[i]>1){ result=i; break; } } return result; } }; //Approach 3: Floyd's Tortoise and Hare (Cycle Detection)
22.952381
57
0.479253
[ "vector" ]
9d329109ebb3d4aa3185d1c4404ff7cf93ff14a4
4,005
hpp
C++
external/vulkancts/modules/vulkan/sparse_resources/vktSparseResourcesBase.hpp
hustwei/deqp
812d768b55dcedf2c0fda63e69db3c05600f379d
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/sparse_resources/vktSparseResourcesBase.hpp
hustwei/deqp
812d768b55dcedf2c0fda63e69db3c05600f379d
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/sparse_resources/vktSparseResourcesBase.hpp
hustwei/deqp
812d768b55dcedf2c0fda63e69db3c05600f379d
[ "Apache-2.0" ]
null
null
null
#ifndef _VKTSPARSERESOURCESBASE_HPP #define _VKTSPARSERESOURCESBASE_HPP /*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2016 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file vktSparseResourcesBase.hpp * \brief Sparse Resources Base Instance *//*--------------------------------------------------------------------*/ #include "tcuDefs.hpp" #include "tcuTestCase.hpp" #include "vktTestCaseUtil.hpp" #include "vktSparseResourcesTestsUtil.hpp" #include "vkDefs.hpp" #include "vkMemUtil.hpp" #include "vkPlatform.hpp" #include "vkRef.hpp" #include "vkTypeUtil.hpp" #include "deSharedPtr.hpp" #include "deUniquePtr.hpp" #include "deStringUtil.hpp" #include <map> #include <vector> namespace vkt { namespace sparse { enum { NO_MATCH_FOUND = ~((deUint32)0) }; struct Queue { vk::VkQueue queueHandle; deUint32 queueFamilyIndex; deUint32 queueIndex; }; struct QueueRequirements { QueueRequirements(const vk::VkQueueFlags qFlags, const deUint32 qCount) : queueFlags(qFlags) , queueCount(qCount) {} vk::VkQueueFlags queueFlags; deUint32 queueCount; }; typedef std::vector<QueueRequirements> QueueRequirementsVec; class SparseResourcesBaseInstance : public TestInstance { public: SparseResourcesBaseInstance (Context &context); protected: typedef std::map<vk::VkQueueFlags, std::vector<Queue> > QueuesMap; typedef std::vector<vk::VkQueueFamilyProperties> QueueFamilyPropertiesVec; typedef vk::Move<vk::VkDevice> DevicePtr; typedef de::SharedPtr< vk::Unique<vk::VkDeviceMemory> > DeviceMemoryUniquePtr; void createDeviceSupportingQueues (const QueueRequirementsVec& queueRequirements); const Queue& getQueue (const vk::VkQueueFlags queueFlags, const deUint32 queueIndex); deUint32 findMatchingMemoryType (const vk::InstanceInterface& instance, const vk::VkPhysicalDevice physicalDevice, const vk::VkMemoryRequirements& objectMemoryRequirements, const vk::MemoryRequirement& memoryRequirement) const; bool checkSparseSupportForImageType (const vk::InstanceInterface& instance, const vk::VkPhysicalDevice physicalDevice, const ImageType imageType) const; bool checkSparseSupportForImageFormat (const vk::InstanceInterface& instance, const vk::VkPhysicalDevice physicalDevice, const vk::VkImageCreateInfo& imageInfo) const; bool checkImageFormatFeatureSupport (const vk::InstanceInterface& instance, const vk::VkPhysicalDevice physicalDevice, const vk::VkFormat format, const vk::VkFormatFeatureFlags featureFlags) const; deUint32 getSparseAspectRequirementsIndex (const std::vector<vk::VkSparseImageMemoryRequirements>&requirements, const vk::VkImageAspectFlags aspectFlags) const; DevicePtr m_logicalDevice; private: deUint32 findMatchingQueueFamilyIndex (const QueueFamilyPropertiesVec& queueFamilyProperties, const vk::VkQueueFlags queueFlags, const deUint32 startIndex) const; QueuesMap m_queues; }; } // sparse } // vkt #endif // _VKTSPARSERESOURCESBASE_HPP
31.785714
113
0.669663
[ "vector" ]
9d3418ea3a40c69e4e8925c6809aebca83b83a25
1,377
cpp
C++
day-05.cpp
MarioLiebisch/Advent-of-Code-2020
da8b2e8e86fa473818a690df2219d4f9c7abd9b6
[ "MIT" ]
null
null
null
day-05.cpp
MarioLiebisch/Advent-of-Code-2020
da8b2e8e86fa473818a690df2219d4f9c7abd9b6
[ "MIT" ]
null
null
null
day-05.cpp
MarioLiebisch/Advent-of-Code-2020
da8b2e8e86fa473818a690df2219d4f9c7abd9b6
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> #include <set> #include "utility.h" auto day05part1(const std::vector<aoc::BoardingPass>& passes) -> unsigned int { unsigned int highest = 0; for (const auto& pass : passes) { if (pass.id > highest) { highest = pass.id; } } return highest; } auto day05part2(std::vector<aoc::BoardingPass>& passes) -> unsigned int { unsigned int last = 0; // Sort them all by ID std::sort(passes.begin(), passes.end()); // Skip empty non-existant seats by assuming the last id is that of the first one last = passes[0].id; for (const auto& pass : passes) { // Did we skip one? My seat! if (last + 1 < pass.id) { return last + 1; } last = pass.id; } // Shouldn't happen return 0; } auto main(int argc, char **argv) -> int { std::vector<aoc::BoardingPass> passes; aoc::BoardingPass s1test = aoc::convert<aoc::BoardingPass>("FBFBBFFRLR"); std::cout << "Sample 1 solution: row " << s1test.row << ", col " << s1test.col << "\n"; aoc::readFromFile<aoc::BoardingPass>("day-05-input.txt", std::back_inserter(passes)); std::cout << "Part 1 solution: " << day05part1(passes) << "\n"; std::cout << "Part 2 solution: " << day05part2(passes) << "\n"; return 0; }
28.102041
91
0.595497
[ "vector" ]
9d34216fab4e9120a3dac09d4f7006d348eb79b4
18,111
hpp
C++
novelty.hpp
guillaumeboehm/gaga
f0d59718fa8222b72dc590685330ce2b798ef783
[ "MIT" ]
null
null
null
novelty.hpp
guillaumeboehm/gaga
f0d59718fa8222b72dc590685330ce2b798ef783
[ "MIT" ]
null
null
null
novelty.hpp
guillaumeboehm/gaga
f0d59718fa8222b72dc590685330ce2b798ef783
[ "MIT" ]
null
null
null
#pragma once #include <chrono> #include <vector> #include "gaga.hpp" namespace GAGA { // Just to be clear on the terms: // signature = signature = phenotype/behavior/feature characterization // // template <typename DNA, typename sig> struct NoveltyIndividual : public Individual<DNA> { using sig_t = sig; using base = Individual<DNA>; sig_t signature; // individual's signature for novelty computation NoveltyIndividual(const DNA &d) : base(d) {} NoveltyIndividual(const json &o) : base(o) { if (o.count("signature")) signature = o.at("signature").get<sig_t>(); } json toJSON() const { auto o = base::toJSON(); o["signature"] = signature; return o; } }; template <typename GA> struct NoveltyExtension { using Ind_t = typename GA::Ind_t; using Iptr = typename GA::Iptr; using sig_t = typename Ind_t::sig_t; using distanceMatrix_t = std::vector<std::vector<double>>; bool nslc = false; // enable noverlty search with local competition std::vector<Ind_t> archive; // novelty archive, Individuals are stored there. size_t K = 7; // size of the neighbourhood for novelty bool saveArchiveEnabled = true; // save the novelty archive size_t maxArchiveSize = 2048; size_t nbOfArchiveAdditionsPerGeneration = 10; void clear() { archive.clear(); } template <typename F> void setComputeSignatureDistanceFunction(F &&f) { computeSignatureDistance = std::forward<F>(f); } template <typename F> void setComputDistanceMatrixFunction(F &&f) { computeDistanceMatrix = std::forward<F>(f); } std::function<double(const sig_t &, const sig_t &)> computeSignatureDistance = [](const auto &, const auto &) { std::cerr << "[GAGA WARNING]: computeSignatureDistance not defined. Returning " "distance = 0. " "Set the signatureDistance method with " "NoveltyExtension::setComputeSignatureDistanceFunction or redefine " "the distane matrix computation with setComputDistanceMatrixFunction" << std::endl; return 0; }; std::function<distanceMatrix_t(const std::vector<Ind_t> &)> computeDistanceMatrix = [&](const auto &ar) { return defaultComputeDistanceMatrix(ar); }; // onRegister Hook, called when extension is registered to a ga instance void onRegister(GA &gagaInstance) { gagaInstance.addPostEvaluationMethod( [this](GA &ga) { updateNovelty(ga.population, ga); }); gagaInstance.addPrintStartMethod([this](const GA &) { std::cout << " - novelty is " << GAGA_COLOR_GREEN << "enabled" << GAGA_COLOR_NORMAL << std::endl; std::cout << " - Nearest Neighbors size = " << GAGA_COLOR_BLUE << K << GAGA_COLOR_NORMAL << std::endl; std::cout << " - Local Competition " << GAGA_COLOR_BLUE << (nslc ? "ON" : "OFF") << GAGA_COLOR_NORMAL << std::endl; std::cout << " - Individual additions per generation = " << GAGA_COLOR_BLUE << nbOfArchiveAdditionsPerGeneration << GAGA_COLOR_NORMAL << std::endl; }); gagaInstance.addPrintIndividualMethod( [](const GA &ga, const auto &ind) -> std::string { if (ga.getVerbosity() >= 3) return signatureToString(ind.signature); return ""; }); gagaInstance.addSavePopMethod([this](const GA &ga) { if (saveArchiveEnabled) saveArchive(ga); }); gagaInstance.addEnabledObjectivesMethod([this](const GA &, auto &objectives) { if (nslc) { objectives.clear(); objectives.insert("novelty"); objectives.insert("local_score"); } }); } bool isArchived(const Ind_t &ind) { return isArchived(ind.id); } bool isArchived(const std::pair<size_t, size_t> &id) { bool archived = false; for (const auto &archInd : archive) { if (archInd.id == id) { archived = true; break; } } return archived; } // SQL bindings size_t archiveSQLId = 0; template <typename SQLPlugin, typename SQLStatement> void onSQLiteRegister(SQLPlugin &saver) { std::vector<std::tuple< std::string, std::string, std::function<void(const Ind_t &, SQLPlugin &, size_t, SQLStatement *)>>> columns; columns.emplace_back("signature", "TEXT", [](const Ind_t &individual, SQLPlugin &sqlPlugin, size_t index, SQLStatement *stmt) { json jsSig = individual.signature; sqlPlugin.sqbind(stmt, index, jsSig.dump()); }); saver.addIndividualColumns(columns); auto onNewRun = [&](auto &sql) { std::string tableCreations = "CREATE TABLE IF NOT EXISTS archive(" "id INTEGER PRIMARY KEY ," "config TEXT," "id_run INTEGER);" "CREATE TABLE IF NOT EXISTS archive_content(" "id INTEGER PRIMARY KEY ," "id_archive INTEGER," "id_individual INTEGER," "id_generation INTEGER);"; sql.exec(tableCreations); nlohmann::json archiveConf; archiveConf["K"] = K; archiveConf["maxArchiveSize"] = maxArchiveSize; archiveConf["nbOfArchiveAdditionsPerGeneration"] = nbOfArchiveAdditionsPerGeneration; SQLStatement *stmt; std::string req = "INSERT INTO archive(config,id_run) VALUES (?1,?2);"; sql.prepare(req, &stmt); sql.bind(stmt, archiveConf.dump(), sql.currentRunId); sql.step(stmt); archiveSQLId = sql.getLastInsertId(); }; auto onNewGen = [&](auto &sql, const auto &) { // insert current archive individuals std::string archSQL = "INSERT INTO archive_content" "(id_archive, id_individual, id_generation) " "VALUES " "(?1, ?2, ?3);"; SQLStatement *stmt; sql.prepare(archSQL, &stmt); for (const auto &ind : archive) { sql.bind(stmt, archiveSQLId, sql.getIndId(ind.id), sql.generationIds.back()); sql.step(stmt); } }; saver.addExtraTableInstructions(onNewRun, onNewGen); } /********************************************************************************* * NOVELTY RELATED METHODS ********************************************************************************/ // Novelty works with signatures. A signature can be anything, and is declared in the // individual type. There also needs to be a distance function defined (c.f // setComputDistanceMatrixFunction and setComputeSignatureDistanceFunction). // -- Default signature: // By default, a signature is just a std::vector of std::vector of doubles. // It is recommended that those doubles are within a same order of magnitude. // Each std::vector<double> could be a "snapshot": it represents the state of the // evaluation of one individual at a certain time. Thus, a complete signature is a // combination of one or more snapshot taken at different points in the simulation (a // std::vector<vector<double>>). Snapshot must be of same size accross individuals. // -- // Signature must be set in the evaluator (see examples) // Options for novelty: // - Local Competition: // distanceMatrix_t defaultComputeDistanceMatrix(const std::vector<Ind_t> &ar) { // this computes both dist(i,j) and dist(j,i), assuming they can be different. distanceMatrix_t dmat(ar.size(), std::vector<double>(ar.size())); for (size_t i = 0; i < ar.size(); ++i) { for (size_t j = 0; j < ar.size(); ++j) { if (i != j) dmat[i][j] = computeSignatureDistance(ar[i].signature, ar[j].signature); } } return dmat; } std::vector<size_t> findKNN(size_t i, size_t knnsize, const distanceMatrix_t &dmat) { return findKNN(i, knnsize, dmat, dmat.size()); } std::vector<size_t> findKNN(size_t i, size_t knnsize, const distanceMatrix_t &dmat, size_t truncateTo) { // returns the K nearest neighbors of i, according to the distance matrix dmat // i excluded if (dmat.size() == 0) return std::vector<size_t>(); assert(dmat[i].size() == dmat.size()); assert(i < dmat.size()); assert(truncateTo <= dmat.size()); const std::vector<double> &distances = dmat[i]; std::vector<size_t> indices(truncateTo); std::iota(indices.begin(), indices.end(), 0); size_t k = std::max(std::min(knnsize, indices.size() - 1), (size_t)0); std::nth_element( indices.begin(), indices.begin() + k, indices.end(), [&distances](size_t a, size_t b) { return distances[a] < distances[b]; }); indices.erase(std::remove(indices.begin(), indices.end(), i), indices.end()); // remove itself from the knn list indices.resize(k); return indices; } std::vector<Ind_t> prevArchive; distanceMatrix_t distanceMatrix; // updateNovelty is called to compute the novelty of all the individuals in a given // population, using both this population and the current archive. void updateNovelty(std::vector<Ind_t> &population, GA &ga) { // we append the current population to the archive auto savedArchiveSize = archive.size(); for (auto &ind : population) archive.push_back(ind); // we compute the distance matrix of the whole archive (with new population appended) auto t0 = std::chrono::high_resolution_clock::now(); distanceMatrix = computeDistanceMatrix(archive); auto t1 = std::chrono::high_resolution_clock::now(); double distanceMatrixTime = std::chrono::duration<double>(t1 - t0).count(); // then update the novelty field of every member of the population for (size_t p_i = 0; p_i < population.size(); p_i++) { size_t i = savedArchiveSize + p_i; // individuals'id in the archive assert(population[p_i].id == archive[i].id); std::vector<size_t> knn = findKNN(i, K, distanceMatrix); if (nslc) { // local competition is enabled // we put all objectives other than novelty into objs auto objs = GA::getAllObjectives(population[p_i]); if (objs.count("novelty")) objs.erase("novelty"); if (objs.count("local_score")) objs.erase("local_score"); std::vector<Ind_t *> knnPtr; // pointers to knn individuals for (auto k : knn) knnPtr.push_back(&archive[k]); knnPtr.push_back(&archive[i]); // + itself // we normalize the rank double knnSize = knn.size() > 0 ? static_cast<double>(knn.size()) : 1.0; double localScore = static_cast<double>(ga.getParetoRank(knnPtr, knnPtr.size() - 1, objs)) / knnSize; population[p_i].fitnesses["local_score"] = 1.0 - localScore; } // sum = sum of distances between i and its knn // novelty = avg dist to knn double sum = 0; for (auto &j : knn) sum += distanceMatrix[i][j]; population[p_i].fitnesses["novelty"] = sum / (double)knn.size(); ga.printLn(3, "Novelty for ind ", population[p_i].id, " -> ", population[p_i].fitnesses["novelty"]); ga.printLn(3, "Ind ", population[p_i].id, " signature is ", signatureToString(population[p_i].signature)); } // Archive maintenance: first we erase the entire pop that we had appended archive.erase(archive.begin() + static_cast<long>(savedArchiveSize), archive.end()); maintainArchiveSize_constantReplacement(population, nbOfArchiveAdditionsPerGeneration); prevArchive = archive; ga.printLn(2, "Distance matrix computation took ", distanceMatrixTime, "s"); ga.printLn(2, "New archive size = ", archive.size()); } void maintainArchiveSize_constantReplacement(const std::vector<Ind_t> &population, size_t nAdditions) { auto computeNovelty = [&](size_t id) { std::vector<size_t> knn = findKNN(id, K, distanceMatrix, archive.size()); double sum = 0; for (auto &j : knn) sum += distanceMatrix[id][j]; return sum / (double)knn.size(); }; // number of ind to replace in archive. There is always nAdditions operations: if the // archive is full all operations are replacement; if it isn't, we just add random // individuals. int toReplace = std::min(static_cast<int>(nAdditions), std::max(0, static_cast<int>(archive.size() + nAdditions) - static_cast<int>(maxArchiveSize))); // number of ind to add int toAdd = nAdditions - toReplace; assert(toReplace + toAdd == (int)nAdditions); std::uniform_int_distribution<size_t> d(0, population.size() - 1); for (int r = 0; r < toReplace; ++r) { // we recompute novelty values in the archive: std::vector<double> tmpNovelties(archive.size()); for (size_t i = 0; i < archive.size(); ++i) tmpNovelties[i] = computeNovelty(i); // we find the least novel individual of the archive auto a_i = std::distance(tmpNovelties.begin(), std::min_element(tmpNovelties.begin(), tmpNovelties.end())); // and replace it with a random pop one size_t p_i = d(GA::globalRand()); // random ind position in population size_t d_i = archive.size() + p_i; // its pos in distanceMatrix (archive + pop) // std::cerr << " -- Replacing " << json(archive[a_i].id).dump() << " with " //<< json(population[p_i].id).dump() << std::endl; archive[a_i] = population[p_i]; // actual replacement // then update the distanceMatrix distanceMatrix[a_i] = distanceMatrix[d_i]; // we replace the row for (size_t a = 0; a < distanceMatrix.size(); ++a) distanceMatrix[a][a_i] = distanceMatrix[a][d_i]; // a_i column of the other rows distanceMatrix[d_i][a_i] = 0; // distance with itself = 0 assert(distanceMatrix[a_i][d_i] == 0); // taken care of during for loop } distanceMatrix.resize(archive.size()); for (auto &r : distanceMatrix) r.resize(archive.size()); // If the archive is not full, we just add random ind for (int i = 0; i < toAdd; ++i) { size_t p_i = d(GA::globalRand()); // random ind position in population archive.push_back(population[p_i]); } } template <typename T> static inline std::string signatureToString(const T &f) { std::ostringstream res; res << "👣 " << json(f).dump(); return res.str(); } void saveArchive(const GA &ga) { json o = Ind_t::popToJSON(archive); o["evaluator"] = ga.getEvaluatorName(); fs::path basePath = ga.getSaveFolder() / GAGA::concat("gen", ga.getCurrentGenerationNumber()); fs::create_directories(basePath); std::string fileName = GAGA::concat("archive", ga.getCurrentGenerationNumber(), ".pop"); fs::path filePath = basePath / fileName; std::ofstream file; file.open(filePath); file << o.dump(); file.close(); } // DISTRIBUTED VERSION (works with gagazmq) template <typename S> void enableDistributed(S &server) { setComputDistanceMatrixFunction( [&](const auto &a) { return distributedComputeDistanceMatrix(a, server); }); } void disableDistributed() { setComputDistanceMatrixFunction( [&](const auto &ar) { return defaultComputeDistanceMatrix(ar); }); } //---------------------------------------------------------------------------- // distributedComputeDistanceMatrix //---------------------------------------------------------------------------- // Computes the distance matrix while avoinding unecessary new recomputations //--- --- --- --- --- --- --- --- --- --- --- --- --- // We assume individuals with same id don't change between generations, and that the // distance between 2 old inds is stable over time. The top left part of the matrix // until the first new individual wont be recomputed. To use that, gaga should always // try to append new individuals at the end of the archive vector, and replace rather // than delete. distanceMatrix_t prevDM; std::vector<Ind_t> prevAr; template <typename SERVER> distanceMatrix_t distributedComputeDistanceMatrix(const std::vector<Ind_t> &ar, SERVER &server) { // the new distance matrix, first filled with zeros. distanceMatrix_t dmat(ar.size(), std::vector<double>(ar.size())); std::vector<size_t> unknown; std::vector<size_t> known; known.reserve(prevArchive.size()); unknown.reserve(ar.size()); // finding id of the known & unknown individuals for (size_t i = 0; i < ar.size(); ++i) { if (i < prevAr.size() && i < prevDM.size() && ar[i].id == prevAr[i].id) { // std::cerr << json(ar[i].id).dump() << " already known" << std::endl; known.push_back(i); } else { // std::cerr << json(ar[i].id).dump() << " UNKNOWN" << std::endl; unknown.push_back(i); } } // std::cerr << "unknown :" << unknown.size() << std::endl; // we fill the new distmatrix with the distances we already know for (const auto &i : known) { for (const auto &j : known) { const auto &d = prevDM[i][j]; dmat[i][j] = d; dmat[j][i] = d; } } // tasks = pairs of ar id for which the workers should compute a distance std::vector<std::pair<size_t, size_t>> distancePairs; distancePairs.reserve(0.5 * std::pow(ar.size() - known.size(), 2)); // we add all known,unknown pairs for (const auto &i : known) for (const auto &j : unknown) distancePairs.emplace_back(i, j); // + all unknown,unknown pairs for (size_t k = 0; k < unknown.size(); ++k) for (size_t j = k + 1; j < unknown.size(); ++j) distancePairs.emplace_back(unknown[k], unknown[j]); // we send the archive as extra content in the request, to each client. auto archive_js = nlohmann::json::array(); for (const auto &i : ar) { auto jsi = i.toJSON(); jsi["infos"] = ""; // we delete infos, often very heavy and not necessary archive_js.push_back(jsi); } json extra_js{{"archive", archive_js}}; // called whenever results are sent by a worker. We just update the distance // matrix auto distanceResults = [&](const auto &req) { auto distances = req.at("distances"); for (auto &d : distances) { // d = [i, j, dist] const size_t &i = d[0]; const size_t &j = d[1]; assert(i < ar.size()); assert(j < ar.size()); double dist = d[2]; dmat[i][j] = dist; dmat[j][i] = dist; } return distances.size(); }; server.taskDispatch("DISTANCE", distancePairs, distanceResults, extra_js); prevDM = dmat; prevAr = ar; return dmat; } }; } // namespace GAGA
38.208861
89
0.638893
[ "vector" ]
9d452e5dd3cea0150b33b312be674b3a4831bad3
5,221
hpp
C++
src/cep/search_manager.hpp
mogproject/cluster-editing-2021
20356800d594f3aaae9cad30a52af3c6f94f049b
[ "Apache-2.0" ]
1
2021-06-23T19:53:25.000Z
2021-06-23T19:53:25.000Z
src/cep/search_manager.hpp
mogproject/cluster-editing-2021
20356800d594f3aaae9cad30a52af3c6f94f049b
[ "Apache-2.0" ]
null
null
null
src/cep/search_manager.hpp
mogproject/cluster-editing-2021
20356800d594f3aaae9cad30a52af3c6f94f049b
[ "Apache-2.0" ]
null
null
null
#pragma once #include "rand_search.hpp" #include "branch_and_bound.hpp" namespace mog { namespace cep { template <int L> class SearchManager { public: // Types typedef mog::data::Graph<L> G; static constexpr int const N = L * B; static std::vector<mog::data::Edge> run(G const& root, int seed = 12345) { // main logic //------------------------------------------------------ // Round 1. Random Search //------------------------------------------------------ std::default_random_engine gen(seed); std::uniform_int_distribution<uint32_t> int_dist({}); SearchResult<L> best({INF, {}}); bool large_graph = root.n >= 300; std::vector<int> strategies = {3, 4}; int stability = 0; int const stability_threshold = large_graph ? 8 : 20; int allowance = INF; int num_branch_samples = 20; int num_max_solutions = 1; int num_tries = large_graph ? 10 : 120; uint32_t best_shuffle_seed = 0, best_branch_seed = 0; int best_strategy = strategies[0]; bool finished = false; for (int i = 0; i < num_tries; ++i) { uint32_t shuffle_seed = int_dist(gen); uint32_t branch_seed = int_dist(gen); int strategy = strategies[i % strategies.size()]; auto ret = RandSearch::run(root, shuffle_seed, branch_seed, num_max_solutions, strategy, num_branch_samples, allowance, nullptr, true); if (ret.second.first < best.first) { // update best best = ret.second; stability = 0; best_shuffle_seed = shuffle_seed; best_branch_seed = branch_seed; best_strategy = strategy; } else { if (++stability == stability_threshold) { if (num_max_solutions == 2) { // done with random search break; } num_max_solutions = 2; stability = 0; } } if (ret.first) { finished = true; break; // complete } } //------------------------------------------------------ // Round 2. Exhaustive Search //------------------------------------------------------ if (!finished) { int num_contexts_per_strategy = 4; int initial_node_limit = 2000; int eliminate_thres = 50; if (root.n >= 300) { num_contexts_per_strategy = std::min(num_contexts_per_strategy, 1); } else if (root.n >= 200) { num_contexts_per_strategy = std::min(num_contexts_per_strategy, 2); eliminate_thres = 20; } // Create search contexts std::vector<SearchContext<L>> contexts; std::vector<double> progress_sofar; std::vector<int> bnb_strategies = {50, 51}; for (auto st : bnb_strategies) { for (int j = 0; j < num_contexts_per_strategy; ++j) { auto ss = st == best_strategy && j == 0 ? best_shuffle_seed : int_dist(gen); auto bs = st == best_strategy && j == 0 ? best_branch_seed : int_dist(gen); auto ctx = SearchContext<L>({st * 100 + j, root, ss, bs, st, num_branch_samples, initial_node_limit, &best}); contexts.push_back(ctx); progress_sofar.push_back(0); } } // main logic int index = 0; while (!finished) { auto bnb_result = BranchAndBound::run(contexts[index], best.first); if (bnb_result.second.first < best.first) { best = bnb_result.second; // update best } if (bnb_result.first) { finished = true; // finish } // context switch if (contexts.size() > 1) { ++index; if (index == contexts.size()) { if (true) { double diff = 0; // normalize limits for (int i = 0; i < contexts.size(); ++i) { auto& ctx = contexts[i]; ctx.node_limit = std::min(100000LL, ctx.node_limit * 2); diff = std::max(diff, ctx.progress.value() - progress_sofar[i]); } // max progress diff bonus for (int i = 0; i < contexts.size(); ++i) { auto& ctx = contexts[i]; double vv = ctx.progress.value(); if (vv - progress_sofar[i] == diff) { ctx.node_limit *= 2; } progress_sofar[i] = vv; } // eliminate one context per strategy int jj = contexts.size() / strategies.size(); if (jj > 1 && contexts[0].node_count > initial_node_limit * eliminate_thres) { for (int s = strategies.size() - 1; s >= 0; --s) { double worst = 2; int ww = -1; for (int j = 0; j < jj; ++j) { auto vv = contexts[s * jj + j].progress.value(); if (vv < worst) { ww = s * jj + j; worst = vv; } } contexts.erase(contexts.begin() + ww); } } } index = 0; } } } } // collect result return (root.nbr1 ^ best.second).to_vector(); } }; } // namespace cep } // namespace mog
32.030675
119
0.502777
[ "vector" ]
9d45ce16431e0a8afb8160992bc63b69c596d444
9,905
cc
C++
src/graph.cc
mathstuf/ninja
abd33d5e3b11ae5470f62cbce49723a4cf62870d
[ "Apache-2.0" ]
null
null
null
src/graph.cc
mathstuf/ninja
abd33d5e3b11ae5470f62cbce49723a4cf62870d
[ "Apache-2.0" ]
null
null
null
src/graph.cc
mathstuf/ninja
abd33d5e3b11ae5470f62cbce49723a4cf62870d
[ "Apache-2.0" ]
null
null
null
// Copyright 2011 Google 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 "graph.h" #include <assert.h> #include <stdio.h> #include "build_log.h" #include "depfile_parser.h" #include "disk_interface.h" #include "metrics.h" #include "parsers.h" #include "state.h" #include "util.h" bool Node::Stat(DiskInterface* disk_interface) { METRIC_RECORD("node stat"); mtime_ = disk_interface->Stat(path_); return mtime_ > 0; } bool Edge::RecomputeDirty(State* state, DiskInterface* disk_interface, string* err) { bool dirty = false; outputs_ready_ = true; if (!rule_->depfile().empty()) { if (!LoadDepFile(state, disk_interface, err)) return false; } // Visit all inputs; we're dirty if any of the inputs are dirty. TimeStamp most_recent_input = 1; for (vector<Node*>::iterator i = inputs_.begin(); i != inputs_.end(); ++i) { if ((*i)->StatIfNecessary(disk_interface)) { if (Edge* edge = (*i)->in_edge()) { if (!edge->RecomputeDirty(state, disk_interface, err)) return false; } else { // This input has no in-edge; it is dirty if it is missing. (*i)->set_dirty(!(*i)->exists()); } } // If an input is not ready, neither are our outputs. if (Edge* edge = (*i)->in_edge()) { if (!edge->outputs_ready_) outputs_ready_ = false; } if (!is_order_only(i - inputs_.begin())) { // If a regular input is dirty (or missing), we're dirty. // Otherwise consider mtime. if ((*i)->dirty()) { dirty = true; } else { if ((*i)->mtime() > most_recent_input) most_recent_input = (*i)->mtime(); } } } // We may also be dirty due to output state: missing outputs, out of // date outputs, etc. Visit all outputs and determine whether they're dirty. if (!dirty) { BuildLog* build_log = state ? state->build_log_ : 0; string command = EvaluateCommand(true); for (vector<Node*>::iterator i = outputs_.begin(); i != outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface); if (RecomputeOutputDirty(build_log, most_recent_input, command, *i)) { dirty = true; break; } } } // Finally, visit each output to mark off that we've visited it, and update // their dirty state if necessary. for (vector<Node*>::iterator i = outputs_.begin(); i != outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface); if (dirty) (*i)->MarkDirty(); } // If we're dirty, our outputs are normally not ready. (It's possible to be // clean but still not be ready in the presence of order-only inputs.) // But phony edges with no inputs have nothing to do, so are always ready. if (dirty && !(is_phony() && inputs_.empty())) outputs_ready_ = false; return true; } bool Edge::RecomputeOutputDirty(BuildLog* build_log, TimeStamp most_recent_input, const string& command, Node* output) { if (is_phony()) { // Phony edges don't write any output. Outputs are only dirty if // there are no inputs and we're missing the output. return inputs_.empty() && !output->exists(); } BuildLog::LogEntry* entry = 0; // Dirty if we're missing the output. if (!output->exists()) return true; // Dirty if the output is older than the input. if (output->mtime() < most_recent_input) { // If this is a restat rule, we may have cleaned the output with a restat // rule in a previous run and stored the most recent input mtime in the // build log. Use that mtime instead, so that the file will only be // considered dirty if an input was modified since the previous run. if (rule_->restat() && build_log && (entry = build_log->LookupByOutput(output->path()))) { if (entry->restat_mtime < most_recent_input) return true; } else { return true; } } // May also be dirty due to the command changing since the last build. // But if this is a generator rule, the command changing does not make us // dirty. if (!rule_->generator() && build_log && (entry || (entry = build_log->LookupByOutput(output->path())))) { if (command != entry->command) return true; } return false; } bool Edge::AllInputsReady() const { for (vector<Node*>::const_iterator i = inputs_.begin(); i != inputs_.end(); ++i) { if ((*i)->in_edge() && !(*i)->in_edge()->outputs_ready()) return false; } return true; } /// An Env for an Edge, providing $in and $out. struct EdgeEnv : public Env { EdgeEnv(Edge* edge) : edge_(edge) {} virtual string LookupVariable(const string& var); /// Given a span of Nodes, construct a list of paths suitable for a command /// line. XXX here is where shell-escaping of e.g spaces should happen. string MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end); Edge* edge_; }; string EdgeEnv::LookupVariable(const string& var) { if (var == "in") { int explicit_deps_count = edge_->inputs_.size() - edge_->implicit_deps_ - edge_->order_only_deps_; return MakePathList(edge_->inputs_.begin(), edge_->inputs_.begin() + explicit_deps_count); } else if (var == "out") { return MakePathList(edge_->outputs_.begin(), edge_->outputs_.end()); } else if (edge_->env_) { return edge_->env_->LookupVariable(var); } else { // XXX shoudl we warn here? return string(); } } string EdgeEnv::MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end) { string result; for (vector<Node*>::iterator i = begin; i != end; ++i) { if (!result.empty()) result.push_back(' '); const string& path = (*i)->path(); if (path.find(" ") != string::npos) { result.append("\""); result.append(path); result.append("\""); } else { result.append(path); } } return result; } string Edge::EvaluateCommand(bool incl_rsp_file) { EdgeEnv env(this); string command = rule_->command().Evaluate(&env); if (incl_rsp_file && HasRspFile()) command += ";rspfile=" + GetRspFileContent(); return command; } string Edge::EvaluateDepFile() { EdgeEnv env(this); return rule_->depfile().Evaluate(&env); } string Edge::GetDescription() { EdgeEnv env(this); return rule_->description().Evaluate(&env); } bool Edge::HasRspFile() { return !rule_->rspfile().empty(); } string Edge::GetRspFile() { EdgeEnv env(this); return rule_->rspfile().Evaluate(&env); } string Edge::GetRspFileContent() { EdgeEnv env(this); return rule_->rspfile_content().Evaluate(&env); } bool Edge::LoadDepFile(State* state, DiskInterface* disk_interface, string* err) { METRIC_RECORD("depfile load"); string path = EvaluateDepFile(); string content = disk_interface->ReadFile(path, err); if (!err->empty()) return false; if (content.empty()) return true; DepfileParser depfile; string depfile_err; if (!depfile.Parse(&content, &depfile_err)) { *err = path + ": " + depfile_err; return false; } // Check that this depfile matches our output. StringPiece opath = StringPiece(outputs_[0]->path()); if (opath != depfile.out_) { *err = "expected depfile '" + path + "' to mention '" + outputs_[0]->path() + "', got '" + depfile.out_.AsString() + "'"; return false; } inputs_.insert(inputs_.end() - order_only_deps_, depfile.ins_.size(), 0); implicit_deps_ += depfile.ins_.size(); vector<Node*>::iterator implicit_dep = inputs_.end() - order_only_deps_ - depfile.ins_.size(); // Add all its in-edges. for (vector<StringPiece>::iterator i = depfile.ins_.begin(); i != depfile.ins_.end(); ++i, ++implicit_dep) { if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, err)) return false; Node* node = state->GetNode(*i); *implicit_dep = node; node->AddOutEdge(this); // If we don't have a edge that generates this input already, // create one; this makes us not abort if the input is missing, // but instead will rebuild in that circumstance. if (!node->in_edge()) { Edge* phony_edge = state->AddEdge(&State::kPhonyRule); node->set_in_edge(phony_edge); phony_edge->outputs_.push_back(node); // RecomputeDirty might not be called for phony_edge if a previous call // to RecomputeDirty had caused the file to be stat'ed. Because previous // invocations of RecomputeDirty would have seen this node without an // input edge (and therefore ready), we have to set outputs_ready_ to true // to avoid a potential stuck build. If we do call RecomputeDirty for // this node, it will simply set outputs_ready_ to the correct value. phony_edge->outputs_ready_ = true; } } return true; } void Edge::Dump() { printf("[ "); for (vector<Node*>::iterator i = inputs_.begin(); i != inputs_.end(); ++i) { printf("%s ", (*i)->path().c_str()); } printf("--%s-> ", rule_->name().c_str()); for (vector<Node*>::iterator i = outputs_.begin(); i != outputs_.end(); ++i) { printf("%s ", (*i)->path().c_str()); } printf("]\n"); } bool Edge::is_phony() const { return rule_ == &State::kPhonyRule; }
31.444444
80
0.630692
[ "vector" ]
9d46993dab28a2549145b33835dc7c43d0122161
5,175
cpp
C++
test-suite/creditriskplus.cpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
3,358
2015-12-18T02:56:17.000Z
2022-03-31T02:42:47.000Z
test-suite/creditriskplus.cpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
965
2015-12-21T10:35:28.000Z
2022-03-30T02:47:00.000Z
test-suite/creditriskplus.cpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
1,663
2015-12-17T17:45:38.000Z
2022-03-31T07:58:29.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2013 Peter Caspers This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include "creditriskplus.hpp" #include "utilities.hpp" #include <ql/experimental/risk/creditriskplus.hpp> #include <ql/math/comparison.hpp> using namespace QuantLib; using namespace boost::unit_test_framework; void CreditRiskPlusTest::testReferenceValues() { BOOST_TEST_MESSAGE( "Testing extended credit risk plus model against reference values..."); static const Real tol = 1E-8; /* Reference Values are taken from [1] Integrating Correlations, Risk, July 1999, table A, table B and figure 1 */ std::vector<Real> sector1Exposure(1000, 1.0); std::vector<Real> sector1Pd(1000, 0.04); std::vector<Size> sector1Sector(1000, 0); std::vector<Real> sector2Exposure(1000, 2.0); std::vector<Real> sector2Pd(1000, 0.02); std::vector<Size> sector2Sector(1000, 1); std::vector<Real> exposure; exposure.insert(exposure.end(), sector1Exposure.begin(), sector1Exposure.end()); exposure.insert(exposure.end(), sector2Exposure.begin(), sector2Exposure.end()); std::vector<Real> pd; pd.insert(pd.end(), sector1Pd.begin(), sector1Pd.end()); pd.insert(pd.end(), sector2Pd.begin(), sector2Pd.end()); std::vector<Size> sector; sector.insert(sector.end(), sector1Sector.begin(), sector1Sector.end()); sector.insert(sector.end(), sector2Sector.begin(), sector2Sector.end()); std::vector<Real> relativeDefaultVariance; relativeDefaultVariance.push_back(0.75 * 0.75); relativeDefaultVariance.push_back(0.75 * 0.75); Matrix rho(2, 2); rho[0][0] = rho[1][1] = 1.0; rho[0][1] = rho[1][0] = 0.50; Real unit = 0.1; CreditRiskPlus cr(exposure, pd, sector, relativeDefaultVariance, rho, unit); if ( std::fabs(cr.sectorExposures()[0] - 1000.0) > tol ) BOOST_FAIL("failed to reproduce sector 1 exposure (" << cr.sectorExposures()[0] << ", should be 1000)"); if ( std::fabs(cr.sectorExposures()[1] - 2000.0) > tol ) BOOST_FAIL("failed to reproduce sector 2 exposure (" << cr.sectorExposures()[1] << ", should be 2000)"); if ( std::fabs(cr.sectorExpectedLoss()[0] - 40.0) > tol ) BOOST_FAIL("failed to reproduce sector 1 expected loss (" << cr.sectorExpectedLoss()[0] << ", should be 40)"); if ( std::fabs(cr.sectorExpectedLoss()[1] - 40.0) > tol ) BOOST_FAIL("failed to reproduce sector 2 expected loss (" << cr.sectorExpectedLoss()[1] << ", should be 40)"); if ( std::fabs(cr.sectorUnexpectedLoss()[0] - 30.7) > 0.05 ) BOOST_FAIL("failed to reproduce sector 1 unexpected loss (" << cr.sectorUnexpectedLoss()[0] << ", should be 30.7)"); if ( std::fabs(cr.sectorUnexpectedLoss()[1] - 31.3) > 0.05 ) BOOST_FAIL("failed to reproduce sector 2 unexpected loss (" << cr.sectorUnexpectedLoss()[1] << ", should be 31.3)"); if ( std::fabs(cr.exposure() - 3000.0) > tol ) BOOST_FAIL("failed to reproduce overall exposure (" << cr.exposure() << ", should be 3000)"); if ( std::fabs(cr.expectedLoss() - 80.0) > tol ) BOOST_FAIL("failed to reproduce overall expected loss (" << cr.expectedLoss() << ", should be 80)"); if ( std::fabs(cr.unexpectedLoss() - 53.1) > 0.01 ) BOOST_FAIL("failed to reproduce overall unexpected loss (" << cr.unexpectedLoss() << ", should be 53.1)"); // the overall relative default variance in the paper seems generously rounded, // but since EL and UL is matching closely and the former is retrieved // as a simple expression in the latter, we do not suspect a problem in our // calculation if ( std::fabs(cr.relativeDefaultVariance() - 0.65 * 0.65) > 0.001 ) BOOST_FAIL("failed to reproduce overall relative default variance (" << cr.relativeDefaultVariance() << ", should be 0.4225)"); if ( std::fabs(cr.lossQuantile(0.99) - 250) > 0.5 ) BOOST_FAIL("failed to reproduce overall 99 percentile (" << cr.lossQuantile(0.99) << ", should be 250)"); } test_suite *CreditRiskPlusTest::suite() { auto* suite = BOOST_TEST_SUITE("Credit risk plus tests"); suite->add(QUANTLIB_TEST_CASE(&CreditRiskPlusTest::testReferenceValues)); return suite; }
40.748031
83
0.643478
[ "vector", "model" ]
9d598d81713b0b3e3dab1e1fdd6cc2d0e87ee553
2,462
cpp
C++
src/game/src/systems/system_manager.cpp
Sampas/cavez
b89185554477b92bf987c9e5d26b0a8abe1ae568
[ "MIT" ]
2
2019-03-11T11:26:52.000Z
2019-09-26T07:50:55.000Z
src/game/src/systems/system_manager.cpp
Sampas/cavez
b89185554477b92bf987c9e5d26b0a8abe1ae568
[ "MIT" ]
1
2020-10-29T15:44:47.000Z
2020-10-29T15:44:47.000Z
src/game/src/systems/system_manager.cpp
Sampas/cavez
b89185554477b92bf987c9e5d26b0a8abe1ae568
[ "MIT" ]
1
2020-10-28T18:56:46.000Z
2020-10-28T18:56:46.000Z
/// Copyright (c) 2019 Joni Louhela /// /// 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 "system_manager.hpp" #include "ec/component_container.hpp" #include "ec/entity_container.hpp" System_manager::System_manager(Rendering_interface& rendering_interface, const Input_interface& input_interface) : m_input_system{input_interface}, m_render_system{rendering_interface}, m_physics_system{} { } void System_manager::set_world_bounds(const math::Vector2I& bounds) { m_physics_system.set_world_bounds(bounds); } void System_manager::update(float delta_time, Cameras& cameras, Entity_container& entities, Component_container& component_container) { m_input_system.update(delta_time, entities, component_container); m_throttle_system.update(delta_time, entities, component_container); m_physics_system.update(delta_time, component_container); m_camera_follow_system.update(delta_time, cameras, entities, component_container); } void System_manager::render(Cameras& cameras, const Level& level, const Entity_container& entities, const Component_container& component_container) { m_render_system.render(cameras, level); m_render_system.render(cameras, entities, component_container); }
44.763636
95
0.721771
[ "render" ]
9d60c5b130ce57ab6f5d0932b821dce729d2ebbf
6,982
cpp
C++
cyberdog_ception/cyberdog_scenedetection/scenedetection/src/scene_detection.cpp
gitter-badger/cyberdog_ros2
f995b3cbf5773a47cd2d7293b0622d91fb409cdc
[ "Apache-2.0" ]
9
2021-12-27T02:51:35.000Z
2022-03-07T14:08:28.000Z
cyberdog_ception/cyberdog_scenedetection/scenedetection/src/scene_detection.cpp
gitter-badger/cyberdog_ros2
f995b3cbf5773a47cd2d7293b0622d91fb409cdc
[ "Apache-2.0" ]
1
2021-12-21T03:05:58.000Z
2021-12-21T03:05:58.000Z
cyberdog_ception/cyberdog_scenedetection/scenedetection/src/scene_detection.cpp
gitter-badger/cyberdog_ros2
f995b3cbf5773a47cd2d7293b0622d91fb409cdc
[ "Apache-2.0" ]
3
2021-10-24T01:14:44.000Z
2021-12-20T11:54:41.000Z
// Copyright (c) 2021 Beijing Xiaomi Mobile Software Co., Ltd. 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 <termios.h> // termios, TCSANOW, ECHO, ICANON #include <unistd.h> // STDIN_FILENO #include <time.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include <syslog.h> #include <math.h> #include <memory> #include <utility> #include <string> #include <fstream> #include <thread> #include <algorithm> #include <cctype> #include <vector> #include <map> #include "sys/stat.h" #include "rclcpp/rclcpp.hpp" #include "std_msgs/msg/string.hpp" #include "motion_msgs/msg/scene.hpp" #include "ception_msgs/srv/gps_scene_node.hpp" #include "cyberdog_utils/lifecycle_node.hpp" #include "ception_base/ception_base.hpp" #include "pluginlib/class_loader.hpp" namespace SceneDetection { typedef enum { UNSET, INDOOR, OUTDOOR } detection_scene; class GpsPubNode : public cyberdog_utils::LifecycleNode { public: GpsPubNode(); ~GpsPubNode(); protected: /* Lifecycle stages */ cyberdog_utils::CallbackReturn on_configure(const rclcpp_lifecycle::State & state) override; cyberdog_utils::CallbackReturn on_activate(const rclcpp_lifecycle::State & state) override; cyberdog_utils::CallbackReturn on_deactivate(const rclcpp_lifecycle::State & state) override; cyberdog_utils::CallbackReturn on_cleanup(const rclcpp_lifecycle::State & state) override; cyberdog_utils::CallbackReturn on_shutdown(const rclcpp_lifecycle::State & state) override; private: std::shared_ptr<pluginlib::ClassLoader<ception_base::Cyberdog_GPS>> classloader_; std::shared_ptr<ception_base::Cyberdog_GPS> gps_; std::shared_ptr<ception_base::Cyberdog_GPS_payload> payload_; void gps_data_receiver_callback(void); void payload_callback(std::shared_ptr<ception_base::Cyberdog_GPS_payload> payload); void handle_service( const std::shared_ptr<rmw_request_id_t> request_header, const std::shared_ptr<ception_msgs::srv::GpsSceneNode::Request> request, const std::shared_ptr<ception_msgs::srv::GpsSceneNode::Response> response); // message struct define here motion_msgs::msg::Scene message; rclcpp::TimerBase::SharedPtr timer_; /* Service */ rclcpp::Service<ception_msgs::srv::GpsSceneNode>::SharedPtr scene_detection_cmd_server_; rclcpp::CallbackGroup::SharedPtr callback_group_; rclcpp_lifecycle::LifecyclePublisher<motion_msgs::msg::Scene>::SharedPtr publisher_; }; // class GpsPubNode } // namespace SceneDetection namespace SceneDetection { GpsPubNode::GpsPubNode() : cyberdog_utils::LifecycleNode("GpsPubNode") { RCLCPP_INFO(get_logger(), "Creating GpsPubNode."); } GpsPubNode::~GpsPubNode() { RCLCPP_INFO(get_logger(), "Destroying GpsPubNode"); } cyberdog_utils::CallbackReturn GpsPubNode::on_configure(const rclcpp_lifecycle::State &) { RCLCPP_INFO(get_logger(), "Configuring"); callback_group_ = this->create_callback_group(rclcpp::CallbackGroupType::Reentrant); publisher_ = this->create_publisher<motion_msgs::msg::Scene>( "SceneDetection", rclcpp::SystemDefaultsQoS()); scene_detection_cmd_server_ = this->create_service<ception_msgs::srv::GpsSceneNode>( "SceneDetection", std::bind( &GpsPubNode::handle_service, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), rmw_qos_profile_default, callback_group_); message = motion_msgs::msg::Scene(); classloader_ = std::make_shared<pluginlib::ClassLoader<ception_base::Cyberdog_GPS>>( "ception_base", "ception_base::Cyberdog_GPS"); gps_ = classloader_->createSharedInstance("bcmgps_plugin::Cyberdog_BCMGPS"); gps_->SetPayloadCallback( std::bind( &GpsPubNode::payload_callback, this, std::placeholders::_1 )); gps_->Open(); RCLCPP_INFO(get_logger(), "Configuring,success"); return cyberdog_utils::CallbackReturn::SUCCESS; } cyberdog_utils::CallbackReturn GpsPubNode::on_activate(const rclcpp_lifecycle::State &) { RCLCPP_INFO(get_logger(), "Activaing"); gps_->Start(); publisher_->on_activate(); timer_ = this->create_wall_timer( std::chrono::seconds(1), std::bind(&SceneDetection::GpsPubNode::gps_data_receiver_callback, this)); return cyberdog_utils::CallbackReturn::SUCCESS; } cyberdog_utils::CallbackReturn GpsPubNode::on_deactivate(const rclcpp_lifecycle::State &) { RCLCPP_INFO(get_logger(), "Deactiving"); gps_->Stop(); publisher_->on_deactivate(); return cyberdog_utils::CallbackReturn::SUCCESS; } cyberdog_utils::CallbackReturn GpsPubNode::on_cleanup(const rclcpp_lifecycle::State &) { gps_->Close(); publisher_.reset(); return cyberdog_utils::CallbackReturn::SUCCESS; } cyberdog_utils::CallbackReturn GpsPubNode::on_shutdown(const rclcpp_lifecycle::State &) { gps_->Close(); publisher_.reset(); return cyberdog_utils::CallbackReturn::SUCCESS; } void GpsPubNode::gps_data_receiver_callback() { auto message = motion_msgs::msg::Scene(); detection_scene environment = UNSET; if (payload_ != nullptr) { if (payload_->fixType == 2 || payload_->fixType == 3) { environment = OUTDOOR; } else { environment = INDOOR; } message.lat = payload_->lat; message.lon = payload_->lon; message.if_danger = false; } else { message.lat = 0; message.lon = 0; message.if_danger = false; } message.type = environment; publisher_->publish(std::move(message)); } void GpsPubNode::payload_callback(std::shared_ptr<ception_base::Cyberdog_GPS_payload> payload) { payload_ = payload; } void GpsPubNode::handle_service( const std::shared_ptr<rmw_request_id_t> request_header, const std::shared_ptr<ception_msgs::srv::GpsSceneNode::Request> request, const std::shared_ptr<ception_msgs::srv::GpsSceneNode::Response> response) { (void)request_header; RCLCPP_INFO(get_logger(), "request: %d", request->command); response->success = true; switch (request->command) { case ception_msgs::srv::GpsSceneNode::Request::GPS_START: gps_->Start(); break; case ception_msgs::srv::GpsSceneNode::Request::GPS_STOP: gps_->Stop(); break; default: response->success = false; break; } } } // namespace SceneDetection int main(int argc, char * argv[]) { rclcpp::init(argc, argv); rclcpp::executors::MultiThreadedExecutor exec_; auto node = std::make_shared<SceneDetection::GpsPubNode>(); exec_.add_node(node->get_node_base_interface()); exec_.spin(); rclcpp::shutdown(); return 0; }
30.757709
95
0.743054
[ "vector" ]
9d621df5aca928385f634596342432748fb14a84
26,191
cpp
C++
src/main.cpp
Q2499279972/klotski
18c16546432f407f74d0c77c41453f5366f6d65f
[ "MIT" ]
1
2017-09-09T13:13:09.000Z
2017-09-09T13:13:09.000Z
src/main.cpp
Q2499279972/klotski
18c16546432f407f74d0c77c41453f5366f6d65f
[ "MIT" ]
null
null
null
src/main.cpp
Q2499279972/klotski
18c16546432f407f74d0c77c41453f5366f6d65f
[ "MIT" ]
null
null
null
#include <stdio.h> #include <windows.h> #include "window.hpp" #include "Klotski.hpp" #include "texture.hpp" #include "misc.hpp" #include "history.hpp" #include "RightButtonMenu.hpp" #include "ReadLuaConfig.hpp" #include <gl/glext.h> #define VERSIONSTRING "0.01" static int delaycnt=0; void KlotskiBlock::Draw() { int j; if(Id=='-') { return; } else if(Id=='#') { for(j=0;j<Width*Height;j++) { if(Shape[j]==' ') continue; int x=j%Width+Posx; int y=j/Width+Posy; glBegin(GL_QUADS); glColor4f(0,0,0,0); glVertex2f(x,y); glVertex2f(x,y+1); glVertex2f(x+1,y+1); glVertex2f(x+1,y); glEnd(); } return; } else if(Id=='.') { for(j=0;j<Width*Height;j++) { if(Shape[j]==' ') continue; int x=j%Width+Posx; int y=j/Width+Posy; unsigned char picnum=ImageMappingMask[j]; int a=picnum%16; int b=picnum/16; glBegin(GL_QUADS); glColor3f(1,1,1); glTexCoord2f(a/16.0, b/16.0/4+1/2.0); glVertex2f(x,y); glTexCoord2f(a/16.0, (b+1)/16.0/4+1/2.0); glVertex2f(x,y+1); glTexCoord2f((a+1)/16.0, (b+1)/16.0/4+1/2.0); glVertex2f(x+1,y+1); glTexCoord2f((a+1)/16.0, b/16.0/4+1/2.0); glVertex2f(x+1,y); glEnd(); } return; } else { float k; if(Id=='*'||Id=='&') k=1.0f; else k=0.0f; for(j=0;j<Width*Height;j++) { if(Shape[j]==' ') continue; int x=j%Width+Posx; int y=j/Width+Posy; unsigned char picnum=ImageMappingMask[j]; int a=picnum%16; int b=picnum/16; glBegin(GL_QUADS); glColor3f(1,1,1); glTexCoord2f(a/16.0, b/16.0/4+k/4); glVertex2f(x,y); glTexCoord2f(a/16.0, (b+1)/16.0/4+k/4); glVertex2f(x,y+1); glTexCoord2f((a+1)/16.0, (b+1)/16.0/4+k/4); glVertex2f(x+1,y+1); glTexCoord2f((a+1)/16.0, b/16.0/4+k/4); glVertex2f(x+1,y); glEnd(); } } } MSG msg; int GameExit=0; int state; Klotski *gKlotski; Window *gKlotskiWindow; POINT pt; int id; char LuaFilePath[256]; static LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch (uMsg) { case WM_DROPFILES: { UINT count; HDROP hDropInfo = (HDROP)wParam; count = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0); if( count==1 ) { DragQueryFile(hDropInfo, 0, LuaFilePath, sizeof(LuaFilePath)); DragFinish(hDropInfo); printf("Drag in file %s\n",LuaFilePath); gKlotski->setState(IDLE); state=5; } break; } case WM_LBUTTONDOWN: { int x=pt.x = GET_X_LPARAM(lParam); int y=pt.y = GET_Y_LPARAM(lParam); printf("LBUTTONDOWN %d %d\n",pt.x,pt.y); if(gKlotski->getState()!=NORMAL) break; x/=gKlotskiWindow->BlockPixel; y/=gKlotskiWindow->BlockPixel; id=gKlotski->Map->GetBlockId(x,y); printf("id= %d %c \n",id, id); break; } case WM_LBUTTONUP: { POINT pt2; printf("LBUTTONUP %d %d\n",pt.x,pt.y); if(gKlotski->getState()!=NORMAL) break; int x=pt2.x = GET_X_LPARAM(lParam); int y=pt2.y = GET_Y_LPARAM(lParam); int dx=pt2.x-pt.x; int dy=pt2.y-pt.y; if(id==' ') return 0; if(abs(dx)>abs(dy)) { if(dx>gKlotskiWindow->BlockPixel*2/3) { gKlotski->DoMove(id,RIGHT); } if(dx<-gKlotskiWindow->BlockPixel*2/3) { gKlotski->DoMove(id,LEFT); } } else { if(dy>gKlotskiWindow->BlockPixel*2/3) { gKlotski->DoMove(id,DOWN); } if(dy<-gKlotskiWindow->BlockPixel*2/3) { gKlotski->DoMove(id,UP); } } if(gKlotski->checkTargetSuccess()==0) { char str[50]; snprintf(str,50,"%s %d/%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); gKlotskiWindow->SetTitle(str); gKlotski->setState(NORMAL); } else { char str[50]; snprintf(str,50,"%s successed %d/%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); gKlotskiWindow->SetTitle(str); gKlotski->setState(FINISHED); } break; } case WM_CLOSE: { PostQuitMessage(0); return( 0 ); break; } case WM_KEYDOWN: { if(gKlotski->getState()!=NORMAL && gKlotski->getState()!=FINISHED) break; if(wParam=='B') { if( gKlotski->His->CanBackward()) { printf("UNDO\n"); StepInfo step = gKlotski->His->GetBackwardStep(); gKlotski->His->DoBackward(); if(step.move==LEFT) step.move=RIGHT; else if(step.move==RIGHT) step.move=LEFT; else if(step.move==UP) step.move=DOWN; else if(step.move==DOWN) step.move=UP; if(step.move==UP) gKlotski->Map->SearchBlockById(step.id)->DoMoveUp(); if(step.move==DOWN) gKlotski->Map->SearchBlockById(step.id)->DoMoveDown(); if(step.move==LEFT) gKlotski->Map->SearchBlockById(step.id)->DoMoveLeft(); if(step.move==RIGHT) gKlotski->Map->SearchBlockById(step.id)->DoMoveRight(); gKlotski->Map->UpdateMap(); gKlotski->Map->Print(); if(gKlotski->checkTargetSuccess()==0) { char str[50]; snprintf(str,50,"%s %d/%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); gKlotskiWindow->SetTitle(str); gKlotski->setState(NORMAL); } else { char str[50]; snprintf(str,50,"%s successed %d/%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); gKlotskiWindow->SetTitle(str); gKlotski->setState(FINISHED); } } } if(wParam=='F') { if( gKlotski->His->CanForward()) { printf("REDO\n"); StepInfo step = gKlotski->His->GetForwardStep(); gKlotski->His->DoForward(); if(step.move==UP) gKlotski->Map->SearchBlockById(step.id)->DoMoveUp(); if(step.move==DOWN) gKlotski->Map->SearchBlockById(step.id)->DoMoveDown(); if(step.move==LEFT) gKlotski->Map->SearchBlockById(step.id)->DoMoveLeft(); if(step.move==RIGHT) gKlotski->Map->SearchBlockById(step.id)->DoMoveRight(); gKlotski->Map->UpdateMap(); gKlotski->Map->Print(); if(gKlotski->checkTargetSuccess()==0) { char str[50]; snprintf(str,50,"%s %d/%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); gKlotskiWindow->SetTitle(str); gKlotski->setState(NORMAL); } else { char str[50]; snprintf(str,50,"%s successed %d/%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); gKlotskiWindow->SetTitle(str); gKlotski->setState(FINISHED); } } } break; } case WM_CONTEXTMENU: { POINT p = {LOWORD(lParam),HIWORD(lParam)}; HMENU hMainMenu = GetMenu(hWnd); HMENU m = CreatePopupMenu(); AppendMenu(m, MF_STRING, 0x8001,"Load level file"); AppendMenu(m, MF_STRING, 0x8002,"Save screen"); AppendMenu(m, MF_STRING, 0x8003,"Save steps"); if(gKlotski->getState()!=IDLE && gKlotski->His->CurrentStep==0) { AppendMenu(m, MF_STRING, 0x8004,"Auto (file.txt)"); } AppendMenu(hMainMenu, MF_STRING | MF_POPUP, (UINT)m, "main"); TrackPopupMenu(m, TPM_VERTICAL|TPM_TOPALIGN, p.x, p.y, 0, hWnd, NULL); DestroyMenu(m); break; } case WM_COMMAND: { switch (wParam) { case 0x8001: { OPENFILENAME ofn; // common dialog box structure char szFile[260]; // buffer for file name // Initialize OPENFILENAME ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = 0; ofn.lpstrFile = szFile; // Set lpstrFile[0] to '\0' so that GetOpenFileName does not // use the contents of szFile to initialize itself. ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(szFile); ofn.lpstrFilter = "All\0*.*\0Lua\0*.Lua\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; // Display the Open dialog box. if (GetOpenFileName(&ofn)==TRUE) { strcpy(LuaFilePath,szFile); gKlotski->setState(IDLE); state=5; } break; } case 0x8002: { //refered http://blog.csdn.net/dreamcs/article/details/6052984 static char head[54]= { 0x42,0x4d,0x66,0x75,0x00,0x00,0x00,0x00, 0x00,0x00,0x36,0x00,0x00,0x00,0x28,0x00, 0x00,0x00,0x64,0x00,0x00,0x00,0x64,0x00, 0x00,0x00,0x01,0x00,0x18,0x00,0x00,0x00, 0x00,0x00,0x30,0x75, }; GLint pixelLength; GLubyte * pixelDate; FILE * wfile; int width=gKlotskiWindow->TotalPixel_x; int height=gKlotskiWindow->TotalPixel_y; pixelLength = width * 3; if ( pixelLength % 4 != 0 ) { pixelLength += 4 - pixelLength%4; } pixelLength *= height; pixelDate = (GLubyte *)malloc( pixelLength ); if ( pixelDate == 0 ) { printf("error: malloc!\n"); break; } char bmpName[100]; char str[50]={0}; if(gKlotski->getState()!=IDLE) snprintf(str,50,"%s %d_%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); SYSTEMTIME tm; GetLocalTime(&tm); snprintf(bmpName,100,".\\%s_%4.4d%2.2d%2.2d_%2.2dh%2.2dm%2.2ds.bmp", str, tm.wYear, tm.wMonth, tm.wDay, tm.wHour, tm.wMinute, tm.wSecond); printf("save screen to file %s\n",bmpName); wfile = fopen( bmpName, "wb" ); if(wfile==NULL) { free( pixelDate ); printf("can't open file %s\n",bmpName); break; } fwrite( head, 54, 1, wfile ); fseek( wfile, 0x0012, SEEK_SET ); fwrite( &width, sizeof(width), 1, wfile ); fwrite( &height, sizeof(height ), 1, wfile ); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glReadPixels( 0, 0, width, height, GL_BGR_EXT, GL_UNSIGNED_BYTE, pixelDate ); fseek( wfile, 0, SEEK_END ); fwrite( pixelDate, pixelLength, 1, wfile ); fclose( wfile ); free( pixelDate ); break; } case 0x8003: { if(gKlotski->getState()!=IDLE) { char str[50]={0}; char name[100]; FILE * wfile; snprintf(str,50,"his_%s",gKlotski->cfg.title.c_str()); SYSTEMTIME tm; GetLocalTime(&tm); snprintf(name,100,".\\%s_%4.4d%2.2d%2.2d_%2.2dh%2.2dm%2.2ds.txt", str, tm.wYear, tm.wMonth, tm.wDay, tm.wHour, tm.wMinute, tm.wSecond); wfile = fopen( name, "w" ); if(wfile==NULL) break; gKlotski->His->SaveHistory(wfile); fclose(wfile); } break; } case 0x8004: { OPENFILENAME ofn; // common dialog box structure char szFile[260]; // buffer for file name // Initialize OPENFILENAME ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = 0; ofn.lpstrFile = szFile; // Set lpstrFile[0] to '\0' so that GetOpenFileName does not // use the contents of szFile to initialize itself. ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof(szFile); ofn.lpstrFilter = "All\0*.*\0txt\0*.txt\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; // Display the Open dialog box. if (GetOpenFileName(&ofn)==TRUE) { FILE * file; gKlotski->setState(AUTO); file = fopen(szFile,"r"); if(file==NULL) break; if(!gKlotski->His->LoadHistory(file)) { fclose(file); break; } delaycnt=0; printf("his load ok %d %d\n",gKlotski->His->CurrentStep,gKlotski->His->TotalStep); } break; } } break; } case WM_HELP: { ::MessageBoxA(0,"leave blank now ...","help",MB_HELP); } } return( DefWindowProc(hWnd,uMsg,wParam,lParam) ); } int main( ) { //for debug CreateConsole(); gKlotskiWindow=new Window(1,1,WndProc); gKlotskiWindow->Create(); gKlotskiWindow->SetTitle("welcome"); gKlotski = new Klotski(); while(!GameExit) { switch (state) { case 0:// IDLE { break; } case 1:// INIT { if( gKlotski->Init(LuaFilePath)) state=2; else state=0; break; } case 4://deinit { gKlotski->Deinit(); state=0; break; } case 5://reinit { gKlotski->Deinit(); if( gKlotski->Init(LuaFilePath)) state=2; else state=0; break; } case 2://Prepare to work { gKlotskiWindow->Destroy(); delete gKlotskiWindow; gKlotskiWindow=new Window(gKlotski->width,gKlotski->height,WndProc); gKlotski->Map->UpdateMap(); gKlotski->Map->Print(); gKlotskiWindow->Create(); SetWindowTextA(gKlotskiWindow->hWnd, "111"); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,gKlotski->width,gKlotski->height,0); glEnable(GL_TEXTURE_2D); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_LESS ,0.9); picgen();//see texture.cpp Texture texture1(32*16,32*16*4,GL_RGBA,(unsigned char *)buf2,0); picrelease(); texture1.Bind(); char str[50]; snprintf(str,50,"%s %d/%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); gKlotskiWindow->SetTitle(str); gKlotski->setState(NORMAL); state=3; break; } case 3://work loop { glClearColor( 0.2f, 0.4f, 1.0f, 0.0f ); glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT ); int i; for(i=0;i<gKlotski->Map->BlockNumber;i++) { gKlotski->Map->Blocks[i].Draw(); } break; } } SwapBuffers( gKlotskiWindow->hDC ); if(gKlotski->getState()==AUTO) { delaycnt++; if(delaycnt==5) { delaycnt=0; } #ifdef _EXPORTBMP_ if(delaycnt==3) { static char head[54]= { 0x42,0x4d,0x66,0x75,0x00,0x00,0x00,0x00, 0x00,0x00,0x36,0x00,0x00,0x00,0x28,0x00, 0x00,0x00,0x64,0x00,0x00,0x00,0x64,0x00, 0x00,0x00,0x01,0x00,0x18,0x00,0x00,0x00, 0x00,0x00,0x30,0x75, }; GLint pixelLength; GLubyte * pixelDate; FILE * wfile; int width=gKlotskiWindow->TotalPixel_x; int height=gKlotskiWindow->TotalPixel_y; pixelLength = width * 3; if ( pixelLength % 4 != 0 ) { pixelLength += 4 - pixelLength%4; } pixelLength *= height; pixelDate = (GLubyte *)malloc( pixelLength ); if ( pixelDate == 0 ) { printf("error: malloc!\n"); } else { char bmpName[100]; char str[50]={0}; if(gKlotski->getState()!=IDLE) snprintf(str,50,"%s %d_%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); SYSTEMTIME tm; GetLocalTime(&tm); snprintf(bmpName,100,".\\%s_%4.4d%2.2d%2.2d_%2.2dh%2.2dm%2.2ds.bmp", str, tm.wYear, tm.wMonth, tm.wDay, tm.wHour, tm.wMinute, tm.wSecond); printf("save screen to file %s\n",bmpName); wfile = fopen( bmpName, "wb" ); if(wfile==NULL) { free( pixelDate ); printf("can't open file %s\n",bmpName); } else { fwrite( head, 54, 1, wfile ); fseek( wfile, 0x0012, SEEK_SET ); fwrite( &width, sizeof(width), 1, wfile ); fwrite( &height, sizeof(height ), 1, wfile ); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glReadPixels( 0, 0, width, height, GL_BGR_EXT, GL_UNSIGNED_BYTE, pixelDate ); fseek( wfile, 0, SEEK_END ); fwrite( pixelDate, pixelLength, 1, wfile ); fclose( wfile ); free( pixelDate ); } } } #endif if(delaycnt==1) { printf("auto..\n"); if( gKlotski->His->CanForward()) { printf("REDO\n"); StepInfo step = gKlotski->His->GetForwardStep(); gKlotski->His->DoForward(); if(step.move==UP) gKlotski->Map->SearchBlockById(step.id)->DoMoveUp(); if(step.move==DOWN) gKlotski->Map->SearchBlockById(step.id)->DoMoveDown(); if(step.move==LEFT) gKlotski->Map->SearchBlockById(step.id)->DoMoveLeft(); if(step.move==RIGHT) gKlotski->Map->SearchBlockById(step.id)->DoMoveRight(); gKlotski->Map->UpdateMap(); gKlotski->Map->Print(); if(gKlotski->checkTargetSuccess()==0) { char str[50]; snprintf(str,50,"%s %d/%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); gKlotskiWindow->SetTitle(str); gKlotski->setState(AUTO); } else { char str[50]; snprintf(str,50,"%s successed %d/%d",gKlotski->cfg.title.c_str(),gKlotski->His->CurrentStep,gKlotski->His->TotalStep); gKlotskiWindow->SetTitle(str); gKlotski->setState(AUTO); } } } if(delaycnt==4) { if(gKlotski->checkTargetSuccess()==1) { gKlotski->setState(FINISHED); } else { if(gKlotski->His->CanForward()) { gKlotski->setState(AUTO); } else { gKlotski->setState(NORMAL); } } } } while( PeekMessage(&msg,0,0,0,PM_REMOVE) ) { if( msg.message==WM_QUIT ) { GameExit=1; } TranslateMessage( &msg ); DispatchMessage( &msg ); } Sleep(50); } gKlotskiWindow->Destroy(); delete(gKlotskiWindow); delete(gKlotski); return 0; }
37.848266
143
0.390554
[ "shape" ]
9d7e3234c33184aabf2078af19e43391822b6746
6,366
cpp
C++
src/layers/legacy/medUtilities/medUtilitiesVTK.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
null
null
null
src/layers/legacy/medUtilities/medUtilitiesVTK.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
null
null
null
src/layers/legacy/medUtilities/medUtilitiesVTK.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
null
null
null
#include "medUtilities.h" #include "medUtilitiesVTK.h" #include <dtkCoreSupport/dtkAbstractProcessFactory.h> #include <medAbstractProcessLegacy.h> #include <vtkCellData.h> #include <vtkLinearTransform.h> #include <vtkMetaDataSet.h> #include <vtkPointData.h> #include <vtkPolyData.h> medAbstractData* medUtilitiesVTK::changeMaxNumberOfMeshTriangles(medAbstractData *mesh, int maxNumber) { vtkMetaDataSet * dataset = reinterpret_cast<vtkMetaDataSet*>(mesh->data()); vtkPolyData * polydata = dynamic_cast<vtkPolyData*>(dataset->GetDataSet()); int initialNumber = polydata->GetNumberOfPolys(); if (maxNumber < initialNumber) // Decimate { double decimateValue = 1.0 - (double)maxNumber/(double)initialNumber; dtkSmartPointer<medAbstractProcessLegacy> process = dtkAbstractProcessFactory::instance()->createSmartPointer("medDecimateMeshProcess"); process->setInput(mesh); process->setParameter(decimateValue); process->update(); return process->output(); } return mesh; } vtkDataArray* medUtilitiesVTK::getArray(medAbstractData* data, QString arrayName) { vtkDataArray* result = nullptr; if (data->identifier().contains("vtkDataMesh") || data->identifier().contains("EPMap")) { vtkMetaDataSet* metaData = static_cast<vtkMetaDataSet*>(data->data()); vtkDataSet* mesh = metaData->GetDataSet(); // try point data first result = mesh->GetPointData()->GetArray(qPrintable(arrayName)); if (!result) { // try cell data result = mesh->GetCellData()->GetArray(qPrintable(arrayName)); if (!result) { // try field data result = mesh->GetFieldData()->GetArray(qPrintable(arrayName)); } } } return result; } int medUtilitiesVTK::getArrayIndex(medAbstractData* data, QString arrayName, DataArrayType* arrayType) { int arrayId = -1; DataArrayType type = DataArrayType::UNKNOWN; if (data->identifier().contains("vtkDataMesh") || data->identifier().contains("EPMap")) { vtkMetaDataSet* metaData = static_cast<vtkMetaDataSet*>(data->data()); vtkDataSet* mesh = metaData->GetDataSet(); // try point data first (void)mesh->GetPointData()->GetAbstractArray(qPrintable(arrayName), arrayId); if (arrayId == -1) { (void)mesh->GetCellData()->GetAbstractArray(qPrintable(arrayName), arrayId); if (arrayId == -1) { (void)mesh->GetFieldData()->GetAbstractArray(qPrintable(arrayName), arrayId); if (arrayId != -1) { type = DataArrayType::FIELD_ARRAY; } } else { type = DataArrayType::CELL_ARRAY; } } else { type = DataArrayType::POINT_ARRAY; } } if (arrayType) { *arrayType = type; } return arrayId; } QList<double> medUtilitiesVTK::peekArray(medAbstractData* data, QString arrayName, int index) { QList<double> result; vtkDataArray* array = getArray(data, arrayName); if (array && (index < array->GetNumberOfTuples())) { int nbComponents = array->GetNumberOfComponents(); double* tuple = new double[nbComponents]; array->GetTuple(index, tuple); for (int i = 0; i < nbComponents; ++i) { result.push_back(tuple[i]); } delete[] tuple; } return result; } bool medUtilitiesVTK::arrayRange(medAbstractData* data, QString arrayName, double* minRange, double* maxRange, int component) { vtkDataArray* array = getArray(data, arrayName); if (array && (component < array->GetNumberOfComponents())) { double* range = new double[2](); array->GetRange(range, component); *minRange = range[0]; *maxRange = range[1]; delete[] range; return true; } return false; } bool medUtilitiesVTK::arrayStats(medAbstractData* data, QString arrayName, double* mean, double* stdDev, int component) { vtkDataArray* array = getArray(data, arrayName); if (array && (component < array->GetNumberOfComponents())) { vtkIdType nbTuples = array->GetNumberOfTuples(); QList<double> samples; double variance = 0.0; for (vtkIdType i = 0; i < nbTuples; ++i) { samples.append(array->GetComponent(i, component)); } medUtilities::computeMeanAndVariance(samples, mean, &variance); *stdDev = std::sqrt(variance); return true; } return false; } void medUtilitiesVTK::transformCoordinates(medAbstractData* data, QStringList arrayNames, vtkLinearTransform* transformFilter) { foreach (QString arrayName, arrayNames) { vtkDataArray* array = getArray(data, arrayName); if (array) { // nbComponents must be a multiple of 3 int nbComponents = array->GetNumberOfComponents(); if ((nbComponents % 3) == 0) { // this array contains coordinates that must be transformed double* inPt = new double[nbComponents]; double* outPt = new double[nbComponents]; for (vtkIdType k = 0; k < array->GetNumberOfTuples(); ++k) { array->GetTuple(k, inPt); for (int l = 0; l < nbComponents / 3; ++l) { transformFilter->InternalTransformPoint(inPt + l * 3, outPt + l * 3); } array->SetTuple(k, outPt); } delete[] inPt; delete[] outPt; } } } }
32.314721
144
0.544769
[ "mesh" ]
9d84b76f1cfc999419dcf7427f26595c3342509b
7,175
cpp
C++
win32gui/win32textarea.cpp
matthew-macgregor/blitzplus_msvc2019
2a4b3b8b9f8e9b7ad2dc81bd80e08bb62c98bcdc
[ "Zlib" ]
69
2015-01-04T08:42:44.000Z
2022-03-13T09:56:24.000Z
win32gui/win32textarea.cpp
JamesLinus/blitzplus
a4615c064f99a70fdd131554b6f5e2241611aff9
[ "Zlib" ]
3
2016-09-24T04:13:55.000Z
2021-11-04T11:11:44.000Z
win32gui/win32textarea.cpp
JamesLinus/blitzplus
a4615c064f99a70fdd131554b6f5e2241611aff9
[ "Zlib" ]
29
2015-05-14T03:59:52.000Z
2020-07-25T02:46:25.000Z
#include "win32textarea.h" #include <vector> using std::vector; static DWORD CALLBACK streamIn( DWORD cookie,BYTE *buff,LONG n,LONG *n_out ){ const char **p=(const char**)cookie; const char *t=*p; while( n-- && *t ) *buff++=*t++; *n_out=t-*p; *p=t; return 0; } static DWORD CALLBACK streamOut( DWORD cookie,BYTE *buf,LONG n,LONG *n_out ){ vector<char> *vec=(vector<char>*)cookie; for( int k=0;k<n;++k ){ vec->push_back( *buf++ ); } return 0; } Win32TextArea::Win32TextArea( BBGroup *group,int style ):BBTextArea(group,style), _prot(false),_locked(0){ HWND parent=(HWND)group->query( BBQID_WIN32CLIENTHWND ); int xstyle=WS_EX_CLIENTEDGE; int wstyle=WS_CHILD|WS_VSCROLL; wstyle|=ES_MULTILINE|ES_NOHIDESEL|ES_AUTOVSCROLL; if( !(style&1) ){ //word wrap? wstyle|=WS_HSCROLL|ES_AUTOHSCROLL; } HWND hwnd=CreateWindowEx( xstyle,"RichEdit","",wstyle,0,0,0,0,parent,0,GetModuleHandle(0),0 ); SendMessage( hwnd,EM_SETLIMITTEXT,1024*1024,0 ); SendMessage( hwnd,EM_SETEVENTMASK,0,(LPARAM)(ENM_CHANGE|ENM_SELCHANGE|ENM_PROTECTED) ); CHARFORMAT cf={sizeof(cf)}; cf.dwMask=CFM_PROTECTED; cf.dwEffects=CFE_PROTECTED; lockAll(); SendMessage( hwnd,EM_SETCHARFORMAT,SCF_SELECTION,(LPARAM)&cf ); unlock(); _gadget.setHwnd(hwnd); _gadget.setWndProc(this); } int Win32TextArea::adjustRange( int &pos,int &len,int units ){ int t=length(units); if( pos<0 ) pos=0; else if( pos>t ) pos=t; if( len<0 || pos+len>t ) len=t-pos; if( !len ) return 0; if( units==UNITS_LINES ){ int n=pos; pos=findChar(pos); len=findChar(n+len)-pos; } return len; } void *Win32TextArea::query( int qid ){ if( void *p=_gadget.query( qid ) ) return p; return BBTextArea::query( qid ); } void Win32TextArea::setFont( BBFont *font ){ _gadget.setFont(font); BBTextArea::setFont(font); } void Win32TextArea::setText( BBString *text ){ _gadget.setText( text ); BBGadget::setText( text ); } void Win32TextArea::setShape( int x,int y,int w,int h ){ _gadget.setShape(x,y,w,h); BBTextArea::setShape(x,y,w,h); } void Win32TextArea::setVisible( bool visible ){ _gadget.setVisible(visible); BBTextArea::setVisible(visible); } void Win32TextArea::setEnabled( bool enabled ){ _gadget.setEnabled(enabled); BBTextArea::setEnabled(enabled); } void Win32TextArea::activate(){ _gadget.activate(); BBTextArea::activate(); } void Win32TextArea::setTabs( int tabs ){ int tabTwips=1440*8/GetDeviceCaps( GetDC(0),LOGPIXELSX ) * tabs; PARAFORMAT pf={sizeof(pf)}; pf.dwMask=PFM_TABSTOPS; pf.cTabCount=MAX_TAB_STOPS; for( int k=0;k<MAX_TAB_STOPS;++k ){ pf.rgxTabs[k]=k*tabTwips; } lockAll(); SendMessage( _gadget.hwnd(),EM_SETPARAFORMAT,0,(LPARAM)&pf ); unlock(); } void Win32TextArea::setTextColor( int r,int g,int b ){ CHARFORMAT cf={sizeof(cf)}; cf.dwMask=CFM_COLOR|CFM_PROTECTED; cf.dwEffects=CFE_PROTECTED; cf.crTextColor=(b<<16)|(g<<8)|r; lockAll(); SendMessage( _gadget.hwnd(),EM_SETCHARFORMAT,SCF_SELECTION,(LPARAM)&cf ); unlock(); } void Win32TextArea::setBackgroundColor( int r,int g,int b ){ SendMessage( _gadget.hwnd(),EM_SETBKGNDCOLOR,0,(LPARAM)((b<<16)|(g<<8)|r) ); } int Win32TextArea::length( int units ){ if( units==UNITS_LINES ){ return SendMessage( _gadget.hwnd(),EM_GETLINECOUNT,0,0 ); } return SendMessage( _gadget.hwnd(),WM_GETTEXTLENGTH,0,0 ); } //return SOL pos int Win32TextArea::findChar( int lin ){ if( lin<0 ) return 0; if( lin>=length(UNITS_LINES) ) return length(UNITS_CHARS); return SendMessage( _gadget.hwnd(),EM_LINEINDEX,lin,0 ); } int Win32TextArea::findLine( int pos ){ if( pos<0 ) return 0; if( pos>length(UNITS_CHARS) ) return length(UNITS_LINES); return SendMessage( _gadget.hwnd(),EM_EXLINEFROMCHAR,0,pos ); } int Win32TextArea::selLength( int units ){ CHARRANGE cr; SendMessage( _gadget.hwnd(),EM_EXGETSEL,0,(LPARAM)&cr ); if( units!=UNITS_LINES ){ return cr.cpMax-cr.cpMin; } return findLine(cr.cpMax)-findLine(cr.cpMin)+1; } int Win32TextArea::cursor( int units ){ CHARRANGE cr; SendMessage( _gadget.hwnd(),EM_EXGETSEL,0,(LPARAM)&cr ); if( units!=UNITS_LINES ){ return cr.cpMin; } return findLine( cr.cpMin ); } void Win32TextArea::addText( BBString *text ){ bool rtf=false; int fmt=rtf ? SF_RTF : SF_TEXT; const char *tp=text->c_str(),**p=&tp; EDITSTREAM es={(DWORD)p,0,streamIn}; lock( length(UNITS_CHARS),0 ); SendMessage( _gadget.hwnd(),EM_STREAMIN,fmt|SFF_SELECTION,(LPARAM)&es ); unlock(); CHARRANGE cr={length(UNITS_CHARS),length(UNITS_CHARS)}; SendMessage( _gadget.hwnd(),EM_EXSETSEL,0,(LPARAM)&cr ); } BBString* Win32TextArea::getText( int pos,int len,int units ){ bool rtf=false; if( !adjustRange( pos,len,units ) ) return BBString::null(); char *buf=new char[len+1]; TEXTRANGE tr={{pos,pos+len},buf}; SendMessage( _gadget.hwnd(),EM_GETTEXTRANGE,0,(LPARAM)&tr ); BBString *t=new BBString( buf,len ); delete[] buf; return t; } void Win32TextArea::setText( BBString *text,int pos,int len,int units ){ bool rtf=false; adjustRange( pos,len,units ); int fmt=rtf ? SF_RTF : SF_TEXT; const char *tp=text->c_str(),**p=&tp; EDITSTREAM es={(DWORD)p,0,streamIn}; lock( pos,len ); SendMessage( _gadget.hwnd(),EM_STREAMIN,fmt|SFF_SELECTION,(LPARAM)&es ); unlock(); } void Win32TextArea::formatText( int r,int g,int b,int flags,int pos,int len,int units ){ if( !adjustRange( pos,len,units ) ) return; CHARFORMAT cf={sizeof(cf)}; cf.dwMask=CFM_COLOR|CFM_BOLD|CFM_ITALIC|CFM_PROTECTED; cf.crTextColor=(b<<16)|(g<<8)|r; if( flags & BBTextArea::FORMAT_BOLD ) cf.dwEffects|=CFE_BOLD; if( flags & BBTextArea::FORMAT_ITALIC ) cf.dwEffects|=CFE_ITALIC; cf.dwEffects|=CFE_PROTECTED; lock( pos,len ); CHARFORMAT of={sizeof(of)}; SendMessage( _gadget.hwnd(),EM_GETCHARFORMAT,SCF_SELECTION,(DWORD)&of ); if( ((cf.dwEffects^of.dwEffects)&(CFE_BOLD|CFE_ITALIC)) || cf.crTextColor!=of.crTextColor ){ SendMessage( _gadget.hwnd(),EM_SETCHARFORMAT,SCF_SELECTION,(DWORD)&cf ); } unlock(); } void Win32TextArea::lock(){ if( !_locked++ ){ SendMessage( _gadget.hwnd(),EM_HIDESELECTION,1,0 ); SendMessage( _gadget.hwnd(),EM_EXGETSEL,0,(LPARAM)&_lockedcr ); } } void Win32TextArea::unlock(){ if( !--_locked ){ SendMessage( _gadget.hwnd(),EM_EXSETSEL,0,(LPARAM)&_lockedcr ); SendMessage( _gadget.hwnd(),EM_HIDESELECTION,0,0 ); } } void Win32TextArea::lock( int pos,int len ){ lock(); CHARRANGE cr={pos,pos+len}; SendMessage( _gadget.hwnd(),EM_EXSETSEL,0,(LPARAM)&cr ); } void Win32TextArea::lockAll(){ lock(); selectAll(); } void Win32TextArea::selectAll(){ SendMessage( _gadget.hwnd(),EM_SETSEL,0,-1 ); } LRESULT Win32TextArea::wndProc( HWND hwnd,UINT msg,WPARAM wp,LPARAM lp,WNDPROC proc ){ switch( msg ){ case WM_COMMAND: switch( HIWORD(wp) ){ case EN_CHANGE: if( _locked ) return 0; if( _prot ){ emit( BBEvent::GADGET_ACTION,1 ); _prot=false; } break; } return 0; case WM_NOTIFY: switch( ((NMHDR*)lp)->code ){ case EN_SELCHANGE: if( _locked ) return 0; if( !_prot ){ emit( BBEvent::GADGET_ACTION,0 ); } break; case EN_PROTECTED: if( _locked ) return 0; _prot=true; break; } return 0; } return CallWindowProc( proc,hwnd,msg,wp,lp ); }
23.145161
95
0.6977
[ "vector" ]
9d8c525d0f6a92de30f8cdc7d026204341cd3c30
3,146
hpp
C++
include/dracosha/validator/utils/is_container.hpp
evgeniums/cpp-validator
e4feccdce19c249369ddb631571b60613926febd
[ "BSL-1.0" ]
27
2020-09-18T13:45:33.000Z
2022-03-16T21:14:37.000Z
include/dracosha/validator/utils/is_container.hpp
evgeniums/cpp-validator
e4feccdce19c249369ddb631571b60613926febd
[ "BSL-1.0" ]
7
2020-08-07T21:48:14.000Z
2021-01-14T12:25:37.000Z
include/dracosha/validator/utils/is_container.hpp
evgeniums/cpp-validator
e4feccdce19c249369ddb631571b60613926febd
[ "BSL-1.0" ]
1
2021-03-30T09:17:58.000Z
2021-03-30T09:17:58.000Z
/** @copyright Evgeny Sidorov 2020 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ /****************************************************************************/ /** @file validator/utils/is_container.hpp * * Defines helper to check if object is if container type. * */ /****************************************************************************/ #ifndef DRACOSHA_VALIDATOR_IS_CONTAINER_HPP #define DRACOSHA_VALIDATOR_IS_CONTAINER_HPP #include <string> #include <dracosha/validator/config.hpp> #include <dracosha/validator/utils/string_view.hpp> DRACOSHA_VALIDATOR_NAMESPACE_BEGIN //------------------------------------------------------------- /** * @brief Default helper for checking if type has begin() method. */ template <typename T, typename=void> struct has_begin { constexpr static const bool value=false; }; DRACOSHA_VALIDATOR_INLINE_LAMBDA auto has_begin_c = hana::is_valid([](auto&& v) -> decltype( (void)hana::traits::declval(v).begin() ) {}); /** * @brief Helper for checking if type has begin() method for case when it has. */ template <typename T> struct has_begin<T, std::enable_if_t<has_begin_c(hana::type_c<std::decay_t<T>>)> > { constexpr static const bool value=true; }; /** * @brief Default helper for checking if type has end() method. */ template <typename T, typename=void> struct has_end { constexpr static const bool value=false; }; DRACOSHA_VALIDATOR_INLINE_LAMBDA auto has_end_c = hana::is_valid([](auto&& v) -> decltype( (void)hana::traits::declval(v).begin() ) {}); /** * @brief Helper for checking if type has end() method for case when it has. */ template <typename T> struct has_end<T, std::enable_if_t<has_end_c(hana::type_c<std::decay_t<T>>)> > { constexpr static const bool value=true; }; /** * @brief Check if type is a container but not string or string_view. **/ template <typename T> using is_container_t=std::integral_constant<bool, has_begin<T>::value && has_end<T>::value && !std::is_same<std::decay_t<T>,std::string>::value && !std::is_same<std::decay_t<T>,string_view>::value >; /** * @brief Check if variable is a container but not string or string_view. * @param v Variable to check. * @return True if variable has begin() and end() methods. */ template <typename T> constexpr auto is_container(T&& v) { std::ignore=v; return is_container_t<T>::value; } //------------------------------------------------------------- DRACOSHA_VALIDATOR_NAMESPACE_END #endif // DRACOSHA_VALIDATOR_IS_CONTAINER_HPP
29.401869
98
0.534965
[ "object" ]
9d8d4c69f19fb158f7314e2ffc4c54de8226b400
7,996
cc
C++
plugins/eeui/WeexSDK/ios/weex_core/Source/js_runtime/runtime/runtime_values.cc
bonniesl/yktapp
3f96b7aad945e9aa110f0643d9a57e28d0645ab6
[ "MIT" ]
null
null
null
plugins/eeui/WeexSDK/ios/weex_core/Source/js_runtime/runtime/runtime_values.cc
bonniesl/yktapp
3f96b7aad945e9aa110f0643d9a57e28d0645ab6
[ "MIT" ]
null
null
null
plugins/eeui/WeexSDK/ios/weex_core/Source/js_runtime/runtime/runtime_values.cc
bonniesl/yktapp
3f96b7aad945e9aa110f0643d9a57e28d0645ab6
[ "MIT" ]
null
null
null
/** # Copyright 2018 Taobao (China) Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. **/ #include "js_runtime/runtime/runtime_values.h" #include <utility> #include "js_runtime/runtime/runtime_object.h" #include "js_runtime/utils/log_utils.h" namespace unicorn { Map::~Map() { for (auto &iter : properties_) { delete iter.second; } } Array::~Array() { for (size_t i = 0; i < Size(); i++) { delete values_[i]; } } Function::~Function() { if (this_object_) delete this_object_; } void Function::SetObject(RuntimeObject *thiz) { this_object_ = thiz; } RuntimeValues::RuntimeValues(RuntimeValues &&origin) { InternalMoveConstructFrom(std::move(origin)); } void RuntimeValues::InternalMoveConstructFrom(RuntimeValues &&that) { type_ = that.type_; switch (type_) { case Type::UNDEFINED: return; case Type::NULLVALUE: return; case Type::BOOLEAN: data_.bool_value_ = that.data_.bool_value_; return; case Type::INTEGER: data_.int_value_ = that.data_.int_value_; return; case Type::DOUBLE: data_.double_value_ = that.data_.double_value_; return; case Type::STRING: new(&data_.string_value_) std::string( std::move(that.data_.string_value_)); break; case Type::OBJECT: common_object_ = std::move(that.common_object_); break; case Type::FUNCTION: function_ = std::move(that.function_); break; case Type::MAP: map_ = std::move(that.map_); break; case Type::ARRAY: array_ = std::move(that.array_); case Type::JSONObject: data_.string_value_=that.data_.string_value_; break; } } RuntimeValues::RuntimeValues(bool in_bool) : type_(Type::BOOLEAN) { data_.bool_value_ = in_bool; } RuntimeValues::RuntimeValues(int in_int) : type_(Type::INTEGER) { data_.int_value_ = in_int; } RuntimeValues::RuntimeValues(double in_double) : type_(Type::DOUBLE) { data_.double_value_ = in_double; } RuntimeValues::RuntimeValues(const char *in_string, size_t length) : type_(Type::STRING) { data_.string_value_ = std::string(in_string, length); } RuntimeValues::RuntimeValues(const std::string &in_string) : type_(Type::STRING) { data_.string_value_ = in_string; // new(&data_.string_value_) std::string(in_string); } RuntimeValues::RuntimeValues(const std::string &in_string,Type type){ data_.string_value_ = in_string; type_ = type; // new(&data_.string_value_) std::string(in_string); } RuntimeValues::RuntimeValues(std::unique_ptr<BaseObject> object) : type_(Type::OBJECT), common_object_(std::move(object)) { } RuntimeValues::RuntimeValues(std::unique_ptr<Map> map) : type_(Type::MAP) { map_ = std::move(map); } RuntimeValues::RuntimeValues(std::unique_ptr<Function> func) : type_(Type::FUNCTION) { function_ = std::move(func); } RuntimeValues::RuntimeValues(std::unique_ptr<Array> array) : type_(Type::ARRAY) { array_ = std::move(array); } RuntimeValues &RuntimeValues::operator=(RuntimeValues &&that) { if (this == &that) return *this; InternalMoveConstructFrom(std::move(that)); return *this; } RuntimeValues::~RuntimeValues() { } void RuntimeValues::SetValue(std::unique_ptr<char[]> &&value) {} void RuntimeValues::SetType(Type type) { if (common_object_) { switch (type) { case Type::UNDEFINED: break; case Type::NULLVALUE: break; case Type::BOOLEAN: { Object *origin_b = static_cast<Object *>(common_object_.release()); data_.bool_value_ = *(static_cast<bool *>(origin_b->GetDataPtr())); } break; case Type::INTEGER: { Object *origin_i = static_cast<Object *>(common_object_.release()); data_.int_value_ = *(static_cast<int *>(origin_i->GetDataPtr())); } break; case Type::DOUBLE: { Object *origin_d = static_cast<Object *>(common_object_.release()); data_.double_value_ = *(static_cast<double *>( origin_d->GetDataPtr())); } break; case Type::STRING: { Object *origin_s = static_cast<Object *>(common_object_.release()); data_.string_value_ = *(static_cast<std::string *>( origin_s->GetDataPtr())); } break; case Type::OBJECT: break; case Type::FUNCTION: break; case Type::MAP: break; case Type::ARRAY: break; default: break; } } type_ = type; } bool RuntimeValues::GetAsBoolean(bool *out_value) const { if (IsBool()) { *out_value = data_.bool_value_; return true; } return false; } bool RuntimeValues::GetAsInteger(int *out_value) const { if (IsDouble()) { *out_value = static_cast<int>(data_.double_value_); return true; } if (IsInt()) { *out_value = data_.int_value_; return true; } return false; } bool RuntimeValues::GetAsDouble(double *out_value) const { if (IsDouble()) { *out_value = data_.double_value_; return true; } if (IsInt()) { *out_value = static_cast<double>(data_.int_value_); return true; } return false; } bool RuntimeValues::GetAsUtf8JsonStr(std::string &out_value) const { if (IsJsonObject()) { out_value.assign(data_.string_value_); return true; } return false; } bool RuntimeValues::GetAsString(std::string *out_value) const { if (IsString()) { out_value->assign(data_.string_value_); return true; } return false; } BaseObject *RuntimeValues::GetAsObject() const { if (IsObject()) { return common_object_.get(); } return nullptr; } BaseObject *RuntimeValues::PassObject() { if (IsObject()) { return common_object_.release(); } return nullptr; } } // namespace unicorn
30.06015
88
0.518134
[ "object" ]
9d8f4e6d2fdbc82bf95a20371d21849f2f2ac47f
3,257
cpp
C++
source/FAST/Examples/Segmentation/convertMeshToSegmentation.cpp
SINTEFMedtek/FAST
d4c1ec49bd542f78d84c00e990bbedd2126cfffa
[ "BSD-2-Clause" ]
3
2019-12-13T07:53:51.000Z
2020-02-05T09:11:58.000Z
source/FAST/Examples/Segmentation/convertMeshToSegmentation.cpp
SINTEFMedtek/FAST
d4c1ec49bd542f78d84c00e990bbedd2126cfffa
[ "BSD-2-Clause" ]
1
2020-02-05T09:28:37.000Z
2020-02-05T09:28:37.000Z
source/FAST/Examples/Segmentation/convertMeshToSegmentation.cpp
SINTEFMedtek/FAST
d4c1ec49bd542f78d84c00e990bbedd2126cfffa
[ "BSD-2-Clause" ]
1
2020-12-10T12:40:59.000Z
2020-12-10T12:40:59.000Z
#include <FAST/Algorithms/MeshToSegmentation/MeshToSegmentation.hpp> #include <FAST/Importers/VTKMeshFileImporter.hpp> #include <FAST/Tools/CommandLineParser.hpp> #include <FAST/Exporters/MetaImageExporter.hpp> #include <FAST/Importers/MetaImageImporter.hpp> #include <FAST/Visualization/SimpleWindow.hpp> #include <FAST/Visualization/TriangleRenderer/TriangleRenderer.hpp> #include <FAST/Visualization/SliceRenderer/SliceRenderer.hpp> using namespace fast; int main(int argc, char** argv) { // TODO add support for 2D Reporter::setGlobalReportMethod(Reporter::COUT); CommandLineParser parser("Convert mesh to segmentation (3D only)"); parser.addPositionVariable(1, "mesh-filename", Config::getTestDataPath() + "/Surface_LV.vtk"); parser.addVariable("segmentation-size", false, "Size of segmentation. Example: 256,256,256"); parser.addVariable("image-filename", Config::getTestDataPath() + "/US/Ball/US-3Dt_0.mhd"); parser.addVariable("output-filename", false, "Filename to store the segmentation in. Example: /path/to/file.mhd"); parser.parse(argc, argv); auto importer = VTKMeshFileImporter::New(); importer->setFilename(parser.get("mesh-filename")); auto converter = MeshToSegmentation::New(); converter->setInputConnection(importer->getOutputPort()); if(parser.gotValue("segmentation-size")) { auto size = split(parser.get("segmentation-size"), ","); if (size.size() != 3) throw Exception("Unable to format input argument segmentation-size: " + parser.get("segmentation-size") + " expected: X,Y,Z"); try { converter->setOutputImageResolution(std::stoi(size[0]), std::stoi(size[1]), std::stoi(size[2])); } catch (std::exception &e) { throw Exception("Unable to format input argument segmentation-size: " + parser.get("segmentation-size") + " expected: X,Y,Z"); } } else if(parser.gotValue("image-filename")) { auto importer2 = MetaImageImporter::New(); importer2->setFilename(parser.get("image-filename")); converter->setInputConnection(1, importer2->getOutputPort()); } else { throw Exception("Need to supply program with either segmentation-size or image-filename"); } if(parser.gotValue("output-filename")) { auto exporter = MetaImageExporter::New(); exporter->setFilename(parser.get("output-filename")); exporter->enableCompression(); exporter->setInputConnection(converter->getOutputPort()); exporter->update(); } else { // Visualize auto triangleRenderer = TriangleRenderer::New(); triangleRenderer->addInputConnection(importer->getOutputPort()); triangleRenderer->setOpacity(0, 0.25); auto sliceRenderer = SliceRenderer::New(); sliceRenderer->addInputConnection(converter->getOutputPort()); sliceRenderer->setOrthogonalSlicePlane(0, PLANE_Z); sliceRenderer->setIntensityWindow(1); sliceRenderer->setIntensityLevel(0.5); auto window = SimpleWindow::New(); window->addRenderer(triangleRenderer); window->addRenderer(sliceRenderer); window->start(); } }
43.426667
118
0.678846
[ "mesh", "3d" ]
9d9f2162dc177cf94127b9ca9f4e7fb125617ecc
2,818
cpp
C++
cpp/equation-solver/src/Main.cpp
sigalor/lookwhaticando
46dae592ad1664e9439c71dee285340a3e55ed5f
[ "Apache-2.0" ]
3
2018-04-11T17:54:07.000Z
2018-10-23T04:33:00.000Z
cpp/equation-solver/src/Main.cpp
sigalor/lookwhaticando
46dae592ad1664e9439c71dee285340a3e55ed5f
[ "Apache-2.0" ]
null
null
null
cpp/equation-solver/src/Main.cpp
sigalor/lookwhaticando
46dae592ad1664e9439c71dee285340a3e55ed5f
[ "Apache-2.0" ]
3
2018-04-11T02:44:23.000Z
2019-12-21T22:47:53.000Z
#include <cstdlib> #include <iostream> #include <string> #include <vector> #include <stdexcept> #include "Formula.hpp" #include "Condition.hpp" #include "LinearSystem.hpp" void quit(int code=0) { std::cout << "\n\nFinished.\n"; exit(code); } int main() { std::vector<std::string> conditionsStrings; std::string temp; std::vector<Condition> conditions; std::vector<Formula> formulas; LinearSystem matrix; std::vector<double> solutions; std::cout << "Please enter all conditions and finish by entering END\n"; std::cout << "Examples: f(0.3)=-3.6\n"; std::cout << " f'(2.5)=1\n"; std::cout << " f''(0)=3\n\n"; do { std::cout << "Condition " << conditionsStrings.size()+1 << ": "; std::getline(std::cin, temp); conditionsStrings.push_back(temp); } while(temp != "END"); conditionsStrings.pop_back(); //check if enough conditions are given (at least 2 for having a linear equation) if(conditionsStrings.size() < 2) { std::cout << "\nError: You have to enter at least 2 conditions."; quit(1); } //try to interpret all conditions unsigned int i = 1, numWarnings = 0; for(std::string& cs : conditionsStrings) { try { conditions.push_back(Condition(cs)); } catch(const std::runtime_error& e) { std::cout << "\nWarning: Unable to interpret condition " << i << " (" << cs << "), ignored it (" << e.what() << ")."; numWarnings++; } i++; } if(numWarnings != 0) std::cout << "\n"; //check if enough conditions were successfully interpreted (like above) if(conditions.size() < 2) { std::cout << "\nError: You have to enter at least 2 interpretable conditions."; quit(1); } //generate base formulas for all conditions (in the beginning they all are of (number of conditions - 1)th degree) and use the interpreted conditions with them std::cout << "\nResolved formulas:"; formulas = std::vector<Formula>(conditions.size(), Formula(conditions.size() - 1)); for(std::size_t i=0; i<conditions.size(); i++) { formulas[i].insert(conditions[i]); std::cout << "\n " << formulas[i].asString(); } //create matrix from formulas std::cout << "\n\nSystem of linear equations:"; matrix.load(formulas); std::cout << matrix.asString(); //solve system of linear equations std::cout << "\n\nSolutions:"; try { matrix.solve(); } catch(const std::runtime_error& e) { std::cout << "\nError: Linear system is not solvable (" << e.what() << ")."; quit(1); } //output solutions solutions = matrix.getSolutions(); for(std::size_t i=0; i<solutions.size(); i++) std::cout << "\n " << static_cast<char>('a' + i) << " = " << solutions[i]; //quit the program with a "Finished." message quit(0); return 0; }
27.359223
161
0.614265
[ "vector" ]
9da4cf802276456ba660640e1ce1c921045e4960
3,052
cpp
C++
src/devices/bus/tmc600/euro.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/bus/tmc600/euro.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/bus/tmc600/euro.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Curt Coder /********************************************************************** Telercas Telmac TMC-600 Eurobus emulation **********************************************************************/ #include "emu.h" #include "euro.h" //************************************************************************** // GLOBAL VARIABLES //************************************************************************** DEFINE_DEVICE_TYPE(TMC600_EUROBUS_SLOT, tmc600_eurobus_slot_device, "tmc600_eurobus_slot", "Telmac Eurobus slot") //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // device_tmc600_eurobus_card_interface - constructor //------------------------------------------------- device_tmc600_eurobus_card_interface::device_tmc600_eurobus_card_interface(const machine_config &mconfig, device_t &device) : device_interface(device, "telmaceurobus") { m_slot = dynamic_cast<tmc600_eurobus_slot_device *>(device.owner()); } //------------------------------------------------- // tmc600_eurobus_slot_device - constructor //------------------------------------------------- tmc600_eurobus_slot_device::tmc600_eurobus_slot_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, TMC600_EUROBUS_SLOT, tag, owner, clock), device_single_card_slot_interface<device_tmc600_eurobus_card_interface>(mconfig, *this) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void tmc600_eurobus_slot_device::device_start() { m_card = get_card_device(); } //------------------------------------------------- // SLOT_INTERFACE( tmc600_eurobus_cards ) //------------------------------------------------- void tmc600_eurobus_cards(device_slot_interface &device) { //device.option_add("tmc710", TMC710); // 5-way expander //device.option_add("tmc720", TMC720); // 5-way expander (new model) //device.option_add("tmce200", TMCE200); // 8 KB RAM (CMOS) //device.option_add("tmce220", TMCE220); // 16/32 KB RAM/EPROM //device.option_add("tmce225", TMCE225); // 16 KB RAM (CMOS) //device.option_add("tmce250", TMCE250); // 32-way input/output //device.option_add("tmce260", TMCE260); // RS-232 //device.option_add("tmce270", TMCE270); // generic ADC card (RCA CA3162 or CA3300, Teledyne 8700/01/02/03/04/05) //device.option_add("tmce2701", TMCE2701); // TMCE-270 with CA3162 //device.option_add("tmce2702", TMCE2702); // TMCE-270 with CA3300 //device.option_add("tmce280", TMCE280); // floppy disc controller for 3x 5.25" and 4x 8" //device.option_add("tmce285", TMCE285); // monochrome CRT controller (min. 80 cps) //device.option_add("tmce300", TMCE300); // slave computer with parallel I/O //device.option_add("tmce305", TMCE304); // slave computer with serial I/O }
38.632911
137
0.539646
[ "model" ]
9da57775def77432bc01d46e6d8f8e85785d9dbf
1,284
cpp
C++
src/frontend/frontend.cpp
ericmei/graphit-exploratory
aa12687a1a0c714653cff0503f4c154488097cfb
[ "MIT" ]
null
null
null
src/frontend/frontend.cpp
ericmei/graphit-exploratory
aa12687a1a0c714653cff0503f4c154488097cfb
[ "MIT" ]
null
null
null
src/frontend/frontend.cpp
ericmei/graphit-exploratory
aa12687a1a0c714653cff0503f4c154488097cfb
[ "MIT" ]
null
null
null
// // Created by Yunming Zhang on 1/15/17. // #include <graphit/frontend/frontend.h> #include <graphit/frontend/parser.h> namespace graphit { /// Parses, typechecks and turns a given Simit-formated stream into Simit IR. int Frontend::parseStream(std::istream &programStream, FIRContext *context, std::vector<ParseError> *errors) { // Lexical and syntactic analyses. TokenStream tokens = Scanner(errors).lex(programStream); fir::Program::Ptr program = Parser(errors).parse(tokens); // Only emit IR if no syntactic or semantic error was found. if (!errors->empty()) { std::cout << "Error in parsing: " << std::endl; for (auto & error : *errors){ std::cout << error << std::endl; } std::stable_sort(errors->begin(), errors->end()); return 1; } context->setProgram(program); return 0; } /// Parses, typechecks and turns a given Simit-formated string into Simit IR. int Frontend::parseString(const std::string &programString) { return 0; } /// Parses, typechecks and turns a given Simit-formated file into Simit IR. int Frontend::parseFile(const std::string &filename) { return 0; } }
28.533333
114
0.61215
[ "vector" ]
9dabc84d47a526356192f8e4fc68de4320fa789d
185
cpp
C++
minimize_maximum_pair_sum_in_array.cpp
spencercjh/sync-leetcode-today-problem-cpp-example
178a974e5848e3a620f4565170b459d50ecfdd6b
[ "Apache-2.0" ]
null
null
null
minimize_maximum_pair_sum_in_array.cpp
spencercjh/sync-leetcode-today-problem-cpp-example
178a974e5848e3a620f4565170b459d50ecfdd6b
[ "Apache-2.0" ]
1
2020-12-17T07:54:03.000Z
2020-12-17T08:00:22.000Z
minimize_maximum_pair_sum_in_array.cpp
spencercjh/sync-leetcode-today-problem-cpp-example
178a974e5848e3a620f4565170b459d50ecfdd6b
[ "Apache-2.0" ]
null
null
null
package leetcode // https://leetcode-cn.com/problems/minimize-maximum-pair-sum-in-array/ class MinimizeMaximumPairSumInArray { public: int minPairSum(vector<int>& nums) { } };
20.555556
71
0.735135
[ "vector" ]
9daef77b6da99e2ca85848ba294a432bd9ec5cb5
4,102
cpp
C++
test/test_clip.cpp
nextgis-borsch/lib_geojsonvt
d24412747fe3054ce4d645767bc0f2eae97a72f5
[ "ISC" ]
null
null
null
test/test_clip.cpp
nextgis-borsch/lib_geojsonvt
d24412747fe3054ce4d645767bc0f2eae97a72f5
[ "ISC" ]
null
null
null
test/test_clip.cpp
nextgis-borsch/lib_geojsonvt
d24412747fe3054ce4d645767bc0f2eae97a72f5
[ "ISC" ]
1
2018-08-01T11:28:18.000Z
2018-08-01T11:28:18.000Z
#include "util.hpp" #include <mapbox/geojsonvt/clip.hpp> #include <gtest/gtest.h> using namespace mapbox::geojsonvt; ProjectedPoint intersectX(const ProjectedPoint& p0, const ProjectedPoint& p1, double x) { return { x, (x - p0.x) * (p1.y - p0.y) / (p1.x - p0.x) + p0.y }; } using F = ProjectedFeature; using P = ProjectedPoint; using R = ProjectedRing; using GR = ProjectedRings; using GP = ProjectedPoints; const auto geom1 = GR{ R{ { P{ 0, 0 }, P{ 50, 0 }, P{ 50, 10 }, P{ 20, 10 }, P{ 20, 20 }, P{ 30, 20 }, P{ 30, 30 }, P{ 50, 30 }, P{ 50, 40 }, P{ 25, 40 }, P{ 25, 50 }, P{ 0, 50 }, P{ 0, 60 }, P{ 25, 60 } } } }; const auto geom2 = GR{ R{ { P{ 0, 0 }, P{ 50, 0 }, P{ 50, 10 }, P{ 0, 10 } } } }; ProjectedPoint min1{ 0, 0 }; ProjectedPoint max1{ 50, 60 }; ProjectedPoint min2{ 0, 0 }; ProjectedPoint max2{ 50, 10 }; TEST(Clip, Polylines) { const std::map<std::string, std::string> tags1; const std::map<std::string, std::string> tags2; const std::vector<F> features{ F{ geom1, ProjectedFeatureType::LineString, tags1, min1, max1 }, F{ geom2, ProjectedFeatureType::LineString, tags2, min2, max2 }, }; const auto clipped = Clip::clip(features, 1, 10, 40, 0, intersectX, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity()); const std::vector<ProjectedFeature> expected = { { GR{ R{ { P{ 10, 0 }, P{ 40, 0 } } }, R{ { P{ 40, 10 }, P{ 20, 10 }, P{ 20, 20 }, P{ 30, 20 }, P{ 30, 30 }, P{ 40, 30 } } }, R{ { P{ 40, 40 }, P{ 25, 40 }, P{ 25, 50 }, P{ 10, 50 } } }, R{ { P{ 10, 60 }, P{ 25, 60 } } }, }, ProjectedFeatureType::LineString, tags1, min1, max1 }, { GR{ R{ { P{ 10, 0 }, P{ 40, 0 } } }, R{ { P{ 40, 10 }, P{ 10, 10 } } }, }, ProjectedFeatureType::LineString, tags2, min2, max2 } }; ASSERT_EQ(expected, clipped); } ProjectedGeometry closed(ProjectedGeometry geometry) { for (auto& ring : geometry.get<ProjectedRings>()) { ring.points.push_back(ring.points.front()); } return geometry; } TEST(Clip, Polygon) { const std::map<std::string, std::string> tags1; const std::map<std::string, std::string> tags2; const std::vector<F> features{ F{ closed(geom1), ProjectedFeatureType::Polygon, tags1, min1, max1 }, F{ closed(geom2), ProjectedFeatureType::Polygon, tags2, min2, max2 }, }; const auto clipped = Clip::clip(features, 1, 10, 40, 0, intersectX, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity()); const std::vector<ProjectedFeature> expected = { { GR{ R{ { P{ 10, 0 }, P{ 40, 0 }, P{ 40, 10 }, P{ 20, 10 }, P{ 20, 20 }, P{ 30, 20 }, P{ 30, 30 }, P{ 40, 30 }, P{ 40, 40 }, P{ 25, 40 }, P{ 25, 50 }, P{ 10, 50 }, P{ 10, 60 }, P{ 25, 60 }, P{ 10, 24 }, P{ 10, 0 } } } }, ProjectedFeatureType::Polygon, tags1, min1, max1 }, { GR{ R{ { P{ 10, 0 }, P{ 40, 0 }, P{ 40, 10 }, P{ 10, 10 }, P{ 10, 0 } } } }, ProjectedFeatureType::Polygon, tags2, min2, max2 } }; ASSERT_EQ(expected, clipped); } TEST(Clip, Points) { const std::map<std::string, std::string> tags1; const std::map<std::string, std::string> tags2; const std::vector<F> features{ F{ geom1[0].points, ProjectedFeatureType::Point, tags1, min1, max1 }, F{ geom2[0].points, ProjectedFeatureType::Point, tags2, min2, max2 }, }; const auto clipped = Clip::clip(features, 1, 10, 40, 0, intersectX, -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity()); const std::vector<ProjectedFeature> expected = { { GP{ P{ 20, 10 }, P{ 20, 20 }, P{ 30, 20 }, P{ 30, 30 }, P{ 25, 40 }, P{ 25, 50 }, P{ 25, 60 } }, ProjectedFeatureType::Point, tags1, min1, max1 }, }; ASSERT_EQ(expected, clipped); }
36.300885
100
0.537543
[ "geometry", "vector" ]
9daf0e1c14b6a038d810fe05c6f1db9e4d799a8a
34,421
cpp
C++
cpp/basix/e-lagrange.cpp
FEniCS/libtab
653b783d90be2501e03813cad0ce572a679bf46a
[ "MIT" ]
3
2020-11-19T19:17:06.000Z
2020-12-04T11:00:26.000Z
cpp/basix/e-lagrange.cpp
FEniCS/libtab
653b783d90be2501e03813cad0ce572a679bf46a
[ "MIT" ]
33
2020-11-08T18:55:27.000Z
2020-12-14T10:08:19.000Z
cpp/basix/e-lagrange.cpp
FEniCS/libtab
653b783d90be2501e03813cad0ce572a679bf46a
[ "MIT" ]
1
2020-11-23T19:40:31.000Z
2020-11-23T19:40:31.000Z
// Copyright (c) 2020 Chris Richardson & Matthew Scroggs // FEniCS Project // SPDX-License-Identifier: MIT #include "e-lagrange.h" #include "lattice.h" #include "maps.h" #include "moments.h" #include "polynomials.h" #include "polyset.h" #include "quadrature.h" #include <xtensor/xbuilder.hpp> #include <xtensor/xpad.hpp> #include <xtensor/xview.hpp> using namespace basix; namespace { //---------------------------------------------------------------------------- std::tuple<lattice::type, lattice::simplex_method, bool> variant_to_lattice(cell::type celltype, element::lagrange_variant variant) { switch (variant) { case element::lagrange_variant::equispaced: return {lattice::type::equispaced, lattice::simplex_method::none, true}; case element::lagrange_variant::gll_warped: return {lattice::type::gll, lattice::simplex_method::warp, true}; case element::lagrange_variant::gll_isaac: return {lattice::type::gll, lattice::simplex_method::isaac, true}; case element::lagrange_variant::gll_centroid: return {lattice::type::gll, lattice::simplex_method::centroid, true}; case element::lagrange_variant::chebyshev_warped: { if (celltype == cell::type::interval or celltype == cell::type::quadrilateral or celltype == cell::type::hexahedron) return {lattice::type::chebyshev, lattice::simplex_method::none, false}; // TODO: is this the best thing to do for simplices? return {lattice::type::chebyshev_plus_endpoints, lattice::simplex_method::warp, false}; } case element::lagrange_variant::chebyshev_isaac: { if (celltype == cell::type::interval or celltype == cell::type::quadrilateral or celltype == cell::type::hexahedron) return {lattice::type::chebyshev, lattice::simplex_method::none, false}; // TODO: is this the best thing to do for simplices? return {lattice::type::chebyshev_plus_endpoints, lattice::simplex_method::isaac, false}; } case element::lagrange_variant::chebyshev_centroid: return {lattice::type::chebyshev, lattice::simplex_method::centroid, false}; case element::lagrange_variant::gl_warped: { if (celltype == cell::type::interval or celltype == cell::type::quadrilateral or celltype == cell::type::hexahedron) return {lattice::type::gl, lattice::simplex_method::none, false}; // TODO: is this the best thing to do for simplices? return {lattice::type::gl_plus_endpoints, lattice::simplex_method::warp, false}; } case element::lagrange_variant::gl_isaac: { if (celltype == cell::type::interval or celltype == cell::type::quadrilateral or celltype == cell::type::hexahedron) return {lattice::type::gl, lattice::simplex_method::none, false}; // TODO: is this the best thing to do for simplices? return {lattice::type::gl_plus_endpoints, lattice::simplex_method::isaac, false}; } case element::lagrange_variant::gl_centroid: return {lattice::type::gl, lattice::simplex_method::centroid, false}; default: throw std::runtime_error("Unsupported variant"); } } //----------------------------------------------------------------------------- FiniteElement create_d_lagrange(cell::type celltype, int degree, element::lagrange_variant variant, lattice::type lattice_type, lattice::simplex_method simplex_method) { const std::size_t tdim = cell::topological_dimension(celltype); const std::size_t ndofs = polyset::dim(celltype, degree); const std::vector<std::vector<std::vector<int>>> topology = cell::topology(celltype); std::array<std::vector<xt::xtensor<double, 3>>, 4> M; std::array<std::vector<xt::xtensor<double, 2>>, 4> x; for (std::size_t i = 0; i < tdim; ++i) { x[i] = std::vector<xt::xtensor<double, 2>>( cell::num_sub_entities(celltype, i), xt::xtensor<double, 2>({0, tdim})); M[i] = std::vector<xt::xtensor<double, 3>>( cell::num_sub_entities(celltype, i), xt::xtensor<double, 3>({0, 1, 0})); } if (celltype == cell::type::prism or celltype == cell::type::pyramid) { throw std::runtime_error( "This variant is not yet supported on prisms and pyramids."); } const int lattice_degree = celltype == cell::type::triangle ? degree + 3 : (celltype == cell::type::tetrahedron ? degree + 4 : degree + 2); // Create points in interior const xt::xtensor<double, 2> pt = lattice::create( celltype, lattice_degree, lattice_type, false, simplex_method); x[tdim].push_back(pt); const std::size_t num_dofs = pt.shape(0); std::array<std::size_t, 3> s = {num_dofs, 1, num_dofs}; M[tdim].push_back(xt::xtensor<double, 3>(s)); xt::view(M[tdim][0], xt::all(), 0, xt::all()) = xt::eye<double>(num_dofs); return FiniteElement(element::family::P, celltype, degree, {}, xt::eye<double>(ndofs), x, M, maps::type::identity, true, degree, degree, variant); } //---------------------------------------------------------------------------- std::vector<std::tuple<std::vector<FiniteElement>, std::vector<int>>> create_tensor_product_factors(cell::type celltype, int degree, element::lagrange_variant variant) { if (celltype == cell::type::quadrilateral) { FiniteElement sub_element = element::create_lagrange(cell::type::interval, degree, variant, true); std::vector<int> perm((degree + 1) * (degree + 1)); if (degree == 0) perm[0] = 0; else { int p = 0; int n = degree - 1; perm[p++] = 0; perm[p++] = 2; for (int i = 0; i < n; ++i) perm[p++] = 4 + n + i; perm[p++] = 1; perm[p++] = 3; for (int i = 0; i < n; ++i) perm[p++] = 4 + 2 * n + i; for (int i = 0; i < n; ++i) { perm[p++] = 4 + i; perm[p++] = 4 + 3 * n + i; for (int j = 0; j < n; ++j) perm[p++] = 4 + i + (4 + j) * n; } } return {{{sub_element, sub_element}, perm}}; } if (celltype == cell::type::hexahedron) { FiniteElement sub_element = element::create_lagrange(cell::type::interval, degree, variant, true); std::vector<int> perm((degree + 1) * (degree + 1) * (degree + 1)); if (degree == 0) perm[0] = 0; else { int p = 0; int n = degree - 1; perm[p++] = 0; perm[p++] = 4; for (int i = 0; i < n; ++i) perm[p++] = 8 + 2 * n + i; perm[p++] = 2; perm[p++] = 6; for (int i = 0; i < n; ++i) perm[p++] = 8 + 6 * n + i; for (int i = 0; i < n; ++i) { perm[p++] = 8 + n + i; perm[p++] = 8 + 9 * n + i; for (int j = 0; j < n; ++j) perm[p++] = 8 + 12 * n + 2 * n * n + i + n * j; } perm[p++] = 1; perm[p++] = 5; for (int i = 0; i < n; ++i) perm[p++] = 8 + 4 * n + i; perm[p++] = 3; perm[p++] = 7; for (int i = 0; i < n; ++i) perm[p++] = 8 + 7 * n + i; for (int i = 0; i < n; ++i) { perm[p++] = 8 + 3 * n + i; perm[p++] = 8 + 10 * n + i; for (int j = 0; j < n; ++j) perm[p++] = 8 + 12 * n + 3 * n * n + i + n * j; } for (int i = 0; i < n; ++i) { perm[p++] = 8 + i; perm[p++] = 8 + 8 * n + i; for (int j = 0; j < n; ++j) perm[p++] = 8 + 12 * n + n * n + i + n * j; perm[p++] = 8 + 5 * n + i; perm[p++] = 8 + 11 * n + i; for (int j = 0; j < n; ++j) perm[p++] = 8 + 12 * n + 4 * n * n + i + n * j; for (int j = 0; j < n; ++j) { perm[p++] = 8 + 12 * n + i + n * j; perm[p++] = 8 + 12 * n + 5 * n * n + i + n * j; for (int k = 0; k < n; ++k) { perm[p++] = 8 + 12 * n + 6 * n * n + i + n * j + n * n * k; } } } } return {{{sub_element, sub_element, sub_element}, perm}}; } return {}; } //---------------------------------------------------------------------------- xt::xtensor<double, 2> vtk_triangle_points(int degree) { const double d = static_cast<double>(1) / static_cast<double>(degree + 3); if (degree == 0) return {{d, d}}; const std::size_t npoints = polyset::dim(cell::type::triangle, degree); xt::xtensor<double, 2> out({npoints, 2}); out(0, 0) = d; out(0, 1) = d; out(1, 0) = 1 - 2 * d; out(1, 1) = d; out(2, 0) = d; out(2, 1) = 1 - 2 * d; int n = 3; if (degree >= 2) { for (int i = 1; i < degree; ++i) { out(n, 0) = d + ((1 - 3 * d) * i) / (degree); out(n, 1) = d; ++n; } for (int i = 1; i < degree; ++i) { out(n, 0) = d + ((1 - 3 * d) * (degree - i)) / (degree); out(n, 1) = d + ((1 - 3 * d) * i) / (degree); ++n; } for (int i = 1; i < degree; ++i) { out(n, 0) = d; out(n, 1) = d + ((1 - 3 * d) * (degree - i)) / (degree); ++n; } } if (degree >= 3) { xt::xtensor<double, 2> pts = vtk_triangle_points(degree - 3); for (std::size_t i = 0; i < pts.shape(0); ++i) { for (std::size_t j = 0; j < pts.shape(1); ++j) out(n, j) = d + (1 - 3 * d) * pts(i, j); ++n; } } return out; } //----------------------------------------------------------------------------- xt::xtensor<double, 2> vtk_tetrahedron_points(int degree) { const double d = static_cast<double>(1) / static_cast<double>(degree + 4); if (degree == 0) return {{d, d, d}}; const std::size_t npoints = polyset::dim(cell::type::tetrahedron, degree); xt::xtensor<double, 2> out({npoints, 3}); out(0, 0) = d; out(0, 1) = d; out(0, 2) = d; out(1, 0) = 1 - 3 * d; out(1, 1) = d; out(1, 2) = d; out(2, 0) = d; out(2, 1) = 1 - 3 * d; out(2, 2) = d; out(3, 0) = d; out(3, 1) = d; out(3, 2) = 1 - 3 * d; int n = 4; if (degree >= 2) { for (int i = 1; i < degree; ++i) { out(n, 0) = d + ((1 - 4 * d) * i) / (degree); out(n, 1) = d; out(n, 2) = d; ++n; } for (int i = 1; i < degree; ++i) { out(n, 0) = d + ((1 - 4 * d) * (degree - i)) / (degree); out(n, 1) = d + ((1 - 4 * d) * i) / (degree); out(n, 2) = d; ++n; } for (int i = 1; i < degree; ++i) { out(n, 0) = d; out(n, 1) = d + ((1 - 4 * d) * (degree - i)) / (degree); out(n, 2) = d; ++n; } for (int i = 1; i < degree; ++i) { out(n, 0) = d; out(n, 1) = d; out(n, 2) = d + ((1 - 4 * d) * i) / (degree); ++n; } for (int i = 1; i < degree; ++i) { out(n, 0) = d + ((1 - 4 * d) * (degree - i)) / (degree); out(n, 1) = d; out(n, 2) = d + ((1 - 4 * d) * i) / (degree); ++n; } for (int i = 1; i < degree; ++i) { out(n, 0) = d; out(n, 1) = d + ((1 - 4 * d) * (degree - i)) / (degree); out(n, 2) = d + ((1 - 4 * d) * i) / (degree); ++n; } } if (degree >= 3) { xt::xtensor<double, 2> pts = vtk_triangle_points(degree - 3); for (std::size_t i = 0; i < pts.shape(0); ++i) { out(n, 0) = d + pts(i, 0) * (1 - 4 * d); out(n, 1) = d; out(n, 2) = d + pts(i, 1) * (1 - 4 * d); ++n; } for (std::size_t i = 0; i < pts.shape(0); ++i) { out(n, 0) = 1 - 3 * d - (pts(i, 0) + pts(i, 1)) * (1 - 4 * d); out(n, 1) = d + pts(i, 0) * (1 - 4 * d); out(n, 2) = d + pts(i, 1) * (1 - 4 * d); ++n; } for (std::size_t i = 0; i < pts.shape(0); ++i) { out(n, 0) = d; out(n, 1) = d + pts(i, 0) * (1 - 4 * d); out(n, 2) = d + pts(i, 1) * (1 - 4 * d); ++n; } for (std::size_t i = 0; i < pts.shape(0); ++i) { out(n, 0) = d + pts(i, 0) * (1 - 4 * d); out(n, 1) = d + pts(i, 1) * (1 - 4 * d); out(n, 2) = d; ++n; } } if (degree >= 4) { xt::view(out, xt::range(n, npoints), xt::all()) = vtk_tetrahedron_points(degree - 4); xt::xtensor<double, 2> pts = vtk_tetrahedron_points(degree - 4); for (std::size_t i = 0; i < pts.shape(0); ++i) { for (std::size_t j = 0; j < pts.shape(1); ++j) out(n, j) = d + (1 - 4 * d) * pts(i, j); ++n; } } return out; } //----------------------------------------------------------------------------- FiniteElement create_vtk_element(cell::type celltype, int degree, bool discontinuous) { if (celltype == cell::type::point) throw std::runtime_error("Invalid celltype"); if (degree == 0) { throw std::runtime_error("Cannot create an order 0 VTK element."); } // DOF transformation don't yet work on this element, so throw runtime error // if trying to make continuous version if (!discontinuous) { throw std::runtime_error("Continuous VTK element not yet supported."); } const std::size_t tdim = cell::topological_dimension(celltype); const std::size_t ndofs = polyset::dim(celltype, degree); const std::vector<std::vector<std::vector<int>>> topology = cell::topology(celltype); std::array<std::vector<xt::xtensor<double, 3>>, 4> M; std::array<std::vector<xt::xtensor<double, 2>>, 4> x; for (std::size_t dim = 0; dim <= tdim; ++dim) { M[dim].resize(topology[dim].size()); x[dim].resize(topology[dim].size()); } switch (celltype) { case cell::type::interval: { // Points at vertices x[0][0] = {{0.}}; x[0][1] = {{1.}}; for (int i = 0; i < 2; ++i) M[0][i] = {{{1.}}}; // Points on interval x[1][0] = xt::xtensor<double, 2>( {static_cast<std::size_t>(degree - 1), static_cast<std::size_t>(1)}); for (int i = 1; i < degree; ++i) x[1][0](i - 1, 0) = static_cast<double>(i) / static_cast<double>(degree); M[1][0] = xt::xtensor<double, 3>({static_cast<std::size_t>(degree - 1), 1, static_cast<std::size_t>(degree - 1)}); xt::view(M[1][0], xt::all(), 0, xt::all()) = xt::eye<double>(degree - 1); break; } case cell::type::triangle: { // Points at vertices x[0][0] = {{0., 0.}}; x[0][1] = {{1., 0.}}; x[0][2] = {{0., 1.}}; for (int i = 0; i < 3; ++i) M[0][i] = {{{1.}}}; // Points on edges std::array<std::size_t, 2> s = {static_cast<std::size_t>(degree - 1), static_cast<std::size_t>(2)}; for (int i = 0; i < 3; ++i) x[1][i] = xt::xtensor<double, 2>(s); for (int i = 1; i < degree; ++i) { x[1][0](i - 1, 0) = static_cast<double>(i) / static_cast<double>(degree); x[1][0](i - 1, 1) = 0; x[1][1](i - 1, 0) = static_cast<double>(degree - i) / static_cast<double>(degree); x[1][1](i - 1, 1) = static_cast<double>(i) / static_cast<double>(degree); x[1][2](i - 1, 0) = 0; x[1][2](i - 1, 1) = static_cast<double>(degree - i) / static_cast<double>(degree); } for (int i = 0; i < 3; ++i) { M[1][i] = xt::xtensor<double, 3>({static_cast<std::size_t>(degree - 1), 1, static_cast<std::size_t>(degree - 1)}); xt::view(M[1][i], xt::all(), 0, xt::all()) = xt::eye<double>(degree - 1); } // Points in triangle if (degree >= 3) { x[2][0] = vtk_triangle_points(degree - 3); M[2][0] = xt::xtensor<double, 3>({x[2][0].shape(0), 1, x[2][0].shape(0)}); xt::view(M[2][0], xt::all(), 0, xt::all()) = xt::eye<double>(x[2][0].shape(0)); } else { x[2][0] = xt::xtensor<double, 2>({0, 2}); M[2][0] = xt::xtensor<double, 3>({0, 1, 0}); } break; } case cell::type::tetrahedron: { // Points at vertices x[0][0] = {{0., 0., 0.}}; x[0][1] = {{1., 0., 0.}}; x[0][2] = {{0., 1., 0.}}; x[0][3] = {{0., 0., 1.}}; for (int i = 0; i < 4; ++i) M[0][i] = {{{1.}}}; // Points on edges std::array<std::size_t, 2> s = {static_cast<std::size_t>(degree - 1), static_cast<std::size_t>(3)}; for (int i = 0; i < 6; ++i) x[1][i] = xt::xtensor<double, 2>(s); for (int i = 1; i < degree; ++i) { x[1][0](i - 1, 0) = static_cast<double>(i) / static_cast<double>(degree); x[1][0](i - 1, 1) = 0; x[1][0](i - 1, 2) = 0; x[1][1](i - 1, 0) = static_cast<double>(degree - i) / static_cast<double>(degree); x[1][1](i - 1, 1) = static_cast<double>(i) / static_cast<double>(degree); x[1][1](i - 1, 2) = 0; x[1][2](i - 1, 0) = 0; x[1][2](i - 1, 1) = static_cast<double>(degree - i) / static_cast<double>(degree); x[1][2](i - 1, 2) = 0; x[1][3](i - 1, 0) = 0; x[1][3](i - 1, 1) = 0; x[1][3](i - 1, 2) = static_cast<double>(i) / static_cast<double>(degree); x[1][4](i - 1, 0) = static_cast<double>(degree - i) / static_cast<double>(degree); x[1][4](i - 1, 1) = 0; x[1][4](i - 1, 2) = static_cast<double>(i) / static_cast<double>(degree); x[1][5](i - 1, 0) = 0; x[1][5](i - 1, 1) = static_cast<double>(degree - i) / static_cast<double>(degree); x[1][5](i - 1, 2) = static_cast<double>(i) / static_cast<double>(degree); } for (int i = 0; i < 6; ++i) { M[1][i] = xt::xtensor<double, 3>({static_cast<std::size_t>(degree - 1), 1, static_cast<std::size_t>(degree - 1)}); xt::view(M[1][i], xt::all(), 0, xt::all()) = xt::eye<double>(degree - 1); } // Points on faces if (degree >= 3) { xt::xtensor<double, 2> pts = vtk_triangle_points(degree - 3); std::array<std::size_t, 2> s = {pts.shape(0), static_cast<std::size_t>(3)}; for (int i = 0; i < 4; ++i) x[2][i] = xt::xtensor<double, 2>(s); for (std::size_t i = 0; i < pts.shape(0); ++i) { const double x0 = pts(i, 0); const double x1 = pts(i, 1); x[2][0](i, 0) = x0; x[2][0](i, 1) = 0; x[2][0](i, 2) = x1; x[2][1](i, 0) = 1 - x0 - x1; x[2][1](i, 1) = x0; x[2][1](i, 2) = x1; x[2][2](i, 0) = 0; x[2][2](i, 1) = x0; x[2][2](i, 2) = x1; x[2][3](i, 0) = x0; x[2][3](i, 1) = x1; x[2][3](i, 2) = 0; } for (int i = 0; i < 4; ++i) { M[2][i] = xt::xtensor<double, 3>({x[2][0].shape(0), 1, x[2][0].shape(0)}); xt::view(M[2][i], xt::all(), 0, xt::all()) = xt::eye<double>(x[2][0].shape(0)); } } else { for (int i = 0; i < 4; ++i) { x[2][i] = xt::xtensor<double, 2>({0, 3}); M[2][i] = xt::xtensor<double, 3>({0, 1, 0}); } } if (degree >= 4) { x[3][0] = vtk_tetrahedron_points(degree - 4); M[3][0] = xt::xtensor<double, 3>({x[3][0].shape(0), 1, x[3][0].shape(0)}); xt::view(M[3][0], xt::all(), 0, xt::all()) = xt::eye<double>(x[3][0].shape(0)); } else { x[3][0] = xt::xtensor<double, 2>({0, 3}); M[3][0] = xt::xtensor<double, 3>({0, 1, 0}); } break; } case cell::type::quadrilateral: { // Points at vertices x[0][0] = {{0., 0.}}; x[0][1] = {{1., 0.}}; x[0][2] = {{1., 1.}}; x[0][3] = {{0., 1.}}; for (int i = 0; i < 4; ++i) M[0][i] = {{{1.}}}; // Points on edges std::array<std::size_t, 2> s = {static_cast<std::size_t>(degree - 1), 2}; for (int i = 0; i < 4; ++i) x[1][i] = xt::xtensor<double, 2>(s); for (int i = 1; i < degree; ++i) { x[1][0](i - 1, 0) = static_cast<double>(i) / static_cast<double>(degree); x[1][0](i - 1, 1) = 0; x[1][1](i - 1, 0) = 1; x[1][1](i - 1, 1) = static_cast<double>(i) / static_cast<double>(degree); x[1][2](i - 1, 0) = static_cast<double>(i) / static_cast<double>(degree); x[1][2](i - 1, 1) = 1; x[1][3](i - 1, 0) = 0; x[1][3](i - 1, 1) = static_cast<double>(i) / static_cast<double>(degree); } for (int i = 0; i < 4; ++i) { M[1][i] = xt::xtensor<double, 3>({static_cast<std::size_t>(degree - 1), 1, static_cast<std::size_t>(degree - 1)}); xt::view(M[1][i], xt::all(), 0, xt::all()) = xt::eye<double>(degree - 1); } // Points in quadrilateral x[2][0] = xt::xtensor<double, 2>( {static_cast<std::size_t>((degree - 1) * (degree - 1)), 2}); int n = 0; for (int j = 1; j < degree; ++j) for (int i = 1; i < degree; ++i) { x[2][0](n, 0) = static_cast<double>(i) / static_cast<double>(degree); x[2][0](n, 1) = static_cast<double>(j) / static_cast<double>(degree); ++n; } M[2][0] = xt::xtensor<double, 3>({x[2][0].shape(0), 1, x[2][0].shape(0)}); xt::view(M[2][0], xt::all(), 0, xt::all()) = xt::eye<double>(x[2][0].shape(0)); break; } case cell::type::hexahedron: { // Points at vertices x[0][0] = {{0., 0., 0.}}; x[0][1] = {{1., 0., 0.}}; x[0][2] = {{1., 1., 0.}}; x[0][3] = {{0., 1., 0.}}; x[0][4] = {{0., 0., 1.}}; x[0][5] = {{1., 0., 1.}}; x[0][6] = {{1., 1., 1.}}; x[0][7] = {{0., 1., 1.}}; for (int i = 0; i < 8; ++i) M[0][i] = {{{1.}}}; // Points on edges std::array<std::size_t, 2> s = {static_cast<std::size_t>(degree - 1), 3}; for (int i = 0; i < 12; ++i) x[1][i] = xt::xtensor<double, 2>(s); for (int i = 1; i < degree; ++i) { x[1][0](i - 1, 0) = static_cast<double>(i) / static_cast<double>(degree); x[1][0](i - 1, 1) = 0; x[1][0](i - 1, 2) = 0; x[1][1](i - 1, 0) = 1; x[1][1](i - 1, 1) = static_cast<double>(i) / static_cast<double>(degree); x[1][1](i - 1, 2) = 0; x[1][2](i - 1, 0) = static_cast<double>(i) / static_cast<double>(degree); x[1][2](i - 1, 1) = 1; x[1][2](i - 1, 2) = 0; x[1][3](i - 1, 0) = 0; x[1][3](i - 1, 1) = static_cast<double>(i) / static_cast<double>(degree); x[1][3](i - 1, 2) = 0; x[1][4](i - 1, 0) = static_cast<double>(i) / static_cast<double>(degree); x[1][4](i - 1, 1) = 0; x[1][4](i - 1, 2) = 1; x[1][5](i - 1, 0) = 1; x[1][5](i - 1, 1) = static_cast<double>(i) / static_cast<double>(degree); x[1][5](i - 1, 2) = 1; x[1][6](i - 1, 0) = static_cast<double>(i) / static_cast<double>(degree); x[1][6](i - 1, 1) = 1; x[1][6](i - 1, 2) = 1; x[1][7](i - 1, 0) = 0; x[1][7](i - 1, 1) = static_cast<double>(i) / static_cast<double>(degree); x[1][7](i - 1, 2) = 1; x[1][8](i - 1, 0) = 0; x[1][8](i - 1, 1) = 0; x[1][8](i - 1, 2) = static_cast<double>(i) / static_cast<double>(degree); x[1][9](i - 1, 0) = 1; x[1][9](i - 1, 1) = 0; x[1][9](i - 1, 2) = static_cast<double>(i) / static_cast<double>(degree); x[1][10](i - 1, 0) = 1; x[1][10](i - 1, 1) = 1; x[1][10](i - 1, 2) = static_cast<double>(i) / static_cast<double>(degree); x[1][11](i - 1, 0) = 0; x[1][11](i - 1, 1) = 1; x[1][11](i - 1, 2) = static_cast<double>(i) / static_cast<double>(degree); } for (int i = 0; i < 12; ++i) { M[1][i] = xt::xtensor<double, 3>({static_cast<std::size_t>(degree - 1), 1, static_cast<std::size_t>(degree - 1)}); xt::view(M[1][i], xt::all(), 0, xt::all()) = xt::eye<double>(degree - 1); } // Points on faces std::array<std::size_t, 2> s2 = {static_cast<std::size_t>((degree - 1) * (degree - 1)), 3}; for (int i = 0; i < 6; ++i) x[2][i] = xt::xtensor<double, 2>(s2); int n = 0; for (int j = 1; j < degree; ++j) for (int i = 1; i < degree; ++i) { x[2][0](n, 0) = 0; x[2][0](n, 1) = static_cast<double>(i) / static_cast<double>(degree); x[2][0](n, 2) = static_cast<double>(j) / static_cast<double>(degree); x[2][1](n, 0) = 1; x[2][1](n, 1) = static_cast<double>(i) / static_cast<double>(degree); x[2][1](n, 2) = static_cast<double>(j) / static_cast<double>(degree); x[2][2](n, 0) = static_cast<double>(i) / static_cast<double>(degree); x[2][2](n, 1) = 0; x[2][2](n, 2) = static_cast<double>(j) / static_cast<double>(degree); x[2][3](n, 0) = static_cast<double>(i) / static_cast<double>(degree); x[2][3](n, 1) = 1; x[2][3](n, 2) = static_cast<double>(j) / static_cast<double>(degree); x[2][4](n, 0) = static_cast<double>(i) / static_cast<double>(degree); x[2][4](n, 1) = static_cast<double>(j) / static_cast<double>(degree); x[2][4](n, 2) = 0; x[2][5](n, 0) = static_cast<double>(i) / static_cast<double>(degree); x[2][5](n, 1) = static_cast<double>(j) / static_cast<double>(degree); x[2][5](n, 2) = 1; ++n; } for (int i = 0; i < 6; ++i) { M[2][i] = xt::xtensor<double, 3>({x[2][0].shape(0), 1, x[2][0].shape(0)}); xt::view(M[2][i], xt::all(), 0, xt::all()) = xt::eye<double>(x[2][0].shape(0)); } // Points in hexahedron x[3][0] = xt::xtensor<double, 2>( {static_cast<std::size_t>((degree - 1) * (degree - 1) * (degree - 1)), 3}); n = 0; for (int k = 1; k < degree; ++k) for (int j = 1; j < degree; ++j) for (int i = 1; i < degree; ++i) { x[3][0](n, 0) = static_cast<double>(i) / static_cast<double>(degree); x[3][0](n, 1) = static_cast<double>(j) / static_cast<double>(degree); x[3][0](n, 2) = static_cast<double>(k) / static_cast<double>(degree); ++n; } M[3][0] = xt::xtensor<double, 3>({x[3][0].shape(0), 1, x[3][0].shape(0)}); xt::view(M[3][0], xt::all(), 0, xt::all()) = xt::eye<double>(x[3][0].shape(0)); break; } default: { throw std::runtime_error("Unsupported cell type."); } } if (discontinuous) { std::tie(x, M) = element::make_discontinuous(x, M, tdim, 1); } return FiniteElement(element::family::P, celltype, degree, {}, xt::eye<double>(ndofs), x, M, maps::type::identity, discontinuous, degree, degree, element::lagrange_variant::vtk); } //----------------------------------------------------------------------------- FiniteElement create_legendre(cell::type celltype, int degree, bool discontinuous) { if (!discontinuous) throw std::runtime_error("Legendre variant must be discontinuous"); const std::size_t tdim = cell::topological_dimension(celltype); const std::size_t ndofs = polyset::dim(celltype, degree); const std::vector<std::vector<std::vector<int>>> topology = cell::topology(celltype); std::array<std::vector<xt::xtensor<double, 3>>, 4> M; std::array<std::vector<xt::xtensor<double, 2>>, 4> x; for (std::size_t i = 0; i < tdim; ++i) { x[i] = std::vector<xt::xtensor<double, 2>>( cell::num_sub_entities(celltype, i), xt::xtensor<double, 2>({0, tdim})); M[i] = std::vector<xt::xtensor<double, 3>>( cell::num_sub_entities(celltype, i), xt::xtensor<double, 3>({0, 1, 0})); } auto [pts, _wts] = quadrature::make_quadrature(quadrature::type::Default, celltype, degree * 2); auto wts = xt::adapt(_wts); // Evaluate moment space at quadrature points const xt::xtensor<double, 2> phi = polynomials::tabulate( polynomials::type::legendre, celltype, degree, pts); for (std::size_t dim = 0; dim <= tdim; ++dim) { M[dim].resize(topology[dim].size()); x[dim].resize(topology[dim].size()); if (dim < tdim) { for (std::size_t e = 0; e < topology[dim].size(); ++e) { x[dim][e] = xt::xtensor<double, 2>({0, tdim}); M[dim][e] = xt::xtensor<double, 3>({0, 1, 0}); } } } x[tdim][0] = pts; M[tdim][0] = xt::xtensor<double, 3>({ndofs, 1, pts.shape(0)}); for (std::size_t i = 0; i < ndofs; ++i) xt::view(M[tdim][0], i, 0, xt::all()) = xt::col(phi, i) * wts; return FiniteElement(element::family::P, celltype, degree, {}, xt::eye<double>(ndofs), x, M, maps::type::identity, discontinuous, degree, degree, element::lagrange_variant::legendre); } //----------------------------------------------------------------------------- } // namespace //---------------------------------------------------------------------------- FiniteElement basix::element::create_lagrange(cell::type celltype, int degree, element::lagrange_variant variant, bool discontinuous) { if (celltype == cell::type::point) { if (degree != 0) throw std::runtime_error("Can only create order 0 Lagrange on a point"); std::array<std::vector<xt::xtensor<double, 3>>, 4> M; std::array<std::vector<xt::xtensor<double, 2>>, 4> x; x[0].push_back(xt::zeros<double>({1, 0})); M[0].push_back({{{1}}}); xt::xtensor<double, 2> wcoeffs = {{1}}; return FiniteElement(element::family::P, cell::type::point, 0, {}, wcoeffs, x, M, maps::type::identity, discontinuous, degree, degree); } if (variant == element::lagrange_variant::unset) { if (degree < 3) variant = element::lagrange_variant::equispaced; else throw std::runtime_error( "Lagrange elements of degree > 2 need to be given a variant."); } if (variant == element::lagrange_variant::vtk) return create_vtk_element(celltype, degree, discontinuous); if (variant == element::lagrange_variant::legendre) return create_legendre(celltype, degree, discontinuous); auto [lattice_type, simplex_method, exterior] = variant_to_lattice(celltype, variant); if (!exterior) { // Points used to define this variant are all interior to the cell, so this // variant requires that the element is discontinuous if (!discontinuous) { throw std::runtime_error("This variant of Lagrange is only supported for " "discontinuous elements"); } return create_d_lagrange(celltype, degree, variant, lattice_type, simplex_method); } const std::size_t tdim = cell::topological_dimension(celltype); const std::size_t ndofs = polyset::dim(celltype, degree); const std::vector<std::vector<std::vector<int>>> topology = cell::topology(celltype); std::array<std::vector<xt::xtensor<double, 3>>, 4> M; std::array<std::vector<xt::xtensor<double, 2>>, 4> x; // Create points at nodes, ordered by topology (vertices first) if (degree == 0) { if (!discontinuous) { throw std::runtime_error( "Cannot create a continuous order 0 Lagrange basis function"); } for (std::size_t i = 0; i < tdim; ++i) { x[i] = std::vector<xt::xtensor<double, 2>>( cell::num_sub_entities(celltype, i), xt::xtensor<double, 2>({0, tdim})); M[i] = std::vector<xt::xtensor<double, 3>>( cell::num_sub_entities(celltype, i), xt::xtensor<double, 3>({0, 1, 0})); } const xt::xtensor<double, 2> pt = lattice::create(celltype, 0, lattice_type, true, simplex_method); x[tdim].push_back(pt); const std::size_t num_dofs = pt.shape(0); std::array<std::size_t, 3> s = {num_dofs, 1, num_dofs}; M[tdim].push_back(xt::xtensor<double, 3>(s)); xt::view(M[tdim][0], xt::all(), 0, xt::all()) = xt::eye<double>(num_dofs); } else { for (std::size_t dim = 0; dim <= tdim; ++dim) { M[dim].resize(topology[dim].size()); x[dim].resize(topology[dim].size()); // Loop over entities of dimension 'dim' for (std::size_t e = 0; e < topology[dim].size(); ++e) { const xt::xtensor<double, 2> entity_x = cell::sub_entity_geometry(celltype, dim, e); if (dim == 0) { x[dim][e] = entity_x; const std::size_t num_dofs = entity_x.shape(0); M[dim][e] = xt::xtensor<double, 3>( {num_dofs, static_cast<std::size_t>(1), num_dofs}); xt::view(M[dim][e], xt::all(), 0, xt::all()) = xt::eye<double>(num_dofs); } else if (dim == tdim) { x[dim][e] = lattice::create(celltype, degree, lattice_type, false, simplex_method); const std::size_t num_dofs = x[dim][e].shape(0); std::array<std::size_t, 3> s = {num_dofs, 1, num_dofs}; M[dim][e] = xt::xtensor<double, 3>(s); xt::view(M[dim][e], xt::all(), 0, xt::all()) = xt::eye<double>(num_dofs); } else { cell::type ct = cell::sub_entity_type(celltype, dim, e); const auto lattice = lattice::create(ct, degree, lattice_type, false, simplex_method); const std::size_t num_dofs = lattice.shape(0); std::array<std::size_t, 3> s = {num_dofs, 1, num_dofs}; M[dim][e] = xt::xtensor<double, 3>(s); xt::view(M[dim][e], xt::all(), 0, xt::all()) = xt::eye<double>(num_dofs); auto x0s = xt::reshape_view( xt::row(entity_x, 0), {static_cast<std::size_t>(1), entity_x.shape(1)}); x[dim][e] = xt::tile(x0s, lattice.shape(0)); auto x0 = xt::row(entity_x, 0); for (std::size_t j = 0; j < lattice.shape(0); ++j) { for (std::size_t k = 0; k < lattice.shape(1); ++k) { xt::row(x[dim][e], j) += (xt::row(entity_x, k + 1) - x0) * lattice(j, k); } } } } } } if (discontinuous) { std::tie(x, M) = element::make_discontinuous(x, M, tdim, 1); } auto tensor_factors = create_tensor_product_factors(celltype, degree, variant); return FiniteElement(element::family::P, celltype, degree, {}, xt::eye<double>(ndofs), x, M, maps::type::identity, discontinuous, degree, degree, variant, tensor_factors); } //-----------------------------------------------------------------------------
32.813155
80
0.485953
[ "shape", "vector" ]
9db2b9dc5e35c90485e6b290e808168c2acd32f1
665
cpp
C++
10050 Hartals.cpp
zihadboss/UVA-Solutions
020fdcb09da79dc0a0411b04026ce3617c09cd27
[ "Apache-2.0" ]
86
2016-01-20T11:36:50.000Z
2022-03-06T19:43:14.000Z
10050 Hartals.cpp
Mehedishihab/UVA-Solutions
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
[ "Apache-2.0" ]
null
null
null
10050 Hartals.cpp
Mehedishihab/UVA-Solutions
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
[ "Apache-2.0" ]
113
2015-12-04T06:40:57.000Z
2022-02-11T02:14:28.000Z
#include <iostream> #include <vector> using namespace std; int parties[123]; int N, P; bool IsDayOff(int d) { for (int i = 0; i < P; ++i) if (d % parties[i] == 0) return true; return false; } int main() { int T; cin >> T; while (T--) { cin >> N >> P; for (int i = 0; i < P; ++i) cin >> parties[i]; int count = 0; for (int d = 1; d <= N; ++d) { // d = 1 means sunday // if (d % 7 != 6 && d % 7 != 0 && IsDayOff(d)) ++count; } cout << count << '\n'; } }
16.219512
56
0.354887
[ "vector" ]
9db7d5590e547ce1f7d56ad29325f202e2080a59
6,654
cpp
C++
src/qt/qtwebkit/Source/WebCore/css/CSSSegmentedFontFace.cpp
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2015-05-27T13:52:20.000Z
2015-05-27T13:52:20.000Z
src/qt/qtwebkit/Source/WebCore/css/CSSSegmentedFontFace.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtwebkit/Source/WebCore/css/CSSSegmentedFontFace.cpp
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2017-03-19T13:03:23.000Z
2017-03-19T13:03:23.000Z
/* * Copyright (C) 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "CSSSegmentedFontFace.h" #include "CSSFontFace.h" #include "CSSFontFaceSource.h" #include "CSSFontSelector.h" #include "Document.h" #include "FontDescription.h" #include "RuntimeEnabledFeatures.h" #include "SegmentedFontData.h" #include "SimpleFontData.h" namespace WebCore { CSSSegmentedFontFace::CSSSegmentedFontFace(CSSFontSelector* fontSelector) : m_fontSelector(fontSelector) { } CSSSegmentedFontFace::~CSSSegmentedFontFace() { pruneTable(); unsigned size = m_fontFaces.size(); for (unsigned i = 0; i < size; i++) m_fontFaces[i]->removedFromSegmentedFontFace(this); } void CSSSegmentedFontFace::pruneTable() { // Make sure the glyph page tree prunes out all uses of this custom font. if (m_fontDataTable.isEmpty()) return; m_fontDataTable.clear(); } bool CSSSegmentedFontFace::isValid() const { // Valid if at least one font face is valid. unsigned size = m_fontFaces.size(); for (unsigned i = 0; i < size; i++) { if (m_fontFaces[i]->isValid()) return true; } return false; } void CSSSegmentedFontFace::fontLoaded(CSSFontFace*) { pruneTable(); #if ENABLE(FONT_LOAD_EVENTS) if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && !isLoading()) { Vector<RefPtr<LoadFontCallback> > callbacks; m_callbacks.swap(callbacks); for (size_t index = 0; index < callbacks.size(); ++index) { if (checkFont()) callbacks[index]->notifyLoaded(); else callbacks[index]->notifyError(); } } #endif } void CSSSegmentedFontFace::appendFontFace(PassRefPtr<CSSFontFace> fontFace) { pruneTable(); fontFace->addedToSegmentedFontFace(this); m_fontFaces.append(fontFace); } static void appendFontDataWithInvalidUnicodeRangeIfLoading(SegmentedFontData* newFontData, PassRefPtr<SimpleFontData> prpFaceFontData, const Vector<CSSFontFace::UnicodeRange>& ranges) { RefPtr<SimpleFontData> faceFontData = prpFaceFontData; if (faceFontData->isLoading()) { newFontData->appendRange(FontDataRange(0, 0, faceFontData)); return; } unsigned numRanges = ranges.size(); if (!numRanges) { newFontData->appendRange(FontDataRange(0, 0x7FFFFFFF, faceFontData)); return; } for (unsigned j = 0; j < numRanges; ++j) newFontData->appendRange(FontDataRange(ranges[j].from(), ranges[j].to(), faceFontData)); } PassRefPtr<FontData> CSSSegmentedFontFace::getFontData(const FontDescription& fontDescription) { if (!isValid()) return 0; FontTraitsMask desiredTraitsMask = fontDescription.traitsMask(); unsigned hashKey = ((fontDescription.computedPixelSize() + 1) << (FontTraitsMaskWidth + FontWidthVariantWidth + 1)) | ((fontDescription.orientation() == Vertical ? 1 : 0) << (FontTraitsMaskWidth + FontWidthVariantWidth)) | fontDescription.widthVariant() << FontTraitsMaskWidth | desiredTraitsMask; RefPtr<SegmentedFontData>& fontData = m_fontDataTable.add(hashKey, 0).iterator->value; if (fontData && fontData->numRanges()) return fontData; // No release, we have a reference to an object in the cache which should retain the ref count it has. if (!fontData) fontData = SegmentedFontData::create(); unsigned size = m_fontFaces.size(); for (unsigned i = 0; i < size; i++) { if (!m_fontFaces[i]->isValid()) continue; FontTraitsMask traitsMask = m_fontFaces[i]->traitsMask(); bool syntheticBold = !(traitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)) && (desiredTraitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)); bool syntheticItalic = !(traitsMask & FontStyleItalicMask) && (desiredTraitsMask & FontStyleItalicMask); if (RefPtr<SimpleFontData> faceFontData = m_fontFaces[i]->getFontData(fontDescription, syntheticBold, syntheticItalic)) { ASSERT(!faceFontData->isSegmented()); appendFontDataWithInvalidUnicodeRangeIfLoading(fontData.get(), faceFontData.release(), m_fontFaces[i]->ranges()); } } if (fontData->numRanges()) return fontData; // No release, we have a reference to an object in the cache which should retain the ref count it has. return 0; } #if ENABLE(FONT_LOAD_EVENTS) bool CSSSegmentedFontFace::isLoading() const { unsigned size = m_fontFaces.size(); for (unsigned i = 0; i < size; i++) { if (m_fontFaces[i]->loadState() == CSSFontFace::Loading) return true; } return false; } bool CSSSegmentedFontFace::checkFont() const { unsigned size = m_fontFaces.size(); for (unsigned i = 0; i < size; i++) { if (m_fontFaces[i]->loadState() != CSSFontFace::Loaded) return false; } return true; } void CSSSegmentedFontFace::loadFont(const FontDescription& fontDescription, PassRefPtr<LoadFontCallback> callback) { getFontData(fontDescription); // Kick off the load. if (callback) { if (isLoading()) m_callbacks.append(callback); else if (checkFont()) callback->notifyLoaded(); else callback->notifyError(); } } #endif }
35.206349
230
0.695521
[ "object", "vector" ]
9dbd90590edd0692e2aa41b6fe0c62408e33917d
1,842
cpp
C++
CSES/Dynamic_Range_min.cpp
aldew5/Competitve-Programming
eb0b93a35af3bd5e806aedc44b835830af01d496
[ "MIT" ]
2
2020-05-09T15:54:18.000Z
2021-01-23T22:32:53.000Z
CSES/Dynamic_Range_min.cpp
aldew5/Competitive-Programming
fc93723fae739d0b06bcf2dbe3b9274584a79a66
[ "MIT" ]
null
null
null
CSES/Dynamic_Range_min.cpp
aldew5/Competitive-Programming
fc93723fae739d0b06bcf2dbe3b9274584a79a66
[ "MIT" ]
null
null
null
/* ID: alec3 LANG: C++14 PROG: */ /* */ #include <bits/stdc++.h> #define check(x) cout<<(#x)<<": "<<x<<" " << endl; #define line cout << "--------------------" << endl; #define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define ss second #define ff first #define pb push_back #define lb lower_bound #define ub upper_bound #define mp make_pair #define FOR(i, a, b) for (int i = a; i < b; i++) #define F0R(i, a) for (int i = 0; i < (a); i++) typedef long long ll; typedef unsigned long long ull; int pct(int x) { return __builtin_popcount(x); } using namespace std; void setIO(string name) { freopen((name+".in").c_str(),"r",stdin); freopen((name+".out").c_str(),"w",stdout); ios_base::sync_with_stdio(0); } using namespace std; const ll MOD = 1e9 + 7; const ll INF = 1e10 + 70; template<class T> struct Seg { // comb(ID,b) = b const T ID = 1e18; T comb(T a, T b) { return min(a,b); } int n; vector<T> seg; void init(int _n) { n = _n; seg.assign(2*n,ID); } void pull(int p) { seg[p] = comb(seg[2*p],seg[2*p+1]); } void upd(int p, T val) { // set val at position p seg[p += n] = val; for (p /= 2; p; p /= 2) pull(p); } T query(int l, int r) { // min on interval [l, r] T ra = ID, rb = ID; for (l += n, r += n+1; l < r; l /= 2, r /= 2) { if (l&1) ra = comb(ra,seg[l++]); if (r&1) rb = comb(seg[--r],rb); } return comb(ra,rb); } }; int main() { int n, q; cin >> n >> q; Seg<int> seg; seg.init(n+1); int it; for (int i = 1; i <= n; i++){ cin >> it; seg.upd(i, it); } int t, a, b; for (int i = 0; i < q; i++){ cin >> t >> a >> b; if (t == 1) seg.upd(a, b); else cout << seg.query(a, b) << endl; } return 0; }
20.241758
65
0.497828
[ "vector" ]
e38804efb8aab8e90b03b6bffe1c9542548863ed
9,781
cpp
C++
test/SpanIntervalTest.cpp
JunLi-Galios/repel
e4e7f4ffc95f8d65dd478861080c9c77bab9b797
[ "MIT" ]
null
null
null
test/SpanIntervalTest.cpp
JunLi-Galios/repel
e4e7f4ffc95f8d65dd478861080c9c77bab9b797
[ "MIT" ]
null
null
null
test/SpanIntervalTest.cpp
JunLi-Galios/repel
e4e7f4ffc95f8d65dd478861080c9c77bab9b797
[ "MIT" ]
null
null
null
#define BOOST_TEST_MODULE SpanInterval #define BOOST_TEST_MAIN #include "../src/config.h" #ifdef USE_DYNAMIC_UNIT_TEST #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <boost/optional.hpp> #include <boost/assign/list_of.hpp> #include "../src/SpanInterval.h" #include "../src/Interval.h" #include "../src/SISet.h" #include <boost/foreach.hpp> #include <iostream> #include <list> #include <iterator> #include <algorithm> using boost::assign::list_of; BOOST_AUTO_TEST_CASE( basic_test ) { { SpanInterval sp1(1,11,1,11); SpanInterval sp2(5,10,5,10); Interval start = sp1.start(); Interval end = sp1.finish(); BOOST_CHECK_EQUAL(start.start(), 1); BOOST_CHECK_EQUAL(start.finish(), 11); BOOST_CHECK_EQUAL(end.start(), 1); BOOST_CHECK_EQUAL(end.finish(), 11); std::list<SpanInterval> removed; sp1.subtract(sp2,back_inserter(removed)); BOOST_CHECK(removed.size() == 3); BOOST_CHECK(std::find(removed.begin(), removed.end(), SpanInterval(1,4,1,11)) != removed.end()); BOOST_CHECK(std::find(removed.begin(), removed.end(), SpanInterval(11,11,11,11)) != removed.end()); BOOST_CHECK(std::find(removed.begin(), removed.end(), SpanInterval(5,10,11,11)) != removed.end()); } { SpanInterval sp1(1,11, 10,14); SpanInterval sp2(5,7, 5,9); std::list<SpanInterval> removed; sp1.subtract(sp2,back_inserter(removed)); BOOST_CHECK(removed.size() == 1); BOOST_CHECK(std::find(removed.begin(), removed.end(), SpanInterval(1,11,10,14))!=removed.end()); } { std::list<SpanInterval> shouldBeEmpty; SpanInterval sp(1,10,1,10); sp.subtract(sp, std::back_inserter(shouldBeEmpty)); BOOST_CHECK_EQUAL(shouldBeEmpty.size(), 0); } } BOOST_AUTO_TEST_CASE( siset_test ) { SpanInterval sp1(1,10,1,10); SpanInterval sp2(8,11,8,11); SISet set(false, Interval(1,11)); BOOST_CHECK(set.isDisjoint()); set.add(sp1); BOOST_CHECK(set.isDisjoint()); set.add(sp2); BOOST_CHECK(!set.isDisjoint()); set.makeDisjoint(); BOOST_CHECK(set.isDisjoint()); // TODO turn this part into a test //std::cout << "compliment of " << set.toString() << " is " << set.compliment().toString() << std::endl; SISet dcompliment = set.compliment().compliment(); dcompliment.makeDisjoint(); // //std::cout << "double compliment is " << dcompliment.toString() << std::endl; } BOOST_AUTO_TEST_CASE( hammingliq_dist_test) { Interval maxInterval(0,50); SISet a(true, maxInterval); SISet b(true, maxInterval); a.add(SpanInterval(1,5,1,5)); b.add(SpanInterval(2,5,2,5)); BOOST_CHECK_EQUAL(hammingDistance(a,b), 1); } BOOST_AUTO_TEST_CASE( hamming_dist_test) { Interval maxInterval(0,50); SISet a(false, maxInterval); SISet b(false, maxInterval); a.add(SpanInterval(1,5,1,5)); b.add(SpanInterval(2,5,2,5)); BOOST_CHECK_EQUAL(hammingDistance(a,b), 5); } BOOST_AUTO_TEST_CASE( rand_siset_test ) { Interval maxInterval(0,100); boost::mt19937 rng; SISet set = SISet::randomSISet(true, maxInterval, rng); BOOST_WARN_EQUAL(set.toString(), "{[0:2], [5:6], [8:8], [10:10], [14:14], [16:17], [21:24], [28:28], [30:30], [33:33], [35:36], [41:42], [45:46], [49:51], [56:56], [59:60], [64:64], [66:66], [70:72], [74:82], [85:87], [89:89], [91:91], [93:93], [96:96]}"); } BOOST_AUTO_TEST_CASE( sisetliq_test ) { SpanInterval sp1(1,10,1,10); SpanInterval sp2(6,11,6,11); SISet set(true, Interval(1,11)); set.add(sp1); set.add(sp2); BOOST_CHECK(set.isDisjoint()); } BOOST_AUTO_TEST_CASE( spanInterval_relations ) { Interval maxInterval(0, 1000); SpanInterval universe(maxInterval); SpanInterval sp1(1,5,6,10); boost::optional<SpanInterval> sp2 = sp1.satisfiesRelation(Interval::MEETS, universe); BOOST_CHECK(sp2); SpanInterval si = sp2.get(); BOOST_CHECK_EQUAL(si.toString(), "[(7, 11), (7, 1000)]"); sp1 = SpanInterval(999, 1000, 1000, 1000); sp2 = sp1.satisfiesRelation(Interval::MEETS, universe); BOOST_CHECK(!sp2); sp1 = SpanInterval(1,4,7,9); sp2 = sp1.satisfiesRelation(Interval::OVERLAPS, universe); BOOST_CHECK(sp2); si = sp2.get(); BOOST_CHECK_EQUAL(si.toString(), "[(2, 9), (8, 1000)]"); sp2 = sp1.satisfiesRelation(Interval::OVERLAPSI, universe); BOOST_CHECK(sp2); si = sp2.get(); BOOST_CHECK_EQUAL(si.toString(), "[(0, 3), (1, 8)]"); sp2 = sp1.satisfiesRelation(Interval::STARTS, universe); BOOST_CHECK(sp2); si = sp2.get(); BOOST_CHECK_EQUAL(si.toString(), "[(1, 4), (8, 1000)]"); sp2 = sp1.satisfiesRelation(Interval::STARTSI, universe); BOOST_CHECK(sp2); si = sp2.get(); BOOST_CHECK_EQUAL(si.toString(), "[(1, 4), (1, 8)]"); } BOOST_AUTO_TEST_CASE( spanIntervalspan ) { SpanInterval sp1(1,5,6,10); SpanInterval sp2(3,7,9,11); SISet set = span(sp1, sp2, Interval(1,11)); /* BOOST_FOREACH(SpanInterval sp, set.set()) { std::cout << "si = " << sp.toString() << std::endl; } set.makeDisjoint(); BOOST_FOREACH(SpanInterval sp, set.set()) { std::cout << "si = " << sp.toString() << std::endl; } */ } BOOST_AUTO_TEST_CASE( spanIntervalSize ) { SpanInterval sp1(5,10,5,10); SpanInterval sp2(1,5,3,6); SpanInterval sp3(5,7,1,2); BOOST_CHECK_EQUAL(sp1.size(), 21); BOOST_CHECK_EQUAL(sp2.size(), 17); BOOST_CHECK_EQUAL(sp3.size(), 0); } BOOST_AUTO_TEST_CASE ( subtractTest) { SpanInterval sp1(1,10,1,10); SpanInterval sp2(5,5,5,5); std::vector<SpanInterval> rVec; sp1.subtract(sp2, back_inserter(rVec)); BOOST_REQUIRE_EQUAL(rVec.size(),3); BOOST_CHECK_EQUAL(rVec[0].toString(), "[(1, 4), (1, 10)]"); BOOST_CHECK_EQUAL(rVec[1].toString(), "[(5, 5), (6, 10)]"); BOOST_CHECK_EQUAL(rVec[2].toString(), "[6:10]"); } BOOST_AUTO_TEST_CASE ( siSetSubtractTest) { SpanInterval sp1(1,10,1,10); SpanInterval sp2(11,15,13,15); SpanInterval sp3(5,5,5,5); SpanInterval sp4(11,15,13,14); SISet set1(false, Interval(1,15)); SISet set2(false, Interval(1,15)); set1.add(sp1); set1.add(sp2); set2.add(sp3); set2.add(sp4); set1.subtract(set2); BOOST_CHECK_EQUAL(set1.toString(), "{[(1, 4), (1, 10)], [(5, 5), (6, 10)], [6:10], [(11, 14), (15, 15)], [15:15]}"); } BOOST_AUTO_TEST_CASE( siSetComplimentTest) { // [(1, 9), (1, 20)], [(1, 18), (20, 20)], [(10, 10), (10, 19)], [11:20] Interval maxInt = Interval(1,20); SpanInterval sp1(1,9,1,20); SpanInterval sp2(1,18,20,20); SpanInterval sp3(10,10,10,19); SpanInterval sp4(11,20,11,20); SISet set(false, maxInt); set.add(sp1); set.add(sp2); set.add(sp3); set.add(sp4); set.makeDisjoint(); BOOST_CHECK_EQUAL(set.toString(), "{[(1, 9), (1, 20)], [(10, 10), (10, 19)], [(10, 18), (20, 20)], [(11, 18), (11, 19)], [19:20]}"); SISet compliment = set.compliment(); BOOST_CHECK_EQUAL(compliment.toString(), "{}"); } BOOST_AUTO_TEST_CASE ( siIteratorTest) { SpanInterval sp(1,10,1,10); std::vector<Interval> intervals; std::copy(sp.begin(), sp.end(), std::inserter(intervals, intervals.begin())); BOOST_CHECK_EQUAL(sp.size(), intervals.size()); // make sure that every interval is in there for (int start = 1; start <= 10; start++) { for (int finish = start; finish <= 10; finish++) { Interval interval(start, finish); BOOST_CHECK(std::find(intervals.begin(), intervals.end(), interval) != intervals.end()); } } } BOOST_AUTO_TEST_CASE (siSetOutputIteratorTest ) { std::list<SpanInterval> list = list_of(SpanInterval(0,1,0,1))(SpanInterval(3,6,3,6))(SpanInterval(9,10,9,10))(SpanInterval(11,11,11,11)); SISet siset(false, Interval(0,15)); std::copy(list.begin(), list.end(), SISetInserter(siset)); BOOST_CHECK_EQUAL(siset.toString(), "{[0:1], [3:6], [9:10], [11:11]}"); } BOOST_AUTO_TEST_CASE( siSetEndpointTest) { { SISet set(true, Interval(0,10)); std::vector<SpanInterval> segments; std::vector<SpanInterval> expected = list_of(SpanInterval(0,10,0,10)); set.collectSegments(std::back_inserter(segments)); BOOST_CHECK_EQUAL_COLLECTIONS(segments.begin(), segments.end(), expected.begin(), expected.end()); } { SISet set(true, Interval(0,10)); set.add(SpanInterval(2,4,2,4)); set.add(SpanInterval(7,7,7,7)); std::set<SpanInterval> segments; std::set<SpanInterval> expected = list_of(SpanInterval(0,1,0,1))(SpanInterval(2,4,2,4))(SpanInterval(5,6,5,6))(SpanInterval(7,7,7,7))(SpanInterval(8,10,8,10)); set.collectSegments(std::inserter(segments, segments.end())); BOOST_CHECK_EQUAL_COLLECTIONS(segments.begin(), segments.end(), expected.begin(), expected.end()); } } BOOST_AUTO_TEST_CASE( intervalSubtract ) { Interval a(1,5); Interval b(6,10); Interval c(4,8); Interval d(3,4); BOOST_REQUIRE_EQUAL(a.subtract(b).size(), 1); BOOST_CHECK_EQUAL(a.subtract(b)[0], Interval(1,5)); BOOST_REQUIRE_EQUAL(b.subtract(a).size(), 1); BOOST_CHECK_EQUAL(b.subtract(a)[0], Interval(6,10)); BOOST_REQUIRE_EQUAL(a.subtract(c).size(), 1); BOOST_CHECK_EQUAL(a.subtract(c)[0], Interval(1,3)); BOOST_REQUIRE_EQUAL(b.subtract(c).size(), 1); BOOST_CHECK_EQUAL(b.subtract(c)[0], Interval(9,10)); BOOST_REQUIRE(d.subtract(a).empty()); BOOST_REQUIRE_EQUAL(a.subtract(d).size(), 2); BOOST_CHECK_EQUAL(a.subtract(d)[0], Interval(1,2)); BOOST_CHECK_EQUAL(a.subtract(d)[1], Interval(5,5)); }
32.280528
260
0.632962
[ "vector" ]
e38bc3bac710332bfaa06fa2476d2955e9de2221
275
cpp
C++
chess_game/source/piece.cpp
mwkpe/apeiron-examples
dc28324479b4583478b68ee0251af8969b0ff5cf
[ "MIT" ]
null
null
null
chess_game/source/piece.cpp
mwkpe/apeiron-examples
dc28324479b4583478b68ee0251af8969b0ff5cf
[ "MIT" ]
null
null
null
chess_game/source/piece.cpp
mwkpe/apeiron-examples
dc28324479b4583478b68ee0251af8969b0ff5cf
[ "MIT" ]
null
null
null
#include "piece.h" example::chess::Piece::Piece(Type type, Chess_color color, const apeiron::opengl::Model* model) : type_{type}, chess_color_{color}, model_{model} { } void example::chess::Piece::render() const { for (const auto& mesh : *model_) mesh.render(); }
18.333333
95
0.683636
[ "mesh", "render", "model" ]
e390e08778c0d4a0da9d80032019a615ce534bb5
8,175
cpp
C++
jni/SDL/src/core/android/SDL_android.cpp
kerlw/CorsixTH-Android
283c787d87f3f48954e0fb1877b679e60c065062
[ "MIT" ]
1
2015-11-06T03:21:09.000Z
2015-11-06T03:21:09.000Z
jni/SDL/src/core/android/SDL_android.cpp
kerlw/CorsixTH-Android
283c787d87f3f48954e0fb1877b679e60c065062
[ "MIT" ]
null
null
null
jni/SDL/src/core/android/SDL_android.cpp
kerlw/CorsixTH-Android
283c787d87f3f48954e0fb1877b679e60c065062
[ "MIT" ]
null
null
null
/* SDL - Simple DirectMedia Layer Copyright (C) 1997-2011 Sam Lantinga This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Sam Lantinga slouken@libsdl.org */ #include "SDL_config.h" #include "SDL_stdinc.h" #include "SDL_android.h" extern "C" { #include "../../events/SDL_events_c.h" #include "../../video/android/SDL_androidkeyboard.h" #include "../../video/android/SDL_androidtouch.h" #include "../../video/android/SDL_androidvideo.h" /* Impelemented in audio/android/SDL_androidaudio.c */ extern void Android_RunAudioThread(); } // C /******************************************************************************* This file links the Java side of Android with libsdl *******************************************************************************/ #include <jni.h> #include <android/log.h> /******************************************************************************* Globals *******************************************************************************/ static JNIEnv* mEnv = NULL; static JNIEnv* mAudioEnv = NULL; // Main activity static jclass mActivityClass; // method signatures static jmethodID midCreateGLContext; static jmethodID midFlipBuffers; static jmethodID midAudioInit;static jmethodID midAudioWriteShortBuffer; static jmethodID midAudioWriteByteBuffer;static jmethodID midAudioQuit; // Accelerometer data storage static float fLastAccelerometer[3]; /******************************************************************************* Functions called by JNI *******************************************************************************/ // Library init extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) { return JNI_VERSION_1_4; } // Called before SDL_main() to initialize JNI bindings extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls) { __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init()"); mEnv = env; mActivityClass = (jclass) mEnv->NewGlobalRef(cls); midCreateGLContext = mEnv->GetStaticMethodID(mActivityClass, "createGLContext", "(II)Z"); midFlipBuffers = mEnv->GetStaticMethodID(mActivityClass, "flipBuffers", "()V"); midAudioInit = mEnv->GetStaticMethodID(mActivityClass, "audioInit", "(IZZI)Ljava/lang/Object;"); midAudioWriteShortBuffer = mEnv->GetStaticMethodID(mActivityClass, "audioWriteShortBuffer", "([S)V"); midAudioWriteByteBuffer = mEnv->GetStaticMethodID(mActivityClass, "audioWriteByteBuffer", "([B)V"); midAudioQuit = mEnv->GetStaticMethodID(mActivityClass, "audioQuit", "()V"); if (!midCreateGLContext || !midFlipBuffers || !midAudioInit || !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioQuit) { __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL: Couldn't locate Java callbacks, check that they're named and typed correctly"); } } // Resize extern "C" void Java_uk_co_armedpineapple_cth_SDLActivity_onNativeResize( JNIEnv* env, jclass jcls, jint width, jint height, jint format) { Android_SetScreenResolution(width, height, format); } // Keydown extern "C" void Java_uk_co_armedpineapple_cth_SDLActivity_onNativeKeyDown( JNIEnv* env, jclass jcls, jint keycode) { Android_OnKeyDown(keycode); } // Keyup extern "C" void Java_uk_co_armedpineapple_cth_SDLActivity_onNativeKeyUp( JNIEnv* env, jclass jcls, jint keycode) { Android_OnKeyUp(keycode); } // Touch extern "C" void Java_uk_co_armedpineapple_cth_SDLActivity_onNativeTouch( JNIEnv* env, jclass jcls, jint touch_device_id_in, jint pointer_finger_id_in, jint action, jfloat x, jfloat y, jfloat p, jint pc, jint gestureTriggered) { Android_OnTouch(touch_device_id_in, pointer_finger_id_in, action, x, y, p, pc, gestureTriggered); } // Accelerometer extern "C" void Java_uk_co_armedpineapple_cth_SDLActivity_onNativeAccel( JNIEnv* env, jclass jcls, jfloat x, jfloat y, jfloat z) { fLastAccelerometer[0] = x; fLastAccelerometer[1] = y; fLastAccelerometer[2] = z; } // Quit extern "C" void Java_uk_co_armedpineapple_cth_SDLActivity_nativeQuit( JNIEnv* env, jclass cls) { // Inject a SDL_QUIT event SDL_SendQuit(); } extern "C" void Java_uk_co_armedpineapple_cth_SDLActivity_nativeRunAudioThread( JNIEnv* env, jclass cls) { /* This is the audio thread, with a different environment */ mAudioEnv = env; Android_RunAudioThread(); } /******************************************************************************* Functions called by SDL into Java *******************************************************************************/ extern "C" SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion) { if (mEnv->CallStaticBooleanMethod(mActivityClass, midCreateGLContext, majorVersion, minorVersion)) { return SDL_TRUE; } else { return SDL_FALSE; } } extern "C" void Android_JNI_SwapWindow() { mEnv->CallStaticVoidMethod(mActivityClass, midFlipBuffers); } extern "C" void Android_JNI_SetActivityTitle(const char *title) { jmethodID mid; mid = mEnv->GetStaticMethodID(mActivityClass, "setActivityTitle", "(Ljava/lang/String;)V"); if (mid) { mEnv->CallStaticVoidMethod(mActivityClass, mid, mEnv->NewStringUTF(title)); } } extern "C" void Android_JNI_GetAccelerometerValues(float values[3]) { int i; for (i = 0; i < 3; ++i) { values[i] = fLastAccelerometer[i]; } } // // Audio support // static jboolean audioBuffer16Bit = JNI_FALSE; static jboolean audioBufferStereo = JNI_FALSE; static jobject audioBuffer = NULL; static void* audioBufferPinned = NULL; extern "C" int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames) { int audioBufferFrames; __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device"); audioBuffer16Bit = is16Bit; audioBufferStereo = channelCount > 1; audioBuffer = mEnv->CallStaticObjectMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames); if (audioBuffer == NULL) { __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: didn't get back a good audio buffer!"); return 0; } audioBuffer = mEnv->NewGlobalRef(audioBuffer); jboolean isCopy = JNI_FALSE; if (audioBuffer16Bit) { audioBufferPinned = mEnv->GetShortArrayElements( (jshortArray) audioBuffer, &isCopy); audioBufferFrames = mEnv->GetArrayLength((jshortArray) audioBuffer); } else { audioBufferPinned = mEnv->GetByteArrayElements((jbyteArray) audioBuffer, &isCopy); audioBufferFrames = mEnv->GetArrayLength((jbyteArray) audioBuffer); } if (audioBufferStereo) { audioBufferFrames /= 2; } return audioBufferFrames; } extern "C" void * Android_JNI_GetAudioBuffer() { return audioBufferPinned; } extern "C" void Android_JNI_WriteAudioBuffer() { if (audioBuffer16Bit) { mAudioEnv->ReleaseShortArrayElements((jshortArray) audioBuffer, (jshort *) audioBufferPinned, JNI_COMMIT); mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray) audioBuffer); } else { mAudioEnv->ReleaseByteArrayElements((jbyteArray) audioBuffer, (jbyte *) audioBufferPinned, JNI_COMMIT); mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray) audioBuffer); } /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */ } extern "C" void Android_JNI_CloseAudioDevice() { mEnv->CallStaticVoidMethod(mActivityClass, midAudioQuit); if (audioBuffer) { mEnv->DeleteGlobalRef(audioBuffer); audioBuffer = NULL; audioBufferPinned = NULL; } } /* vi: set ts=4 sw=4 expandtab: */
31.442308
89
0.701774
[ "object" ]
e396113a43a4ccb79170b4240c26025519f54975
7,438
cpp
C++
examples/diffusion_2d/diffusion_2d.cpp
ikorotkin/dae-cpp
4c538d5d82d95a2147efe0dce742831750d6184f
[ "MIT" ]
31
2019-05-10T17:56:23.000Z
2022-02-23T09:22:11.000Z
examples/diffusion_2d/diffusion_2d.cpp
ikorotkin/dae-cpp
4c538d5d82d95a2147efe0dce742831750d6184f
[ "MIT" ]
17
2019-05-09T16:11:42.000Z
2021-07-13T09:12:01.000Z
examples/diffusion_2d/diffusion_2d.cpp
ikorotkin/dae-cpp
4c538d5d82d95a2147efe0dce742831750d6184f
[ "MIT" ]
6
2019-12-11T13:21:31.000Z
2021-09-30T12:00:24.000Z
/* * This example solves the system of ODEs that describes diffusion in 2D plane: * * dC/dt = D*(d/dx(dC/dx) + d/dy(dC/dy)), * * where C is the concentration (dimensionless) on the square unit domain, * 0 <= x <= 1 and 0 <= y <= 1. D is the diffusion coefficient. * * Initial condition is an instantaneous point source in two dimensions: * C(x,y,t=0) = delta_function(x-1/2,y-1/2). * Boundary conditions: dC/dx = dC/dy = 0 on the boundaries. * * The system will be resolved using Finite Volume approach in the time * interval 0 <= t <= 0.01, and compared with the analytical solution. * Since the scheme is conservative and there are no sources in the domain, * the total concentration in the domain should be constant and equal to 1. * * Keywords: diffusion equation, 2D, finite volume method. */ #include <iostream> #include <chrono> #include <cmath> #include "../../src/solver.h" // the main header of dae-cpp library solver #include "diffusion_2d_RHS.h" // RHS of the problem namespace dae = daecpp; // A shortcut to dae-cpp library namespace // python3 + numpy + matplotlib should be installed in order to enable plotting // #define PLOTTING #ifdef PLOTTING #include "../../src/external/matplotlib-cpp/matplotlibcpp.h" namespace plt = matplotlibcpp; #endif // To compare dae-cpp solution with the analytical solution int solution_check(dae::state_type &x, MKL_INT N, double t, double D); /* * MAIN FUNCTION * ============================================================================= * Returns '0' if solution comparison is OK or '1' if solution error is above * acceptable tolerance. */ int main() { // These parameters can be obtained from a parameter file or as command line // options. Here for simplicity we define them as constants. const MKL_INT N = 51; // Number of cells along one axis. Should be odd // in order to place an instantaneous point source // exactly in the middle of the plane const double D = 1.0; // Diffusion coefficient (dimensionless) const double t1 = 0.01; // Integration time (0 < t < t1) std::cout << "N = " << N << "; D = " << D << "; t = " << t1 << '\n'; using clock = std::chrono::high_resolution_clock; using time_unit = std::chrono::milliseconds; // Define state vectors. Here N*N is the total number of the equations. dae::state_type x(N * N); // Initial conditions for(MKL_INT i = 0; i < N * N; i++) { x[i] = 0.0; } x[N * N / 2] = N * N; // = 1/(h*h) -- numerical delta-function // Set up the RHS of the problem. // Class MyRHS inherits abstract RHS class from dae-cpp library. MyRHS rhs(N, D); // Set up the Mass Matrix of the problem. In this case this matrix is // identity, so we can use a helper class provided by dae-cpp library. dae::MassMatrixIdentity mass(N * N); // Create an instance of the solver options and update some of the solver // parameters defined in solver_options.h dae::SolverOptions opt; opt.dt_init = 5.0e-5; // Change initial time step opt.fact_every_iter = false; // Gain some speed (delay the update // of Jacobian and the matrix factorisation) // We can override Jacobian class from dae-cpp library and provide // analytical Jacobian. But we will use numerically estimated one. dae::Jacobian jac_est(rhs); // Create an instance of the solver with particular RHS, Mass matrix, // Jacobian and solver options dae::Solver solve(rhs, jac_est, mass, opt); // Now we are ready to solve the set of DAEs std::cout << "\nStarting DAE solver...\n"; { auto tic0 = clock::now(); double t = t1 / 10; // Produce intermediate results at t = t1 / 10 solve(x, t); // This line is given here just as an example. // Here we produce an intermediate solution at time // t = (t1 / 10). This solution will be stored in the // vector x. Note that a better way to get // intermediate results is to override observer // function from daecpp::Solver class. // Tweak the solver paramters between the solver calls, for example, opt.dt_increase_factor = 2.0; t = t1; // Now produce the final solution at time t = t1 solve(x, t); // Reuse vector x as an initial condition and get the // final solution at time t = t1. auto tic1 = clock::now(); std::cout << "Solver execution time: " << std::chrono::duration_cast<time_unit>(tic1 - tic0).count() / 1000.0 << " sec." << '\n'; } // Compare result with the analytical solution int check_result = solution_check(x, N, t1, D); // Plot the solution #ifdef PLOTTING const double h = 1.0 / (double)N; dae::state_type_matrix x_axis, y_axis, z_axis; for(MKL_INT i = 0; i < N; i++) { dae::state_type x_row, y_row, z_row; for(MKL_INT j = 0; j < N; j++) { x_row.push_back((double)j * h + h * 0.5); y_row.push_back((double)i * h + h * 0.5); z_row.push_back(x[j + i * N]); } x_axis.push_back(x_row); y_axis.push_back(y_row); z_axis.push_back(z_row); } plt::figure(); plt::figure_size(800, 600); plt::plot_surface(x_axis, y_axis, z_axis); // Save figure const char *filename = "diffusion_2d.png"; std::cout << "Saving result to " << filename << "...\n"; plt::save(filename); #endif if(check_result) std::cout << "...Test FAILED\n\n"; else std::cout << "...done\n\n"; return check_result; } /* * Returns analytical solution */ double analyt(double x, double y, double t, double D) { double Dt4 = 1.0 / (D * t * 4.0); return Dt4 / 3.1415926535897932384626433832795 * exp(-((x - 0.5) * (x - 0.5) + (y - 0.5) * (y - 0.5)) * Dt4); } /* * Returns '0' if solution comparison is OK or '1' if the error is above * acceptable tolerance */ int solution_check(dae::state_type &x, MKL_INT N, double t, double D) { std::cout << "Solution check:\n"; const double h = 1.0 / (double)N; double total_C = 0; double err_max = 0; for(MKL_INT i = 0; i < N; i++) { for(MKL_INT j = 0; j < N; j++) { MKL_INT ind = j + i * N; total_C += x[ind]; double xi = (double)j * h + h * 0.5; double yi = (double)i * h + h * 0.5; double an = analyt(xi, yi, t, D); if(an > 1.0) { double error = (x[ind] - an) / an * 100.0; // relative error if(std::abs(error) > err_max) { err_max = std::abs(error); } } } } total_C *= h * h; double err_conc = std::abs(total_C - 1.0) * 100; std::cout << "Total concentration: " << total_C << " (" << err_conc << "% deviation from the analytical value)\n"; std::cout << "Maximum relative error: " << err_max << "%\n"; #ifdef DAE_SINGLE if(err_max < 1.0 && err_conc < 2.0e-5) #else if(err_max < 1.0 && err_conc < 1.0e-10) #endif return 0; else return 1; }
31.516949
80
0.574348
[ "vector" ]
e3a37e35640315f72b0115796392e9aa5aa1a1a4
28,942
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/CDownloadManager.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/CDownloadManager.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/app/CDownloadManager.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/ext/frameworkext.h" #include "Elastos.Droid.Provider.h" #include "elastos/droid/app/CDownloadManagerRequest.h" #include "elastos/droid/app/CDownloadManagerQuery.h" #include "elastos/droid/app/CDownloadManager.h" #include "elastos/droid/content/CContentUris.h" #include "elastos/droid/content/CContentValues.h" #include "elastos/droid/net/Uri.h" #include "elastos/droid/provider/CDownloadsImpl.h" #include "elastos/droid/provider/CSettingsGlobal.h" #include "elastos/droid/text/TextUtils.h" #include <elastos/utility/logging/Logger.h> #include <elastos/core/StringUtils.h> #include <elastos/core/StringBuilder.h> using Elastos::Droid::Content::CContentUris; using Elastos::Droid::Content::IContentUris; using Elastos::Droid::Content::CContentValues; using Elastos::Droid::Content::IContentValues; using Elastos::Droid::Database::EIID_ICursor; using Elastos::Droid::Database::EIID_ICursorWrapper; using Elastos::Droid::Net::Uri; using Elastos::Droid::Provider::CDownloadsImpl; using Elastos::Droid::Provider::IBaseColumns; using Elastos::Droid::Provider::IDownloadsImpl; using Elastos::Droid::Provider::CSettingsGlobal; using Elastos::Droid::Provider::ISettingsGlobal; using Elastos::Droid::Text::TextUtils; using Elastos::Core::CInteger32; using Elastos::Core::CString; using Elastos::Core::IInteger32; using Elastos::Core::StringUtils; using Elastos::Core::StringBuilder; using Elastos::Utility::Logging::Logger; using Elastos::IO::CFile; using Elastos::IO::ICloseable; namespace Elastos { namespace Droid { namespace App { static AutoPtr<ArrayOf<String> > InitUNDERLYINGCOLUMNS() { AutoPtr<ArrayOf<String> > columns = ArrayOf<String>::Alloc(15); columns->Set(0, IBaseColumns::ID); columns->Set(1, IDownloadsImpl::_DATA + " AS " + IDownloadManager::COLUMN_LOCAL_FILENAME); columns->Set(2, IDownloadsImpl::COLUMN_MEDIAPROVIDER_URI); columns->Set(3, IDownloadsImpl::COLUMN_DESTINATION); columns->Set(4, IDownloadsImpl::COLUMN_TITLE); columns->Set(5, IDownloadsImpl::COLUMN_DESCRIPTION); columns->Set(6, IDownloadsImpl::COLUMN_URI); columns->Set(7, IDownloadsImpl::COLUMN_STATUS); columns->Set(8, IDownloadsImpl::COLUMN_FILE_NAME_HINT); columns->Set(9, IDownloadsImpl::COLUMN_MIME_TYPE + " AS " + IDownloadManager::COLUMN_MEDIA_TYPE); columns->Set(10, IDownloadsImpl::COLUMN_TOTAL_BYTES + " AS " + IDownloadManager::COLUMN_TOTAL_SIZE_BYTES); columns->Set(11, IDownloadsImpl::COLUMN_LAST_MODIFICATION + " AS " + IDownloadManager::COLUMN_LAST_MODIFIED_TIMESTAMP); columns->Set(12, IDownloadsImpl::COLUMN_CURRENT_BYTES + " AS " + IDownloadManager::COLUMN_BYTES_DOWNLOADED_SO_FAR); columns->Set(13, IDownloadsImpl::COLUMN_ALLOW_WRITE); /* add the following 'computed' columns to the cursor. * they are not 'returned' by the database, but their inclusion * eliminates need to have lot of methods in CursorTranslator */ columns->Set(14, String("'placeholder' AS ") + IDownloadManager::COLUMN_LOCAL_URI); columns->Set(15, String("'placeholder' AS ") + IDownloadManager::COLUMN_REASON); return columns; } const String CDownloadManager::NON_DOWNLOADMANAGER_DOWNLOAD("non-dwnldmngr-download-dont-retry2download"); const AutoPtr<ArrayOf<String> > CDownloadManager::UNDERLYING_COLUMNS = InitUNDERLYINGCOLUMNS(); //============================================================================================== // CDownloadManager //============================================================================================== CDownloadManager::CursorTranslator::CursorTranslator() {} ECode CDownloadManager::CursorTranslator::constructor( /* [in] */ ICursor* cursor, /* [in] */ IUri* baseUri) { CursorWrapper::constructor(cursor); mBaseUri = baseUri; return NOERROR; } // @Override ECode CDownloadManager::CursorTranslator::GetInt32( /* [in] */ Int32 columnIndex, /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value); Int64 ivalue; GetInt64(columnIndex, &ivalue); *value = (Int32)ivalue; return NOERROR; } // @Override ECode CDownloadManager::CursorTranslator::GetInt64( /* [in] */ Int32 columnIndex, /* [out] */ Int64* value) { VALIDATE_NOT_NULL(value); String name; GetColumnName(columnIndex, &name); if (name.Equals(COLUMN_REASON)) { Int32 index; GetColumnIndex(IDownloadsImpl::COLUMN_STATUS, &index); Int32 indexValue; CursorWrapper::GetInt32(index, &indexValue); *value = GetReason(indexValue); return NOERROR; } else if (name.Equals(COLUMN_STATUS)) { Int32 index; GetColumnIndex(IDownloadsImpl::COLUMN_STATUS, &index); Int32 indexValue; CursorWrapper::GetInt32(index, &indexValue); *value = TranslateStatus(indexValue); return NOERROR; } return CursorWrapper::GetInt64(columnIndex, value); } // @Override ECode CDownloadManager::CursorTranslator::GetString( /* [in] */ Int32 columnIndex, /* [out] */ String* value) { VALIDATE_NOT_NULL(value); String name; GetColumnName(columnIndex, &name); String svalue; CursorWrapper::GetString(columnIndex, &svalue); *value = (name.Equals(COLUMN_LOCAL_URI)) ? GetLocalUri() : svalue; return NOERROR; } String CDownloadManager::CursorTranslator::GetLocalUri() { Int32 index; GetColumnIndex(IDownloadsImpl::COLUMN_DESTINATION, &index); Int64 destinationType; GetInt64(index, &destinationType); if (destinationType == IDownloadsImpl::DESTINATION_FILE_URI || destinationType == IDownloadsImpl::DESTINATION_EXTERNAL || destinationType == IDownloadsImpl::DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) { Int32 cindex; GetColumnIndex(COLUMN_LOCAL_FILENAME, &cindex); String localPath; GetString(cindex, &localPath); if (localPath.IsNull()) { return String(NULL); } AutoPtr<IFile> file; CFile::New(localPath, (IFile**)&file); AutoPtr<IUri> uri; Uri::FromFile(file, (IUri**)&uri); return Object::ToString(uri); } // return content URI for cache download Int32 idIndex; GetColumnIndex(IBaseColumns::ID, &idIndex); Int64 downloadId; GetInt64(idIndex, &downloadId); AutoPtr<IContentUris> cUris; CContentUris::AcquireSingleton((IContentUris**)&cUris); AutoPtr<IUri> uri; cUris->WithAppendedId(mBaseUri, downloadId, (IUri**)&uri); return Object::ToString(uri); } Int64 CDownloadManager::CursorTranslator::GetReason( /* [in] */ Int32 status) { switch (TranslateStatus(status)) { case STATUS_FAILED: return GetErrorCode(status); case STATUS_PAUSED: return GetPausedReason(status); default: return 0; // arbitrary value when status is not an error } } Int64 CDownloadManager::CursorTranslator::GetPausedReason( /* [in] */ Int32 status) { switch (status) { case IDownloadsImpl::STATUS_WAITING_TO_RETRY: return PAUSED_WAITING_TO_RETRY; case IDownloadsImpl::STATUS_WAITING_FOR_NETWORK: return PAUSED_WAITING_FOR_NETWORK; case IDownloadsImpl::STATUS_QUEUED_FOR_WIFI: return PAUSED_QUEUED_FOR_WIFI; case IDownloadsImpl::STATUS_PAUSED_BY_APP: return PAUSED_BY_APP; default: return PAUSED_UNKNOWN; } } Int64 CDownloadManager::CursorTranslator::GetErrorCode( /* [in] */ Int32 status) { if ((400 <= status && status < IDownloadsImpl::MIN_ARTIFICIAL_ERROR_STATUS) || (500 <= status && status < 600)) { // HTTP status code return status; } switch (status) { case IDownloadsImpl::STATUS_FILE_ERROR: return ERROR_FILE_ERROR; case IDownloadsImpl::STATUS_UNHANDLED_HTTP_CODE: case IDownloadsImpl::STATUS_UNHANDLED_REDIRECT: return ERROR_UNHANDLED_HTTP_CODE; case IDownloadsImpl::STATUS_HTTP_DATA_ERROR: return ERROR_HTTP_DATA_ERROR; case IDownloadsImpl::STATUS_TOO_MANY_REDIRECTS: return ERROR_TOO_MANY_REDIRECTS; case IDownloadsImpl::STATUS_INSUFFICIENT_SPACE_ERROR: return ERROR_INSUFFICIENT_SPACE; case IDownloadsImpl::STATUS_DEVICE_NOT_FOUND_ERROR: return ERROR_DEVICE_NOT_FOUND; case IDownloadsImpl::STATUS_CANNOT_RESUME: return ERROR_CANNOT_RESUME; case IDownloadsImpl::STATUS_FILE_ALREADY_EXISTS_ERROR: return ERROR_FILE_ALREADY_EXISTS; default: return ERROR_UNKNOWN; } } Int32 CDownloadManager::CursorTranslator::TranslateStatus( /* [in] */ Int32 status) { switch (status) { case IDownloadsImpl::STATUS_PENDING: return STATUS_PENDING; case IDownloadsImpl::STATUS_RUNNING: return STATUS_RUNNING; case IDownloadsImpl::STATUS_PAUSED_BY_APP: case IDownloadsImpl::STATUS_WAITING_TO_RETRY: case IDownloadsImpl::STATUS_WAITING_FOR_NETWORK: case IDownloadsImpl::STATUS_QUEUED_FOR_WIFI: return STATUS_PAUSED; case IDownloadsImpl::STATUS_SUCCESS: return STATUS_SUCCESSFUL; default: { AutoPtr<IDownloadsImpl> impl; CDownloadsImpl::AcquireSingleton((IDownloadsImpl**)&impl); Boolean res; impl->IsStatusError(status, &res); assert(res != FALSE); return STATUS_FAILED; } } } //============================================================================================== // CDownloadManager //============================================================================================== CAR_INTERFACE_IMPL(CDownloadManager, Object, IDownloadManager) CAR_OBJECT_IMPL(CDownloadManager) ECode CDownloadManager::constructor( /* [in] */ IContentResolver* resolver, /* [in] */ const String& packageName) { mResolver = resolver; mPackageName = packageName; AutoPtr<IDownloadsImpl> impl; CDownloadsImpl::AcquireSingleton((IDownloadsImpl**)&impl); impl->GetCONTENT_URI((IUri**)&mBaseUri); return NOERROR; } ECode CDownloadManager::SetAccessAllDownloads( /* [in] */ Boolean accessAllDownloads) { AutoPtr<IDownloadsImpl> dImpl; CDownloadsImpl::AcquireSingleton((IDownloadsImpl**)&dImpl); if (accessAllDownloads) { dImpl->GetALL_DOWNLOADS_CONTENT_URI((IUri**)&mBaseUri); } else { dImpl->GetCONTENT_URI((IUri**)&mBaseUri); } return NOERROR; } ECode CDownloadManager::Enqueue( /* [in] */ IDownloadManagerRequest* request, /* [out] */ Int64* id) { VALIDATE_NOT_NULL(id); *id = 0; AutoPtr<IContentValues> values = ((CDownloadManagerRequest*)request)->ToContentValues(mPackageName); AutoPtr<IDownloadsImpl> dImpl; CDownloadsImpl::AcquireSingleton((IDownloadsImpl**)&dImpl); AutoPtr<IUri> uri; dImpl->GetCONTENT_URI((IUri**)&uri); AutoPtr<IUri> downloadUri; mResolver->Insert(uri, values, (IUri**)&downloadUri); String segment; downloadUri->GetLastPathSegment(&segment); *id = StringUtils::ParseInt64(segment); return NOERROR; } ECode CDownloadManager::MarkRowDeleted( /* [in] */ ArrayOf<Int64>* ids, /* [out] */ Int32* number) { VALIDATE_NOT_NULL(number); *number = 0; if (ids == NULL || ids->GetLength() == 0) { // called with nothing to remove! // throw new IllegalArgumentException("input param 'ids' can't be null"); Logger::E("CDownloadManager", "input param 'ids' can't be null"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } AutoPtr<IContentValues> values; CContentValues::New((IContentValues**)&values); AutoPtr<IInteger32> column; CInteger32::New(1, (IInteger32**)&column); values->Put(IDownloadsImpl::COLUMN_DELETED, column); // if only one id is passed in, then include it in the uri itself. // this will eliminate a full database scan in the download service. if (ids->GetLength() == 1) { AutoPtr<IContentUris> curis; CContentUris::AcquireSingleton((IContentUris**)&curis); AutoPtr<IUri> uri; curis->WithAppendedId(mBaseUri, (*ids)[0], (IUri**)&uri); return mResolver->Update(uri, values, String(NULL), NULL, number); } AutoPtr<ArrayOf<String> > args = GetWhereArgsForIds(ids); return mResolver->Update(mBaseUri, values, GetWhereClauseForIds(ids), args, number); } ECode CDownloadManager::Remove( /* [in] */ ArrayOf<Int64>* ids, /* [out] */ Int32* number) { VALIDATE_NOT_NULL(number); return MarkRowDeleted(ids, number); } ECode CDownloadManager::Query( /* [in] */ IDownloadManagerQuery* query, /* [out] */ ICursor** cursor) { VALIDATE_NOT_NULL(cursor); AutoPtr<ICursor> underlyingCursor = ((CDownloadManagerQuery*)query)->RunQuery(mResolver, UNDERLYING_COLUMNS, mBaseUri); if (underlyingCursor == NULL) { *cursor = NULL; return NOERROR; } AutoPtr<CursorTranslator> ct = new CursorTranslator(); ct->constructor(underlyingCursor, mBaseUri); *cursor = (ICursor*)ct.Get(); REFCOUNT_ADD(*cursor); return NOERROR; } ECode CDownloadManager::OpenDownloadedFile( /* [in] */ Int64 id, /* [out] */ IParcelFileDescriptor** descriptor) { VALIDATE_NOT_NULL(descriptor); return mResolver->OpenFileDescriptor(GetDownloadUri(id), String("r"), descriptor); } ECode CDownloadManager::GetUriForDownloadedFile( /* [in] */ Int64 id, /* [out] */ IUri** uri) { VALIDATE_NOT_NULL(uri); *uri = NULL; // to check if the file is in cache, get its destination from the database AutoPtr<IDownloadManagerQuery> query; CDownloadManagerQuery::New((IDownloadManagerQuery**)&query); AutoPtr<ArrayOf<Int64> > idArray = ArrayOf<Int64>::Alloc(1); idArray->Set(0, id); query->SetFilterById(idArray); AutoPtr<ICursor> cursor; // try { Query(query, (ICursor**)&cursor); if (cursor == NULL) { return NOERROR; } Boolean hasFirst; if (cursor->MoveToFirst(&hasFirst), hasFirst) { Int32 cindex; cursor->GetColumnIndexOrThrow(COLUMN_STATUS, &cindex); Int32 status; cursor->GetInt32(cindex, &status); if (IDownloadManager::STATUS_SUCCESSFUL == status) { Int32 indx; cursor->GetColumnIndexOrThrow( IDownloadsImpl::COLUMN_DESTINATION, &indx); Int32 destination; cursor->GetInt32(indx, &destination); // TODO: if we ever add API to DownloadManager to let the caller specify // non-external storage for a downloaded file, then the following code // should also check for that destination. if (destination == IDownloadsImpl::DESTINATION_CACHE_PARTITION || destination == IDownloadsImpl::DESTINATION_SYSTEMCACHE_PARTITION || destination == IDownloadsImpl::DESTINATION_CACHE_PARTITION_NOROAMING || destination == IDownloadsImpl::DESTINATION_CACHE_PARTITION_PURGEABLE) { // return private uri AutoPtr<IContentUris> cUris; CContentUris::AcquireSingleton((IContentUris**)&cUris); AutoPtr<IDownloadsImpl> impl; CDownloadsImpl::AcquireSingleton((IDownloadsImpl**)&impl); AutoPtr<IUri> contentUri; impl->GetCONTENT_URI((IUri**)&contentUri); cUris->WithAppendedId(contentUri, id, uri); if (cursor != NULL) { ICloseable::Probe(cursor)->Close(); } return NOERROR; } else { // return public uri Int32 index; cursor->GetColumnIndexOrThrow(COLUMN_LOCAL_FILENAME, &index); String path; cursor->GetString(index, &path); AutoPtr<IFile> file; CFile::New(path, (IFile**)&file); Uri::FromFile(file, uri); if (cursor != NULL) { ICloseable::Probe(cursor)->Close(); } return NOERROR; } } } // } finally { if (cursor != NULL) { ICloseable::Probe(cursor)->Close(); } // } // downloaded file not found or its status is not 'successfully completed' return NOERROR; } ECode CDownloadManager::GetMimeTypeForDownloadedFile( /* [in] */ Int64 id, /* [out] */ String* uri) { VALIDATE_NOT_NULL(uri); *uri = String(NULL); AutoPtr<IDownloadManagerQuery> query; CDownloadManagerQuery::New((IDownloadManagerQuery**)&query); AutoPtr<ArrayOf<Int64> > idArray = ArrayOf<Int64>::Alloc(1); idArray->Set(0, id); query->SetFilterById(idArray); AutoPtr<ICursor> cursor; // try { Query(query, (ICursor**)&cursor); if (cursor == NULL) { return NOERROR; } Boolean toFirst; while (cursor->MoveToFirst(&toFirst), toFirst) { Int32 index; cursor->GetColumnIndexOrThrow(COLUMN_MEDIA_TYPE, &index); cursor->GetString(index, uri); if (cursor != NULL) { ICloseable::Probe(cursor)->Close(); } return NOERROR; } // } finally { if (cursor != NULL) { ICloseable::Probe(cursor)->Close(); } // } // downloaded file not found or its status is not 'successfully completed' return NOERROR; } ECode CDownloadManager::RestartDownload( /* [in] */ ArrayOf<Int64>* ids) { AutoPtr<IDownloadManagerQuery> query; CDownloadManagerQuery::New((IDownloadManagerQuery**)&query); query->SetFilterById(ids); AutoPtr<ICursor> cursor; Query(query, (ICursor**)&cursor); assert(cursor != NULL); // try { Boolean toFirst = FALSE; cursor->MoveToFirst(&toFirst); if (toFirst) { Boolean afterLast = FALSE; Boolean hasNext = FALSE; cursor->IsAfterLast(&afterLast); for (; !afterLast && hasNext;) { Int32 index; cursor->GetColumnIndex(COLUMN_STATUS, &index); Int32 status; cursor->GetInt32(index, &status); if (status != STATUS_SUCCESSFUL && status != STATUS_FAILED) { // throw new IllegalArgumentException("Cannot restart incomplete download: " // + cursor.getLong(cursor.getColumnIndex(COLUMN_ID))); Int32 idIndex; cursor->GetColumnIndex(COLUMN_ID, &idIndex); Int64 idValue; cursor->GetInt64(idIndex, &idValue); Logger::E("CDownloadManager", "Cannot restart incomplete download: %d", idValue); ICloseable::Probe(cursor)->Close(); return E_ILLEGAL_ARGUMENT_EXCEPTION; } cursor->MoveToNext(&hasNext); cursor->IsAfterLast(&afterLast); } } // } finally { ICloseable::Probe(cursor)->Close(); // } AutoPtr<IContentValues> values; CContentValues::New((IContentValues**)&values); AutoPtr<IInteger32> value; CInteger32::New(0, (IInteger32**)&value); values->Put(IDownloadsImpl::COLUMN_CURRENT_BYTES, value); value = NULL; CInteger32::New(-1, (IInteger32**)&value); values->Put(IDownloadsImpl::COLUMN_TOTAL_BYTES, value); values->PutNull(IDownloadsImpl::_DATA); value = NULL; CInteger32::New(IDownloadsImpl::STATUS_PENDING, (IInteger32**)&value); values->Put(IDownloadsImpl::COLUMN_STATUS, value); AutoPtr<ArrayOf<String> > args = GetWhereArgsForIds(ids); Int32 res; mResolver->Update(mBaseUri, values, GetWhereClauseForIds(ids), args, &res); return NOERROR; } ECode CDownloadManager::PauseDownload( /* [in] */ Int64 id) { AutoPtr<IContentValues> values; CContentValues::New((IContentValues**)&values); values->Put(IDownloadsImpl::COLUMN_CONTROL, IDownloadsImpl::CONTROL_PAUSED); AutoPtr<IContentUris> cUris; CContentUris::AcquireSingleton((IContentUris**)&cUris); AutoPtr<IUri> uri; cUris->WithAppendedId(mBaseUri, id, (IUri**)&uri); Int32 res; mResolver->Update(uri, values, String(NULL), NULL, &res); return NOERROR; } ECode CDownloadManager::ResumeDownload( /* [in] */ Int64 id) { AutoPtr<IContentValues> values; CContentValues::New((IContentValues**)&values); values->Put(IDownloadsImpl::COLUMN_CONTROL, IDownloadsImpl::CONTROL_RUN); AutoPtr<IContentUris> cUris; CContentUris::AcquireSingleton((IContentUris**)&cUris); AutoPtr<IUri> uri; cUris->WithAppendedId(mBaseUri, id, (IUri**)&uri); Int32 res; mResolver->Update(uri, values, String(NULL), NULL, &res); return NOERROR; } ECode CDownloadManager::GetMaxBytesOverMobile( /* [in] */ IContext* context, /* [out] */ Int64* size) { VALIDATE_NOT_NULL(size); *size = 0; // try { AutoPtr<IContentResolver> resolver; context->GetContentResolver((IContentResolver**)&resolver); AutoPtr<ISettingsGlobal> global; CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&global); return global->GetInt64(resolver, ISettingsGlobal::DOWNLOAD_MAX_BYTES_OVER_MOBILE, size); // } catch (SettingNotFoundException exc) { // return null; // } } ECode CDownloadManager::GetRecommendedMaxBytesOverMobile( /* [in] */ IContext* context, /* [out] */ Int64* size) { VALIDATE_NOT_NULL(size); *size = 0; // try { AutoPtr<IContentResolver> resolver; context->GetContentResolver((IContentResolver**)&resolver); AutoPtr<ISettingsGlobal> global; CSettingsGlobal::AcquireSingleton((ISettingsGlobal**)&global); return global->GetInt64(resolver, ISettingsGlobal::DOWNLOAD_RECOMMENDED_MAX_BYTES_OVER_MOBILE, size); // } catch (SettingNotFoundException exc) { // return null; // } } ECode CDownloadManager::IsActiveNetworkExpensive( /* [in] */ IContext* context, /* [out] */ Boolean* actived) { VALIDATE_NOT_NULL(actived); // TODO: connect to NetworkPolicyManager *actived = FALSE; return NOERROR; } ECode CDownloadManager::GetActiveNetworkWarningBytes( /* [in] */ IContext* context, /* [out] */ Int64* bytes) { VALIDATE_NOT_NULL(bytes); // TODO: connect to NetworkPolicyManager *bytes = -1; return NOERROR; } ECode CDownloadManager::AddCompletedDownload( /* [in] */ const String& title, /* [in] */ const String& description, /* [in] */ Boolean isMediaScannerScannable, /* [in] */ const String& mimeType, /* [in] */ const String& path, /* [in] */ Int64 length, /* [in] */ Boolean showNotification, /* [out] */ Int64* id) { return AddCompletedDownload(title, description, isMediaScannerScannable, mimeType, path, length, showNotification, FALSE, id); } ECode CDownloadManager::AddCompletedDownload( /* [in] */ const String& title, /* [in] */ const String& description, /* [in] */ Boolean isMediaScannerScannable, /* [in] */ const String& mimeType, /* [in] */ const String& path, /* [in] */ Int64 length, /* [in] */ Boolean showNotification, /* [in] */ Boolean allowWrite, /* [out] */ Int64* id) { VALIDATE_NOT_NULL(id); *id = 0; // make sure the input args are non-null/non-zero ValidateArgumentIsNonEmpty(String("title"), title); ValidateArgumentIsNonEmpty(String("description"), description); ValidateArgumentIsNonEmpty(String("path"), path); ValidateArgumentIsNonEmpty(String("mimeType"), mimeType); if (length < 0) { // throw new IllegalArgumentException(" invalid value for param: totalBytes"); Logger::E("CDownloadManager", " invalid value for param: totalBytes"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } // if there is already an entry with the given path name in downloads.db, return its id AutoPtr<IDownloadManagerRequest> request; CDownloadManagerRequest::New(NON_DOWNLOADMANAGER_DOWNLOAD, (IDownloadManagerRequest**)&request); AutoPtr<ICharSequence> cs; CString::New(title, (ICharSequence**)&cs); request->SetTitle(cs); cs = NULL; CString::New(description, (ICharSequence**)&cs); request->SetDescription(cs); request->SetMimeType(mimeType); AutoPtr<IContentValues> values = ((CDownloadManagerRequest*)request.Get())->ToContentValues(String(NULL)); AutoPtr<IInteger32> value; CInteger32::New(IDownloadsImpl::DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD, (IInteger32**)&value); values->Put(IDownloadsImpl::COLUMN_DESTINATION, value); cs = NULL; CString::New(path, (ICharSequence**)&cs); values->Put(IDownloadsImpl::_DATA, cs); value = NULL; CInteger32::New(IDownloadsImpl::STATUS_SUCCESS, (IInteger32**)&value); values->Put(IDownloadsImpl::COLUMN_STATUS, value); value = NULL; CInteger32::New(length, (IInteger32**)&value); values->Put(IDownloadsImpl::COLUMN_TOTAL_BYTES, value); AutoPtr<IInteger32> yes, no; CInteger32::New(CDownloadManagerRequest::SCANNABLE_VALUE_YES, (IInteger32**)&yes); CInteger32::New(CDownloadManagerRequest::SCANNABLE_VALUE_NO, (IInteger32**)&no); values->Put(IDownloadsImpl::COLUMN_MEDIA_SCANNED, (isMediaScannerScannable) ? yes : no); AutoPtr<IInteger32> completion, hidden; CInteger32::New(IDownloadManagerRequest::VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION, (IInteger32**)&completion); CInteger32::New(IDownloadManagerRequest::VISIBILITY_HIDDEN, (IInteger32**)&hidden); values->Put(IDownloadsImpl::COLUMN_VISIBILITY, (showNotification) ? completion : hidden); values->Put(IDownloadsImpl::COLUMN_ALLOW_WRITE, allowWrite ? 1 : 0); AutoPtr<IDownloadsImpl> impl; CDownloadsImpl::AcquireSingleton((IDownloadsImpl**)&impl); AutoPtr<IUri> contentUri; impl->GetCONTENT_URI((IUri**)&contentUri); AutoPtr<IUri> downloadUri; mResolver->Insert(contentUri, values, (IUri**)&downloadUri); if (downloadUri == NULL) { *id = -1; return NOERROR; } String segment; downloadUri->GetLastPathSegment(&segment); *id = StringUtils::ParseInt64(segment); return NOERROR; } ECode CDownloadManager::ValidateArgumentIsNonEmpty( /* [in] */ const String& paramName, /* [in] */ const String& val) { if (TextUtils::IsEmpty(val)) { // throw new IllegalArgumentException(paramName + " can't be null"); Logger::E("CDownloadManager", "%s can't be null", paramName.string()); return E_ILLEGAL_ARGUMENT_EXCEPTION; } return NOERROR; } AutoPtr<IUri> CDownloadManager::GetDownloadUri( /* [in] */ Int64 id) { AutoPtr<IContentUris> cUris; CContentUris::AcquireSingleton((IContentUris**)&cUris); AutoPtr<IUri> uri; cUris->WithAppendedId(mBaseUri, id, (IUri**)&uri); return uri; } ECode CDownloadManager::GetDownloadUri( /* [in] */ Int64 id, /* [out] */ IUri** result) { VALIDATE_NOT_NULL(result) AutoPtr<IUri> uri = GetDownloadUri(id); *result = uri; REFCOUNT_ADD(*result) return NOERROR; } /** * Get a parameterized SQL WHERE clause to select a bunch of IDs. */ String CDownloadManager::GetWhereClauseForIds( /* [in] */ ArrayOf<Int64>* ids) { StringBuilder whereClause; whereClause += "("; for (Int32 i = 0; i < ids->GetLength(); i++) { if (i > 0) { whereClause += "OR "; } whereClause += IBaseColumns::ID; whereClause += " = ? "; } whereClause += ")"; return whereClause.ToString(); } /** * Get the selection args for a clause returned by {@link #getWhereClauseForIds(long[])}. */ AutoPtr< ArrayOf<String> > CDownloadManager::GetWhereArgsForIds( /* [in] */ ArrayOf<Int64>* ids) { Int32 length = ids->GetLength(); AutoPtr<ArrayOf<String> > whereArgs = ArrayOf<String>::Alloc(length); for (Int32 i = 0; i < length; i++) { whereArgs->Set(i, StringUtils::ToString((*ids)[i])); } return whereArgs; } } // namespace App } // namespace Droid } // namespace Elastos
34.332147
123
0.651199
[ "object" ]
e3a94c776e57180785fd30abd4d16e94a3750769
5,217
cpp
C++
CENTRAL 3D/Source/ImporterScene.cpp
AitorSimona/3DEngines
01700230b4733e6976fb14971dcc835374f8db12
[ "MIT" ]
2
2020-01-20T12:28:42.000Z
2020-05-10T23:06:58.000Z
CENTRAL 3D/Source/ImporterScene.cpp
AitorSimona/3DEngines
01700230b4733e6976fb14971dcc835374f8db12
[ "MIT" ]
3
2020-01-20T13:15:28.000Z
2020-04-07T10:53:53.000Z
CENTRAL 3D/Source/ImporterScene.cpp
AitorSimona/3DEngines
01700230b4733e6976fb14971dcc835374f8db12
[ "MIT" ]
4
2019-10-22T20:56:48.000Z
2021-01-10T14:24:43.000Z
#include "ImporterScene.h" #include "Application.h" #include "ModuleResourceManager.h" #include "ModuleFileSystem.h" #include "ModuleSceneManager.h" #include "ResourceScene.h" #include "GameObject.h" #include "ImporterMeta.h" #include "ResourceMeta.h" #include "mmgr/mmgr.h" ImporterScene::ImporterScene() : Importer(Importer::ImporterType::Scene) { } ImporterScene::~ImporterScene() { } // MYTODO: Give some use to return type (bool) in all functions (if load fails log...) Resource* ImporterScene::Import(ImportData& IData) const { // --- Meta was deleted, just trigger a load with a new uid --- Resource* scene = Load(IData.path); return scene; } Resource* ImporterScene::Load(const char* path) const { ResourceScene* scene = nullptr; // --- Load Scene file --- if (path) { ImporterMeta* IMeta = App->resources->GetImporter<ImporterMeta>(); ResourceMeta* meta = (ResourceMeta*)IMeta->Load(path); if (meta) { scene = App->resources->scenes.find(meta->GetUID()) != App->resources->scenes.end() ? App->resources->scenes.find(meta->GetUID())->second : (ResourceScene*)App->resources->CreateResourceGivenUID(Resource::ResourceType::SCENE, meta->GetOriginalFile(), meta->GetUID()); } else { scene = (ResourceScene*)App->resources->CreateResource(Resource::ResourceType::SCENE, path); } } return scene; } void ImporterScene::SaveSceneToFile(ResourceScene* scene) const { // --- Save Scene/Model to file --- json file; for (std::unordered_map<uint, GameObject*>::iterator it = scene->NoStaticGameObjects.begin(); it != scene->NoStaticGameObjects.end(); ++it) { std::string string_uid = std::to_string((*it).second->GetUID()); // --- Create GO Structure --- file[string_uid]; file[string_uid]["Name"] = (*it).second->GetName(); file[string_uid]["Active"] = (*it).second->GetActive(); file[string_uid]["Static"] = (*it).second->Static; file[string_uid]["Index"] = (*it).second->index; file[string_uid]["PrefabChild"] = (*it).second->is_prefab_child; file[string_uid]["PrefabInstance"] = (*it).second->is_prefab_instance; if ((*it).second->parent != App->scene_manager->GetRootGO()) file[string_uid]["Parent"] = std::to_string((*it).second->parent->GetUID()); else file[string_uid]["Parent"] = "-1"; file[string_uid]["Components"]; std::vector<Component*> go_components = (*it).second->GetComponents(); for (uint i = 0; i < go_components.size(); ++i) { // --- Save Components to file --- file[string_uid]["Components"][std::to_string(go_components[i]->GetUID())] = go_components[i]->Save(); file[string_uid]["Components"][std::to_string(go_components[i]->GetUID())]["Index"] = i; file[string_uid]["Components"][std::to_string(go_components[i]->GetUID())]["Type"] = (uint)go_components[i]->GetType(); file[string_uid]["Components"][std::to_string(go_components[i]->GetUID())]["Active"] = go_components[i]->GetActive(); } } for (std::unordered_map<uint, GameObject*>::iterator it = scene->StaticGameObjects.begin(); it != scene->StaticGameObjects.end(); ++it) { std::string string_uid = std::to_string((*it).second->GetUID()); // --- Create GO Structure --- file[string_uid]; file[string_uid]["Name"] = (*it).second->GetName(); file[string_uid]["Active"] = (*it).second->GetActive(); file[string_uid]["Static"] = (*it).second->Static; file[string_uid]["Parent"] = std::to_string((*it).second->parent->GetUID()); file[string_uid]["Index"] = (*it).second->index; file[string_uid]["PrefabChild"] = (*it).second->is_prefab_child; file[string_uid]["PrefabInstance"] = (*it).second->is_prefab_instance; if ((*it).second->parent != App->scene_manager->GetRootGO()) file[string_uid]["Parent"] = std::to_string((*it).second->parent->GetUID()); else file[string_uid]["Parent"] = "-1"; file[string_uid]["Components"]; std::vector<Component*> go_components = (*it).second->GetComponents(); for (uint i = 0; i < go_components.size(); ++i) { // --- Save Components to file --- file[string_uid]["Components"][std::to_string(go_components[i]->GetUID())] = go_components[i]->Save(); file[string_uid]["Components"][std::to_string(go_components[i]->GetUID())]["Index"] = i; file[string_uid]["Components"][std::to_string(go_components[i]->GetUID())]["Type"] = (uint)go_components[i]->GetType(); file[string_uid]["Components"][std::to_string(go_components[i]->GetUID())]["Active"] = go_components[i]->GetActive(); } } // --- Serialize JSON to string --- std::string data; App->GetJLoader()->Serialize(file, data); // --- Finally Save to file --- char* buffer = (char*)data.data(); uint size = data.length(); App->fs->Save(scene->GetResourceFile(), buffer, size); scene->SetOriginalFile(scene->GetResourceFile()); // --- Create meta --- ImporterMeta* IMeta = App->resources->GetImporter<ImporterMeta>(); ResourceMeta* meta = (ResourceMeta*)App->resources->CreateResourceGivenUID(Resource::ResourceType::META, scene->GetResourceFile(), scene->GetUID()); if (meta) { meta->Date = App->fs->GetLastModificationTime(scene->GetOriginalFile()); IMeta->Save(meta); } else CONSOLE_LOG("|[error]: Could not load meta from: %s", scene->GetResourceFile()); }
34.098039
270
0.677017
[ "vector", "model" ]
e3ae12c71fd7dc4cb9fe545c3b940232eec52e0e
2,144
cpp
C++
Mina.cpp
VictorCastao/NEPS_Academy-Resolvidos
71800aaf24770fde368e62b223bdf2b8099817eb
[ "MIT" ]
null
null
null
Mina.cpp
VictorCastao/NEPS_Academy-Resolvidos
71800aaf24770fde368e62b223bdf2b8099817eb
[ "MIT" ]
null
null
null
Mina.cpp
VictorCastao/NEPS_Academy-Resolvidos
71800aaf24770fde368e62b223bdf2b8099817eb
[ "MIT" ]
null
null
null
#include <iostream> #include <bitset> #include <queue> #include <cstdio> using namespace std; struct ponto{ int peso, x, y; }; struct Comp{ bool operator()(const ponto& a, const ponto& b){ return a.peso>b.peso; } }; int main(){ int ordem, resp; scanf("%d", &ordem); int M[ordem][ordem]; for(int i=0; i<ordem; i++){ for(int j=0; j<ordem; j++){ scanf("%d", &M[i][j]); } } bitset <100> visitado [100]; for(int i=0; i<100; i++){ for(int j=0; j<100; j++){ visitado[i][j] = 0; } } int matriz[ordem][ordem]; for(int i=0; i<ordem; i++){ for(int j=0; j<ordem; j++){ matriz[i][j] = 1000000; } } matriz[0][0] = 0; ponto temp; temp.peso = 0; temp.x = 0; temp.y = 0; priority_queue<ponto, vector<ponto>, Comp> fila; fila.push(temp); while(true){ int f = -1; while(!fila.empty()){ temp = fila.top(); fila.pop(); if(visitado[temp.x][temp.y]==0){ f = 1; break; } } if(f==-1) break; ponto temp2; visitado[temp.x][temp.y] = 1; if(temp.x>0 and temp.peso + M[temp.x-1][temp.y] < matriz[temp.x-1][temp.y]){ matriz[temp.x-1][temp.y] = temp.peso + M[temp.x-1][temp.y]; temp2.peso = matriz[temp.x-1][temp.y]; temp2.x = temp.x-1; temp2.y = temp.y; fila.push(temp2); } //x<ordem-1 if(temp.x<ordem-1 and temp.peso + M[temp.x+1][temp.y] < matriz[temp.x+1][temp.y]){ matriz[temp.x+1][temp.y] = temp.peso + M[temp.x+1][temp.y]; temp2.peso = matriz[temp.x+1][temp.y]; temp2.x = temp.x+1; temp2.y = temp.y; fila.push(temp2); } //y>0 if(temp.y>0 and temp.peso + M[temp.x][temp.y-1] < matriz[temp.x][temp.y-1]){ matriz[temp.x][temp.y-1] = temp.peso + M[temp.x][temp.y-1]; temp2.peso = matriz[temp.x][temp.y-1]; temp2.x = temp.x; temp2.y = temp.y-1; fila.push(temp2); } //y<ordem-1 if(temp.y<ordem-1 and temp.peso + M[temp.x][temp.y+1] < matriz[temp.x][temp.y+1]){ matriz[temp.x][temp.y+1] = temp.peso + M[temp.x][temp.y+1]; temp2.peso = matriz[temp.x][temp.y+1]; temp2.x = temp.x; temp2.y = temp.y+1; fila.push(temp2); } } resp = matriz[ordem-1][ordem-1]; printf("%d\n", resp); return 0; }
20.815534
84
0.564366
[ "vector" ]
e3ae9d1add5de6c1ae9ba03da6fa48752e2462a9
21,625
cpp
C++
inetsrv/iis/svcs/staxcore/dnslib/mxdns.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/svcs/staxcore/dnslib/mxdns.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/svcs/staxcore/dnslib/mxdns.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "dnsincs.h" #include <stdlib.h> extern void DeleteDnsRec(PSMTPDNS_RECS pDnsRec); CAsyncMxDns::CAsyncMxDns(char *MyFQDN) { lstrcpyn(m_FQDNToDrop, MyFQDN, sizeof(m_FQDNToDrop)); m_fUsingMx = TRUE; m_Index = 0; m_LocalPref = 256; m_SeenLocal = FALSE; m_AuxList = NULL; m_fMxLoopBack = FALSE; ZeroMemory (m_Weight, sizeof(m_Weight)); ZeroMemory (m_Prefer, sizeof(m_Prefer)); } //----------------------------------------------------------------------------- // Description: // Given a pDnsRec (array of host IP pairs) and an index into it, this // tries to resolve the host at the Index position. It is assumed that // the caller (GetMissingIpAddresses) has checked that the host at that // index lacks an IP address. // Arguments: // IN PSMTPDNS_RECS pDnsRec --- Array of (host, IP) pairs. // IN DWORD Index --- Index of host in pDnsRec to set IP for. // Returns: // TRUE --- Success IP was filled in for host. // FALSE --- Either the host was not resolved from DNS or an error // occurred (like "out of memory"). //----------------------------------------------------------------------------- BOOL CAsyncMxDns::GetIpFromDns(PSMTPDNS_RECS pDnsRec, DWORD Index) { MXIPLIST_ENTRY * pEntry = NULL; BOOL fReturn = FALSE; DWORD dwStatus = ERROR_SUCCESS; DWORD rgdwIpAddresses[SMTP_MAX_DNS_ENTRIES]; DWORD cIpAddresses = SMTP_MAX_DNS_ENTRIES; PIP_ARRAY pipDnsList = NULL; TraceFunctEnterEx((LPARAM) this, "CAsyncMxDns::GetIpFromDns"); fReturn = GetDnsIpArrayCopy(&pipDnsList); if(!fReturn) { ErrorTrace((LPARAM) this, "Unable to get DNS server list copy"); TraceFunctLeaveEx((LPARAM) this); return FALSE; } dwStatus = ResolveHost( pDnsRec->DnsArray[Index]->DnsName, pipDnsList, DNS_QUERY_STANDARD, rgdwIpAddresses, &cIpAddresses); if(dwStatus == ERROR_SUCCESS) { fReturn = TRUE; for (DWORD Loop = 0; !IsShuttingDown() && Loop < cIpAddresses; Loop++) { pEntry = new MXIPLIST_ENTRY; if(pEntry != NULL) { pDnsRec->DnsArray[Index]->NumEntries++; CopyMemory(&pEntry->IpAddress, &rgdwIpAddresses[Loop], 4); InsertTailList(&pDnsRec->DnsArray[Index]->IpListHead, &pEntry->ListEntry); } else { fReturn = FALSE; ErrorTrace((LPARAM) this, "Not enough memory"); SetLastError(ERROR_NOT_ENOUGH_MEMORY); break; } } } else { ErrorTrace((LPARAM) this, "gethostbyname failed on %s", pDnsRec->DnsArray[Index]->DnsName); SetLastError(ERROR_NO_MORE_ITEMS); } ReleaseDnsIpArray(pipDnsList); TraceFunctLeaveEx((LPARAM) this); return fReturn; } //----------------------------------------------------------------------------- // Description: // This runs through the list of hosts (MX hosts, or if no MX records were // returned, the single target host) and verifies that they all have been // resolved to IP addresses. If any have been found that do not have IP // addresses, it will call GetIpFromDns to resolve it. // Arguments: // IN PSMTPDNS_RECS pDnsRec -- Object containing Host-IP pairs. Hosts // without and IP are filled in. // Returns: // TRUE -- Success, all hosts have IP addresses. // FALSE -- Unable to resolve all hosts to IP addresses, or some internal // error occurred (like "out of memory" or "shutdown in progress". //----------------------------------------------------------------------------- BOOL CAsyncMxDns::GetMissingIpAddresses(PSMTPDNS_RECS pDnsRec) { DWORD Count = 0; DWORD Error = 0; BOOL fSucceededOnce = FALSE; if(pDnsRec == NULL) { return FALSE; } while(!IsShuttingDown() && pDnsRec->DnsArray[Count] != NULL) { if(IsListEmpty(&pDnsRec->DnsArray[Count]->IpListHead)) { SetLastError(NO_ERROR); if(!GetIpFromDns(pDnsRec, Count)) { Error = GetLastError(); if(Error != ERROR_NO_MORE_ITEMS) { return FALSE; } } else { fSucceededOnce = TRUE; } } else { fSucceededOnce = TRUE; } Count++; } return ( fSucceededOnce ); } int MxRand(char * host) { int hfunc = 0; unsigned int seed = 0;; seed = rand() & 0xffff; hfunc = seed; while (*host != '\0') { int c = *host++; if (isascii((UCHAR)c) && isupper((UCHAR)c)) c = tolower(c); hfunc = ((hfunc << 1) ^ c) % 2003; } hfunc &= 0xff; return hfunc; } BOOL CAsyncMxDns::CheckList(void) { MXIPLIST_ENTRY * pEntry = NULL; BOOL fRet = TRUE; DWORD dwStatus = ERROR_SUCCESS; DWORD rgdwIpAddresses[SMTP_MAX_DNS_ENTRIES]; DWORD cIpAddresses = SMTP_MAX_DNS_ENTRIES; PIP_ARRAY pipDnsList = NULL; TraceFunctEnterEx((LPARAM) this, "CAsyncDns::CheckList"); if(m_Index == 0) { DebugTrace((LPARAM) this, "m_Index == 0 in CheckList"); m_fUsingMx = FALSE; DeleteDnsRec(m_AuxList); m_AuxList = new SMTPDNS_RECS; if(m_AuxList == NULL) { ErrorTrace((LPARAM) this, "m_AuxList = new SMTPDNS_RECS failed"); TraceFunctLeaveEx((LPARAM)this); return FALSE; } ZeroMemory(m_AuxList, sizeof(SMTPDNS_RECS)); m_AuxList->NumRecords = 1; m_AuxList->DnsArray[0] = new MX_NAMES; if(m_AuxList->DnsArray[0] == NULL) { ErrorTrace((LPARAM) this, "m_AuxList->DnsArray[0] = new MX_NAMES failed"); TraceFunctLeaveEx((LPARAM)this); return FALSE; } m_AuxList->DnsArray[0]->NumEntries = 0; InitializeListHead(&m_AuxList->DnsArray[0]->IpListHead); lstrcpyn(m_AuxList->DnsArray[0]->DnsName, m_HostName, sizeof(m_AuxList->DnsArray[m_Index]->DnsName)); fRet = GetDnsIpArrayCopy(&pipDnsList); if(!fRet) { ErrorTrace((LPARAM) this, "Unable to get DNS server list copy"); TraceFunctLeaveEx((LPARAM) this); return FALSE; } dwStatus = ResolveHost( m_HostName, pipDnsList, DNS_QUERY_STANDARD, rgdwIpAddresses, &cIpAddresses); if(dwStatus == ERROR_SUCCESS && cIpAddresses) { for (DWORD Loop = 0; Loop < cIpAddresses; Loop++) { pEntry = new MXIPLIST_ENTRY; if(pEntry != NULL) { m_AuxList->DnsArray[0]->NumEntries++; CopyMemory(&pEntry->IpAddress, &rgdwIpAddresses[Loop], 4); InsertTailList(&m_AuxList->DnsArray[0]->IpListHead, &pEntry->ListEntry); } else { fRet = FALSE; ErrorTrace((LPARAM) this, "pEntry = new MXIPLIST_ENTRY failed in CheckList"); break; } } } else { fRet = FALSE; } ReleaseDnsIpArray(pipDnsList); } TraceFunctLeaveEx((LPARAM)this); return fRet; } BOOL CAsyncMxDns::SortMxList(void) { BOOL fRet = TRUE; /* sort the records */ for (DWORD i = 0; i < m_Index; i++) { for (DWORD j = i + 1; j < m_Index; j++) { if (m_Prefer[i] > m_Prefer[j] || (m_Prefer[i] == m_Prefer[j] && m_Weight[i] > m_Weight[j])) { DWORD temp; MX_NAMES *temp1; temp = m_Prefer[i]; m_Prefer[i] = m_Prefer[j]; m_Prefer[j] = temp; temp1 = m_AuxList->DnsArray[i]; m_AuxList->DnsArray[i] = m_AuxList->DnsArray[j]; m_AuxList->DnsArray[j] = temp1; temp = m_Weight[i]; m_Weight[i] = m_Weight[j]; m_Weight[j] = temp; } } if (m_SeenLocal && m_Prefer[i] >= m_LocalPref) { /* truncate higher preference part of list */ m_Index = i; } } m_AuxList->NumRecords = m_Index; if(!CheckList()) { DeleteDnsRec(m_AuxList); m_AuxList = NULL; fRet = FALSE; } return fRet; } void CAsyncMxDns::ProcessMxRecord(PDNS_RECORD pnewRR) { DWORD Len = 0; TraceFunctEnterEx((LPARAM) this, "CAsyncDns::ProcessMxRecord"); // // Leave room for NULL-termination of array // if(m_Index >= SMTP_MAX_DNS_ENTRIES-1) { DebugTrace((LPARAM) this, "SMTP_MAX_DNS_ENTRIES reached for %s", m_HostName); TraceFunctLeaveEx((LPARAM)this); return; } if((pnewRR->wType == DNS_TYPE_MX) && pnewRR->Data.MX.nameExchange) { Len = lstrlen(pnewRR->Data.MX.nameExchange); if(pnewRR->Data.MX.nameExchange[Len - 1] == '.') { pnewRR->Data.MX.nameExchange[Len - 1] = '\0'; } DebugTrace((LPARAM) this, "Received MX rec %s with priority %d for %s", pnewRR->Data.MX.nameExchange, pnewRR->Data.MX.wPreference, m_HostName); if(lstrcmpi(pnewRR->Data.MX.nameExchange, m_FQDNToDrop)) { m_AuxList->DnsArray[m_Index] = new MX_NAMES; if(m_AuxList->DnsArray[m_Index]) { m_AuxList->DnsArray[m_Index]->NumEntries = 0;; InitializeListHead(&m_AuxList->DnsArray[m_Index]->IpListHead); lstrcpyn(m_AuxList->DnsArray[m_Index]->DnsName,pnewRR->Data.MX.nameExchange, sizeof(m_AuxList->DnsArray[m_Index]->DnsName)); m_Weight[m_Index] = MxRand (m_AuxList->DnsArray[m_Index]->DnsName); m_Prefer[m_Index] = pnewRR->Data.MX.wPreference; m_Index++; } else { DebugTrace((LPARAM) this, "Out of memory allocating MX_NAMES for %s", m_HostName); } } else { if (!m_SeenLocal || pnewRR->Data.MX.wPreference < m_LocalPref) m_LocalPref = pnewRR->Data.MX.wPreference; m_SeenLocal = TRUE; } } else if(pnewRR->wType == DNS_TYPE_A) { MXIPLIST_ENTRY * pEntry = NULL; for(DWORD i = 0; i < m_Index; i++) { if(lstrcmpi(pnewRR->nameOwner, m_AuxList->DnsArray[i]->DnsName) == 0) { pEntry = new MXIPLIST_ENTRY; if(pEntry != NULL) { m_AuxList->DnsArray[i]->NumEntries++;; pEntry->IpAddress = pnewRR->Data.A.ipAddress; InsertTailList(&m_AuxList->DnsArray[i]->IpListHead, &pEntry->ListEntry); } break; } } } TraceFunctLeaveEx((LPARAM)this); } void CAsyncMxDns::ProcessARecord(PDNS_RECORD pnewRR) { MXIPLIST_ENTRY * pEntry = NULL; if(pnewRR->wType == DNS_TYPE_A) { pEntry = new MXIPLIST_ENTRY; if(pEntry != NULL) { pEntry->IpAddress = pnewRR->Data.A.ipAddress; InsertTailList(&m_AuxList->DnsArray[0]->IpListHead, &pEntry->ListEntry); } } } //----------------------------------------------------------------------------- // Description: // Checks to see if any of the IP addresses returned by DNS belong to this // machine. This is a common configuration when there are backup mail // spoolers. To avoid mail looping, we should delete all MX records that // are less preferred than the record containing the local IP address. // // Arguments: // None. // Returns: // TRUE if no loopback // FALSE if loopback detected //----------------------------------------------------------------------------- BOOL CAsyncMxDns::CheckMxLoopback() { ULONG i = 0; ULONG cLocalIndex = 0; BOOL fSeenLocal = TRUE; DWORD dwIpAddress = INADDR_NONE; DWORD dwLocalPref = 256; PLIST_ENTRY pListHead = NULL; PLIST_ENTRY pListTail = NULL; PLIST_ENTRY pListCurrent = NULL; PMXIPLIST_ENTRY pMxIpListEntry = NULL; TraceFunctEnterEx((LPARAM)this, "CAsyncMxDns::CheckMxLoopback"); if(!m_AuxList) { TraceFunctLeaveEx((LPARAM)this); return TRUE; } // // m_AuxList is a sorted list of MX records. Scan through it searching // for an MX record with a local-IP address. cLocalIndex is set to the // index, within m_AuxList, of this record. // while(m_AuxList->DnsArray[cLocalIndex] != NULL) { pListTail = &(m_AuxList->DnsArray[cLocalIndex]->IpListHead); pListHead = m_AuxList->DnsArray[cLocalIndex]->IpListHead.Flink; pListCurrent = pListHead; while(pListCurrent != pListTail) { pMxIpListEntry = CONTAINING_RECORD(pListCurrent, MXIPLIST_ENTRY, ListEntry); dwIpAddress = pMxIpListEntry->IpAddress; if(IsAddressMine(dwIpAddress)) { DNS_PRINTF_MSG("Local host's IP is one of the target IPs.\n"); DNS_PRINTF_MSG("Discarding all equally or less-preferred IP addresses.\n"); DebugTrace((LPARAM)this, "Local record found in MX list, name=%s, pref=%d, ip=%08x", m_AuxList->DnsArray[cLocalIndex]->DnsName, m_Prefer[cLocalIndex], dwIpAddress); // All records with preference > m_Prefer[cLocalIndex] should be deleted. Since // m_AuxList is sorted by preference, we need to delete everthing with index > // cLocalIndex. However since there may be some records with preference == local- // preference, which occur before cLocalIndex, we walk backwards till we find // the first record with preference = m_Prefer[cLocalIndex]. dwLocalPref = m_Prefer[cLocalIndex]; while(cLocalIndex > 0 && dwLocalPref == m_Prefer[cLocalIndex]) cLocalIndex--; if(dwLocalPref != m_Prefer[cLocalIndex]) cLocalIndex++; fSeenLocal = TRUE; // All records > cLocalIndex are even less preferred than this one, // (since m_AuxList already sorted) and will be deleted. goto END_SEARCH; } pListCurrent = pListCurrent->Flink; } cLocalIndex++; } END_SEARCH: // // If a local-IP address was found, delete all less-preferred records // if(fSeenLocal) { DebugTrace((LPARAM)this, "Deleting all MX records with lower preference than %d", m_Prefer[cLocalIndex]); for(i = cLocalIndex; m_AuxList->DnsArray[i] != NULL; i++) { if(!m_AuxList->DnsArray[i]->DnsName[0]) continue; while(!IsListEmpty(&(m_AuxList->DnsArray[i]->IpListHead))) { pListCurrent = RemoveHeadList(&(m_AuxList->DnsArray[i]->IpListHead)); pMxIpListEntry = CONTAINING_RECORD(pListCurrent, MXIPLIST_ENTRY, ListEntry); delete pMxIpListEntry; } delete m_AuxList->DnsArray[i]; m_AuxList->DnsArray[i] = NULL; } m_AuxList->NumRecords = cLocalIndex; // No records left if(m_AuxList->NumRecords == 0) { DNS_PRINTF_ERR("DNS configuration error (loopback), messages will be NDRed.\n"); DNS_PRINTF_ERR("Local host's IP address is the most preferred MX record.\n"); ErrorTrace((LPARAM)this, "Possible misconfiguration: most preferred MX record is loopback"); _ASSERT(m_AuxList->pMailMsgObj == NULL); delete m_AuxList; m_AuxList = NULL; return FALSE; } } TraceFunctLeaveEx((LPARAM)this); return TRUE; } void CAsyncMxDns::DnsProcessReply( DWORD status, PDNS_RECORD pRecordList) { TraceFunctEnterEx((LPARAM) this, "CAsyncDns::DnsParseMessage"); PDNS_RECORD pTmp = NULL; m_SeenLocal = FALSE; m_LocalPref = 256; m_AuxList = new SMTPDNS_RECS; if(!m_AuxList) { return; } ZeroMemory(m_AuxList, sizeof(SMTPDNS_RECS)); // // Due to Raid #122555 m_fUsingMx is always TRUE in this function // - hence we will always go a GetHostByName() if there is no MX // record. It would be better Perf if we did a A record lookup. // DebugTrace((LPARAM) this, "Parsed DNS record for %s. status = 0x%08x", m_HostName, status); switch(status) { case ERROR_SUCCESS: // // Got the DNS record we want. // DNS_PRINTF_MSG("Processing MX/A records in reply.\n"); DebugTrace((LPARAM) this, "Success: DNS record parsed"); pTmp = pRecordList; while( pTmp ) { if( m_fUsingMx ) { ProcessMxRecord( pTmp ); } else { ProcessARecord( pTmp ); } pTmp = pTmp->pNext; } if(m_fUsingMx) { // // SortMxList sorts the MX records by preference and calls // gethostbyname() to resolve A records for Mail Exchangers // if needed (when the A records are not returned in the // supplementary info). // DNS_PRINTF_MSG("Sorting MX records by priority.\n"); if(SortMxList()) { status = ERROR_SUCCESS; DebugTrace((LPARAM) this, "SortMxList() succeeded."); } else { status = ERROR_RETRY; ErrorTrace((LPARAM) this, "SortMxList() failed. Message will stay queued."); } } break; case DNS_ERROR_RCODE_NAME_ERROR: // Fall through to using gethostbyname() case DNS_INFO_NO_RECORDS: // Non authoritative host not found. // Fall through to using gethostbyname() default: DebugTrace((LPARAM) this, "Error in query: status = 0x%08x.", status); // // Use gethostbyname to resolve the hostname: // One issue with our approach is that sometimes we will NDR the message // on non-permanent errors, "like WINS server down", when gethostbyname // fails. However, there's no way around it --- gethostbyname doesn't // report errors in a reliable manner, so it's not possible to distinguish // between permanent and temporary errors. // if (!CheckList ()) { if(status == DNS_ERROR_RCODE_NAME_ERROR) { DNS_PRINTF_ERR("Host does not exist in DNS. Messages will be NDRed.\n"); ErrorTrace((LPARAM) this, "Authoritative error"); status = ERROR_NOT_FOUND; } else { DNS_PRINTF_ERR("Host could not be resolved. Messages will be retried later.\n"); ErrorTrace((LPARAM) this, "Retryable error"); status = ERROR_RETRY; } } else { DebugTrace ((LPARAM) this, "Successfully resolved using gethostbyname"); status = ERROR_SUCCESS; } break; } // // Make a last ditch effort to fill in the IP addresses for any hosts // that are still unresolved. // if(m_AuxList && status == ERROR_SUCCESS) { if(!GetMissingIpAddresses(m_AuxList)) { DeleteDnsRec(m_AuxList); m_AuxList = NULL; status = ERROR_RETRY; goto Exit; } if(!CheckMxLoopback()) { m_fMxLoopBack = TRUE; DeleteDnsRec(m_AuxList); m_AuxList = NULL; TraceFunctLeaveEx((LPARAM) this); return; } } // // End of resolve: HandleCompleted data examines the DnsStatus and results, and sets up // member variables of CAsyncMxDns to either NDR messages, connect to the remote host // or ack this queue for retry when the object is deleted. // Exit: HandleCompletedData(status); return; }
31.708211
152
0.523422
[ "object" ]
e3af70abe87b0980efcd68270829a58225410a86
26,826
cpp
C++
enigma.cpp
blastdoor7/enigma
01937f4d8a23b225aa968960d2fdf1a5f11dc48e
[ "MIT" ]
null
null
null
enigma.cpp
blastdoor7/enigma
01937f4d8a23b225aa968960d2fdf1a5f11dc48e
[ "MIT" ]
null
null
null
enigma.cpp
blastdoor7/enigma
01937f4d8a23b225aa968960d2fdf1a5f11dc48e
[ "MIT" ]
null
null
null
#include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <set> #include <map> #include <vector> #include <algorithm> #include <stdexcept> #include <iostream> #include <sstream> #include <exception> #include <limits> #include <assert.h> #include <time.h> using namespace std; const char* ROTORS[] = { //ABCDEFGHIJKLMNOPQRSTUVWXYZ "EKMFLGDQVZNTOWYHXUSPAIBRCJ<R", //I "AJDKSIRUXBLHWTMCQGZNPYFVOE<F", //II "BDFHJLCPRTXVZNYEIWGAKMUSQO<W", //III "ESOVPZJAYQUIRHXLNFTGKDCMWB<K", //IV "VZBRGITYUPSDNHLXAWMJQOFECK<A", //V "JPGVOUMFYQBENHZRDKASXLICTW<AN", //VI "NZJHGRCXMYSWBOUFAIVLPEKQDT<AN", //VII "FKQHTLXOCBJSPDZRAMEWNIUYGV<AN" //VIII }; const char* ROTORS_FOURTH[] = { "LEYJVCNIXWPBQMDRTAKZGFUHOS", //Beta "FSOKANUERHMBTIYCWLQPZXVGJD" //Gamma }; const char* REFLECTORS[] = { "AY BR CU DH EQ FS GL IP JX KN MO TZ VW", //B "AF BV CP DJ EI GO HY KR LZ MX NW TQ SU", //C "AE BN CK DQ FU GY HW IJ LO MP RX SZ TV", //B Thin "AR BD CO EJ FN GT HK IV LM PW QZ SX UY" //C Thin }; const char LETTERS[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; bool all_unique_uppercase(const string& s) { for(int i=0; i<s.size(); i++) { if(!isupper(static_cast<unsigned char>(s[i]))) return false; } set<char> u(s.begin(), s.end()); return u.size() == s.size(); } int Mod(int a, int m) { int r = a % m; if(r < 0) r += m; return r; } ///** // * Map a letter to a number in 0..25. // * // * @param {char} c // * @param {boolean} permissive - Case insensitive; don't throw errors on other chars. // * @returns {number} // */ int a2i(const char c) { //cout << "entered a2i arg char " << c << " numeric " << (int)c << endl; if (c >= 65 && c <= 90) { return c - 65; } else if(c == 32) return -1; throw invalid_argument("a2i called on non-uppercase ASCII character"); } // ///** // * Map a number in 0..25 to a letter. // * // * @param {number} i // * @returns {char} // */ char i2a(const int i) { //cout << "i2a arg " << i << endl; if (i >= 0 && i < 26) { return (char)(i+65); } throw invalid_argument("i2a called on value outside 0..25"); } // ///** // * A rotor in the Enigma machine. // */ class Rotor { public: /** * Rotor constructor. * * @param {string} wiring - A 26 character string of the wiring order. * @param {string} steps - A 0..26 character string of stepping points. * @param {char} ringSetting - The ring setting. * @param {char} initialPosition - The initial position of the rotor. */ Rotor(string& wiring, string& steps, char ringSetting, char initialPosition) { if (!all_unique_uppercase(wiring)) { throw invalid_argument("Rotor wiring must be 26 unique uppercase letters"); } if (!all_unique_uppercase(steps)) { throw invalid_argument("Rotor steps must be 0-26 unique uppercase letters"); } if ('A' > ringSetting || ringSetting > 'Z') { throw invalid_argument("Rotor ring setting must be exactly one uppercase letter"); } if ('A' > initialPosition || initialPosition > 'Z') { throw invalid_argument("Rotor initial position must be exactly one uppercase letter"); } set<int> uniq; for (unsigned i=0; i<26; i++) { const int a = a2i(LETTERS[i]); const int b = a2i(wiring[i]); this->map_[a] = b; this->revMap_[b] = a; uniq.insert(b); } if (uniq.size() != 26) { throw invalid_argument("Rotor wiring must have each letter exactly once"); } this->rs = a2i(ringSetting); for(unsigned i=0; i<steps.size(); i++) { this->stepSet.insert(Mod((a2i(steps[i]) - rs) , 26)); } if (this->stepSet.size() != steps.size()) { // This isn't strictly fatal, but it's probably a mistake throw invalid_argument("Rotor steps must be unique"); } this->pos = Mod((a2i(initialPosition) - rs), 26); //cout << "Rotor initial pos " << pos << endl; } Rotor(const string& wiring, const string& steps) { this->steps = steps; if (!all_unique_uppercase(wiring)) { throw invalid_argument("Rotor wiring must be 26 unique uppercase letters"); } if (!all_unique_uppercase(steps)) { throw invalid_argument("Rotor steps must be 0-26 unique uppercase letters"); } set<int> uniq; for (unsigned i=0; i<26; i++) { const int a = a2i(LETTERS[i]); const int b = a2i(wiring[i]); this->map_[a] = b; this->revMap_[b] = a; uniq.insert(b); } if (uniq.size() != 26) { throw invalid_argument("Rotor wiring must have each letter exactly once"); } } void ringSetting(char ringSetting) { this->rs = a2i(ringSetting); this->stepSet.clear(); for(unsigned i=0; i<steps.size(); i++) { this->stepSet.insert(Mod((a2i(steps[i]) - rs) , 26)); } if (this->stepSet.size() != steps.size()) { // This isn't strictly fatal, but it's probably a mistake throw invalid_argument("Rotor steps must be unique"); } } void windowSetting(char initialPosition) { this->pos = Mod((a2i(initialPosition) - rs), 26); } /** * Step the rotor forward by one. */ int step() { //cout << "Rotor::step before pos " << pos << endl; this->pos = Mod((this->pos + 1), 26); //cout << "Rotor::step after pos " << pos << endl; return this->pos; } /** * Transform a character through this rotor forwards. * * @param {number} c - The character. * @returns {number} */ int transform(int c) { //cout << " TRANS input letter " << i2a(c) << endl; char perm = this->map_[Mod(c + this->pos, 26)]; //cout << " letter permuted to " << i2a(perm) << endl; //cout << " permuted letter after offset " << i2a(Mod((perm - pos), 26)) << endl; return Mod((perm - this->pos), 26); } /** * Transform a character through this rotor backwards. * * @param {number} c - The character. * @returns {number} */ int revTransform(char c) { //cout << " REVERSE TRANS input letter " << i2a(c) << endl; char perm = this->revMap_[Mod(c + this->pos, 26)]; //cout << " REVERSE letter permuted to " << i2a(perm) << endl; //cout << " REVERSE permuted letter after offset " << i2a(Mod((perm - pos), 26)) << endl; return Mod(perm - this->pos , 26); } Rotor& operator=(const Rotor& o) { this->steps = o.steps; this->pos = o.pos; this->rs = o.rs; this->stepSet = o.stepSet; this->map_ = o.map_; this->revMap_ = o.revMap_; return *this; } //private: string steps; int pos; int rs; set<int> stepSet; map<int, int> map_; map<int, int> revMap_; }; // ///** // * Base class for plugboard and reflector (since these do effectively the same // * thing). // */ class PairMapBase { public: /** * PairMapBase constructor. * * @param {string} pairs - A whitespace separated string of letter pairs to swap. * @param {string} [name='PairMapBase'] - For errors, the name of this object. */ PairMapBase(const string& pairs, const string& name="PairMapBase") { // I've chosen to make whitespace significant here to make a) code and // b) inputs easier to read this->pairs = pairs; if (pairs == "") { return; } //cout << "PairMapBase " << pairs << endl; istringstream iss(pairs); string pair; while(getline(iss, pair, ' ')) { //cout << "parsing pairs " << pair << endl; if(pair.size() != 2 && !all_unique_uppercase(pair)) { throw invalid_argument(name + " must be a whitespace-separated list of uppercase letter pairs"); } const int a = a2i(pair[0]), b = a2i(pair[1]); if (this->map_.count(a)) { throw invalid_argument(name + " connects " + pair[0] + " more than once"); } if (this->map_.count(b)) { throw invalid_argument(name + " connects " + pair[1] + " more than once"); } //cout << "PairMapBase set map " << a << " -> " << b << endl; //cout << "PairMapBase set map " << b << " -> " << a << endl; this->map_[a] = b; this->map_[b] = a; } //cout << "PairMapBase map_ size " << this->map_.size() << endl; } /** * Transform a character through this object. * Returns other characters unchanged. * * @param {number} c - The character. * @returns {number} */ int transform(int c) { if (!this->map_.count(c)) { return c; } return this->map_[c]; } /** * Alias for transform, to allow interchangeable use with rotors. * * @param {number} c - The character. * @returns {number} */ int revTransform(int c) { return this->transform(c); } protected: string pairs; map<int, int> map_; }; ///** // * Reflector. PairMapBase but requires that all characters are accounted for. // * // * Includes a couple of optimisations on that basis. // */ class Reflector : public PairMapBase { public: /** * Reflector constructor. See PairMapBase. * Additional restriction: every character must be accounted for. */ Reflector(const string& pairs) : PairMapBase(pairs, "Reflector") { this->pairs = pairs; if (this->map_.size() != 26) { throw invalid_argument("Reflector must have exactly 13 pairs covering every letter"); } for(map<int, int>::iterator iter = this->map_.begin(); iter != this->map_.end(); iter++) { this->optMap_[iter->first] = this->map_[iter->first]; } this->map_ = this->optMap_; } Reflector() : PairMapBase("","") {} /** * Transform a character through this object. * * @param {number} c - The character. * @returns {number} */ int transform(int c) { return this->map_[c]; } private: map<int, int> optMap_; }; /** * Plugboard. Unmodified PairMapBase. */ class Plugboard : public PairMapBase { public: /** * Plugboard constructor. See PairMapbase. */ Plugboard(const string& pairs) : PairMapBase(pairs, "Plugboard") { } Plugboard() : PairMapBase("","") {} Plugboard& operator=(const Plugboard& o) { this->pairs = o.pairs; this->map_ = o.map_; return *this; } }; // ///** // * Base class for the Enigma machine itself. Holds rotors, a reflector, and a plugboard. // */ class EnigmaBase { public: /** * EnigmaBase constructor. * * @param {Object[]} rotors - List of Rotors. * @param {Object} reflector - A Reflector. * @param {Plugboard} plugboard - A Plugboard. */ EnigmaBase(vector<Rotor>& rotors, const Reflector& reflector, const Plugboard& plugboard) { this->rotors = rotors; Rotor& RIGHT = rotors[0]; Rotor& MIDDLE = rotors[1]; Rotor& LEFT = rotors[2]; this->rotorsRev.push_back(LEFT); this->rotorsRev.push_back(MIDDLE); this->rotorsRev.push_back(RIGHT); this->reflector = reflector; this->plugboard = plugboard; } void conf(vector<Rotor>& rotors, const Reflector& reflector, const Plugboard& plugboard) { this->rotors[0] = rotors[0]; this->rotors[1] = rotors[1]; this->rotors[2] = rotors[2]; this->rotorsRev[0] = rotors[2]; this->rotorsRev[1] = rotors[1]; this->rotorsRev[2] = rotors[0]; //this->reflector = reflector; this->plugboard = plugboard; } /** * Step the rotors forward by one. * * This happens before the output character is generated. * * Note that rotor 4, if it's there, never steps. * * Why is all the logic in EnigmaBase and not a nice neat method on * Rotor that knows when it should advance the next item? * Because the double stepping anomaly is a thing. tl;dr if the left rotor * should step the next time the middle rotor steps, the middle rotor will * immediately step. */ void step() { Rotor& r0 = this->rotors[0]; Rotor& r1 = this->rotors[1]; //cout << "EnigmaBase Rotor 0 pos " << r0.pos << " Rotor 1 pos " << r1.pos << endl; r0.step(); //cout << "EnigmaBase after calling step Rotor 0 pos " << r0.pos << endl; // The second test here is the double-stepping anomaly if (r0.stepSet.count(r0.pos) || r1.stepSet.count(Mod((r1.pos + 1) , 26))) { r1.step(); if (r1.stepSet.count(r1.pos)) { Rotor& r2 = this->rotors[2]; r2.step(); } } } /** * Encrypt (or decrypt) some data. * Takes an arbitrary string and runs the Engima machine on that data from * *its current state*, and outputs the result. Non-alphabetic characters * are returned unchanged. * * @param {string} input - Data to encrypt. * @returns {string} */ void crypt(char* input, char* result, unsigned LEN) { //cout << " crypt input " << input << endl; for(unsigned ii=0; ii<LEN; ii++) { //cout << "input letter " << input[i] << endl; int letter = a2i(input[ii]); if (letter == -1) { result[ii] = input[ii]; continue; } // First, step the rotors forward. //for (unsigned i=0; i<this->rotors.size(); i++) { // cout << "BEFORE STEP rotor " << i << " POS " << rotors[i].pos << endl; //} this->step(); //for (unsigned i=0; i<this->rotors.size(); i++) { //cout << "AFTER STEP rotor " << i << " POS " << rotors[i].pos << endl; //} // Now, run through the plugboard. //cout << " before plugboard transform " << letter << endl; letter = this->plugboard.transform(letter); //cout << " plugboard transform " << letter << endl; // Then through each wheel in sequence, through the reflector, and // backwards through the wheels again. for (unsigned i=0; i<this->rotors.size(); i++) { //cout << "ROTOR vector index " << i << endl; //cout << "ROTOR pos " << rotors[i].pos << endl; //cout << "before rotor trans letter " << i2a(letter) << endl; letter = rotors[i].transform(letter); //cout << "after rotor trans letter " << i2a(letter) << endl; } letter = this->reflector.transform(letter); //cout << "after reflection letter " << i2a(letter) << endl; for (int i=2; i>=0; i--) { //cout << "REVERSE PATH ROTOR vector index " << i << endl; //cout << "REVERSE ROTOR pos " << rotors[i].pos << endl; //cout << "before rotor reverse trans letter " << i2a(letter) << endl; letter = rotors[i].revTransform(letter); //cout << "after rotor reverse trans letter " << i2a(letter) << endl; } // Finally, back through the plugboard. letter = this->plugboard.revTransform(letter); //cout << " i2a 1" << endl; result[ii] = i2a(letter); } } void crypt(const string& input, string& result) { //cout << " crypt input " << input << endl; result = ""; for(unsigned i=0; i<input.size(); i++) { //cout << "input letter " << input[i] << endl; int letter = a2i(input[i]); if (letter == -1) { result += input[i]; continue; } // First, step the rotors forward. //for (unsigned i=0; i<this->rotors.size(); i++) { // cout << "BEFORE STEP rotor " << i << " POS " << rotors[i].pos << endl; //} this->step(); //for (unsigned i=0; i<this->rotors.size(); i++) { //cout << "AFTER STEP rotor " << i << " POS " << rotors[i].pos << endl; //} // Now, run through the plugboard. //cout << " before plugboard transform " << letter << endl; letter = this->plugboard.transform(letter); //cout << " plugboard transform " << letter << endl; // Then through each wheel in sequence, through the reflector, and // backwards through the wheels again. for (unsigned i=0; i<this->rotors.size(); i++) { //cout << "ROTOR vector index " << i << endl; //cout << "ROTOR pos " << rotors[i].pos << endl; //cout << "before rotor trans letter " << i2a(letter) << endl; letter = rotors[i].transform(letter); //cout << "after rotor trans letter " << i2a(letter) << endl; } letter = this->reflector.transform(letter); //cout << "after reflection letter " << i2a(letter) << endl; for (int i=2; i>=0; i--) { //cout << "REVERSE PATH ROTOR vector index " << i << endl; //cout << "REVERSE ROTOR pos " << rotors[i].pos << endl; //cout << "before rotor reverse trans letter " << i2a(letter) << endl; letter = rotors[i].revTransform(letter); //cout << "after rotor reverse trans letter " << i2a(letter) << endl; } // Finally, back through the plugboard. letter = this->plugboard.revTransform(letter); //cout << " i2a 1" << endl; result += i2a(letter); } } protected: vector<Rotor> rotors; vector<Rotor> rotorsRev; Reflector reflector; Plugboard plugboard; }; /** * The Enigma machine itself. Holds 3-4 rotors, a reflector, and a plugboard. */ class EnigmaMachine : public EnigmaBase { public: /** * EnigmaMachine constructor. * * @param {Object[]} rotors - List of Rotors. * @param {Object} reflector - A Reflector. * @param {Plugboard} plugboard - A Plugboard. */ EnigmaMachine(vector<Rotor>& rotors, Reflector& reflector, Plugboard& plugboard) : EnigmaBase(rotors, reflector, plugboard) { if (rotors.size() != 3 && rotors.size() != 4) { throw invalid_argument("Enigma must have 3 or 4 rotors"); } } }; int main(int argc, char** argv) { { cout << "running test 1 ..." << endl; const string rotorSelection = "IV V III"; const string ringSetting = "X R V"; const string messageKey = "M P Y"; const string plugboardCfg = "SY EK NZ OR CG JM QU PV BI LW"; const string reflectorCfg = "B"; const string ciphertext = "UFJZS NKIRA CGTPF UONXD GQMPU QXUGF OWEZS TCBJD" "JLFME AZQRM NZZYI CGSSR YOFQX ADSPU QIMXM MELYR" "XKXYI MDEEW ISKDP RSTFR TCOKB GGQTQ KPKMP NCCGH" "YUVJO TIVMA IVIGK WQKWJ FOYMR VFBVY RKEZF SYCBY" "QQSOQ CIZUU SUTB"; map<string, int> rotorNameMap; rotorNameMap["I"] = 0; rotorNameMap["II"] = 1; rotorNameMap["III"] = 2; rotorNameMap["IV"] = 3; rotorNameMap["V"] = 4; rotorNameMap["VI"] = 5; rotorNameMap["VII"] = 6; rotorNameMap["VIII"] = 7; vector<char> ringSettingVec; istringstream issRingSetting(ringSetting); string rs; while(getline(issRingSetting, rs, ' ')) { ringSettingVec.push_back(rs[0]); } vector<char> messageKeyVec; istringstream issMessageKeyVec(messageKey); string wp; while(getline(issMessageKeyVec, wp, ' ')) { messageKeyVec.push_back(wp[0]); } vector<Rotor> rotorsRev; istringstream iss(rotorSelection); int k=0; string rotorName; while(getline(iss, rotorName, ' ')) { if(rotorNameMap.count(rotorName) == 0) throw invalid_argument("selected rotor name incorrect must be I...VIII"); string rotorCfg = ROTORS[rotorNameMap[rotorName]]; istringstream ss(rotorCfg); string token; string rotorCfgArray[2]; int i=0; while(getline(ss, token, '<')) { rotorCfgArray[i] = token; i++; } string rotorWiring = rotorCfgArray[0]; string rotorSteps = rotorCfgArray[1]; Rotor r = Rotor(rotorWiring, rotorSteps, ringSettingVec[k], messageKeyVec[k]); rotorsRev.push_back(r); k++; } Reflector reflector(REFLECTORS[0]); Plugboard plugboard(plugboardCfg); string input; if(argc == 2) input = string(argv[1]); else input = ciphertext; vector<Rotor> rotors; rotors.push_back(rotorsRev[2]); rotors.push_back(rotorsRev[1]); rotors.push_back(rotorsRev[0]); string result; EnigmaMachine(rotors, reflector, plugboard).crypt(input, result); cout << "test input " << input << endl; cout << "result " << result << endl; string test1_decrypted = "ANOKH XDRIN GENDX MELDE XAUFF INDUN GXZAH LREICHERXM ENSCH LICHE RXUEB ERRES TEXZW OELFX KMXWESTLIC HXSMO LENSK XGROE SSERE XAUSM ASSEX MOGLICHXTA USEND EYWIE XVERF AHREX ICHXW EITER YOBERSTXFE LDPOL IZEI"; assert(result == test1_decrypted); cout << "test 1 success" << endl; } { cout << "running test 2 ..." << endl; const string rotorSelection = "IV II V"; const string ringSetting = "G M Y"; const string messageKey = "D H O"; const string plugboardCfg = "DN GR IS KC QX TM PV HY FW BJ"; const string reflectorCfg = "B"; const string ciphertext = "GXS"; //"NQVLT YQFSE WWGJZ GQHVS EIXIM YKCNW IEBMB ATPPZ TDVCU PKAY"; map<string, int> rotorNameMap; rotorNameMap["I"] = 0; rotorNameMap["II"] = 1; rotorNameMap["III"] = 2; rotorNameMap["IV"] = 3; rotorNameMap["V"] = 4; rotorNameMap["VI"] = 5; rotorNameMap["VII"] = 6; rotorNameMap["VIII"] = 7; vector<char> ringSettingVec; istringstream issRingSetting(ringSetting); string rs; while(getline(issRingSetting, rs, ' ')) { ringSettingVec.push_back(rs[0]); } vector<char> messageKeyVec; istringstream issMessageKeyVec(messageKey); string wp; while(getline(issMessageKeyVec, wp, ' ')) { messageKeyVec.push_back(wp[0]); } vector<Rotor> rotorsRev; istringstream iss(rotorSelection); int k=0; string rotorName; while(getline(iss, rotorName, ' ')) { if(rotorNameMap.count(rotorName) == 0) throw invalid_argument("selected rotor name incorrect must be I...VIII"); string rotorCfg = ROTORS[rotorNameMap[rotorName]]; istringstream ss(rotorCfg); string token; string rotorCfgArray[2]; int i=0; while(getline(ss, token, '<')) { rotorCfgArray[i] = token; i++; } string rotorWiring = rotorCfgArray[0]; string rotorSteps = rotorCfgArray[1]; Rotor r = Rotor(rotorWiring, rotorSteps, ringSettingVec[k], messageKeyVec[k]); rotorsRev.push_back(r); k++; } Reflector reflector(REFLECTORS[0]); Plugboard plugboard(plugboardCfg); string input; if(argc == 2) input = string(argv[1]); else input = ciphertext; vector<Rotor> rotors; rotors.push_back(rotorsRev[2]); rotors.push_back(rotorsRev[1]); rotors.push_back(rotorsRev[0]); string result; EnigmaMachine(rotors, reflector, plugboard).crypt(input, result); cout << "test input " << input << endl; cout << "result " << result << endl; assert(result == "RLP"); cout << "test 2 success" << endl; } { cout << "running test 3 ..." << endl; const string rotorSelection = "IV II V"; const string ringSetting = "G M Y"; const string messageKey = "R L P"; const string plugboardCfg = "DN GR IS KC QX TM PV HY FW BJ"; const string reflectorCfg = "B"; const string ciphertext = "NQVLT YQFSE WWGJZ GQHVS EIXIM YKCNW IEBMB ATPPZ TDVCU PKAY"; map<string, int> rotorNameMap; rotorNameMap["I"] = 0; rotorNameMap["II"] = 1; rotorNameMap["III"] = 2; rotorNameMap["IV"] = 3; rotorNameMap["V"] = 4; rotorNameMap["VI"] = 5; rotorNameMap["VII"] = 6; rotorNameMap["VIII"] = 7; vector<char> ringSettingVec; istringstream issRingSetting(ringSetting); string rs; while(getline(issRingSetting, rs, ' ')) { ringSettingVec.push_back(rs[0]); } vector<char> messageKeyVec; istringstream issMessageKeyVec(messageKey); string wp; while(getline(issMessageKeyVec, wp, ' ')) { messageKeyVec.push_back(wp[0]); } vector<Rotor> rotorsRev; istringstream iss(rotorSelection); int k=0; string rotorName; while(getline(iss, rotorName, ' ')) { if(rotorNameMap.count(rotorName) == 0) throw invalid_argument("selected rotor name incorrect must be I...VIII"); string rotorCfg = ROTORS[rotorNameMap[rotorName]]; istringstream ss(rotorCfg); string token; string rotorCfgArray[2]; int i=0; while(getline(ss, token, '<')) { rotorCfgArray[i] = token; i++; } string rotorWiring = rotorCfgArray[0]; string rotorSteps = rotorCfgArray[1]; Rotor r = Rotor(rotorWiring, rotorSteps, ringSettingVec[k], messageKeyVec[k]); rotorsRev.push_back(r); k++; } Reflector reflector(REFLECTORS[0]); Plugboard plugboard(plugboardCfg); string input; if(argc == 2) input = string(argv[1]); else input = ciphertext; vector<Rotor> rotors; rotors.push_back(rotorsRev[2]); rotors.push_back(rotorsRev[1]); rotors.push_back(rotorsRev[0]); string result; EnigmaMachine(rotors, reflector, plugboard).crypt(input, result); cout << "test input " << input << endl; cout << "result " << result << endl; string test1_decrypted = "FLUGZ EUGFU EHRER ISTOF WYYXF UELLG RAFXF UELLG PAFXP OFOP"; assert(result == test1_decrypted); cout << "test 3 success" << endl; return 0; } }
32.165468
236
0.557854
[ "object", "vector", "transform" ]
e3b3de91e24bb003b0d793b357084f514198634a
310
hpp
C++
framework/include/star.hpp
flor2468/-CGLab_Wichmann121512_Doering119611
ac9014ea402ed5e06c40ee9230488a2be5b55eb1
[ "MIT" ]
2
2020-11-13T15:59:08.000Z
2020-11-13T16:04:22.000Z
framework/include/star.hpp
flor2468/CGLab_Wichmann121512_Doering119611
ac9014ea402ed5e06c40ee9230488a2be5b55eb1
[ "MIT" ]
null
null
null
framework/include/star.hpp
flor2468/CGLab_Wichmann121512_Doering119611
ac9014ea402ed5e06c40ee9230488a2be5b55eb1
[ "MIT" ]
null
null
null
#ifndef STAR_HPP #define STAR_HPP #include <iostream> #include <cmath> #include <math.h> #include <list> #include <../../external/glm-0.9.6.3/glm/glm.hpp> struct Star { std::vector<float> position_; std::vector<float> color_; std::vector<float> posColData_; model_object model_; }; #endif
16.315789
49
0.677419
[ "vector" ]
e3c50eaed600fd532810b3a2574691ab7d18c61e
6,196
hpp
C++
inference-engine/tests_deprecated/functional/shared_tests/single_layer_tests/activation_tests.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
2
2021-02-26T15:46:19.000Z
2021-05-16T20:48:13.000Z
inference-engine/tests_deprecated/functional/shared_tests/single_layer_tests/activation_tests.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
4
2021-04-01T08:29:48.000Z
2021-08-30T16:12:52.000Z
inference-engine/tests_deprecated/functional/shared_tests/single_layer_tests/activation_tests.hpp
anton-potapov/openvino
84119afe9a8c965e0a0cd920fff53aee67b05108
[ "Apache-2.0" ]
3
2021-03-09T08:27:29.000Z
2021-04-07T04:58:54.000Z
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <ie_core.hpp> #include "tests_common.hpp" #include "single_layer_common.hpp" #include "ir_gen_helper.hpp" using namespace ::testing; using namespace InferenceEngine; using namespace single_layer_tests; struct activation_base_params { struct { size_t w; size_t h; size_t c; } in; float n_clope; }; struct activation_test_params : activation_base_params { std::string device_name; std::string activationType; activation_test_params(std::string name, activation_base_params params, std::string activationType) : activation_base_params(params), device_name(name), activationType(activationType) {} }; template <typename data_t> void ref_activation(const data_t *src_data, data_t *dst_data, activation_test_params prm) { size_t IW = prm.in.w; size_t IH = prm.in.h; size_t IC = prm.in.c; for (uint32_t c = 0; c < IC; c++) { for (uint32_t h = 0; h < IH; h++) { for (uint32_t w = 0; w < IW; w++) { uint32_t oidx = c * IH * IW + h * IW + w; if (prm.activationType == "exp") dst_data[oidx] = exp(src_data[oidx]); else if (prm.activationType == "not") dst_data[oidx] = !(src_data[oidx]); else if (prm.activationType == "sin") dst_data[oidx] = sin(src_data[oidx]); else if (prm.activationType == "sinh") dst_data[oidx] = sinh(src_data[oidx]); else if (prm.activationType == "cos") dst_data[oidx] = cos(src_data[oidx]); else if (prm.activationType == "cosh") dst_data[oidx] = cosh(src_data[oidx]); else dst_data[oidx] = src_data[oidx] >= 0.0 ? src_data[oidx] : src_data[oidx] * prm.n_clope; } } } } class ActivationTest: public TestsCommon, public WithParamInterface<activation_test_params> { std::string layers_t = R"V0G0N( <layer name="_ACTIVATION_TYPE_" id="1" type="_ACTIVATION_TYPE_" precision="FP32"> <input> <port id="0"> <dim>_IN_</dim> <dim>_IC_</dim> <dim>_IH_</dim> <dim>_IW_</dim> </port> </input> <output> <port id="1"> <dim>_IN_</dim> <dim>_IC_</dim> <dim>_IH_</dim> <dim>_IW_</dim> </port> </output> </layer> )V0G0N"; std::string edges_t = R"V0G0N( <edge from-layer="0" from-port="0" to-layer="1" to-port="0"/> )V0G0N"; std::string getModel(activation_test_params p) { std::string model = layers_t; if (p.activationType == "exp") REPLACE_WITH_STR(model, "_ACTIVATION_TYPE_", "Exp"); else if (p.activationType == "not") REPLACE_WITH_STR(model, "_ACTIVATION_TYPE_", "Not"); else if (p.activationType == "sin") REPLACE_WITH_STR(model, "_ACTIVATION_TYPE_", "Sin"); else if (p.activationType == "sinh") REPLACE_WITH_STR(model, "_ACTIVATION_TYPE_", "Sinh"); else if (p.activationType == "cos") REPLACE_WITH_STR(model, "_ACTIVATION_TYPE_", "Cos"); else if (p.activationType == "cosh") REPLACE_WITH_STR(model, "_ACTIVATION_TYPE_", "Cosh"); else REPLACE_WITH_STR(model, "_ACTIVATION_TYPE_", "ReLU"); // Default value REPLACE_WITH_NUM(model, "_IN_", 1); REPLACE_WITH_NUM(model, "_IW_", p.in.w); REPLACE_WITH_NUM(model, "_IH_", p.in.h); REPLACE_WITH_NUM(model, "_IC_", p.in.c); model = IRTemplateGenerator::getIRTemplate(p.activationType + "_Only", {1lu, p.in.c, p.in.h, p.in.w}, "FP32", model, edges_t); return model; } protected: virtual void SetUp() { try { activation_test_params p = ::testing::WithParamInterface<activation_test_params>::GetParam(); std::string model = getModel(p); Core ie; CNNNetwork net = ie.ReadNetwork(model, Blob::CPtr()); InputsDataMap in_info_map = net.getInputsInfo(); OutputsDataMap out_info_map = net.getOutputsInfo(); ExecutableNetwork executable_network = ie.LoadNetwork(net, p.device_name); InferRequest inferRequest = executable_network.CreateInferRequest(); SizeVector dims_src = {1, p.in.c, p.in.h, p.in.w}; Blob::Ptr inputBlob = inferRequest.GetBlob(in_info_map.begin()->first); float* src = inputBlob->buffer().as<float*>(); fill_data(src, inputBlob->size()); SizeVector dims_dst = dims_src; Blob::Ptr outputBlob = inferRequest.GetBlob(out_info_map.begin()->first); TBlob<float> dst_ref({ Precision::FP32, dims_dst, Layout::NCHW }); dst_ref.allocate(); inferRequest.Infer(); ref_activation<float>(src, dst_ref.data(), p); const float* res = outputBlob->buffer().as<float*>(); const float* ref = dst_ref.data(); compare(res, ref, outputBlob->size()); } catch (const InferenceEngine::details::InferenceEngineException &e) { FAIL() << e.what(); } } }; #define case_1 activation_base_params({{228, 228, 3}, 0.0}) TEST_P(ActivationTest, TestsActivationFunctions) {} std::string getTestCaseName(testing::TestParamInfo<activation_test_params> obj) { return obj.param.device_name + "_w" + std::to_string(obj.param.in.w) + "_h" + std::to_string(obj.param.in.h) + "_c" + std::to_string(obj.param.in.c) + "_" + obj.param.activationType; }
34.422222
134
0.549548
[ "model" ]
e3c8a49ce77b25ab3cc9af34e05db04a86eae6bf
7,704
cpp
C++
test/ssc_test/cmod_battwatts_test.cpp
NREL/ssc
bf6e73a89dbe81ac7c896d192929c28011bc6d24
[ "BSD-3-Clause" ]
61
2017-08-09T15:10:59.000Z
2022-02-15T21:45:31.000Z
test/ssc_test/cmod_battwatts_test.cpp
NREL/ssc
4ce1d67d0e709ff3f016135c80cdb6aca0fccf34
[ "BSD-3-Clause" ]
462
2017-07-31T21:26:46.000Z
2022-03-30T22:53:50.000Z
test/ssc_test/cmod_battwatts_test.cpp
NREL/ssc
bf6e73a89dbe81ac7c896d192929c28011bc6d24
[ "BSD-3-Clause" ]
73
2017-08-24T17:39:31.000Z
2022-03-28T08:37:47.000Z
/** BSD-3-Clause Copyright 2019 Alliance for Sustainable Energy, LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met : 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <gtest/gtest.h> #include "../input_cases/code_generator_utilities.h" #include "vartab.h" #include "cmod_battwatts_test.h" #include "battwatts_cases.h" #include "lib_util.h" TEST_F(CMBattwatts_cmod_battwatts, ResilienceMetricsHalfLoad){ CreateData(1); auto ssc_dat = static_cast<ssc_data_t>(&data); int errors = run_module(ssc_dat, "battwatts"); EXPECT_FALSE(errors); auto resilience_hours = data.as_vector_ssc_number_t("resilience_hrs"); double resilience_hrs_min = data.as_number("resilience_hrs_min"); double resilience_hrs_max = data.as_number("resilience_hrs_max"); double resilience_hrs_avg = data.as_number("resilience_hrs_avg"); auto outage_durations = data.as_vector_ssc_number_t("outage_durations"); auto pdf_of_surviving = data.as_vector_ssc_number_t("pdf_of_surviving"); double avg_critical_load = data.as_double("avg_critical_load"); // Load met EXPECT_EQ(resilience_hours[0], 14); EXPECT_EQ(resilience_hours[1], 14); EXPECT_NEAR(avg_critical_load, 7.98, 0.1); EXPECT_NEAR(resilience_hrs_avg, 31.66, 0.01); EXPECT_EQ(resilience_hrs_min, 14); EXPECT_EQ(outage_durations[0], 14); EXPECT_EQ(resilience_hrs_max, 32); EXPECT_EQ(outage_durations[16], 30); EXPECT_NEAR(pdf_of_surviving[0], 0.00068, 1e-3); EXPECT_NEAR(pdf_of_surviving[1], 0.00217, 1e-3); } TEST_F(CMBattwatts_cmod_battwatts, ResilienceMetricsHalfLoadLifetime){ CreateData(2); auto ssc_dat = static_cast<ssc_data_t>(&data); int errors = run_module(ssc_dat, "battwatts"); EXPECT_FALSE(errors); auto resilience_hours = data.as_vector_ssc_number_t("resilience_hrs"); double resilience_hrs_min = data.as_number("resilience_hrs_min"); double resilience_hrs_max = data.as_number("resilience_hrs_max"); double resilience_hrs_avg = data.as_number("resilience_hrs_avg"); auto outage_durations = data.as_vector_ssc_number_t("outage_durations"); auto pdf_of_surviving = data.as_vector_ssc_number_t("pdf_of_surviving"); auto cdf_of_surviving = data.as_vector_ssc_number_t("cdf_of_surviving"); double avg_critical_load = data.as_double("avg_critical_load"); EXPECT_EQ(resilience_hours[0], 14); EXPECT_EQ(resilience_hours[1], 14); EXPECT_NEAR(avg_critical_load, 8.026, 0.1); EXPECT_NEAR(resilience_hrs_avg, 31.83, 0.01); EXPECT_EQ(resilience_hrs_min, 14); EXPECT_EQ(resilience_hrs_max, 32); EXPECT_EQ(outage_durations[0], 14); EXPECT_EQ(outage_durations[16], 30); EXPECT_NEAR(pdf_of_surviving[0], 0.00034, 1e-5); EXPECT_NEAR(pdf_of_surviving[1], 0.00103, 1e-5); } TEST_F(CMBattwatts_cmod_battwatts, ResidentialDefaults) { auto ssc_dat = static_cast<ssc_data_t>(&data); pvwatts_pv_defaults(ssc_dat); simple_battery_data(ssc_dat); int errors = run_module(ssc_dat, "battwatts"); EXPECT_FALSE(errors); double charge_percent = data.as_number("batt_system_charge_percent"); EXPECT_NEAR(charge_percent, 95.63, 0.1); auto batt_power_data = data.as_vector_ssc_number_t("batt_power"); ssc_number_t peakKwDischarge = *std::max_element(batt_power_data.begin(), batt_power_data.end()); ssc_number_t peakKwCharge = *std::min_element(batt_power_data.begin(), batt_power_data.end()); EXPECT_NEAR(peakKwDischarge, 2.16, 0.1); EXPECT_NEAR(peakKwCharge, -3.04, 0.1); auto batt_voltage = data.as_vector_ssc_number_t("batt_voltage"); ssc_number_t peakVoltage = *std::max_element(batt_voltage.begin(), batt_voltage.end()); EXPECT_NEAR(peakVoltage, 578.9, 0.1); auto cycles = data.as_vector_ssc_number_t("batt_cycles"); ssc_number_t maxCycles = *std::max_element(cycles.begin(), cycles.end()); EXPECT_NEAR(maxCycles, 613, 0.1); } TEST_F(CMBattwatts_cmod_battwatts, ResidentialDefaultsLeadAcid) { auto ssc_dat = static_cast<ssc_data_t>(&data); pvwatts_pv_defaults(ssc_dat); simple_battery_data(ssc_dat); // Set lead acid ssc_data_set_number(ssc_dat, "batt_simple_chemistry", 0); int errors = run_module(ssc_dat, "battwatts"); EXPECT_FALSE(errors); double charge_percent = data.as_number("batt_system_charge_percent"); EXPECT_NEAR(charge_percent, 95.98, 0.1); auto batt_power_data = data.as_vector_ssc_number_t("batt_power"); ssc_number_t peakKwDischarge = *std::max_element(batt_power_data.begin(), batt_power_data.end()); ssc_number_t peakKwCharge = *std::min_element(batt_power_data.begin(), batt_power_data.end()); EXPECT_NEAR(peakKwDischarge, 1.97, 0.1); EXPECT_NEAR(peakKwCharge, -2.57, 0.1); auto batt_voltage = data.as_vector_ssc_number_t("batt_voltage"); ssc_number_t peakVoltage = *std::max_element(batt_voltage.begin(), batt_voltage.end()); EXPECT_NEAR(peakVoltage, 61.43, 0.1); auto cycles = data.as_vector_ssc_number_t("batt_cycles"); ssc_number_t maxCycles = *std::max_element(cycles.begin(), cycles.end()); EXPECT_NEAR(maxCycles, 613, 0.1); } TEST_F(CMBattwatts_cmod_battwatts, NoPV) { auto ssc_dat = static_cast<ssc_data_t>(&data); pvwatts_pv_defaults(ssc_dat); simple_battery_data(ssc_dat); std::vector<double> ac(8760, 0); data.assign("ac", ac); int errors = run_module(ssc_dat, "battwatts"); EXPECT_FALSE(errors); double charge_percent = data.as_number("batt_system_charge_percent"); EXPECT_NEAR(charge_percent, 0.0, 0.1); auto batt_power_data = data.as_vector_ssc_number_t("batt_power"); ssc_number_t peakKwDischarge = *std::max_element(batt_power_data.begin(), batt_power_data.end()); ssc_number_t peakKwCharge = *std::min_element(batt_power_data.begin(), batt_power_data.end()); EXPECT_NEAR(peakKwDischarge, 0.9, 0.1); EXPECT_NEAR(peakKwCharge, -0.7, 0.1); auto batt_voltage = data.as_vector_ssc_number_t("batt_voltage"); ssc_number_t peakVoltage = *std::max_element(batt_voltage.begin(), batt_voltage.end()); EXPECT_NEAR(peakVoltage, 573.5, 0.1); auto cycles = data.as_vector_ssc_number_t("batt_cycles"); ssc_number_t maxCycles = *std::max_element(cycles.begin(), cycles.end()); EXPECT_NEAR(maxCycles, 522, 0.1); }
44.275862
117
0.757269
[ "vector" ]
e3cd5bdcb9fb66c8639d71cb57e54ff4828672fc
3,309
cpp
C++
GEC_2/MarioBaseProject/GameScreenWinHatquest.cpp
nerolileung/cgd_year1
211e91c37831a388b1abe1a1cc496716a4e9ca44
[ "MIT" ]
null
null
null
GEC_2/MarioBaseProject/GameScreenWinHatquest.cpp
nerolileung/cgd_year1
211e91c37831a388b1abe1a1cc496716a4e9ca44
[ "MIT" ]
null
null
null
GEC_2/MarioBaseProject/GameScreenWinHatquest.cpp
nerolileung/cgd_year1
211e91c37831a388b1abe1a1cc496716a4e9ca44
[ "MIT" ]
1
2019-12-09T22:41:49.000Z
2019-12-09T22:41:49.000Z
#include "GameScreenWinHatquest.h" #include <fstream> GameScreenWinHatquest::GameScreenWinHatquest(SDL_Renderer* renderer) : GameScreen::GameScreen(renderer){ mRenderer = renderer; mTextParser = new TextParser(renderer); mBackgroundTexture = new Texture2D(mRenderer); if (!mBackgroundTexture->LoadFromFile("Images/victory hatquest.png")) { cout << "Failed to load background texture!"; return; } mScore = 0; for (int i = 0; i < 3; i++) deathCounter[i] = 0; //initialisation ifstream inFile; inFile.open("hatquest_scores.txt"); if (!inFile.good()) { cout << "could not open scores file" << endl; return; } streampos start = inFile.tellg(); inFile.seekg(0, ios::end); //set eof to true streampos end = inFile.tellg(); if (start != end) { //there is data in file inFile.clear(); inFile.seekg(0, ios::beg); inFile >> mScore; string causeOfDeath; while (!inFile.eof()) { int score; inFile >> score; // move file pointer getline(inFile, causeOfDeath); if (causeOfDeath.compare(" gravity") == 0) deathCounter[0]++; else if (causeOfDeath.compare(" perforation") == 0) deathCounter[1]++; else if (causeOfDeath.compare(" blunt trauma") == 0) deathCounter[2]++; else if (causeOfDeath.compare(" suffocation") == 0) deathCounter[3]++; } } inFile.close(); // clear saves ofstream outFile; outFile.open("hatquest_scores.txt", ios::trunc); outFile.close(); mState = RUNNING; } GameScreenWinHatquest::~GameScreenWinHatquest(){} void GameScreenWinHatquest::Render() { mBackgroundTexture->Render(Vector2D(0, 0), SDL_FLIP_NONE); mTextParser->TextToSprite("YOU WIN", 4); mTextParser->Render(Vector2D(mTextParser->AlignXCentre(), 10)); mTextParser->TextToSprite("FINAL SCORE"); mTextParser->Render(Vector2D(mTextParser->AlignXCentre(), 62)); mTextParser->TextToSprite(to_string(mScore)); mTextParser->Render(Vector2D(mTextParser->AlignXCentre(), 82)); // left align mTextParser->TextToSprite("DEATHS BY"); mTextParser->Render(Vector2D(10, 144)); mTextParser->TextToSprite("GRAVITY"); mTextParser->Render(Vector2D(10, 176)); mTextParser->TextToSprite(to_string(deathCounter[0])); mTextParser->Render(Vector2D(40, 196)); mTextParser->TextToSprite("PERFORATION"); mTextParser->Render(Vector2D(10, 228)); mTextParser->TextToSprite(to_string(deathCounter[1])); mTextParser->Render(Vector2D(40, 248)); //right align mTextParser->TextToSprite("DEATHS BY"); mTextParser->Render(Vector2D(mTextParser->AlignXRight() - 10, 144)); mTextParser->TextToSprite("BLUNT TRAUMA"); mTextParser->Render(Vector2D(mTextParser->AlignXRight()-10, 176)); mTextParser->TextToSprite(to_string(deathCounter[2])); mTextParser->Render(Vector2D(mTextParser->AlignXRight() - 40, 196)); mTextParser->TextToSprite("SUFFOCATION"); mTextParser->Render(Vector2D(mTextParser->AlignXRight() - 10, 228)); mTextParser->TextToSprite(to_string(deathCounter[3])); mTextParser->Render(Vector2D(mTextParser->AlignXRight() - 40, 248)); //bottom text mTextParser->TextToSprite("PRESS SPACE TO RETURN TO MAIN MENU"); mTextParser->Render(Vector2D(mTextParser->AlignXCentre(), 320)); mTextParser->TextToSprite("PRESS ESCAPE TO QUIT"); mTextParser->Render(Vector2D(mTextParser->AlignXCentre(), 352)); }
39.86747
105
0.711998
[ "render" ]
e3d2ac37a9e48ab595a28de93639ec90a3078555
3,714
cpp
C++
intro/intro.cpp
ddolzhenko/training_algos_2017_03
e622b391a87b1ce0435854acad3cfaddcebb8bb8
[ "MIT" ]
null
null
null
intro/intro.cpp
ddolzhenko/training_algos_2017_03
e622b391a87b1ce0435854acad3cfaddcebb8bb8
[ "MIT" ]
null
null
null
intro/intro.cpp
ddolzhenko/training_algos_2017_03
e622b391a87b1ce0435854acad3cfaddcebb8bb8
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; template <class T> ostream& operator<<(ostream& o, const vector<T>& v) { o << "["; for(auto& x : v) { o << x << ", "; } return o << "]"; } template <class TFunc, class TResult, class TParam1> void test(TResult expect, TFunc f, TParam1 p1) { auto got = f(p1); if(got != expect) { cerr << "failed: " << expect << " != " << got << endl; } } template <class TFunc, class TResult, class TParam1, class TParam2> void test(TResult expect, TFunc f, TParam1 p1, TParam2 p2) { auto got = f(p1, p2); if(got != expect) { cerr << "failed: f(" << p1 << ", " << p2 << ") = " << got << " != " << expect << endl; } } int search_0(int v[], size_t size, int key) { for (int i = 0; i < size; ++i) { if (v[i] == key) { return i; } } return -1; } int search_1(int v[], size_t size, int key) { v[size] = key; int i = 0; while (v[i] != key) { ++i; } if (i != size) { return i; } return -1; } int search_2(const std::vector<int>& v, int key) { for (int i = 0; i < v.size(); ++i) { if (v[i] == key) { return i; } } return -1; } int search_3(std::vector<int>& v, int key) { v.push_back(key); int i = 0; while (v[i] != key) { ++i; } v.pop_back(); if (i != v.size()) { return i; } return -1; } int binary_search_helper (const vector<int>& v, size_t begin, size_t end, int key, size_t depth=0) { assert(depth < 1000); assert(std::is_sorted(v.begin(), v.end())); if(b < e) { // [b, e) = [b, m) U [m] U [m+1, e) size_t m = (begin + end) / 2; assert((m-begin) + (end-m) == (end-begin)); if (key < v[m]) { return binary_search_helper(v, begin, m, key, depth+1); } else if (v[m] < key) { return binary_search_helper(v, m+1, end, key, depth+1); } else { return m; } } return -1; } int binary_search(const vector<int>& v, int key) { assert(std::is_sorted(v.begin(), v.end())); size_t b = 0; size_t e = v.size(); while(b < e) { // [b, e) = [b, m) U [m] U [m+1, e) size_t m = b + (end-begin)/2; if (key < v[m]) { e = m; } else if (v[m] < key) { b = m+1; } else { return m; } } return -1; } void test_search() { typedef vector<int> Array; auto search = search_2; auto key = 8; // key not exists in array test(-1, search, Array(), key); // degerate test(-1, search, Array({key-1}), key); // trivial test(-1, search, Array({key-1, key+1}), key); // trivial2 test(-1, search, Array({1,2,3,4,5,7}), key); // general test(-1, search, Array({9,10,11,12}), key); // general test(-1, search, Array({4,1,2,7,10}), key); // general // key exists in array // non appliable // degerate test(0, search, Array({key}), key); // trivial test(0, search, Array({key, key+1}), key); // trivial2 test(1, search, Array({key-1, key}), key); // trivial2 test(8, search, Array({0,1,2,3,4,5,6,7,key}), key); // general test(0, search, Array({key, 9,10,11,12}), key); // general test(2, search, Array({4,1,key,7,10}), key); // general test(0, search, Array({key,1,key,7,10}), key); // general test(2, search, Array({2,1,key,7,key}), key); // general } int main(int argc, char const *argv[]) { test_search(); return 0; }
23.96129
81
0.475767
[ "vector" ]
e3dbfe812c223db9b07a95dfc3cd8290b50fb492
10,587
hh
C++
Shared/BrainCloudMatchMaking.hh
pascalf1309/braincloud-objc
d3519eb26d753515a0d57d2ce07fe26399c14fac
[ "Apache-2.0" ]
null
null
null
Shared/BrainCloudMatchMaking.hh
pascalf1309/braincloud-objc
d3519eb26d753515a0d57d2ce07fe26399c14fac
[ "Apache-2.0" ]
3
2018-10-02T12:30:24.000Z
2020-02-21T12:53:12.000Z
Shared/BrainCloudMatchMaking.hh
pascalf1309/braincloud-objc
d3519eb26d753515a0d57d2ce07fe26399c14fac
[ "Apache-2.0" ]
5
2018-05-23T17:06:24.000Z
2021-02-24T18:57:20.000Z
// // BrainCloudMatchMaking.h // brainCloudClientObjc // // Created by Hill, Bradley on 2015-08-10. // Copyright (c) 2016 bitHeads. All rights reserved. // #import <Foundation/Foundation.h> #import "BrainCloudCompletionBlocks.hh" @class BrainCloudClient; @interface BrainCloudMatchMaking : NSObject /** * Initializes the brainCloudService */ - (instancetype) init: (BrainCloudClient*) client; /** * Read match making record * * Service Name - MatchMaking * Service Operation - Read * * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)read:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Sets player rating * * Service Name - MatchMaking * Service Operation - SetPlayerRating * * @param playerRating The new player rating. * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)setPlayerRating:(int)rating completionBlock:(BCCompletionBlock)completionBlock errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Resets player rating * * Service Name - MatchMaking * Service Operation - ResetPlayerRating * * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)resetPlayerRating:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Increments player rating * * Service Name - MatchMaking * Service Operation - IncrementPlayerRating * * @param increment The increment amount * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)incrementPlayerRating:(int)increment completionBlock:(BCCompletionBlock)completionBlock errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Decrements player rating * * Service Name - MatchMaking * Service Operation - DecrementPlayerRating * * @param decrement The decrement amount * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)decrementPlayerRating:(int)decrement completionBlock:(BCCompletionBlock)completionBlock errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Turns shield on * * Service Name - MatchMaking * Service Operation - ShieldOn * * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)turnShieldOn:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Turns shield on for the specified number of minutes * * Service Name - MatchMaking * Service Operation - ShieldOnFor * * @param minutes Number of minutes to turn the shield on for * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)turnShieldOnFor:(int)minutes completionBlock:(BCCompletionBlock)completionBlock errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Turns shield off * * Service Name - MatchMaking * Service Operation - ShieldOff * * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)turnShieldOff:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Increases the shield on time by specified number of minutes * * Service Name - MatchMaking * Service Operation - ShieldOnFor * * @param minutes Number of minutes to increase the shield time for * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)incrementShieldOnFor:(int) minutes completionBlock:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Gets the shield expiry for the given player id. Passing in a null player id * will return the shield expiry for the current player. The value returned is * the time in UTC millis when the shield will expire. * * Service Name - MatchMaking * Service Operation - GetShieldExpiry * * @param playerId The player id or use null to retrieve for the current player * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)getShieldExpiry:(NSString *)playerId completionBlock:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Finds matchmaking enabled players * * Service Name - MatchMaking * Service Operation - FIND_PLAYERS * * @param rangeDelta The range delta * @param numMatches The maximum number of matches to return * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)findPlayers:(int)rangeDelta numMatches:(int)numMatches completionBlock:(BCCompletionBlock)completionBlock errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Finds matchmaking enabled players with additional attributes * * Service Name - MatchMaking * Service Operation - FIND_PLAYERS * * @param rangeDelta The range delta * @param numMatches The maximum number of matches to return * @param jsonAttributes Attributes match criteria * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)findPlayersWithAttributes:(int)rangeDelta numMatches:(int)numMatches jsonAttributes:(NSString *)jsonAttributes completionBlock:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Finds matchmaking enabled players using a cloud code filter * * Service Name - MatchMaking * Service Operation - FIND_PLAYERS_USING_FILTER * * @param rangeDelta The range delta * @param numMatches The maximum number of matches to return * @param jsonExtraParms Other parameters * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)findPlayersUsingFilter:(int)rangeDelta numMatches:(int)numMatches jsonExtraParams:(NSString *)jsonExtraParams completionBlock:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Finds matchmaking enabled players using a cloud code filter * and additional attributes * * Service Name - MatchMaking * Service Operation - FIND_PLAYERS_USING_FILTER * * @param rangeDelta The range delta * @param numMatches The maximum number of matches to return * @param jsonAttributes Attributes match criteria * @param jsonExtraParms Parameters to pass to the CloudCode filter script * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)findPlayersWithAttributesUsingFilter:(int)rangeDelta numMatches:(int)numMatches jsonAttributes:(NSString *)jsonAttributes jsonExtraParams:(NSString *)jsonExtraParams completionBlock:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Enables Match Making for the Player * * Service Name - MatchMaking * Service Operation - EnableMatchMaking * * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)enableMatchMaking:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; /** * Disables Match Making for the Player * * Service Name - MatchMaking * Service Operation - EnableMatchMaking * * @param completionBlock Block to call on return of successful server response * @param errorCompletionBlock Block to call on return of unsuccessful server response * @param cbObject User object sent to the completion blocks */ - (void)disableMatchMaking:(BCCompletionBlock)cb errorCompletionBlock:(BCErrorCompletionBlock)ecb cbObject:(BCCallbackObject)cbObject; @end
37.017483
86
0.752338
[ "object" ]
e3de899f16760f6ff3c206d4a6c910a82665c5d6
5,431
cpp
C++
HP_ID_Print_App/Classes/PopupLayer/PopupLayer.cpp
yangboz/petulant-octo-dubstep
61a475ee8a94ad7cb2ade4fab8911ea0d6857c1e
[ "MIT" ]
1
2021-06-25T21:59:17.000Z
2021-06-25T21:59:17.000Z
HP_ID_Print_App/Classes/PopupLayer/PopupLayer.cpp
yangboz/petulant-octo-dubstep
61a475ee8a94ad7cb2ade4fab8911ea0d6857c1e
[ "MIT" ]
null
null
null
HP_ID_Print_App/Classes/PopupLayer/PopupLayer.cpp
yangboz/petulant-octo-dubstep
61a475ee8a94ad7cb2ade4fab8911ea0d6857c1e
[ "MIT" ]
null
null
null
// // PopupLayer.cpp // TestCpp // // Created by leafsoar on 7/29/13. // // #include "PopupLayer.h" PopupLayer::PopupLayer() : m__pMenu(NULL) , m_contentPadding(0) , m_contentPaddingTop(0) , m_callbackListener(NULL) , m_callback(NULL) , m__sfBackGround(NULL) , m__s9BackGround(NULL) , m__ltContentText(NULL) , m__ltTitle(NULL) { } PopupLayer::~PopupLayer(){ CC_SAFE_RELEASE(m__pMenu); CC_SAFE_RELEASE(m__sfBackGround); CC_SAFE_RELEASE(m__ltContentText); CC_SAFE_RELEASE(m__ltTitle); CC_SAFE_RELEASE(m__s9BackGround); } bool PopupLayer::init(){ bool bRef = false; do{ CC_BREAK_IF(!CCLayer::init()); this->setContentSize(CCSizeZero); // 初始化需要的 Menu CCMenu* menu = CCMenu::create(); menu->setPosition(CCPointZero); setMenuButton(menu); setTouchEnabled(true); bRef = true; } while (0); return bRef; } /* void PopupLayer::registerWithTouchDispatcher(){ // 这里的触摸优先级设置为 -128 这保证了,屏蔽下方的触摸 CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, -128, true); } */ /* bool PopupLayer::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent){ // CCLog("PopupLayer touch"); return true; } */ PopupLayer* PopupLayer::create(const char *backgroundImage){ PopupLayer* ml = PopupLayer::create(); ml->setSpriteBackGround(CCSprite::create(backgroundImage)); //ml->setSprite9BackGround(CCScale9Sprite::create(backgroundImage)); cocos2d::CCRect centerRect = cocos2d::CCRectMake(0, 0, 100, 100); ml->setSprite9BackGround(CCScale9Sprite::scale9SpriteWithFile(backgroundImage, centerRect)); return ml; } void PopupLayer::setTitle(const char *title, int fontsize){ CCLabelTTF* ltfTitle = CCLabelTTF::create(title, "", fontsize); setLabelTitle(ltfTitle); } void PopupLayer::setContentText(const char *text, int fontsize, int padding, int paddingTop){ CCLabelTTF* ltf = CCLabelTTF::create(text, "", fontsize); setLabelContentText(ltf); m_contentPadding = padding; m_contentPaddingTop = paddingTop; } void PopupLayer::setCallbackFunc(cocos2d::CCObject *target, SEL_CallFuncN callfun){ m_callbackListener = target; m_callback = callfun; } bool PopupLayer::addButton(const char *normalImage, const char *selectedImage, const char *title, int tag){ CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCPoint pCenter = ccp(winSize.width / 2, winSize.height / 2); // 创建图片菜单按钮 CCMenuItemImage* menuImage = CCMenuItemImage::create(normalImage, selectedImage, this, menu_selector(PopupLayer::buttonCallback)); menuImage->setTag(tag); menuImage->setPosition(pCenter); // 添加文字说明并设置位置 CCSize imenu = menuImage->getContentSize(); CCLabelTTF* ttf = CCLabelTTF::create(title, "", 20); ttf->setColor(ccc3(0, 0, 0)); ttf->setPosition(ccp(imenu.width / 2, imenu.height / 2)); menuImage->addChild(ttf); getMenuButton()->addChild(menuImage); return true; } void PopupLayer::buttonCallback(cocos2d::CCObject *pSender){ CCNode* node = dynamic_cast<CCNode*>(pSender); CCLog("touch tag: %d", node->getTag()); if (m_callback && m_callbackListener){ (m_callbackListener->*m_callback)(node); } this->removeFromParent(); } void PopupLayer::onEnter(){ CCLayer::onEnter(); CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCPoint pCenter = ccp(winSize.width / 2, winSize.height / 2); CCSize contentSize; // 设定好参数,在运行时加载 if (getContentSize().equals(CCSizeZero)) { getSpriteBackGround()->setPosition(ccp(winSize.width / 2, winSize.height / 2)); this->addChild(getSpriteBackGround(), 0, 0); contentSize = getSpriteBackGround()->getTexture()->getContentSize(); } else { CCScale9Sprite *background = getSprite9BackGround(); background->setContentSize(getContentSize()); background->setPosition(ccp(winSize.width / 2, winSize.height / 2)); this->addChild(background, 0, 0); contentSize = getContentSize(); } // 添加按钮,并设置其位置 this->addChild(getMenuButton()); float btnWidth = contentSize.width / (getMenuButton()->getChildrenCount() + 1); cocos2d::Vector<cocos2d::CCNode *> array = getMenuButton()->getChildren(); //CCArray* array = getMenuButton()->getChildren(); CCObject* pObj = NULL; int i = 0; int count = array.size(); for (auto sp : array) { //CCLOG("sprite tag = %d", sp->getTag()); CCNode* node = dynamic_cast<CCNode*>(sp); node->setPosition(ccp(winSize.width / 2 - contentSize.width / 2 + btnWidth * (i + 1), winSize.height / 2 - contentSize.height / 3)); i++; } /* CCARRAY_FOREACH(array, pObj){ CCNode* node = dynamic_cast<CCNode*>(pObj); node->setPosition(ccp(winSize.width / 2 - contentSize.width / 2 + btnWidth * (i + 1), winSize.height / 2 - contentSize.height / 3)); i++; } */ // 显示对话框标题 if (getLabelTitle()){ getLabelTitle()->setPosition(ccpAdd(pCenter, ccp(0, contentSize.height / 2 - 35.0f))); this->addChild(getLabelTitle()); } // 显示文本内容 if (getLabelContentText()){ CCLabelTTF* ltf = getLabelContentText(); ltf->setPosition(ccp(winSize.width / 2, winSize.height / 2)); ltf->setDimensions(CCSizeMake(contentSize.width - m_contentPadding * 2, contentSize.height - m_contentPaddingTop)); ltf->setHorizontalAlignment(kCCTextAlignmentLeft); this->addChild(ltf); } // 弹出效果 CCAction* popupLayer = CCSequence::create(CCScaleTo::create(0.0, 0.0), CCScaleTo::create(0.06, 1.05), CCScaleTo::create(0.08, 0.95), CCScaleTo::create(0.08, 1.0), NULL); this->runAction(popupLayer); } void PopupLayer::onExit(){ CCLog("popup on exit."); CCLayer::onExit(); }
27.994845
134
0.719941
[ "vector" ]
e3f1fc525c296170564b218e2ab595e556263a60
2,257
cpp
C++
src/GSparseVolumesVdb/VdbUtil.cpp
matthew-reid/Graphtane
3148039993da185cfb328f89b96c9e5a5b384197
[ "MIT" ]
38
2015-01-01T05:55:38.000Z
2022-03-12T23:19:50.000Z
src/GSparseVolumesVdb/VdbUtil.cpp
matthew-reid/Graphtane
3148039993da185cfb328f89b96c9e5a5b384197
[ "MIT" ]
1
2019-07-29T21:48:40.000Z
2020-01-13T12:08:08.000Z
src/GSparseVolumesVdb/VdbUtil.cpp
matthew-reid/Graphtane
3148039993da185cfb328f89b96c9e5a5b384197
[ "MIT" ]
8
2016-04-22T06:41:47.000Z
2021-11-23T23:44:22.000Z
// Copyright (c) 2013-2014 Matthew Paul Reid // 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 "VdbUtil.h" #include <GCommon/Logger.h> #include <boost/foreach.hpp> using namespace GCommon; namespace GSparseVolumes { std::vector<openvdb::GridBase::Ptr> loadGridsFromFile(const std::string& filename, const std::vector<std::string>& gridNames) { std::vector<openvdb::GridBase::Ptr> grids; // Get first grid from file openvdb::initialize(); openvdb::io::File file(filename); file.open(); defaultLogger()->logLine("Available grids:"); for (openvdb::io::File::NameIterator nameIterator = file.beginName(); nameIterator != file.endName(); ++nameIterator) { std::string gridName = *nameIterator; defaultLogger()->logLine(gridName); } if (file.beginName() == file.endName()) { throw std::runtime_error("No grids found in file"); } BOOST_FOREACH(const std::string& gridName, gridNames) { defaultLogger()->logLine("Loading grid: '" + gridName + "'"); openvdb::GridBase::Ptr grid = file.readGrid(gridName); if (grid) { grids.push_back(grid); } else { throw std::runtime_error("Grid '" + gridName + "' not found"); } } file.close(); return grids; } } // namespace GSparseVolumes
31.788732
126
0.727514
[ "vector" ]
e3f653bff25bb03e8231fc71f7789d4d76640316
2,466
hh
C++
include/kbbq/readutils.hh
adamjorr/cbbq
9167b72599892a33493d8ebdc01fac33990c1738
[ "MIT" ]
4
2019-11-03T08:18:55.000Z
2021-03-17T01:05:04.000Z
include/kbbq/readutils.hh
adamjorr/cbbq
9167b72599892a33493d8ebdc01fac33990c1738
[ "MIT" ]
9
2019-02-11T22:33:03.000Z
2021-05-21T05:34:46.000Z
include/kbbq/readutils.hh
adamjorr/cbbq
9167b72599892a33493d8ebdc01fac33990c1738
[ "MIT" ]
null
null
null
#ifndef READUTILS_H #define READUTILS_H #include <vector> #include <unordered_map> #include <string> #include <errno.h> // #include <htslib/sam.h> #include <htslib/kseq.h> #include <htslib/bgzf.h> #include "bloom.hh" #include "covariateutils.hh" #include "kseq.hh" #define INFER_ERROR_BAD_QUAL 2 //fwd declare namespace covariateutils{ struct dq_t; } namespace readutils{ static int8_t complement[16] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; // int correction_len(const bloom::bloomary_t& t, int k); //get read sequence as a string in the forward orientation inline std::string bam_seq_str(bam1_t* bamrecord){ std::string seq; char* s = (char*)bam_get_seq(bamrecord); for(size_t i = 0; i < bamrecord->core.l_qseq; ++i){ seq.push_back(bam_is_rev(bamrecord) ? seq_nt16_str[seq_nt16_table['0' + 3-seq_nt16_int[bam_seqi(s, i)]]] : seq_nt16_str[bam_seqi(s, i)]); } if(bam_is_rev(bamrecord)){ std::reverse(seq.begin(), seq.end()); } return seq; } class CReadData{ public: static std::unordered_map<std::string, std::string> rg_to_pu; static std::unordered_map<std::string, int> rg_to_int; CReadData(){} CReadData(bam1_t* bamrecord, bool use_oq = false); // hello? CReadData(kseq::kseq_t* fastqrecord, std::string rg = "", int second = 2, std::string namedelimiter = "_"); std::string seq; std::vector<uint8_t> qual; std::vector<bool> skips; std::string name; std::string rg; bool second; std::vector<bool> errors; std::string str_qual(); std::string canonical_name(); inline int get_rg_int() const{return this->rg_to_int[this->rg];} inline std::string get_pu() const{return this->rg_to_pu[this->rg];} std::vector<bool> not_skipped_errors() const; //fill errors attribute given sampled kmers and thresholds. void infer_read_errors(const bloom::Bloom& b, const std::vector<int>& thresholds, int k); //fix one error and return the index of the fixed base; std::string::npos if no fixes are found size_t correct_one(const bloom::Bloom& t, int k); static void load_rgs_from_bamfile(bam_hdr_t* header); //fill errors attribute given trusted kmers std::vector<bool> get_errors(const bloom::Bloom& trusted, int k, int minqual = 6, bool first_call = true); std::vector<uint8_t> recalibrate(const covariateutils::dq_t& dqs, int minqual = 6) const; CReadData substr(size_t pos = 0, size_t count = std::string::npos) const; }; } #endif
31.615385
110
0.697486
[ "vector" ]
e3f91e5e87dfc109f61a23311a72a8db54d945f0
2,054
cpp
C++
leetcode/30_days_challenge/2021_2_Feb/27.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
1
2020-05-05T13:06:51.000Z
2020-05-05T13:06:51.000Z
leetcode/30_days_challenge/2021_2_Feb/27.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
leetcode/30_days_challenge/2021_2_Feb/27.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
/**************************************************** Date: Feb 27th link: https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/587/week-4-february-22nd-february-28th/3649/ ****************************************************/ #include <iostream> #include <vector> #include <list> #include <algorithm> #include <string> #include <stack> #include <queue> #include <map> #include <unordered_map> #include <unordered_set> #include <cmath> #include <limits.h> using namespace std; /* Q: Divide Two Integers Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. Return the quotient after dividing dividend by divisor. The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2. Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 231 − 1 when the division result overflows. Example 1: Input: dividend = 10, divisor = 3 Output: 3 Explanation: 10/3 = truncate(3.33333..) = 3. Example 2: Input: dividend = 7, divisor = -3 Output: -2 Explanation: 7/-3 = truncate(-2.33333..) = -2. Example 3: Input: dividend = 0, divisor = 1 Output: 0 Example 4: Input: dividend = 1, divisor = 1 Output: 1 Constraints: -231 <= dividend, divisor <= 231 - 1 divisor != 0 */ class Solution { public: int divide(int dividend, int divisor) { if (dividend == INT_MIN && divisor == -1) { return INT_MAX; } long dvd = labs(dividend), dvs = labs(divisor), ans = 0; int sign = dividend > 0 ^ divisor > 0 ? -1 : 1; while (dvd >= dvs) { long temp = dvs, m = 1; while (temp << 1 <= dvd) { temp <<= 1; m <<= 1; } dvd -= temp; ans += m; } return sign * ans; } };
23.883721
129
0.597858
[ "vector" ]
e3fce6219f0cbabf981af869858fbbb02efed0b3
3,281
cpp
C++
lonestar/patternmining/rest_plan.cpp
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
lonestar/patternmining/rest_plan.cpp
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
lonestar/patternmining/rest_plan.cpp
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
#include "def.h" #include <iostream> RestPlan::RestPlan(ExecutionPlan& ep, int _id): id(_id), vertices(ep.vertices), rest(ep.restrictions) { //construct the plans at each level for what we loop on //first element on loopon is the set for v1 //first construct what they depend on, put them in //This loop implements single-plan set operation motion for(int i= 1; i < ep.vertices;++i){ std::vector<int> ins(ep.depend[i].first.begin(),ep.depend[i].first.end()); std::vector<int> out(ep.depend[i].second.begin(),ep.depend[i].second.end()); // std::vector<int> rs(ep.restrictions.begin()+1, ep.restrictions.end()); // loopons.emplace_back(ins,out,rs); loopons.emplace_back(ins,out,ep.restrictions); depends.emplace_back(); //don't include the last one // std::cout<<i<<" "<<ep.vertices<<std::endl; if(i!=ep.vertices-1) depends[i-1].insert(loopons[i-1]); std::cout << "\n processing rs: " << loopons[i-1]; RestSet curr = loopons[i-1].parent(); while(curr.ins.size()>0){ std::cout << "\n parent rs: " << curr; depends[curr.depth].insert(curr); curr = curr.parent(); } // std::cout<<depends[i-1].size()<<std::endl; } } //expected memory allocated to vertex sets double RestPlan::data_complexity(){ //go through depends and loopons, iterating down std::vector<int> multcounts(vertices); //for(int i=0;i<vertices;++i)multcounts[0] = 0; double res=0; //expected times a loop happens is // (normal expected times) / product (multcounts) double expectedloopness = GLOBAL_VERTEX_COUNT; for(int i=0;i<vertices-1;++i){ //go down on loopon int mc = i; while(mc!=-1){ ++multcounts[mc]; mc=rest[mc]; } double inexpect = expectedloopness; for(int j=0;j<=i;++j) inexpect/=multcounts[j]; for(RestSet s: depends[i]){ res+=s.data_complexity_ignoring_restrictions()*inexpect; } expectedloopness*=loopons[i].data_complexity_ignoring_restrictions(); } //delete[] multcounts; //std::cout<<res<<std::endl; return res; } //expected time to compute double RestPlan::time_complexity(){ //go through depends and loopons, iterating down std::vector<int> multcounts(vertices); //int* multcounts = new int[vertices]; for(int i=0;i<vertices;++i)multcounts[i] = 0; double res=0; //expected times a loop happens is // (normal expected times) / product (multcounts) double expectedloopness = GLOBAL_VERTEX_COUNT; for(int i=0;i<vertices-1;++i){ //go down on loopon int mc = i; while(mc!=-1){ ++multcounts[mc]; mc=rest[mc]; } double inexpect = expectedloopness; for(int j=0;j<=i;++j) { //std::cout<<j<<"has mult "<<multcounts[j]<<" at step "<<i<<std::endl; inexpect/=multcounts[j]; } // double oldres=res; for(RestSet s: depends[i]){ res+=s.time_complexity_ignoring_restrictions()*inexpect; } if(i==vertices-2){ //std::cout<<" Adding complexity of the loop "<<std::endl; res+=loopons[i].time_complexity_ignoring_restrictions()*inexpect; } // std::cout<<i<<" makes " <<oldres<<" res "<<res<<" "<<res-oldres<<std::endl; expectedloopness*=loopons[i].data_complexity_ignoring_restrictions(); } return res; }
32.485149
103
0.640354
[ "vector" ]
541548c126a3bbf8738d4313eb9fbb4720c7d552
530
cpp
C++
uppsrc/Updater/Updater.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppsrc/Updater/Updater.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppsrc/Updater/Updater.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include <CtrlLib/CtrlLib.h> using namespace Upp; GUI_APP_MAIN { const Vector<String>& cmdline = CommandLine(); SetDefaultCharset(CHARSET_WIN1250); if(cmdline.IsEmpty()) { Exclamation("[* UPDATER] should be run from another applications"); return; } String name = cmdline[0]; UpdateFile(name); String exec = GetExeDirFile(name); for(int i = 1; i < cmdline.GetCount(); i++) if(cmdline[i].Find(' ') >= 0) exec << " \"" << cmdline[i] << "\""; else exec << " " << cmdline[i]; WinExec(exec, SW_SHOWNORMAL); }
22.083333
69
0.64717
[ "vector" ]
54162ad7cfa894f30d78c1fc96e845465d30050f
3,676
hpp
C++
Libraries/Macaronlib/include/Macaronlib/Vector.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
21
2021-08-22T19:06:54.000Z
2022-03-31T12:44:30.000Z
Libraries/Macaronlib/include/Macaronlib/Vector.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
1
2021-09-01T22:55:59.000Z
2021-09-08T20:52:09.000Z
Libraries/Macaronlib/include/Macaronlib/Vector.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
null
null
null
#pragma once #include "Common.hpp" #include "Runtime.hpp" #include "SimpleIterator.hpp" template <typename T> class Vector { public: Vector() = default; Vector(size_t size) : m_size(size) , m_capacity(size) { m_data = (T*)malloc(m_capacity * sizeof(T)); } Vector(const Vector& v) { realloc(v.capacity()); m_size = v.size(); copy(m_data, v.m_data, m_size); } Vector(Vector&& v) { m_capacity = v.m_capacity; m_size = v.m_size; m_data = v.m_data; v.m_size = 0; v.m_capacity = 0; v.m_data = nullptr; } ~Vector() { clear(); if (m_data) { free(m_data); m_data = nullptr; } }; Vector& operator=(const Vector& v) { clear(); if (v.size() > m_capacity) { realloc(v.capacity()); } m_size = v.size(); copy(m_data, v.m_data, v.size()); return *this; } Vector& operator=(Vector&& v) { if (this != &v) { clear(); m_capacity = v.m_capacity; m_size = v.m_size; m_data = v.m_data; v.m_size = 0; v.m_capacity = 0; v.m_data = nullptr; } return *this; } size_t size() const { return m_size; }; size_t capacity() const { return m_capacity; } T* data() { return m_data; } const T* data() const { return m_data; } // Element access T& operator[](size_t pos) { return m_data[pos]; } const T& operator[](size_t pos) const { return m_data[pos]; } T& front() { return m_data[0]; } const T& front() const { return m_data[0]; } T& back() { return m_data[m_size - 1]; } const T& back() const { return m_data[m_size - 1]; } // Modifiers void push_back(T&& val) { if (m_size >= m_capacity) { realloc(m_capacity * 2 + 1); } new (m_data + m_size++) T(move(val)); } void push_back(const T& val) { push_back(T(val)); } void pop_back() { if (m_size > 0) { m_data[--m_size].~T(); } } void clear() { for (size_t i = 0; i < m_size; i++) { m_data[i].~T(); } m_size = 0; } // Compare operators bool operator==(const Vector& v) const { if (m_size != v.size()) { return false; } for (size_t i = 0; i < v.size(); i++) { if ((*this)[i] != v[i]) { return false; } } return true; } // Iterators using ConstIterator = SimpleIterator<const Vector, const T>; using Iterator = SimpleIterator<Vector, T>; ConstIterator begin() const { return ConstIterator(*this, 0); } Iterator begin() { return Iterator(*this, 0); } ConstIterator end() const { return ConstIterator(*this, m_size); } Iterator end() { return Iterator(*this, m_size); } private: void realloc(size_t size) { auto new_data = (T*)malloc(size * sizeof(T)); for (size_t i = 0; i < m_size; i++) { new (&new_data[i]) T(move(m_data[i])); } for (size_t i = 0; i < m_size; i++) { m_data[i].~T(); } free(m_data); m_data = new_data; m_capacity = size; } void copy(T* to, T* from, size_t len) { for (size_t i = 0; i < len; i++) { new (to) T(*from); to++; from++; } } private: T* m_data { nullptr }; size_t m_size { 0 }; size_t m_capacity { 0 }; };
21.623529
70
0.480141
[ "vector" ]
5428019b61fabf905a9cb026eb193a9dc4d9b0e9
29,631
cpp
C++
asteria/src/statement.cpp
MaskRay/asteria
56a9251f5bb80b92e5aff25eac145f8cd2495096
[ "BSD-3-Clause" ]
null
null
null
asteria/src/statement.cpp
MaskRay/asteria
56a9251f5bb80b92e5aff25eac145f8cd2495096
[ "BSD-3-Clause" ]
null
null
null
asteria/src/statement.cpp
MaskRay/asteria
56a9251f5bb80b92e5aff25eac145f8cd2495096
[ "BSD-3-Clause" ]
null
null
null
// This file is part of Asteria. // Copyleft 2018, LH_Mouse. All wrongs reserved. #include "precompiled.hpp" #include "statement.hpp" #include "xpnode.hpp" #include "global_context.hpp" #include "analytic_context.hpp" #include "executive_context.hpp" #include "variable.hpp" #include "instantiated_function.hpp" #include "exception.hpp" #include "utilities.hpp" namespace Asteria { Statement::~Statement() { } namespace { void do_safe_set_named_reference(Abstract_context &ctx_io, const char *desc, const String &name, Reference ref) { if(name.empty()) { return; } if(ctx_io.is_name_reserved(name)) { ASTERIA_THROW_RUNTIME_ERROR("The name `", name, "` of this ", desc, " is reserved and cannot be used."); } ctx_io.set_named_reference(name, std::move(ref)); } } void Statement::fly_over_in_place(Abstract_context &ctx_io) const { switch(Index(this->m_stor.index())) { case index_expr: case index_block: { return; } case index_var_def: { const auto &alt = this->m_stor.as<S_var_def>(); // Create a dummy reference for further name lookups. do_safe_set_named_reference(ctx_io, "skipped variable", alt.name, { }); return; } case index_func_def: { const auto &alt = this->m_stor.as<S_func_def>(); // Create a dummy reference for further name lookups. do_safe_set_named_reference(ctx_io, "skipped function", alt.head.get_func(), { }); return; } case index_if: case index_switch: case index_do_while: case index_while: case index_for: case index_for_each: case index_try: case index_break: case index_continue: case index_throw: case index_return: { break; } default: { ASTERIA_TERMINATE("An unknown statement type enumeration `", this->m_stor.index(), "` has been encountered."); } } } Statement Statement::bind_in_place(Analytic_context &ctx_io, const Global_context &global) const { switch(Index(this->m_stor.index())) { case index_expr: { const auto &alt = this->m_stor.as<S_expr>(); // Bind the expression recursively. auto expr_bnd = alt.expr.bind(global, ctx_io); Statement::S_expr alt_bnd = { std::move(expr_bnd) }; return std::move(alt_bnd); } case index_block: { const auto &alt = this->m_stor.as<S_block>(); // Bind the body recursively. auto body_bnd = alt.body.bind(global, ctx_io); Statement::S_block alt_bnd = { std::move(body_bnd) }; return std::move(alt_bnd); } case index_var_def: { const auto &alt = this->m_stor.as<S_var_def>(); // Create a dummy reference for further name lookups. do_safe_set_named_reference(ctx_io, "variable", alt.name, { }); // Bind the initializer recursively. auto init_bnd = alt.init.bind(global, ctx_io); Statement::S_var_def alt_bnd = { alt.name, alt.immutable, std::move(init_bnd) }; return std::move(alt_bnd); } case index_func_def: { const auto &alt = this->m_stor.as<S_func_def>(); // Create a dummy reference for further name lookups. do_safe_set_named_reference(ctx_io, "function", alt.head.get_func(), { }); // Bind the function body recursively. Analytic_context ctx_next(&ctx_io); ctx_next.initialize_for_function(alt.head); auto body_bnd = alt.body.bind_in_place(ctx_next, global); Statement::S_func_def alt_bnd = { alt.head, std::move(body_bnd) }; return std::move(alt_bnd); } case index_if: { const auto &alt = this->m_stor.as<S_if>(); // Bind the condition and both branches recursively. auto cond_bnd = alt.cond.bind(global, ctx_io); auto branch_true_bnd = alt.branch_true.bind(global, ctx_io); auto branch_false_bnd = alt.branch_false.bind(global, ctx_io); Statement::S_if alt_bnd = { std::move(cond_bnd), std::move(branch_true_bnd), std::move(branch_false_bnd) }; return std::move(alt_bnd); } case index_switch: { const auto &alt = this->m_stor.as<S_switch>(); // Bind the control expression and all clauses recursively. auto ctrl_bnd = alt.ctrl.bind(global, ctx_io); // Note that all `switch` clauses share the same context. Analytic_context ctx_next(&ctx_io); Bivector<Expression, Block> clauses_bnd; clauses_bnd.reserve(alt.clauses.size()); for(const auto &pair : alt.clauses) { auto first_bnd = pair.first.bind(global, ctx_next); auto second_bnd = pair.second.bind_in_place(ctx_next, global); clauses_bnd.emplace_back(std::move(first_bnd), std::move(second_bnd)); } Statement::S_switch alt_bnd = { std::move(ctrl_bnd), std::move(clauses_bnd) }; return std::move(alt_bnd); } case index_do_while: { const auto &alt = this->m_stor.as<S_do_while>(); // Bind the loop body and condition recursively. auto body_bnd = alt.body.bind(global, ctx_io); auto cond_bnd = alt.cond.bind(global, ctx_io); Statement::S_do_while alt_bnd = { std::move(body_bnd), std::move(cond_bnd) }; return std::move(alt_bnd); } case index_while: { const auto &alt = this->m_stor.as<S_while>(); // Bind the condition and loop body recursively. auto cond_bnd = alt.cond.bind(global, ctx_io); auto body_bnd = alt.body.bind(global, ctx_io); Statement::S_while alt_bnd = { std::move(cond_bnd), std::move(body_bnd) }; return std::move(alt_bnd); } case index_for: { const auto &alt = this->m_stor.as<S_for>(); // If the initialization part is a variable definition, the variable defined shall not outlast the loop body. Analytic_context ctx_next(&ctx_io); // Bind the loop initializer, condition, step expression and loop body recursively. auto init_bnd = alt.init.bind(global, ctx_next); auto cond_bnd = alt.cond.bind(global, ctx_next); auto step_bnd = alt.step.bind(global, ctx_next); auto body_bnd = alt.body.bind(global, ctx_next); Statement::S_for alt_bnd = { std::move(init_bnd), std::move(cond_bnd), std::move(step_bnd), std::move(body_bnd) }; return std::move(alt_bnd); } case index_for_each: { const auto &alt = this->m_stor.as<S_for_each>(); // The key and mapped variables shall not outlast the loop body. Analytic_context ctx_next(&ctx_io); do_safe_set_named_reference(ctx_next, "`for each` key", alt.key_name, { }); do_safe_set_named_reference(ctx_next, "`for each` reference", alt.mapped_name, { }); // Bind the range initializer and loop body recursively. auto init_bnd = alt.init.bind(global, ctx_next); auto body_bnd = alt.body.bind(global, ctx_next); Statement::S_for_each alt_bnd = { alt.key_name, alt.mapped_name, std::move(init_bnd), std::move(body_bnd) }; return std::move(alt_bnd); } case index_try: { const auto &alt = this->m_stor.as<S_try>(); // The `try` branch needs no special treatement. auto body_try_bnd = alt.body_try.bind(global, ctx_io); // The exception variable shall not outlast the `catch` body. Analytic_context ctx_next(&ctx_io); do_safe_set_named_reference(ctx_next, "exception", alt.except_name, { }); // Bind the `catch` branch recursively. auto body_catch_bnd = alt.body_catch.bind_in_place(ctx_next, global); Statement::S_try alt_bnd = { std::move(body_try_bnd), alt.except_name, std::move(body_catch_bnd) }; return std::move(alt_bnd); } case index_break: { const auto &alt = this->m_stor.as<S_break>(); // Copy it as-is. Statement::S_break alt_bnd = { alt.target }; return std::move(alt_bnd); } case index_continue: { const auto &alt = this->m_stor.as<S_continue>(); // Copy it as-is. Statement::S_continue alt_bnd = { alt.target }; return std::move(alt_bnd); } case index_throw: { const auto &alt = this->m_stor.as<S_throw>(); // Bind the exception initializer recursively. auto expr_bnd = alt.expr.bind(global, ctx_io); Statement::S_throw alt_bnd = { alt.loc, std::move(expr_bnd) }; return std::move(alt_bnd); } case index_return: { const auto &alt = this->m_stor.as<S_return>(); // Bind the result initializer recursively. auto expr_bnd = alt.expr.bind(global, ctx_io); Statement::S_return alt_bnd = { alt.by_ref, std::move(expr_bnd) }; return std::move(alt_bnd); } default: { ASTERIA_TERMINATE("An unknown statement type enumeration `", this->m_stor.index(), "` has been encountered."); } } } Block::Status Statement::execute_in_place(Reference &ref_out, Executive_context &ctx_io, Global_context &global) const { switch(Index(this->m_stor.index())) { case index_expr: { const auto &alt = this->m_stor.as<S_expr>(); // Evaluate the expression. ref_out = alt.expr.evaluate(global, ctx_io); return Block::status_next; } case index_block: { const auto &alt = this->m_stor.as<S_block>(); // Execute the body. return alt.body.execute(ref_out, global, ctx_io); } case index_var_def: { const auto &alt = this->m_stor.as<S_var_def>(); // Create a dummy reference for further name lookups. // A variable becomes visible before its initializer, where it is initialized to `null`. const auto var = global.create_tracked_variable(); Reference_root::S_variable ref_c = { var }; do_safe_set_named_reference(ctx_io, "variable", alt.name, std::move(ref_c)); // Create a variable using the initializer. ref_out = alt.init.evaluate(global, ctx_io); auto value = ref_out.read(); ASTERIA_DEBUG_LOG("Creating named variable: name = ", alt.name, ", immutable = ", alt.immutable, ": ", value); var->reset(std::move(value), alt.immutable); return Block::status_next; } case index_func_def: { const auto &alt = this->m_stor.as<S_func_def>(); // Create a dummy reference for further name lookups. // A function becomes visible before its definition, where it is initialized to `null`. const auto var = global.create_tracked_variable(); Reference_root::S_variable ref_c = { var }; do_safe_set_named_reference(ctx_io, "function", alt.head.get_func(), std::move(ref_c)); // Instantiate the function here. auto func = alt.body.instantiate_function(global, ctx_io, alt.head); ASTERIA_DEBUG_LOG("Creating named function: prototype = ", alt.head, ", location = ", alt.head.get_location()); var->reset(D_function(std::move(func)), true); return Block::status_next; } case index_if: { const auto &alt = this->m_stor.as<S_if>(); // Evaluate the condition and pick a branch. ref_out = alt.cond.evaluate(global, ctx_io); const auto status = (ref_out.read().test() ? alt.branch_true : alt.branch_false).execute(ref_out, global, ctx_io); if(status != Block::status_next) { // Forward anything unexpected to the caller. return status; } return Block::status_next; } case index_switch: { const auto &alt = this->m_stor.as<S_switch>(); // Evaluate the control expression. ref_out = alt.ctrl.evaluate(global, ctx_io); const auto value_ctrl = ref_out.read(); // Note that all `switch` clauses share the same context. // We will iterate from the first clause to the last one. If a `default` clause is encountered in the middle // and there is no match `case` clause, we will have to jump back into half of the scope. To simplify design, // a nested scope is created when a `default` clause is encountered. When jumping to the `default` scope, we // simply discard the new scope. Executive_context ctx_first(&ctx_io); Executive_context ctx_second(&ctx_first); auto ctx_next = std::ref(ctx_first); // There is a 'match' at the end of the clause array initially. auto match = alt.clauses.end(); // This is a pointer to where new references are created. auto ctx_test = ctx_next; for(auto it = alt.clauses.begin(); it != alt.clauses.end(); ++it) { if(it->first.empty()) { // This is a `default` clause. if(match != alt.clauses.end()) { ASTERIA_THROW_RUNTIME_ERROR("Multiple `default` clauses exist in the same `switch` statement."); } // From now on, all declarations go into the second context. match = it; ctx_test = std::ref(ctx_second); } else { // This is a `case` clause. ref_out = it->first.evaluate(global, ctx_next); const auto value_comp = ref_out.read(); if(value_ctrl.compare(value_comp) == Value::compare_equal) { // If this is a match, we resume from wherever `ctx_test` is pointing. match = it; ctx_next = ctx_test; break; } } // Create null references for declarations in the clause skipped. it->second.fly_over_in_place(ctx_test); } // Iterate from the match clause to the end of the body, falling through clause boundaries if any. for(auto it = match; it != alt.clauses.end(); ++it) { const auto status = it->second.execute_in_place(ref_out, ctx_next, global); if(rocket::is_any_of(status, { Block::status_break_unspec, Block::status_break_switch })) { // Break out of the body as requested. break; } if(status != Block::status_next) { // Forward anything unexpected to the caller. return status; } } return Block::status_next; } case index_do_while: { const auto &alt = this->m_stor.as<S_do_while>(); for(;;) { // Execute the loop body. Executive_context ctx_next(&ctx_io); const auto status = alt.body.execute_in_place(ref_out, ctx_next, global); if(rocket::is_any_of(status, { Block::status_break_unspec, Block::status_break_while })) { // Break out of the body as requested. break; } if(rocket::is_none_of(status, { Block::status_next, Block::status_continue_unspec, Block::status_continue_while })) { // Forward anything unexpected to the caller. return status; } // Check the loop condition. // This differs from a `while` loop where the context for the loop body is destroyed before this check. ref_out = alt.cond.evaluate(global, ctx_next); if(!ref_out.read().test()) { break; } } return Block::status_next; } case index_while: { const auto &alt = this->m_stor.as<S_while>(); for(;;) { // Check the loop condition. ref_out = alt.cond.evaluate(global, ctx_io); if(!ref_out.read().test()) { break; } // Execute the loop body. const auto status = alt.body.execute(ref_out, global, ctx_io); if(rocket::is_any_of(status, { Block::status_break_unspec, Block::status_break_while })) { // Break out of the body as requested. break; } if(rocket::is_none_of(status, { Block::status_next, Block::status_continue_unspec, Block::status_continue_while })) { // Forward anything unexpected to the caller. return status; } } return Block::status_next; } case index_for: { const auto &alt = this->m_stor.as<S_for>(); // If the initialization part is a variable definition, the variable defined shall not outlast the loop body. Executive_context ctx_next(&ctx_io); // Execute the initializer. The status is ignored. ASTERIA_DEBUG_LOG("Begin running `for` initialization..."); alt.init.execute_in_place(ref_out, ctx_next, global); ASTERIA_DEBUG_LOG("Done running `for` initialization: ", ref_out.read()); for(;;) { // Check the loop condition. if(!alt.cond.empty()) { ref_out = alt.cond.evaluate(global, ctx_next); if(!ref_out.read().test()) { break; } } // Execute the loop body. const auto status = alt.body.execute(ref_out, global, ctx_next); if(rocket::is_any_of(status, { Block::status_break_unspec, Block::status_break_for })) { // Break out of the body as requested. break; } if(rocket::is_none_of(status, { Block::status_next, Block::status_continue_unspec, Block::status_continue_for })) { // Forward anything unexpected to the caller. return status; } // Evaluate the loop step expression. alt.step.evaluate(global, ctx_next); } return Block::status_next; } case index_for_each: { const auto &alt = this->m_stor.as<S_for_each>(); // The key and mapped variables shall not outlast the loop body. Executive_context ctx_for(&ctx_io); // A variable becomes visible before its initializer, where it is initialized to `null`. do_safe_set_named_reference(ctx_for, "`for each` key", alt.key_name, { }); do_safe_set_named_reference(ctx_for, "`for each` reference", alt.mapped_name, { }); // Calculate the range using the initializer. auto mapped = alt.init.evaluate(global, ctx_for); const auto range_value = mapped.read(); switch(rocket::weaken_enum(range_value.type())) { case Value::type_array: { const auto &array = range_value.check<D_array>(); for(auto it = array.begin(); it != array.end(); ++it) { Executive_context ctx_next(&ctx_for); // Initialize the per-loop key constant. auto key = D_integer(it - array.begin()); ASTERIA_DEBUG_LOG("Creating key constant with `for each` scope: name = ", alt.key_name, ": ", key); Reference_root::S_constant ref_c = { std::move(key) }; do_safe_set_named_reference(ctx_for, "`for each` key", alt.key_name, std::move(ref_c)); // Initialize the per-loop value reference. Reference_modifier::S_array_index refmod_c = { it - array.begin() }; mapped.zoom_in(std::move(refmod_c)); do_safe_set_named_reference(ctx_for, "`for each` reference", alt.mapped_name, mapped); ASTERIA_DEBUG_LOG("Created value reference with `for each` scope: name = ", alt.mapped_name, ": ", mapped.read()); mapped.zoom_out(); // Execute the loop body. const auto status = alt.body.execute_in_place(ref_out, ctx_next, global); if(rocket::is_any_of(status, { Block::status_break_unspec, Block::status_break_for })) { // Break out of the body as requested. break; } if(rocket::is_none_of(status, { Block::status_next, Block::status_continue_unspec, Block::status_continue_for })) { // Forward anything unexpected to the caller. return status; } } break; } case Value::type_object: { const auto &object = range_value.check<D_object>(); for(auto it = object.begin(); it != object.end(); ++it) { Executive_context ctx_next(&ctx_for); // Initialize the per-loop key constant. auto key = D_string(it->first); ASTERIA_DEBUG_LOG("Creating key constant with `for each` scope: name = ", alt.key_name, ": ", key); Reference_root::S_constant ref_c = { std::move(key) }; do_safe_set_named_reference(ctx_for, "`for each` key", alt.key_name, std::move(ref_c)); // Initialize the per-loop value reference. Reference_modifier::S_object_key refmod_c = { it->first }; mapped.zoom_in(std::move(refmod_c)); do_safe_set_named_reference(ctx_for, "`for each` reference", alt.mapped_name, mapped); ASTERIA_DEBUG_LOG("Created value reference with `for each` scope: name = ", alt.mapped_name, ": ", mapped.read()); mapped.zoom_out(); // Execute the loop body. const auto status = alt.body.execute_in_place(ref_out, ctx_next, global); if(rocket::is_any_of(status, { Block::status_break_unspec, Block::status_break_for })) { // Break out of the body as requested. break; } if(rocket::is_none_of(status, { Block::status_next, Block::status_continue_unspec, Block::status_continue_for })) { // Forward anything unexpected to the caller. return status; } } break; } default: { ASTERIA_THROW_RUNTIME_ERROR("The `for each` statement does not accept a range of type `", Value::get_type_name(range_value.type()), "`."); } } return Block::status_next; } case index_try: { const auto &alt = this->m_stor.as<S_try>(); try { // Execute the `try` body. // This is straightforward and hopefully zero-cost if no exception is thrown. const auto status = alt.body_try.execute(ref_out, global, ctx_io); if(status != Block::status_next) { // Forward anything unexpected to the caller. return status; } } catch(std::exception &stdex) { // Prepare the backtrace as an `array` for processing by code inside `catch`. D_array backtrace; const auto push_backtrace = [&](const Source_location &loc) { D_object elem; elem.insert_or_assign(String::shallow("file"), D_string(loc.get_file())); elem.insert_or_assign(String::shallow("line"), D_integer(loc.get_line())); backtrace.emplace_back(std::move(elem)); }; // The exception variable shall not outlast the `catch` body. Executive_context ctx_next(&ctx_io); try { // Translate the exception as needed. throw; } catch(Exception &except) { // Handle an `Asteria::Exception`. ASTERIA_DEBUG_LOG("Creating exception reference with `catch` scope: name = ", alt.except_name, ": ", except.get_value()); Reference_root::S_temporary ref_c = { except.get_value() }; do_safe_set_named_reference(ctx_next, "exception", alt.except_name, std::move(ref_c)); // Unpack the backtrace array. backtrace.reserve(1 + except.get_backtrace().size()); push_backtrace(except.get_location()); std::for_each(except.get_backtrace().begin(), except.get_backtrace().end(), push_backtrace); } catch(...) { // Handle an `std::exception`. ASTERIA_DEBUG_LOG("Creating exception reference with `catch` scope: name = ", alt.except_name, ": ", stdex.what()); Reference_root::S_temporary ref_c = { D_string(stdex.what()) }; do_safe_set_named_reference(ctx_next, "exception", alt.except_name, std::move(ref_c)); // We say the exception was thrown from native code. push_backtrace(Exception(stdex).get_location()); } ASTERIA_DEBUG_LOG("Exception backtrace:\n", Value(backtrace)); Reference_root::S_temporary ref_c = { std::move(backtrace) }; ctx_next.set_named_reference(String::shallow("__backtrace"), std::move(ref_c)); // Execute the `catch` body. const auto status = alt.body_catch.execute(ref_out, global, ctx_next); if(status != Block::status_next) { // Forward anything unexpected to the caller. return status; } } return Block::status_next; } case index_break: { const auto &alt = this->m_stor.as<S_break>(); switch(rocket::weaken_enum(alt.target)) { case Statement::target_switch: { return Block::status_break_switch; } case Statement::target_while: { return Block::status_break_while; } case Statement::target_for: { return Block::status_break_for; } } return Block::status_break_unspec; } case index_continue: { const auto &alt = this->m_stor.as<S_continue>(); switch(rocket::weaken_enum(alt.target)) { case Statement::target_switch: { ASTERIA_TERMINATE("`target_switch` is not allowed to follow `continue`."); } case Statement::target_while: { return Block::status_continue_while; } case Statement::target_for: { return Block::status_continue_for; } } return Block::status_continue_unspec; } case index_throw: { const auto &alt = this->m_stor.as<S_throw>(); // Evaluate the expression. ref_out = alt.expr.evaluate(global, ctx_io); auto value = ref_out.read(); ASTERIA_DEBUG_LOG("Throwing exception: ", value); throw Exception(alt.loc, std::move(value)); } case index_return: { const auto &alt = this->m_stor.as<S_return>(); // Evaluate the expression. ref_out = alt.expr.evaluate(global, ctx_io); // If `by_ref` is `false`, replace it with a temporary value. if(!alt.by_ref) { ref_out.convert_to_temporary(); } return Block::status_return; } default: { ASTERIA_TERMINATE("An unknown statement type enumeration `", this->m_stor.index(), "` has been encountered."); } } } void Statement::enumerate_variables(const Abstract_variable_callback &callback) const { switch(Index(this->m_stor.index())) { case index_expr: { const auto &alt = this->m_stor.as<S_expr>(); alt.expr.enumerate_variables(callback); return; } case index_block: { const auto &alt = this->m_stor.as<S_block>(); alt.body.enumerate_variables(callback); return; } case index_var_def: { const auto &alt = this->m_stor.as<S_var_def>(); alt.init.enumerate_variables(callback); return; } case index_func_def: { const auto &alt = this->m_stor.as<S_func_def>(); alt.body.enumerate_variables(callback); return; } case index_if: { const auto &alt = this->m_stor.as<S_if>(); alt.cond.enumerate_variables(callback); alt.branch_true.enumerate_variables(callback); alt.branch_false.enumerate_variables(callback); return; } case index_switch: { const auto &alt = this->m_stor.as<S_switch>(); alt.ctrl.enumerate_variables(callback); for(const auto &pair : alt.clauses) { pair.first.enumerate_variables(callback); pair.second.enumerate_variables(callback); } return; } case index_do_while: { const auto &alt = this->m_stor.as<S_do_while>(); alt.body.enumerate_variables(callback); alt.cond.enumerate_variables(callback); return; } case index_while: { const auto &alt = this->m_stor.as<S_while>(); alt.cond.enumerate_variables(callback); alt.body.enumerate_variables(callback); return; } case index_for: { const auto &alt = this->m_stor.as<S_for>(); alt.init.enumerate_variables(callback); alt.cond.enumerate_variables(callback); alt.step.enumerate_variables(callback); alt.body.enumerate_variables(callback); return; } case index_for_each: { const auto &alt = this->m_stor.as<S_for_each>(); alt.init.enumerate_variables(callback); alt.body.enumerate_variables(callback); return; } case index_try: { const auto &alt = this->m_stor.as<S_try>(); alt.body_try.enumerate_variables(callback); alt.body_catch.enumerate_variables(callback); return; } case index_break: case index_continue: { return; } case index_throw: { const auto &alt = this->m_stor.as<S_throw>(); alt.expr.enumerate_variables(callback); return; } case index_return: { const auto &alt = this->m_stor.as<S_return>(); alt.expr.enumerate_variables(callback); return; } default: { ASTERIA_TERMINATE("An unknown statement type enumeration `", this->m_stor.index(), "` has been encountered."); } } } }
43.897778
150
0.604873
[ "object" ]
f9b404c696c6a7633dda4df916b2d5aeb1ead2da
4,756
cpp
C++
src/engine/scene/lights/SpotLight.cpp
kosua20/GL_Template
ba0dcf3c041389a333f6c21e674d1ddfea5e0a99
[ "MIT" ]
108
2016-11-15T20:27:46.000Z
2019-05-22T01:09:58.000Z
src/engine/scene/lights/SpotLight.cpp
kosua20/GL_Template
ba0dcf3c041389a333f6c21e674d1ddfea5e0a99
[ "MIT" ]
1
2016-10-14T22:58:21.000Z
2016-11-14T10:46:02.000Z
src/engine/scene/lights/SpotLight.cpp
kosua20/GL_Template
ba0dcf3c041389a333f6c21e674d1ddfea5e0a99
[ "MIT" ]
7
2017-08-05T21:44:36.000Z
2019-02-22T02:48:25.000Z
#include "scene/lights/SpotLight.hpp" #include "graphics/GPU.hpp" #include "resources/Bounds.hpp" SpotLight::SpotLight(const glm::vec3 & worldPosition, const glm::vec3 & worldDirection, const glm::vec3 & color, float innerAngle, float outerAngle, float radius) : Light(color), _lightDirection(glm::normalize(worldDirection)), _lightPosition(worldPosition), _angles(0.5f * innerAngle, 0.5f * outerAngle), _radius(radius) { } void SpotLight::draw(LightRenderer & renderer) { renderer.draw(this); } void SpotLight::update(double fullTime, double frameTime) { glm::vec4 position = glm::vec4(_lightPosition.get(), 1.0f); glm::vec4 direction = glm::vec4(_lightDirection.get(), 0.0f); for(auto & anim : _animations) { position = anim->apply(position, fullTime, frameTime); direction = anim->apply(direction, fullTime, frameTime); } _lightPosition = glm::vec3(position); _lightDirection = glm::normalize(glm::vec3(direction)); setScene(_sceneBox); } void SpotLight::setScene(const BoundingBox & sceneBox) { _sceneBox = sceneBox; _viewMatrix = glm::lookAt(_lightPosition.get(), _lightPosition.get() + _lightDirection.get(), glm::vec3(0.0f, 1.0f, 0.0f)); // Compute the projection matrix, automatically finding the near and far. float near; float far; if(_sceneBox.contains(_lightPosition)) { const float size = glm::length(_sceneBox.getSize()); near = 0.01f * size; far = 1.0f * size; } else { const BoundingBox lightSpacebox = _sceneBox.transformed(_viewMatrix); const float absz1 = std::abs(lightSpacebox.minis[2]); const float absz2 = std::abs(lightSpacebox.maxis[2]); near = std::min(absz1, absz2); far = std::max(absz1, absz2); } _projectionMatrix = Frustum::perspective(2.0f * _angles.y, 1.0f, near, far); _vp = _projectionMatrix * _viewMatrix; // Compute the model matrix to scale the cone based on the outer angle and the radius. const float width = 2.0f * std::tan(_angles.y); _model = glm::inverse(_viewMatrix) * glm::scale(glm::mat4(1.0f), _radius * glm::vec3(width, width, 1.0f)); } glm::vec3 SpotLight::sample(const glm::vec3 & position, float & dist, float & attenuation) const { glm::vec3 direction = _lightPosition.get() - position; dist = glm::length(direction); attenuation = 0.0f; // Early exit if we are outside the sphere of influence. if(dist > _radius) { return {}; } if(dist > 0.0f) { direction /= dist; } // Compute the angle between the light direction and the (light, surface point) vector. const float currentCos = glm::dot(-direction, _lightDirection.get()); const float outerCos = std::cos(_angles.y); // If we are outside the spotlight cone, no lighting. if(currentCos < std::cos(outerCos)) { return {}; } // Compute the spotlight attenuation factor based on our angle compared to the inner and outer spotlight angles. const float innerCos = std::cos(_angles.x); const float angleAttenuation = glm::clamp((currentCos - outerCos) / (innerCos - outerCos), 0.0f, 1.0f); // Attenuation with increasing distance to the light. const float radiusRatio = dist / _radius; const float radiusRatio2 = radiusRatio * radiusRatio; const float attenNum = glm::clamp(1.0f - radiusRatio2, 0.0f, 1.0f); attenuation = angleAttenuation * attenNum * attenNum; return direction; } bool SpotLight::decode(const KeyValues & params) { bool success = Light::decodeBase(params); for(const auto & param : params.elements) { if(param.key == "direction") { const glm::vec3 newDir = Codable::decodeVec3(param); if(newDir == glm::vec3(0.0f)){ Log::Error() << "Invalid light direction." << std::endl; return false; } _lightDirection.reset(glm::normalize(newDir)); } else if(param.key == "position") { _lightPosition.reset(Codable::decodeVec3(param)); } else if(param.key == "cone" && param.values.size() >= 2) { const float innerAngle = std::stof(param.values[0]); const float outerAngle = std::stof(param.values[1]); _angles = 0.5f * glm::vec2(innerAngle, outerAngle); } else if(param.key == "radius" && !param.values.empty()) { _radius = std::stof(param.values[0]); } } return success; } KeyValues SpotLight::encode() const { KeyValues light = Light::encode(); light.key = "spot"; light.elements.emplace_back("position"); light.elements.back().values = Codable::encode(_lightPosition.initial()); light.elements.emplace_back("direction"); light.elements.back().values = Codable::encode(_lightDirection.initial()); light.elements.emplace_back("radius"); light.elements.back().values = { std::to_string(_radius) }; light.elements.emplace_back("cone"); light.elements.back().values = { std::to_string(_angles[0] * 2.0f), std::to_string(_angles[1] * 2.0f) }; return light; }
38.983607
164
0.701009
[ "vector", "model" ]
f9bfe706ec3643f2131310994865d3da3620361a
1,092
cpp
C++
sorts/odd_even_sort/main.cpp
Kingcitaldo125/Sorts
ce6d60359497490e982640de39370d56d4f17eba
[ "Apache-2.0" ]
null
null
null
sorts/odd_even_sort/main.cpp
Kingcitaldo125/Sorts
ce6d60359497490e982640de39370d56d4f17eba
[ "Apache-2.0" ]
5
2021-12-21T13:08:27.000Z
2022-01-17T14:37:41.000Z
sorts/odd_even_sort/main.cpp
Kingcitaldo125/Sorts
ce6d60359497490e982640de39370d56d4f17eba
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> #include "SortUtils.hpp" void odd_even_sort(std::vector<int>::iterator begin, std::vector<int>::iterator end) { bool swap = true; while (swap) { swap = false; for (auto i = begin; i < end - 1; i += 2) { const auto second = i + 1; if (*i > *second) { std::iter_swap(i, second); swap = true; } } for (auto i = begin + 1; i < end - 1; i += 2) { const auto second = i + 1; if (*i > *second) { std::iter_swap(i, second); swap = true; } } } } int main() { std::vector<int> mints{10, 67, 44, 48, 23, 5, 18, 24, 53, 48, 17, 47, 67, 37, 83, 77, 57, 2, 49, 92, 27, 28, 67, 98, 90, 26, 99, 32, 3, 57, 40, 98, 97, 38, 81, 11, 3, 85, 61, 10, 17, 11, 70, 1, 58, 10, 36, 76, 66, 35}; odd_even_sort(mints.begin(), mints.end()); SortUtils::print_vector(mints); SortUtils::print_sorted<int>(mints.begin(), mints.end(), "mints"); return 0; }
25.395349
76
0.489927
[ "vector" ]
f9c43d28b1cadb7c4d7529b5076e83c491b06e2f
1,980
cpp
C++
src/differentiation/differentiation.cpp
rvillegasm/Numalizer
3903d070b168cf184cc14a6fb2b8368f82448634
[ "MIT" ]
3
2019-11-28T01:14:27.000Z
2020-12-29T12:55:19.000Z
src/differentiation/differentiation.cpp
rvillegasm/Numalizer
3903d070b168cf184cc14a6fb2b8368f82448634
[ "MIT" ]
null
null
null
src/differentiation/differentiation.cpp
rvillegasm/Numalizer
3903d070b168cf184cc14a6fb2b8368f82448634
[ "MIT" ]
4
2019-08-29T04:23:31.000Z
2020-01-25T20:40:14.000Z
#include "differentiation.h" #include "../../lib/point.h" #include "../../lib/exceptions.h" #include <vector> #include <iostream> /** * x, y lista de x y f(x) * direction 0=backwards, 1=forward, 2 = central */ namespace numath{ namespace differentiation{ double differentiation( std::vector<Point> &points, int direction, double h, int num ){ if(num==2){ //Two points return (points[1].y-points[0].y)/h; }else if(num==3){ //Uses the first three points if(direction==0){ // Three points backwards return (points[0].y-4*points[1].y+3*points[2].y)/(2*h); }else if (direction==1){ // Three points forward return (-points[2].y+4*points[1].y-3*points[0].y)/(2*h); }else if(direction ==2){ // Three points center return (-points[0].y+points[2].y)/(2*h); }else{ throw MethodException(); } }else if(num==5){ //Uses the first five points if(direction==0){ // Five points backwards return ((25*points[4].y)-(48*points[3].y)+(36*points[2].y)-(16*points[1].y)+(3*points[0].y))/(12*h); }else if (direction==1){ // Five points forward return (-25*points[0].y+48*points[1].y-36*points[2].y+16*points[3].y-3*points[4].y)/(12*h); }else if(direction ==2){ // Five points center return (points[0].y-8*points[1].y+8*points[3].y-points[4].y)/(12*h); }else{ throw MethodException(); } }else{ throw MethodException(); } } } }
38.823529
121
0.435354
[ "vector" ]
f9c46481cd325df1280a070186ccb91601569155
866
cpp
C++
src/39.cpp
dxscjx123/SwordOffer
e04958beb3f99c103f879b09f3da547679a208c4
[ "MIT" ]
3
2018-04-20T14:07:14.000Z
2019-08-29T14:35:30.000Z
src/39.cpp
dxscjx123/SwordOffer
e04958beb3f99c103f879b09f3da547679a208c4
[ "MIT" ]
null
null
null
src/39.cpp
dxscjx123/SwordOffer
e04958beb3f99c103f879b09f3da547679a208c4
[ "MIT" ]
null
null
null
// 分析: // 由于数组是递增有序的,定义头指针和尾指针。头+尾>num,尾后移,头+尾<num, // 头前移。找到满足条件的元素,判断乘积大小是否进一步满足条件,更新结果。 class Solution { public: vector<int> FindNumbersWithSum(vector<int> array,int sum) { if (array.empty()) return vector<int>(); int start = 0; int end = array.size() - 1; int head, tail; int cursum = 0; int product = INT_MAX; bool found = false; while (start < end) { head = array[start]; tail = array[end]; cursum = head + tail; if (cursum == sum) { int tmp_pro = head * tail; found = true; if (tmp_pro < product) { first = head; second = tail; product = tmp_pro; } start++; end--; } else if (cursum > sum) end--; else start++; } if (found) result = {first, second}; return result; } private: int first, second; vector<int> result; };
16.980392
63
0.556582
[ "vector" ]
f9c4b8a82c668272700b7b3514361c8c9a9b2b19
1,249
hpp
C++
module-audio/Audio/test/MockEndpoint.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
369
2021-11-10T09:20:29.000Z
2022-03-30T06:36:58.000Z
module-audio/Audio/test/MockEndpoint.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
149
2021-11-10T08:38:35.000Z
2022-03-31T23:01:52.000Z
module-audio/Audio/test/MockEndpoint.hpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
41
2021-11-10T08:30:37.000Z
2022-03-29T08:12:46.000Z
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #pragma once #include <Audio/Endpoint.hpp> #include <gmock/gmock.h> namespace testing::audio { class MockSink : public ::audio::Sink { public: MOCK_METHOD(::audio::Endpoint::Traits, getTraits, (), (const, override)); MOCK_METHOD(std::vector<::audio::AudioFormat>, getSupportedFormats, (), (override)); MOCK_METHOD(::audio::AudioFormat, getSinkFormat, (), (override)); MOCK_METHOD(void, onDataSend, (), (override)); MOCK_METHOD(void, enableOutput, (), (override)); MOCK_METHOD(void, disableOutput, (), (override)); }; class MockSource : public ::audio::Source { public: MOCK_METHOD(::audio::Endpoint::Traits, getTraits, (), (const, override)); MOCK_METHOD(std::vector<::audio::AudioFormat>, getSupportedFormats, (), (override)); MOCK_METHOD(::audio::AudioFormat, getSourceFormat, (), (override)); MOCK_METHOD(void, onDataReceive, (), (override)); MOCK_METHOD(void, enableInput, (), (override)); MOCK_METHOD(void, disableInput, (), (override)); }; } // namespace testing::audio
35.685714
92
0.640512
[ "vector" ]
f9c91577bed18c31232fb44099d778007ad470d3
22,987
cpp
C++
src/assoc.cpp
njau-sri/rtm-gwas-assoc
db8d8ce2803e119e1034240a460c102ddf442a8a
[ "MIT" ]
null
null
null
src/assoc.cpp
njau-sri/rtm-gwas-assoc
db8d8ce2803e119e1034240a460c102ddf442a8a
[ "MIT" ]
null
null
null
src/assoc.cpp
njau-sri/rtm-gwas-assoc
db8d8ce2803e119e1034240a460c102ddf442a8a
[ "MIT" ]
null
null
null
#include <cmath> #include <fstream> #include <iostream> #include <functional> #include "version.h" #include "cmdline.h" #include "util.h" #include "vcf.h" #include "pheno.h" #include "statsutil.h" #include "lsfit.h" #include "stepreg.h" #include "anova.h" using std::ptrdiff_t; using std::size_t; namespace { struct Parameter { std::string vcf; std::string pheno; std::string covar; std::string out; double rsq = 0.95; double alpha = 0.01; double preselect = 0.05; int mtc = 0; bool nogxe = false; bool openmp = false; } par ; void filter_ind(const std::vector<size_t> &idx, Phenotype &pt) { subset(pt.ind,idx).swap(pt.ind); if ( ! pt.env.empty() ) subset(pt.env,idx).swap(pt.env); if ( ! pt.blk.empty() ) subset(pt.blk,idx).swap(pt.blk); for (auto &e : pt.dat) subset(e,idx).swap(e); } void filter_ind(const std::vector<size_t> &idx, Covariate &ct) { subset(ct.ind,idx).swap(ct.ind); for (auto &e : ct.dat) subset(e,idx).swap(e); } void merge(Genotype &gt, Phenotype &pt, Covariate &ct, std::vector<size_t> &gi) { bool docovar = ! ct.phe.empty() && ! ct.ind.empty(); bool domerge = gt.ind != pt.ind; if ( ! domerge && docovar ) domerge = gt.ind != ct.ind; if ( ! domerge ) { gi.resize(gt.ind.size()); std::iota(gi.begin(), gi.end(), 0); return; } std::cerr << "INFO: performing data intersection by individual...\n"; auto ind = intersect(gt.ind, pt.ind); if ( docovar ) ind = intersect(ind, ct.ind); gi.clear(); std::vector<size_t> pi, ci; size_t n = pt.ind.size(); for (size_t i = 0; i < n; ++i) { if ( std::binary_search(ind.begin(), ind.end(), pt.ind[i]) ) { pi.push_back(i); gi.push_back( index(gt.ind, pt.ind[i]) ); if ( docovar ) ci.push_back( index(ct.ind, pt.ind[i]) ); } } filter_ind(pi, pt); if ( docovar ) filter_ind(ci, ct); std::cerr << "INFO: there are " << ind.size() << " individuals after intersection\n"; } void parse_envblk(const Phenotype &pt, std::vector< std::vector<double> > &ac, std::vector< std::vector<double> > &ic) { std::vector< std::vector<double> > xenv, xblk; if ( ! pt.env.empty() ) { idummy1(factor(pt.env), xenv); ac.insert(ac.end(), xenv.begin(), xenv.end()); ic.insert(ic.end(), xenv.begin(), xenv.end()); } if ( ! pt.blk.empty() ) { idummy1(factor(pt.blk), xblk); if ( xenv.empty() ) ac.insert(ac.end(), xblk.begin(), xblk.end()); else { idummy3(factor(pt.env), xenv); for (auto &e : xenv) { for (auto v : xblk) { std::transform(e.begin(), e.end(), v.begin(), v.begin(), std::multiplies<double>()); ac.push_back(v); } } } } } int assoc_glm(const Genotype &gt, const std::vector<size_t> &gi, const std::vector<double> &y, const std::vector< std::vector<double> > &ac, const std::vector< std::vector<double> > &ic, std::vector< std::vector<double> > &res) { auto n = y.size(); auto m = gt.dat.size(); // modelP, modelR2, mainP, mainR2, intP, intR2 res.assign(ic.empty() ? 2 : 6, std::vector<double>(m, std::numeric_limits<double>::quiet_NaN())); double sst = calc_css(y); std::vector<double> x0(n, 1); for (auto &v : ac) x0.insert(x0.end(), v.begin(), v.end()); std::vector<double> b; double dfe0 = 0, sse0 = 0; lsfit(y, x0, b, dfe0, sse0); std::vector<allele_t> g1; std::vector< std::pair<allele_t,allele_t> > g2; std::vector<double> x, y2; for (size_t j = 0; j < m; ++j) { std::vector<size_t> idx; std::vector< std::vector<double> > x1; if (gt.ploidy == 1) { g1.clear(); for (size_t i = 0; i < n; ++i) { auto ii = gi[i]; auto a = gt.dat[j][ii]; if ( a ) { g1.push_back(a); idx.push_back(i); } } idummy2(factor(g1), x1); } else { g2.clear(); for (size_t i = 0; i < n; ++i) { auto ii = gi[i]; auto a = gt.dat[j][ii*2]; auto b = gt.dat[j][ii*2+1]; if ( a && b ) { if (a > b) std::swap(a, b); g2.emplace_back(a, b); idx.push_back(i); } } idummy2(factor(g2), x1); } if ( x1.empty() ) continue; auto n2 = idx.size(); auto jsst = sst; auto jdfe0 = dfe0; auto jsse0 = sse0; if (n2 == n) { y2 = y; x = x0; } else { y2 = subset(y, idx); jsst = calc_css(y2); x.assign(n2, 1); for (auto &e : ac) { auto z = subset(e, idx); x.insert(x.end(), z.begin(), z.end()); } lsfit(y2, x, b, jdfe0, jsse0); } for (auto &e : x1) x.insert(x.end(), e.begin(), e.end()); double jdfe1 = 0, jsse1 = 0; lsfit(y2, x, b, jdfe1, jsse1); auto dfx = jdfe0 - jdfe1; auto ssx = jsse0 - jsse1; if ( ic.empty() ) { if (dfx > 0 && ssx > 0 && jdfe1 > 0 && jsse1 > 0) { auto f = (ssx / dfx) / (jsse1 / jdfe1); res[0][j] = fpval(f, dfx, jdfe1); res[1][j] = ssx / jsst; } } else { for (auto &e : x1) { for (auto z : ic) { if (n2 != n) z = subset(z, idx); std::transform(e.begin(), e.end(), z.begin(), z.begin(), std::multiplies<double>()); x.insert(x.end(), z.begin(), z.end()); } } double jdfe2 = 0, jsse2 = 0; lsfit(y2, x, b, jdfe2, jsse2); auto dfm = jdfe0 - jdfe2; auto ssm = jsse0 - jsse2; if (dfm > 0 && ssm > 0 && jdfe2 > 0 && jsse2 > 0) { auto f = (ssm / dfm) / (jsse2 / jdfe2); res[0][j] = fpval(f, dfm, jdfe2); res[1][j] = ssm / jsst; } if (dfx > 0 && ssx > 0 && jdfe2 > 0 && jsse2 > 0) { auto f = (ssx / dfx) / (jsse2 / jdfe2); res[2][j] = fpval(f, dfx, jdfe2); res[3][j] = ssx / jsst; } auto dfxi = jdfe1 - jdfe2; auto ssxi = jsse1 - jsse2; if (dfxi > 0 && ssxi > 0 && jdfe2 > 0 && jsse2 > 0) { auto f = (ssxi / dfxi) / (jsse2 / jdfe2); res[4][j] = fpval(f, dfxi, jdfe2); res[5][j] = ssxi / jsst; } } } return 0; } int assoc_glm_omp(const Genotype &gt, const std::vector<size_t> &gi, const std::vector<double> &y, const std::vector< std::vector<double> > &ac, const std::vector< std::vector<double> > &ic, std::vector< std::vector<double> > &res) { auto n = y.size(); auto m = gt.dat.size(); // modelP, modelR2, mainP, mainR2, intP, intR2 res.assign(ic.empty() ? 2 : 6, std::vector<double>(m, std::numeric_limits<double>::quiet_NaN())); double sst = calc_css(y); std::vector<double> x0(n, 1); for (auto &v : ac) x0.insert(x0.end(), v.begin(), v.end()); std::vector<double> b0; double dfe0 = 0, sse0 = 0; lsfit(y, x0, b0, dfe0, sse0); // in earlier OpenMP specifications (<3.0), unsigned integer is not allowed in loop construct auto m2 = static_cast<ptrdiff_t>(m); #pragma omp parallel for for (ptrdiff_t j2 = 0; j2 < m2; ++j2) { auto j = static_cast<size_t>(j2); std::vector<size_t> idx; std::vector< std::vector<double> > x1; if (gt.ploidy == 1) { std::vector<allele_t> g; for (size_t i = 0; i < n; ++i) { auto ii = gi[i]; auto a = gt.dat[j][ii]; if ( a ) { g.push_back(a); idx.push_back(i); } } idummy2(factor(g), x1); } else { std::vector< std::pair<allele_t,allele_t> > g; for (size_t i = 0; i < n; ++i) { auto ii = gi[i]; auto a = gt.dat[j][ii*2]; auto b = gt.dat[j][ii*2+1]; if ( a && b ) { if (a > b) std::swap(a, b); g.emplace_back(a, b); idx.push_back(i); } } idummy2(factor(g), x1); } if ( x1.empty() ) continue; auto n2 = idx.size(); auto jsst = sst; auto jdfe0 = dfe0; auto jsse0 = sse0; std::vector<double> x, y2, b; if (n2 == n) { y2 = y; x = x0; } else { y2 = subset(y, idx); jsst = calc_css(y2); x.assign(n2, 1); for (auto &e : ac) { auto z = subset(e, idx); x.insert(x.end(), z.begin(), z.end()); } lsfit(y2, x, b, jdfe0, jsse0); } for (auto &e : x1) x.insert(x.end(), e.begin(), e.end()); double jdfe1 = 0, jsse1 = 0; lsfit(y2, x, b, jdfe1, jsse1); auto dfx = jdfe0 - jdfe1; auto ssx = jsse0 - jsse1; if ( ic.empty() ) { if (dfx > 0 && ssx > 0 && jdfe1 > 0 && jsse1 > 0) { auto f = (ssx / dfx) / (jsse1 / jdfe1); res[0][j] = fpval(f, dfx, jdfe1); res[1][j] = ssx / jsst; } } else { for (auto &e : x1) { for (auto z : ic) { if (n2 != n) z = subset(z, idx); std::transform(e.begin(), e.end(), z.begin(), z.begin(), std::multiplies<double>()); x.insert(x.end(), z.begin(), z.end()); } } double jdfe2 = 0, jsse2 = 0; lsfit(y2, x, b, jdfe2, jsse2); auto dfm = jdfe0 - jdfe2; auto ssm = jsse0 - jsse2; if (dfm > 0 && ssm > 0 && jdfe2 > 0 && jsse2 > 0) { auto f = (ssm / dfm) / (jsse2 / jdfe2); res[0][j] = fpval(f, dfm, jdfe2); res[1][j] = ssm / jsst; } if (dfx > 0 && ssx > 0 && jdfe2 > 0 && jsse2 > 0) { auto f = (ssx / dfx) / (jsse2 / jdfe2); res[2][j] = fpval(f, dfx, jdfe2); res[3][j] = ssx / jsst; } auto dfxi = jdfe1 - jdfe2; auto ssxi = jsse1 - jsse2; if (dfxi > 0 && ssxi > 0 && jdfe2 > 0 && jsse2 > 0) { auto f = (ssxi / dfxi) / (jsse2 / jdfe2); res[4][j] = fpval(f, dfxi, jdfe2); res[5][j] = ssxi / jsst; } } } return 0; } int assoc_stepwise(const Genotype &gt, const std::vector<size_t> &gi, const std::vector<double> &y, const std::vector< std::vector<double> > &ac, const std::vector< std::vector<double> > &ic, std::vector<double> &ps, std::vector<size_t> &in) { auto n = y.size(); auto m = gt.dat.size(); std::vector<double> x0(n,1); for (auto &e : ac) x0.insert(x0.end(), e.begin(), e.end()); std::vector<size_t> idx; std::vector<allele_t> g1; std::vector<std::pair<allele_t, allele_t> > g2; std::vector<size_t> c1; std::vector<double> x1; for (size_t j = 0; j < m; ++j) { std::vector< std::vector<double> > xg; // !!! missing genotype is not allowed !!! if (gt.ploidy == 1) { g1.clear(); for (auto i : gi) g1.push_back(gt.dat[j][i]); idummy1(factor(g1), xg); } else { g2.clear(); for (auto i : gi) { auto a = gt.dat[j][i*2]; auto b = gt.dat[j][i*2+1]; if (a > b) std::swap(a, b); g2.emplace_back(a, b); } idummy1(factor(g2), xg); } if (xg.empty()) continue; idx.push_back(j); if ( ! ic.empty() ) { auto ng = xg.size(); for (size_t k = 0; k < ng; ++k) { for (auto v : ic) { std::transform(v.begin(), v.end(), xg[k].begin(), v.begin(), std::multiplies<double>()); xg.push_back(v); } } } c1.push_back( xg.size() ); for (auto &e : xg) x1.insert(x1.end(), e.begin(), e.end()); } StepReg sr; sr.sle = sr.sls = par.alpha; sr.rsq = par.rsq; sr.mtc = par.mtc; std::vector<double> px; if ( par.openmp ) sr.forward_omp(x0, x1, c1, y, px, in); else sr.forward(x0, x1, c1, y, px, in); sr.backward(x0, x1, c1, y, px, in); subset(idx,in).swap(in); ps.assign(m, std::numeric_limits<double>::quiet_NaN()); auto nx = idx.size(); for (size_t i = 0; i < nx; ++i) ps[idx[i]] = px[i]; return 0; } int fit_multi_locus_model(size_t t, const std::vector<size_t> &loc, const Genotype &gt, const std::vector<size_t> &gi, const Phenotype &pt, const Covariate &ct, std::string &est, std::string &aov1, std::string &aov3) { auto y = pt.dat[t]; auto n = y.size(); std::vector<size_t> obs; for (size_t i = 0; i < n; ++i) { if (std::isfinite(y[i])) obs.push_back(i); } auto nv = obs.size(); if (nv != n) subset(y,obs).swap(y); std::vector<std::string> env; if ( ! pt.env.empty() ) subset(pt.env,obs).swap(env); std::vector<std::string> blk; if ( ! pt.blk.empty() ) subset(pt.blk,obs).swap(blk); ANOVA aov; if ( ! env.empty() ) aov.add_main("_ENV_", env); if ( ! blk.empty() ) { if ( env.empty() ) aov.add_main("_BLK_", blk); else aov.add_nested("_BLK_(_ENV_)", blk, env); } if ( ! ct.phe.empty() && ! ct.ind.empty() ) { auto m = ct.phe.size(); for (size_t i = 0; i < m; ++i) { if (nv == n) aov.add_reg(ct.phe[i], ct.dat[i]); else aov.add_reg(ct.phe[i], subset(ct.dat[i],obs)); } } subset(gi,obs).swap(obs); for (auto j : loc) { std::vector<std::string> gs; if (gt.ploidy == 1) { for (auto i : obs) { auto a = gt.dat[j][i]; if (a) gs.push_back(gt.allele[j][a-1]); else gs.push_back("."); } } else { for (auto i : obs) { auto a = gt.dat[j][i*2]; auto b = gt.dat[j][i*2+1]; if (a > b) std::swap(a, b); if (a && b) gs.push_back(gt.allele[j][a-1] + '/' + gt.allele[j][b-1]); else gs.push_back("./."); } } aov.add_main(gt.loc[j], gs); if ( ! env.empty() && ! par.nogxe ) aov.add_crossed(gt.loc[j] + "*_ENV_", gs, env); } auto sol = aov.solution(y); auto at1 = aov.solve1(y); auto at3 = aov.solve3(y); for (auto &e : at1.p) { if (e == 0.0) e = std::numeric_limits<double>::min(); } for (auto &e : at3.p) { if (e == 0.0) e = std::numeric_limits<double>::min(); } est = sol.to_string(); aov1 = at1.to_string(); aov3 = at3.to_string(); return 0; } } // namespace int rtm_gwas_assoc(int argc, char *argv[]) { std::cerr << "RTM-GWAS " RTM_GWAS_VERSION_STRING " ASSOC (Built on " __DATE__ " " __TIME__ ")\n"; CmdLine cmd; cmd.add("--vcf", "VCF file", ""); cmd.add("--pheno", "phenotype file", ""); cmd.add("--covar", "covariate file", ""); cmd.add("--out", "output file", "assoc.out"); cmd.add("--alpha", "significance level", "0.01"); cmd.add("--preselect", "pre-selection threshold", "0.05"); cmd.add("--mtc", "multiple testing correction, BON/FDR", ""); cmd.add("--rsq", "maximum model r-square", "0.95"); cmd.add("--no-gxe", "ignore GxE interaction effect"); cmd.add("--openmp", "enable OpenMP multithreading"); cmd.parse(argc, argv); if (argc < 2) { cmd.show(); return 1; } par.vcf = cmd.get("--vcf"); par.pheno = cmd.get("--pheno"); par.covar = cmd.get("--covar"); par.out = cmd.get("--out"); par.alpha = std::stod(cmd.get("--alpha")); par.preselect = std::stod(cmd.get("--preselect")); par.rsq = std::stod(cmd.get("--rsq")); par.nogxe = cmd.has("--no-gxe"); par.openmp = cmd.has("--openmp"); if ( ! cmd.get("--mtc").empty() ) { auto mtc = cmd.get("--mtc"); std::transform(mtc.begin(), mtc.end(), mtc.begin(), ::toupper); if (mtc == "BON") par.mtc = 1; else if (mtc == "FDR") par.mtc = 2; else if (mtc == "HOLM") par.mtc = 3; else par.mtc = 1; } Genotype gt; Phenotype pt; Covariate ct; std::cerr << "INFO: reading genotype file...\n"; if (read_vcf(par.vcf, gt) != 0) return 1; std::cerr << "INFO: " << gt.ind.size() << " individuals, " << gt.loc.size() << " loci\n"; std::cerr << "INFO: reading phenotype file...\n"; if (read_pheno(par.pheno, pt) != 0) return 1; std::cerr << "INFO: " << pt.ind.size() << " observations, " << pt.phe.size() << " traits\n"; if ( ! par.covar.empty() ) { std::cerr << "INFO: reading covariate file...\n"; if (read_covar(par.covar, ct) != 0) return 1; std::cerr << "INFO: " << ct.ind.size() << " individuals, " << ct.phe.size() << " covariates\n"; } std::vector<size_t> gi; merge(gt, pt, ct, gi); if ( gi.empty() ) { std::cerr << "ERROR: no valid observations are found\n"; return 1; } std::vector< std::vector<double> > ac, ic; parse_envblk(pt, ac, ic); if (par.nogxe) ic.clear(); ac.insert(ac.end(), ct.dat.begin(), ct.dat.end()); std::ofstream ofs_loc(par.out + ".loc"); if ( ! ofs_loc ) { std::cerr << "ERROR: can't open file: " << par.out << ".loc" << "\n"; return 1; } std::ofstream ofs_est(par.out + ".est"); if (!ofs_est) { std::cerr << "ERROR: can't open file: " << par.out << ".est" << "\n"; return 1; } std::ofstream ofs_aov1(par.out + ".aov1"); if (!ofs_aov1) { std::cerr << "ERROR: can't open file: " << par.out << ".aov1" << "\n"; return 1; } std::ofstream ofs_aov3(par.out + ".aov3"); if (!ofs_aov3) { std::cerr << "ERROR: can't open file: " << par.out << ".aov3" << "\n"; return 1; } auto m = gt.loc.size(); auto nt = pt.phe.size(); std::vector< std::vector<double> > ps; for (size_t t = 0; t < nt; ++t) { std::vector<char> keep; for (auto e : pt.dat[t]) keep.push_back(std::isfinite(e)); auto y = pt.dat[t]; auto ac2 = ac; auto ic2 = ic; auto gi2 = gi; if (std::find(keep.begin(), keep.end(), 0) != keep.end()) { y = subset(y, keep); for (auto &e : ac2) e = subset(e, keep); for (auto &e : ic2) e = subset(e, keep); gi2 = subset(gi, keep); } std::vector<size_t> loc; std::vector<double> p1; if (par.preselect <= 0 || par.preselect >= 1) assoc_stepwise(gt, gi2, y, ac2, ic2, p1, loc); else { std::vector< std::vector<double> > glm; if ( par.openmp ) assoc_glm_omp(gt, gi2, y, ac2, ic2, glm); else assoc_glm(gt, gi2, y, ac2, ic2, glm); std::vector<size_t> idx; if ( ic.empty() ) { p1 = glm[0]; for (size_t j = 0; j < m; ++j) { auto pval = glm[0][j]; if (std::isfinite(pval) && pval <= par.preselect) idx.push_back(j); } } else { p1 = glm[2]; for (size_t j = 0; j < m; ++j) { auto pval = glm[2][j]; if (std::isfinite(pval) && pval <= par.preselect) { idx.push_back(j); continue; } pval = glm[4][j]; if (std::isfinite(pval) && pval <= par.preselect) idx.push_back(j); } } std::cerr << "INFO: after pre-selection, there are " << idx.size() << " loci\n"; if ( ! idx.empty() ) { Genotype gt2; gt2.ploidy = gt.ploidy; subset(gt.dat,idx).swap(gt2.dat); subset(gt.loc,idx).swap(gt2.loc); std::vector<double> p2; assoc_stepwise(gt2, gi2, y, ac2, ic2, p2, loc); subset(idx,loc).swap(loc); for (size_t k = 0; k < idx.size(); ++k) p1[idx[k]] = p2[k]; } } ps.push_back(p1); ofs_loc << ">" << pt.phe[t] << "\n"; for (auto j : loc) ofs_loc << gt.loc[j] << "\n"; ofs_loc << "\n"; std::string est, aov1, aov3; fit_multi_locus_model(t, loc, gt, gi, pt, ct, est, aov1, aov3); ofs_est << ">" << pt.phe[t] << "\n" << est << "\n"; ofs_aov1 << ">" << pt.phe[t] << "\n" << aov1 << "\n"; ofs_aov3 << ">" << pt.phe[t] << "\n" << aov3 << "\n"; } std::ofstream ofs_ps(par.out + ".pval"); if ( ! ofs_ps ) { std::cerr << "ERROR: can't open file: " << par.out << ".pval" << "\n"; return 1; } ofs_ps << "Locus\tChromosome\tPosition"; for (auto &e : pt.phe) ofs_ps << "\t" << e; ofs_ps << "\n"; for (size_t j = 0; j < m; ++j) { ofs_ps << gt.loc[j] << "\t" << gt.chr[j] << "\t" << gt.pos[j]; for (size_t t = 0; t < nt; ++t) ofs_ps << "\t" << ps[t][j]; ofs_ps << "\n"; } return 0; }
27.695181
118
0.435333
[ "vector", "model", "transform" ]