hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
60314451e1e4e034ceea302e35e5e5cc9c11edd4
21,382
hpp
C++
torch/lib/c10d/Utils.hpp
mleshen/pytorch
314a578154d9f0981bc08397aaaeaf50d8233730
[ "Intel" ]
3
2021-01-03T16:39:28.000Z
2022-02-02T14:49:37.000Z
torch/lib/c10d/Utils.hpp
mleshen/pytorch
314a578154d9f0981bc08397aaaeaf50d8233730
[ "Intel" ]
1
2021-05-10T01:18:33.000Z
2021-05-10T01:18:33.000Z
torch/lib/c10d/Utils.hpp
mleshen/pytorch
314a578154d9f0981bc08397aaaeaf50d8233730
[ "Intel" ]
1
2021-08-06T22:50:37.000Z
2021-08-06T22:50:37.000Z
#pragma once #include <ATen/ATen.h> #include <c10/util/accumulate.h> #include <c10d/Types.hpp> #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> typedef SSIZE_T ssize_t; #pragma comment(lib, "Ws2_32.lib") #else #include <fcntl.h> #include <netdb.h> #include <sys/poll.h> #include <sys/socket.h> #include <unistd.h> #endif #include <sys/types.h> #include <chrono> #include <cstdint> #include <cstdlib> #include <functional> #include <limits> #include <string> #include <system_error> #include <tuple> #include <vector> namespace c10d { // Distributed c10d debug levels enum DistributedDebugLevel { OFF = 0, DETAIL = 1, INFO = 2, }; // String debug log levels extern const char* kDistDebugEnvVar; extern const char* kDistDebugDetailLogLevel; extern const char* kDistDebugInfoLogLevel; extern const char* kDistDebugOffLogLevel; std::string parse_env(const char* env_var_name); DistributedDebugLevel parseDistDebugLevel(); // Turns at::IntArrayRef into "(1, 2, 3, 4)". inline std::string toString(at::IntArrayRef l) { std::stringstream ss; ss << "("; for (size_t i = 0; i < l.size(); i++) { if (i > 0) { ss << ", "; } ss << l[i]; } ss << ")"; return ss.str(); } inline std::string toString(const c10::Layout& layout) { std::stringstream ss; ss << layout; return ss.str(); } inline void assertSameType( const at::DeprecatedTypeProperties& type, const std::vector<at::Tensor>& tensors) { for (size_t i = 0; i < tensors.size(); i++) { if (!tensors[i].options().type_equal(type.options())) { const std::string expected = type.toString(); const std::string actual = tensors[i].toString(); throw std::invalid_argument( "mixed types (" + expected + " and " + actual + ")"); } } } inline bool parseEnvVarFlag(const char* envVarName) { char* stringValue = std::getenv(envVarName); if (stringValue != nullptr) { int val; try { val = std::stoi(stringValue); } catch (std::exception& e) { throw std::runtime_error( "Invalid value for environment variable: " + std::string(envVarName)); } if (val == 1) { return true; } else if (val == 0) { return false; } else { throw std::runtime_error( "Invalid value for environment variable: " + std::string(envVarName)); } } return false; } inline void assertSameSizes( const at::IntArrayRef& sizes, const std::vector<at::Tensor>& tensors) { for (size_t i = 0; i < tensors.size(); i++) { if (!tensors[i].sizes().equals(sizes)) { const auto expected = toString(sizes); const auto actual = toString(tensors[i].sizes()); throw std::invalid_argument( "mixed sizes (" + expected + " and " + actual + ")"); } } } inline void assertSameSizeAndType(const std::vector<at::Tensor>& tensors) { // Ensure we have at least one tensor if (tensors.size() == 0) { throw std::invalid_argument("argument is empty"); } // Ensure all tensors have identical type and shape auto options = tensors[0].options(); auto sizes = tensors[0].sizes(); for (size_t i = 1; i < tensors.size(); i++) { if (!tensors[i].options().type_equal(options)) { const auto expected = toString(options); const auto actual = toString(tensors[i].options()); throw std::invalid_argument( "argument contains mixed types (" + expected + " and " + actual + ")"); } if (!tensors[i].sizes().equals(sizes)) { const auto expected = toString(sizes); const auto actual = toString(tensors[i].sizes()); throw std::invalid_argument( "argument contains mixed sizes (" + expected + " and " + actual + ")"); } } } inline void assertTypeMatch( std::function<void(const std::string&)> fn, const at::DeprecatedTypeProperties& type, const at::ArrayRef<at::Tensor> tensors, size_t index) { if (!tensors[index].options().type_equal(type.options())) { fn("invalid tensor type at index " + std::to_string(index) + " (expected " + type.toString() + ", got " + tensors[index].toString() + ")"); } } inline void assertTypeMatch( std::function<void(const std::string&)> fn, const at::TensorOptions& options, const at::ArrayRef<at::Tensor> tensors, size_t index) { if (!tensors[index].options().type_equal(options)) { fn("invalid tensor type at index " + std::to_string(index) + " (expected " + toString(options) + ", got " + toString(tensors[index].options()) + ")"); } } inline void assertSizesMatch( std::function<void(const std::string&)> fn, const at::IntArrayRef& sizes, const at::ArrayRef<at::Tensor> tensors, size_t index) { if (tensors[index].sizes() != sizes) { fn("invalid tensor size at index " + std::to_string(index) + " (expected " + toString(sizes) + ", got " + toString(tensors[index].sizes()) + ")"); } } inline void assertLayoutMatch( std::function<void(const std::string&)> fn, const c10::Layout& expected, const at::ArrayRef<at::Tensor> tensors, size_t index) { const auto& actual = tensors[index].layout(); if (actual != expected) { fn("invalid tensor layout at index " + std::to_string(index) + " (expected " + toString(expected) + ", got " + toString(actual) + ")"); } } inline void assertLayoutMatch( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors) { const auto& layout = tensors[0].layout(); for (size_t i = 1; i < tensors.size(); i++) { assertLayoutMatch(fn, layout, tensors, i); } } inline void assertNonEmpty( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors) { if (tensors.size() == 0) { fn("requires non-empty tensor list"); } } inline void assertSingleElement( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors) { if (tensors.size() != 1) { fn("requires a single-element tensor list"); } } inline void assertSingleElementInput( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors) { if (tensors.size() != 1) { fn("requires a single-element input tensor list"); } } inline void assertSingleElementOutput( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors) { if (tensors.size() != 1) { fn("requires a single-element output tensor list"); } } inline void assertRootRank( std::function<void(const std::string&)> fn, int rank, int size) { if (rank < 0 || rank >= size) { fn("invalid root rank: " + std::to_string(rank)); } } inline void assertRootTensor( std::function<void(const std::string&)> fn, int rank, int size) { if (rank < 0 || rank >= size) { fn("invalid root tensor: " + std::to_string(rank)); } } inline void assertDense( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors) { const auto& layout = tensors[0].layout(); if (layout != at::kStrided) { fn("only supports dense tensors"); } } inline void assertCPU( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors) { const auto& device = tensors[0].device(); if (device.type() != at::kCPU) { fn("only supports CPU tensors"); } } inline void assertSameDevice( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors) { if (tensors.size() < 2) { return; } const auto& device = tensors[0].device(); for (int i = 1; i < tensors.size(); ++i) { if (tensors[i].device() != device) { fn("tensors should be on the same device"); } } } inline void assertTypeAndSizesMatch( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors, const at::DeprecatedTypeProperties& type, const at::IntArrayRef& sizes) { for (size_t i = 0; i < tensors.size(); i++) { assertTypeMatch(fn, type, tensors, i); assertSizesMatch(fn, sizes, tensors, i); } } inline void assertTypeAndSizesMatch( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors, const at::TensorOptions& options, const at::IntArrayRef& sizes) { for (size_t i = 0; i < tensors.size(); i++) { assertTypeMatch(fn, options, tensors, i); assertSizesMatch(fn, sizes, tensors, i); } } inline void assertTypeAndSizesMatch( std::function<void(const std::string&)> fn, const at::ArrayRef<at::Tensor> tensors) { const auto& options = tensors[0].options(); const auto sizes = tensors[0].sizes(); assertTypeAndSizesMatch(fn, tensors.slice(1), options, sizes); } // Copied from ATen/core/functional.h. template <typename F, typename T> inline auto fmap(T& inputs, const F& fn) -> std::vector<decltype(fn(*inputs.begin()))> { std::vector<decltype(fn(*inputs.begin()))> r; r.reserve(inputs.size()); for (auto& input : inputs) { r.push_back(fn(input)); } return r; } // Copied from torch/csrc/utils/tensor_flatten.h. inline at::Tensor flattenDenseTensors(at::TensorList tensors) { static const auto flatten = [](const at::Tensor& t) { return t.contiguous().view({-1}); }; if (tensors.size() == 1) { return flatten(tensors[0]); } return at::cat(::c10d::fmap(tensors, flatten)); } inline at::Tensor newLikeFlat( std::vector<std::vector<at::Tensor>>& tensors, size_t deviceIdx) { if (tensors.size() == 0 || tensors[0].size() == 0) { throw std::runtime_error("Received an empty list"); } if (deviceIdx >= tensors.size()) { throw std::runtime_error("Invalid device index"); } auto& t = tensors[deviceIdx][0]; auto device = t.device(); for (size_t i = 1; i < tensors[deviceIdx].size(); ++i) { if (tensors[deviceIdx][i].device() != device) { throw std::runtime_error("Expecting all tensors on the same device"); } } at::DeviceGuard gpuGuard(device); std::vector<int64_t> sizes{static_cast<int64_t>(tensors[deviceIdx].size())}; std::vector<int64_t> strides{static_cast<int64_t>(t.numel())}; sizes.insert(sizes.end(), t.sizes().begin(), t.sizes().end()); strides.insert(strides.end(), t.strides().begin(), t.strides().end()); return at::empty_strided( sizes, strides, t.options().memory_format(c10::nullopt)); } inline at::Tensor newLikeFlat(std::vector<at::Tensor>& tensors) { if (tensors.size() == 0) { throw std::runtime_error("Received an empty list"); } auto& t = tensors[0]; at::DeviceGuard gpuGuard(t.device()); std::vector<int64_t> sizes{static_cast<int64_t>(tensors.size())}; sizes.insert(sizes.end(), t.sizes().begin(), t.sizes().end()); return at::empty(sizes, t.options()); } inline std::vector<std::vector<int64_t>> getSizes( const std::vector<at::Tensor>& tensors) { std::vector<std::vector<int64_t>> sizes(tensors.size()); for (size_t i = 0; i < tensors.size(); i++) { sizes[i] = tensors[i].sizes().vec(); } return sizes; } inline std::vector<int> getDevices(const std::vector<at::Tensor>& tensors) { std::vector<int> devices(tensors.size(), -1); if (tensors[0].device().is_cuda()) { for (size_t i = 0; i < tensors.size(); i++) { devices[i] = tensors[i].storage().device().index(); } } return devices; } template <typename T> inline T* getDataPointer(const at::Tensor& tensor) { // This method is only used in ProcessGroupGloo for now. Call sites must make // sure that the input tensor is contiguous. It is OK if the tensor does not // start from the beginning of the storage. For example, it could come from // chunk(..., dim=0)[1]. Hence, we need to use data_ptr() instead of // tensor.storage().data() // NB: not using tensor.data<T>() because tensor is not aware of gloo::TYPE return static_cast<T*>(tensor.data_ptr()); } template <typename T> std::vector<T*> getDataPointers(const std::vector<at::Tensor>& tensors) { std::vector<T*> ptrs(tensors.size()); for (size_t i = 0; i < tensors.size(); i++) { ptrs[i] = getDataPointer<T>(tensors[i]); } return ptrs; } // For alltoall split size sanity check inline void checkSplitSizes( const std::vector<int64_t>& split_sizes, const at::Tensor& tensor, int group_size) { if (split_sizes.size() == 0) { TORCH_CHECK( tensor.size(0) % group_size == 0, "Tensor's dim 0 does not divide equally across group size"); } else { TORCH_CHECK( split_sizes.size() == group_size, "Number of tensor splits not equal to group size"); const auto sum = c10::sum_integers(split_sizes); TORCH_CHECK( sum == tensor.size(0), "Split sizes doesn't match total dim 0 size"); } } // Compute alltoall lengths and offsets, handling multi-dimension tensors template <typename T> size_t computeLengthsAndOffsets( const std::vector<int64_t>& split_sizes, const at::Tensor& tensor, std::vector<T>* lengths, std::vector<T>* offsets) { size_t group_size = lengths->size(); bool equal_splits = false; size_t dim0_size = tensor.size(0); size_t row_size = (dim0_size ? tensor.numel() / dim0_size : 1); size_t split_size = 0; size_t offset = 0; if (split_sizes.size() == 0) { equal_splits = true; split_size = tensor.size(0) / group_size; } for (int i = 0; i < group_size; i++) { size_t length = row_size * (equal_splits ? split_size : split_sizes[i]); TORCH_INTERNAL_ASSERT( length <= std::numeric_limits<int>::max() && offset <= std::numeric_limits<int>::max(), "Length or offset larger than INT_MAX not supported"); (*lengths)[i] = length; (*offsets)[i] = offset; offset += length; } return offset; } template <typename T> size_t computeLengthsAndOffsets( const std::vector<at::Tensor>& tensors, std::vector<T>* lengths, std::vector<T>* offsets) { size_t group_size = lengths->size(); size_t offset = 0; for (int i = 0; i < group_size; i++) { size_t length = tensors[i].numel(); TORCH_INTERNAL_ASSERT( length <= std::numeric_limits<int>::max() && offset <= std::numeric_limits<int>::max(), "Length or offset larger than INT_MAX not supported"); (*lengths)[i] = length; (*offsets)[i] = offset; offset += length; } return offset; } using RankType = uint32_t; using PortType = uint16_t; using SizeType = uint64_t; // `errno` is only meaningful when it fails. E.g., a successful `fork()` sets // `errno` to `EINVAL` in child process on some macos // (https://stackoverflow.com/a/20295079), and thus `errno` should really only // be inspected if an error occurred. // // `success_cond` is an expression used to check if an error has happend. So for // `fork()`, we can use `SYSCHECK(pid = fork(), pid != -1)`. The function output // is stored in variable `__output` and may be used in `success_cond`. #ifdef _WIN32 #define SYSCHECK(expr, success_cond) \ while (true) { \ auto __output = (expr); \ auto errno_local = WSAGetLastError(); \ (void)__output; \ if (!(success_cond)) { \ if (errno == EINTR) { \ continue; \ } else if ( \ errno_local == WSAETIMEDOUT || errno_local == WSAEWOULDBLOCK) { \ throw std::runtime_error("Socket Timeout"); \ } else { \ throw std::system_error(errno_local, std::system_category()); \ } \ } else { \ break; \ } \ } #else #define SYSCHECK(expr, success_cond) \ while (true) { \ auto __output = (expr); \ (void)__output; \ if (!(success_cond)) { \ if (errno == EINTR) { \ continue; \ } else if (errno == EAGAIN || errno == EWOULDBLOCK) { \ throw std::runtime_error("Socket Timeout"); \ } else { \ throw std::system_error(errno, std::system_category()); \ } \ } else { \ break; \ } \ } #endif // Most functions indicate error by returning `-1`. This is a helper macro for // this common case with `SYSCHECK`. // Since SOCKET_ERROR = -1 in MSVC, so also leverage SYSCHECK_ERR_RETURN_NEG1 #define SYSCHECK_ERR_RETURN_NEG1(expr) SYSCHECK(expr, __output != -1) // Helper resource guard class class ResourceGuard { public: ResourceGuard(std::function<void()> destructor) : destructor_(std::move(destructor)), released_(false) {} ~ResourceGuard() { if (!released_) { destructor_(); } } void release() { released_ = true; } private: std::function<void()> destructor_; bool released_; }; namespace tcputil { constexpr std::chrono::milliseconds kNoTimeout = std::chrono::milliseconds(-1); const std::string kConnectTimeoutMsg = "connect() timed out."; // Send and receive template <typename T> void sendBytes( int socket, const T* buffer, size_t length, bool moreData = false) { size_t bytesToSend = sizeof(T) * length; if (bytesToSend == 0) { return; } auto bytes = reinterpret_cast<const uint8_t*>(buffer); uint8_t* currentBytes = const_cast<uint8_t*>(bytes); int flags = 0; #ifdef MSG_MORE if (moreData) { // there is more data to send flags |= MSG_MORE; } #endif // Ignore SIGPIPE as the send() return value is always checked for error #ifdef MSG_NOSIGNAL flags |= MSG_NOSIGNAL; #endif while (bytesToSend > 0) { ssize_t bytesSent; SYSCHECK_ERR_RETURN_NEG1( bytesSent = ::send(socket, (const char*)currentBytes, bytesToSend, flags)) if (bytesSent == 0) { throw std::system_error(ECONNRESET, std::system_category()); } bytesToSend -= bytesSent; currentBytes += bytesSent; } } template <typename T> void recvBytes(int socket, T* buffer, size_t length) { size_t bytesToReceive = sizeof(T) * length; if (bytesToReceive == 0) { return; } auto bytes = reinterpret_cast<uint8_t*>(buffer); uint8_t* currentBytes = bytes; while (bytesToReceive > 0) { ssize_t bytesReceived; SYSCHECK_ERR_RETURN_NEG1( bytesReceived = recv(socket, (char*)currentBytes, bytesToReceive, 0)) if (bytesReceived == 0) { throw std::system_error(ECONNRESET, std::system_category()); } bytesToReceive -= bytesReceived; currentBytes += bytesReceived; } } // send a vector's length and data template <typename T> void sendVector(int socket, const std::vector<T>& vec, bool moreData = false) { SizeType size = vec.size(); sendBytes<SizeType>(socket, &size, 1, true); sendBytes<T>(socket, vec.data(), size, moreData); } // receive a vector as sent in sendVector template <typename T> std::vector<T> recvVector(int socket) { SizeType valueSize; recvBytes<SizeType>(socket, &valueSize, 1); std::vector<T> value(valueSize); recvBytes<T>(socket, value.data(), value.size()); return value; } // this is only for convenience when sending rvalues template <typename T> void sendValue(int socket, const T& value, bool moreData = false) { sendBytes<T>(socket, &value, 1, moreData); } template <typename T> T recvValue(int socket) { T value; recvBytes<T>(socket, &value, 1); return value; } // send a string's length and data inline void sendString( int socket, const std::string& str, bool moreData = false) { SizeType size = str.size(); sendBytes<SizeType>(socket, &size, 1, true); sendBytes<char>(socket, str.data(), size, moreData); } // receive a string as sent in sendString inline std::string recvString(int socket) { SizeType valueSize; recvBytes<SizeType>(socket, &valueSize, 1); std::vector<char> value(valueSize); recvBytes<char>(socket, value.data(), value.size()); return std::string(value.data(), value.size()); } // Other helpers std::string sockaddrToString(struct sockaddr* addr); std::pair<int, PortType> listen(PortType port); int connect( const std::string& address, PortType port, bool wait = true, const std::chrono::milliseconds& timeout = kNoTimeout); std::tuple<int, std::string> accept( int listenSocket, const std::chrono::milliseconds& timeout = kNoTimeout); } // namespace tcputil } // namespace c10d
30.854257
80
0.605322
mleshen
60372c6fa6c3a74f40295d237ce2e860ee2ee61c
28,301
cpp
C++
tests/test_cases/reorder_gpu_test.cpp
kyper999/clDNN_neuset
85148cef898dbf1b314ef742092824c447474f2d
[ "BSL-1.0", "Intel", "Apache-2.0" ]
1
2018-06-07T09:21:08.000Z
2018-06-07T09:21:08.000Z
tests/test_cases/reorder_gpu_test.cpp
kyper999/clDNN_neuset
85148cef898dbf1b314ef742092824c447474f2d
[ "BSL-1.0", "Intel", "Apache-2.0" ]
null
null
null
tests/test_cases/reorder_gpu_test.cpp
kyper999/clDNN_neuset
85148cef898dbf1b314ef742092824c447474f2d
[ "BSL-1.0", "Intel", "Apache-2.0" ]
null
null
null
/* // Copyright (c) 2016 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ /////////////////////////////////////////////////////////////////////////////////////////////////// #include <gtest/gtest.h> #include "api/CPP/memory.hpp" #include <api/CPP/input_layout.hpp> #include "api/CPP/reorder.hpp" #include <api/CPP/topology.hpp> #include <api/CPP/network.hpp> #include <api/CPP/engine.hpp> #include "test_utils/test_utils.h" #include <api/CPP/data.hpp> #include <cmath> #include <gmock/gmock.h> #include <limits> using namespace cldnn; using namespace tests; using namespace testing; TEST(reorder_gpu_f32, basic) { // Input : yxfb:2x2x2x2 // Output : bfyx:2x2x2x2 // // Input: // f0: b0: 1 2 b1: 0 0 // f0: b0: 3 4 b1: 0.5 -0.5 // f1: b0: 5 6 b1: 1.5 5.2 // f1: b0: 7 8 b1: 12 8 // // Output: // b0 f0: 1 2 // b0 f0: 3 4 // // b0 f1: 5 6 // b0 f1: 7 8 // // b1 f0: 0 0 // b1 f0: 0.5 -0.5 // // b1 f1: 1.5 5.2 // b1 f1: 12 8 // engine engine; auto input = memory::allocate(engine, { data_types::f32, format::yxfb, { 2, 2, 2, 2 } }); layout output_layout(data_types::f32, format::bfyx,{ 2,2,2,2 }); set_values(input, { 1.f, 0.f, 5.f, 1.5f, 2.f, 0.f, 6.f, 5.2f, 3.f, 0.5f, 7.f, 12.f, 4.f, -0.5f, 8.f, 8.f }); topology topology( input_layout("input", input.get_layout()), reorder("reorder", "input", output_layout)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "reorder"); auto output = outputs.begin()->second.get_memory(); float answers[16] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 0.0f, 0.0f, 0.5f, -0.5f, 1.5f, 5.2f, 12.0f, 8.0f }; auto output_ptr = output.pointer<float>(); for (int i = 0; i < 16; i++) { EXPECT_FLOAT_EQ(answers[i], output_ptr[i]); } } TEST(reorder_gpu_f32, basic_subtract) { // Input : 2x2x2x2 // Output : 2x2x2x2 // Subtract : 1x2x2x2 (only first batch is taken into consideration) // // Input: // f0: b0: 1 2 b1: 0 0 // f0: b0: 3 4 b1: 0.5 -0.5 // f1: b0: 5 6 b1: 1.5 5.2 // f1: b0: 7 8 b1: 12 8 // // Subtract: // f0: b0: 1 1.5 // f0: b0: 2 2.5 // f1: b0: 4 3 // f1: b0: 2 1 // // // Output: // b0 f0: 0 0.5 // b0 f0: 1 1.5 // // b0 f1: 1 3 // b0 f1: 5 7 // // b1 f0: -1 -1.5 // b1 f0: -1.5 -3 // // b1 f1: -2.5 2.2 // b1 f1: 10 7 // engine engine; auto input = memory::allocate(engine, { data_types::f32, format::yxfb, { 2, 2, 2, 2 } }); layout output_layout( data_types::f32, format::bfyx, {2,2,2,2} ); auto subtract = memory::allocate(engine, { data_types::f32, format::byxf, { 1, 2, 2, 2 } }); set_values(input, { 1.f, 0.f, 5.f, 1.5f, 2.f, 0.f, 6.f, 5.2f, 3.f, 0.5f, 7.f, 12.f, 4.f, -0.5f, 8.f, 8.f }); set_values(subtract, { 1.0f, 4.0f, 1.5f, 3.0f, 2.0f, 2.0f, 2.5f, 1.0f, }); topology topology( input_layout("input", input.get_layout()), input_layout("subtract", subtract.get_layout()), reorder("reorder", "input", output_layout, "subtract")); network network(engine, topology); network.set_input_data("input", input); network.set_input_data("subtract", subtract); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "reorder"); auto output = outputs.begin()->second.get_memory(); float answers[16] = { 0.0f, 0.5f, 1.0f, 1.5f, 1.0f, 3.0f, 5.0f, 7.0f, -1.0f, -1.5f, -1.5f, -3.0f, -2.5f, 2.2f, 10.0f, 7.0f }; auto output_ptr = output.pointer<float>(); for (int i = 0; i < 16; i++) { EXPECT_FLOAT_EQ(answers[i], output_ptr[i]); } } TEST(reorder_gpu_f32, basic_subtract_value) { // Values_to_subtract : 2 // Input : 2x2x2x2 // Output : 2x2x2x2 // // Input: // f0: b0: 1 2 b1: 0 0 // f0: b0: 3 4 b1: 0.5 -0.5 // f1: b0: 5 6 b1: 1.5 5.2 // f1: b0: 7 8 b1: 12 8 // // subtract values // f0: 0.5 // f1: 2.5 // // Output: // b0 f0: 0.5 1.5 // b0 f0: 2.5 3.5 // // b0 f1: 2.5 3.5 // b0 f1: 4.5 5.5 // // b1 f0: -0.5 -0.5 // b1 f0: 0.0 -1.0 // // b1 f1: -1.0 2.7 // b1 f1: 9.5 5.5 // engine engine; auto input = memory::allocate(engine, { data_types::f32, format::yxfb, { 2, 2, 2, 2 } }); layout output_layout(data_types::f32, format::bfyx,{ 2,2,2,2 }); std::vector<float> subtract_val = { 0.5, 2.5 }; set_values(input, { 1.f, 0.f, 5.f, 1.5f, 2.f, 0.f, 6.f, 5.2f, 3.f, 0.5f, 7.f, 12.f, 4.f, -0.5f, 8.f, 8.f }); topology topology; topology.add(input_layout("input", input.get_layout()), reorder("reorder", "input", output_layout, subtract_val)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "reorder"); auto output = outputs.begin()->second.get_memory(); float answers[16] = { 0.5f, 1.5f, 2.5f, 3.5f, 2.5f, 3.5f, 4.5f, 5.5f, -0.5f, -0.5f, 0.0f, -1.0f, -1.0f, 2.7f, 9.5f, 5.5f }; auto output_ptr = output.pointer<float>(); for (int i = 0; i < 16; i++) { EXPECT_TRUE(are_equal(answers[i], output_ptr[i])); } } TEST(reorder_gpu_f16, basic_subtract_f32_output_f32) { // Input : 2x2x2x2 (FP16) // Output : 2x2x2x2 (FP32) // Subtract : 1x2x2x2 (FP32, only first batch is taken into consideration) // // Input: // f0: b0: 1 2 b1: 0 0 // f0: b0: 3 4 b1: 0.5 -0.5 // f1: b0: 5 6 b1: 1.5 5.2 // f1: b0: 7 8 b1: 12 8 // // Subtract (FP32 - converted internally to FP16 before subtraction): // f0: b0: 1 1.5 // f0: b0: 2 2.5 // f1: b0: 4 3 // f1: b0: 2 1 // // // Output: // b0 f0: 0 0.5 // b0 f0: 1 1.5 // // b0 f1: 1 3 // b0 f1: 5 7 // // b1 f0: -1 -1.5 // b1 f0: -1.5 -3 // // b1 f1: -2.5 2.2 // b1 f1: 10 7 // engine engine; if (!engine.get_info().supports_fp16) { std::cout << "[ SKIPPED ] The test is skipped (cl_khr_fp16 is not supported)." << std::endl; EXPECT_EQ(1, 1); return; } auto input = memory::allocate(engine, { data_types::f16, format::yxfb, { 2, 2, 2, 2 } }); layout output_layout(data_types::f32, format::bfyx,{ 2,2,2,2 }); auto subtract = memory::allocate(engine, { data_types::f32, format::byxf, { 1, 2, 2, 2 } }); set_values(input, { half_t(0x3C00), half_t(0x0000), // 1.f, 0.f, half_t(0x4500), half_t(0x3E00), // 5.f, 1.5f, half_t(0x4000), half_t(0x0000), // 2.f, 0.f, half_t(0x4600), half_t(0x4533), // 6.f, 5.2f, half_t(0x4200), half_t(0x3800), // 3.f, 0.5f, half_t(0x4700), half_t(0x4A00), // 7.f, 12.f, half_t(0x4400), half_t(0xB800), // 4.f, -0.5f, half_t(0x4800), half_t(0x4800) // 8.f, 8.f }); set_values(subtract, { 1.0f, 4.0f, 1.5f, 3.0f, 2.0f, 2.0f, 2.5f, 1.0f, }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(data("subtract", subtract)); topology.add(reorder("reorder", "input", output_layout, "subtract")); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "reorder"); auto output = outputs.begin()->second.get_memory(); float answers[16] = { 0.0f, 0.5f, 1.0f, 1.5f, 1.0f, 3.0f, 5.0f, 7.0f, -1.0f, -1.5f, -1.5f, -3.0f, -2.5f, 2.2f, 10.0f, 7.0f }; auto output_ptr = output.pointer<float>(); for (int i = 0; i < 16; i++) { EXPECT_TRUE(are_equal(answers[i], output_ptr[i])); } } TEST(reorder_gpu_f16, basic_subtract_value) { // Values_to_subtract : 2 // Input : 2x2x2x2 (FP16) // Output : 2x2x2x2 (FP16) // // Input: // f0: b0: 1 2 b1: 0 0 // f0: b0: 3 4 b1: 0.5 -0.5 // f1: b0: 5 6 b1: 1.5 5.2 // f1: b0: 7 8 b1: 12 8 // // subtract values (FP32 - converted internally to FP16 before subtraction) // f0: 0.5 // f1: 2.5 // // Output: // b0 f0: 0.5 1.5 // b0 f0: 2.5 3.5 // // b0 f1: 2.5 3.5 // b0 f1: 4.5 5.5 // // b1 f0: -0.5 -0.5 // b1 f0: 0.0 -1.0 // // b1 f1: -1.0 2.7 // b1 f1: 9.5 5.5 // engine engine; if (!engine.get_info().supports_fp16) { std::cout << "[ SKIPPED ] The test is skipped (cl_khr_fp16 is not supported)." << std::endl; EXPECT_EQ(1, 1); return; } auto input = memory::allocate(engine, { data_types::f16, format::yxfb, { 2, 2, 2, 2 } }); layout output_layout(data_types::f16, format::bfyx,{ 2,2,2,2 }); std::vector<float> subtract_val = { 0.5, 2.5 }; set_values(input, { half_t(0x3C00), half_t(0x0000), // 1.f, 0.f, half_t(0x4500), half_t(0x3E00), // 5.f, 1.5f, half_t(0x4000), half_t(0x0000), // 2.f, 0.f, half_t(0x4600), half_t(0x4533), // 6.f, 5.2f, half_t(0x4200), half_t(0x3800), // 3.f, 0.5f, half_t(0x4700), half_t(0x4A00), // 7.f, 12.f, half_t(0x4400), half_t(0xB800), // 4.f, -0.5f, half_t(0x4800), half_t(0x4800) // 8.f, 8.f }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(reorder("reorder", "input", output_layout, subtract_val)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "reorder"); auto output = outputs.begin()->second.get_memory(); half_t answers[16] = { half_t(0x3800), half_t(0x3E00), // 0.5f, 1.5f, half_t(0x4100), half_t(0x4300), // 2.5f, 3.5f, half_t(0x4100), half_t(0x4300), // 2.5f, 3.5f, half_t(0x4480), half_t(0x4580), // 4.5f, 5.5f, half_t(0xB800), half_t(0xB800), // -0.5f, -0.5f, half_t(0x0000), half_t(0xBC00), // 0.0f, -1.0f, half_t(0xBC00), half_t(0x4166), // -1.0f, 2.7f, half_t(0x48C0), half_t(0x4580) // 9.5f, 5.5f }; auto output_ptr = output.pointer<half_t>(); for (int i = 0; i < 16; i++) { EXPECT_TRUE(are_equal(static_cast<uint16_t>(answers[i]), static_cast<uint16_t>(output_ptr[i]))); } } TEST(reorder_gpu, basic_convert_f16_f32_f16) { // Converts entire unambiguous range of FP16 numbers to FP32 and back. // // Input : 2x2x15873x1 (FP16) // Intermediate : 1x2x2x15873 (FP32) {different mem format but the same ordering because batch is 1} // Output : 2x2x15673x1 (FP16) // // Output is expected to contain the same value as input in range of indices from 0x0000 to 0xF801. // engine engine; if (!engine.get_info().supports_fp16) { std::cout << "[ SKIPPED ] The test is skipped (cl_khr_fp16 is not supported)." << std::endl; EXPECT_EQ(1, 1); return; } std::vector<half_t> expected_values; expected_values.resize(0xF804); for (int i = 0; i < 0x7C00; ++i) expected_values[i] = half_t(i); // norms/denorms/zero (positive). for (int i = 0x7C00; i < 0xF800; ++i) expected_values[i] = half_t(i + 0x0400); // norms/denorms (negative). expected_values[0x7C00] = half_t(0x0000); // NOTE: do not do final test for negative 0 (-0). // Special values. expected_values[0xF800] = half_t(0x7C00); // +infinity expected_values[0xF801] = half_t(0xFC00); // -infinity // Special values (ambiguous ones). expected_values[0xF802] = half_t(0x8000); // -0 expected_values[0xF803] = half_t(0xFC12); // A NaN (sample: -NaN.0x12). auto input = memory::allocate(engine, { data_types::f16, format::yxfb, { 1, static_cast<int32_t>(expected_values.size()) / 4, 2, 2 } }); layout interm_layout( data_types::f32, format::byxf, { 1, static_cast<int32_t>(expected_values.size()) / 4, 2, 2 }); auto output_layout = input.get_layout(); set_values(input, expected_values); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(reorder("reorder_f16_f32", "input", interm_layout)); topology.add(reorder("reorder_f32_f16", "reorder_f16_f32", output_layout)); network network( engine, topology, { build_option::outputs({"reorder_f16_f32", "reorder_f32_f16"}) }); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(2)); EXPECT_TRUE(outputs.find("reorder_f16_f32") != outputs.end()); EXPECT_TRUE(outputs.find("reorder_f32_f16") != outputs.end()); auto interm = outputs.at("reorder_f16_f32").get_memory(); auto interm_ptr = interm.pointer<float>(); // Sample positive. EXPECT_TRUE(are_equal(interm_ptr[0x3400], 0.25f)); EXPECT_TRUE(are_equal(interm_ptr[0x3800], 0.5f)); EXPECT_TRUE(are_equal(interm_ptr[0x3C00], 1.0f)); EXPECT_TRUE(are_equal(interm_ptr[0x4000], 2.0f)); EXPECT_TRUE(are_equal(interm_ptr[0x4400], 4.0f)); // Sample negative. EXPECT_TRUE(are_equal(interm_ptr[0x3400 + 0x7C00], -0.25f)); EXPECT_TRUE(are_equal(interm_ptr[0x3800 + 0x7C00], -0.5f)); EXPECT_TRUE(are_equal(interm_ptr[0x3C00 + 0x7C00], -1.0f)); EXPECT_TRUE(are_equal(interm_ptr[0x4000 + 0x7C00], -2.0f)); EXPECT_TRUE(are_equal(interm_ptr[0x4400 + 0x7C00], -4.0f)); // Special values. EXPECT_TRUE(are_equal(interm_ptr[0xF800], std::numeric_limits<float>::infinity())); EXPECT_TRUE(are_equal(interm_ptr[0xF801], -std::numeric_limits<float>::infinity())); EXPECT_TRUE(are_equal(interm_ptr[0xF802], -0.0f)); EXPECT_TRUE(std::isnan(interm_ptr[0xF803])); auto output = outputs.at("reorder_f32_f16").get_memory(); auto output_ptr = output.pointer<half_t>(); for (int i = 0; i < 0xF802; ++i) // NOTE: do not test for possibly ambiguous values of floating point (-0, NaNs). { EXPECT_TRUE(are_equal(static_cast<uint16_t>(expected_values[i]), static_cast<uint16_t>(output_ptr[i]))); } } TEST(DISABLED_reorder_gpu_f32, basic_flatten_yxfb_to_bx) { // Input : yxfb:2x2x2x2 // Output : bx:2x8 // // Input: // f0: b0: 1 2 b1: 0 0 // f0: b0: 3 4 b1: 0.5 -0.5 // f1: b0: 5 6 b1: 1.5 5.2 // f1: b0: 7 8 b1: 12 8 // // Output: // b0: 1 2 3 4 5 6 7 8 // b1: 0 0 0.5 -0.5 1.5 5.2 12 8 engine engine; auto batch_num = 2; auto feature_num = 2; auto x_size = 2; auto y_size = 2; auto input = memory::allocate(engine, { data_types::f32, format::yxfb,{ batch_num, feature_num, x_size, y_size } }); layout output_layout(data_types::f32, format::bfyx,{ batch_num, 1, y_size * x_size * feature_num, 1 }); std::vector<float> input_vec = { 1.f, 0.f, 5.f, 1.5f, 2.f, 0.f, 6.f, 5.2f, 3.f, 0.5f, 7.f, 12.f, 4.f, -0.5f, 8.f, 8.f }; set_values(input, input_vec); topology topology( input_layout("input", input.get_layout()), reorder("reorder", "input", output_layout)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "reorder"); auto output = outputs.begin()->second.get_memory(); auto output_ptr = output.pointer<float>(); for (int i = 0; i < batch_num; ++i) { //B for (int j = 0; j < feature_num * y_size * x_size; ++j) { //F * Y * X int linear_id_output = j + i * feature_num * y_size * x_size; int cpos = j / (x_size * y_size); int ypos = (j / x_size) % y_size; int xpos = j % x_size; int linear_id = i + batch_num * (cpos + feature_num * (xpos + x_size * ypos)); EXPECT_EQ(output_ptr[linear_id_output], input_vec[linear_id]); } } } TEST(DISABLED_reorder_gpu_f32, basic_flatten_yxfb_to_xb) { // Input : yxfb:2x2x2x2 // Output : bx:2x8 // // Input: // f0: b0: 1 2 b1: 0 0 // f0: b0: 3 4 b1: 0.5 -0.5 // f1: b0: 5 6 b1: 1.5 5.2 // f1: b0: 7 8 b1: 12 8 // // Output: // b0: 1 2 3 4 5 6 7 8 // b1: 0 0 0.5 -0.5 1.5 5.2 12 8 engine engine; auto batch_num = 2; auto feature_num = 2; auto x_size = 2; auto y_size = 2; auto input = memory::allocate(engine, { data_types::f32, format::yxfb,{ batch_num, feature_num, x_size, y_size } }); layout output_layout(data_types::f32, format::yxfb,{ batch_num, 1, y_size * x_size * feature_num, 1 }); std::vector<float> input_vec = { 1.f, 0.f, 5.f, 1.5f, 2.f, 0.f, 6.f, 5.2f, 3.f, 0.5f, 7.f, 12.f, 4.f, -0.5f, 8.f, 8.f }; set_values(input, input_vec); topology topology( input_layout("input", input.get_layout()), reorder("reorder", "input", output_layout)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "reorder"); auto output = outputs.begin()->second.get_memory(); auto output_ptr = output.pointer<float>(); std::vector<float> debug, debug2, debug3; for (int j = 0; j < batch_num * feature_num * y_size * x_size; ++j) { debug.push_back(output_ptr[j]); } for (int i = 0; i < batch_num; ++i) { //B for (int j = 0; j < feature_num * y_size * x_size; ++j) { //F * Y * X int linear_id_output = j * batch_num + i; int cpos = j / (x_size * y_size); int ypos = (j / x_size) % y_size; int xpos = j % x_size; int linear_id = i + batch_num * (cpos + feature_num * (xpos + x_size * ypos)); EXPECT_EQ(output_ptr[linear_id_output], input_vec[linear_id]); } } } TEST(DISABLED_reorder_gpu_f32, basic_flatten_bfyx_to_bx) { // Input : yxfb:2x2x2x2 // Output : bx:2x8 // // Input: // f0: b0: 1 2 b1: 0 0 // f0: b0: 3 4 b1: 0.5 -0.5 // f1: b0: 5 6 b1: 1.5 5.2 // f1: b0: 7 8 b1: 12 8 // // Output: // b0: 1 2 3 4 5 6 7 8 // b1: 0 0 0.5 -0.5 1.5 5.2 12 8 engine engine; auto batch_num = 2; auto feature_num = 2; auto x_size = 2; auto y_size = 2; auto input = memory::allocate(engine, { data_types::f32,format::bfyx,{ batch_num, feature_num, x_size, y_size } }); layout output_layout(data_types::f32, format::bfyx,{ batch_num, 1, y_size * x_size * feature_num, 1 }); std::vector<float> input_vec = { 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 0.f, 0.f, 0.5f, -0.5f, 1.5f, 5.2f, 12.f, 8.f }; set_values(input, input_vec); topology topology( input_layout("input", input.get_layout()), reorder("reorder", "input", output_layout)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "reorder"); auto output = outputs.begin()->second.get_memory(); auto output_ptr = output.pointer<float>(); for (int i = 0; i < batch_num; ++i) { //B for (int j = 0; j < feature_num * y_size * x_size; ++j) { //F * Y * X int linear_id = j + i * feature_num * y_size * x_size; EXPECT_EQ(output_ptr[linear_id], input_vec[linear_id]); } } } TEST(DISABLED_reorder_gpu_f32, basic_flatten_yxfb_to_x) { // Input : yxfb:2x2x2x2 // Output : bx:2x8 // // Input: // f0: b0: 1 2 b1: 0 0 // f0: b0: 3 4 b1: 0.5 -0.5 // f1: b0: 5 6 b1: 1.5 5.2 // f1: b0: 7 8 b1: 12 8 // // Output: // 1 0 5 1.5 2 0 6 5.2 3 0.5 7 12 4 -0.5 8 8 engine engine; auto batch_num = 2; auto feature_num = 2; auto x_size = 2; auto y_size = 2; auto input = memory::allocate(engine, { data_types::f32,format::yxfb,{ batch_num, feature_num, x_size, y_size } }); layout output_layout(data_types::f32, format::yxfb,{ 1, 1, y_size * x_size * feature_num * batch_num, 1 }); std::vector<float> input_vec = { 1.f, 0.f, 5.f, 1.5f, 2.f, 0.f, 6.f, 5.2f, 3.f, 0.5f, 7.f, 12.f, 4.f, -0.5f, 8.f, 8.f }; set_values(input, input_vec); topology topology( input_layout("input", input.get_layout()), reorder("reorder", "input", output_layout)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "reorder"); auto output = outputs.begin()->second.get_memory(); auto output_ptr = output.pointer<float>(); for (int i = 0; i < batch_num; ++i) { //B for (int j = 0; j < feature_num * y_size * x_size; ++j) { //F * Y * X int linear_id_output = j * batch_num + i; int cpos = j / (x_size * y_size); int ypos = (j / x_size) % y_size; int xpos = j % x_size; int linear_id = i + batch_num * (cpos + feature_num * (xpos + x_size * ypos)); EXPECT_EQ(output_ptr[linear_id_output], input_vec[linear_id]); } } } using namespace cldnn; class reorder_test : public tests::generic_test { public: static void TearDownTestCase() { for (auto generic_params : all_generic_params) { delete generic_params; } for (auto test_param : all_test_params) { auto primitive = std::get<1>(test_param); delete primitive; } } static std::vector<std::tuple<test_params*, cldnn::primitive*>> generate_specific_test_params() { generic_test::generate_generic_test_params(all_generic_params, true); const std::vector<cldnn::data_types> data_types = { cldnn::data_types::f32 , cldnn::data_types::f16 }; for (auto test_param : all_generic_params) { cldnn::tensor input_tensor = test_param->input_layouts[0]; std::vector<cldnn::layout> output_layouts = {}; for (auto dt : data_types) { for (auto fmt : generic_test::test_input_formats) { output_layouts.push_back({ dt, fmt, input_tensor }); } } // TODO: check unsupported formats. //TODO: check subtract. std::vector<float> subtract = {}; for (auto output_layout : output_layouts) { //TODO: check input + output padding. all_test_params.push_back(std::make_tuple(test_param, new reorder("reorder", "input0", output_layout, subtract))); } } return all_test_params; } virtual bool is_format_supported(cldnn::format format) { return ( (format == cldnn_format_type::cldnn_format_yxfb) || (format == cldnn_format_type::cldnn_format_byxf) || (format == cldnn_format_type::cldnn_format_bfyx) || (format == cldnn_format_type::cldnn_format_fyxb) ); } template<typename InputType, typename OutputType> memory generate_reference_typed(const std::vector<cldnn::memory>& inputs) { const cldnn::reorder* reorder = (cldnn::reorder*)layer_params; primitive_id mean = reorder->mean; std::vector<float> subtract_per_feature = reorder->subtract_per_feature; assert(mean == ""); assert(subtract_per_feature.size() == 0); auto output = memory::allocate(engine, cldnn::layout(reorder->output_data_type, inputs[0].get_layout().format, inputs[0].get_layout().size)); cldnn::pointer<InputType> input_mem = inputs[0].pointer<InputType>(); cldnn::pointer<OutputType> output_mem = output.pointer<OutputType>(); for (size_t i = 0; i < inputs[0].get_layout().get_linear_size(); i++) { // Write the output in the same order as the input with type conversion as needed. // The correct order will be checked in generic_test::compare_buffers. output_mem[i] = (OutputType)input_mem[i]; } return output; } virtual memory generate_reference(const std::vector<cldnn::memory>& inputs) { if (generic_params->data_type == data_types::f32) { if (((cldnn::reorder*)layer_params)->output_data_type == data_types::f32) { return generate_reference_typed<float, float>(inputs); } else { return generate_reference_typed<float, FLOAT16>(inputs); } } else { if (((cldnn::reorder*)layer_params)->output_data_type == data_types::f32) { return generate_reference_typed<FLOAT16, float>(inputs); } else { return generate_reference_typed<FLOAT16, FLOAT16>(inputs); } } } private: static std::vector<tests::test_params*> all_generic_params; static std::vector<std::tuple<test_params*, cldnn::primitive*>> all_test_params; }; std::vector<tests::test_params*> reorder_test::all_generic_params = {}; std::vector<std::tuple<test_params*, cldnn::primitive*>> reorder_test::all_test_params = {}; TEST_P(reorder_test, DISABLED_test_all) { run_single_test(); } INSTANTIATE_TEST_CASE_P(REORDER, reorder_test, ::testing::ValuesIn(reorder_test::generate_specific_test_params()), tests::generic_test::custom_param_name_functor());
29.449532
143
0.543126
kyper999
6037404ef7b5caba437ed595f53dd4890ed0802a
964
hpp
C++
cpp/bls/include/bls/msg.hpp
aguycalled/react-native-mcl
a4754aa23b473db2765ceac288a44cca39b20087
[ "MIT" ]
212
2016-08-10T03:54:55.000Z
2022-03-28T02:43:08.000Z
cpp/bls/include/bls/msg.hpp
aguycalled/react-native-mcl
a4754aa23b473db2765ceac288a44cca39b20087
[ "MIT" ]
78
2016-09-06T22:22:52.000Z
2022-03-29T11:21:33.000Z
cpp/bls/include/bls/msg.hpp
aguycalled/react-native-mcl
a4754aa23b473db2765ceac288a44cca39b20087
[ "MIT" ]
112
2016-09-06T02:32:02.000Z
2022-03-28T07:41:10.000Z
#pragma once /** @file @brief check msg @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <stdint.h> #include <set> #include <memory.h> namespace bls_util { const size_t MSG_SIZE = 32; struct Msg { uint8_t v[MSG_SIZE]; bool operator<(const Msg& rhs) const { for (size_t i = 0; i < MSG_SIZE; i++) { if (v[i] < rhs.v[i]) return true; if (v[i] > rhs.v[i]) return false; } return false; } bool operator==(const Msg& rhs) const { return memcmp(v, rhs.v, MSG_SIZE) == 0; } }; inline bool areAllMsgDifferent(const void *buf, size_t bufSize) { size_t n = bufSize / MSG_SIZE; if (bufSize != n * MSG_SIZE) { return false; } const Msg *msg = (const Msg*)buf; typedef std::set<Msg> MsgSet; MsgSet ms; for (size_t i = 0; i < n; i++) { std::pair<MsgSet::iterator, bool> ret = ms.insert(msg[i]); if (!ret.second) return false; } return true; } } // bls_util
18.901961
63
0.644191
aguycalled
603b990e12f490d760778268ff031a8f3583032e
3,012
cpp
C++
ovPCRE.cpp
theloox/ovSTR
f1fddb6a6e0e3761c770ab604728f7e7f8805466
[ "MIT" ]
null
null
null
ovPCRE.cpp
theloox/ovSTR
f1fddb6a6e0e3761c770ab604728f7e7f8805466
[ "MIT" ]
null
null
null
ovPCRE.cpp
theloox/ovSTR
f1fddb6a6e0e3761c770ab604728f7e7f8805466
[ "MIT" ]
null
null
null
/*************************************************************************** * 2005 by Axel Gonzalez * * loox@e-shell.net * * * * This software is in the public domain. Permission to use, copy, * * modify, and distribute this software and its documentation for any * * purpose and without fee is hereby granted, without any conditions or * * restrictions. This software is provided "as is" without express or * * implied warranty. * * * ***************************************************************************/ #include "ovPCRE.h" ovPCRE::ovPCRE() { pattern = "*"; flags = 0; options = 0; error = NULL; erroffset = 0; re = NULL; re = pcre_compile(pattern, flags, &error, &erroffset, NULL); } ovPCRE::ovPCRE(ovStr p) { pattern = p; flags = 0; options = 0; error = NULL; erroffset = 0; re = NULL; re = pcre_compile(pattern, flags, &error, &erroffset, NULL); } ovPCRE::ovPCRE(ovStr p, int f) { pattern = p; flags = PCRE_CASELESS; options = 0; error = NULL; erroffset = 0; re = NULL; re = pcre_compile(pattern, flags, &error, &erroffset, NULL); } ovPCRE::~ovPCRE() { if (re != NULL) pcre_free(re); } void ovPCRE::SetPattern(ovStr p) { pattern = p; flags = 0; if (re != NULL) pcre_free(re); re = pcre_compile(pattern, flags, &error, &erroffset, NULL); } int ovPCRE::GetOptions() { return(this->flags); } void ovPCRE::SetOptions(int f) { this->flags = f; } int ovPCRE::Match(ovStr subject) { int rc; if (re == NULL) return(0); rc = pcre_exec(re, NULL, subject, subject.Len(), 0, this->options, ovector, MAX_VECTORS); if (rc < 0) return(0); return(ovector[0] + 1); } int ovPCRE::MatchAll(ovStr subject, ovStrArray &matches, unsigned int index) { int i; int count, rc; int offset; const char **listptr; ovStr str; i = 0; offset = 0; if (index < 0) index = 0; matches.Clean(); while ((count = pcre_exec(re, NULL, subject, subject.Len(), offset, options, ovector, MAX_VECTORS)) > 0) { rc = pcre_get_substring_list(subject, ovector, count, &listptr); if (rc < 0) return(0); str = listptr[0]; offset = subject.strpos(str, offset) + str.Len(); str = listptr[index < count ? index : (count - 1)]; matches.Add(str); pcre_free_substring_list(listptr); i++; } //printf("COunt: %d\n", count); return(i); } ovStr ovPCRE::Replace() { } ovStr ovPCRE::Error() { if (error == NULL) return(""); else return(error); }
17.928571
110
0.479748
theloox
603bb4a1397054f1c4d25d2c2ee7114147f8466f
5,759
cpp
C++
fpdfsdk/src/pdfwindow/PWL_ListCtrl.cpp
quanganh2627/bytm-x64-L-w05-2015_external_pdfium
86957661fc29ce82c3101107f95a11d1f9e59932
[ "BSD-3-Clause" ]
4
2015-06-24T17:11:51.000Z
2015-07-16T13:10:25.000Z
fpdfsdk/src/pdfwindow/PWL_ListCtrl.cpp
quanganh2627/bytm-x64-L-w05-2015_external_pdfium
86957661fc29ce82c3101107f95a11d1f9e59932
[ "BSD-3-Clause" ]
null
null
null
fpdfsdk/src/pdfwindow/PWL_ListCtrl.cpp
quanganh2627/bytm-x64-L-w05-2015_external_pdfium
86957661fc29ce82c3101107f95a11d1f9e59932
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "../../include/pdfwindow/PDFWindow.h" #include "../../include/pdfwindow/PWL_Wnd.h" #include "../../include/pdfwindow/PWL_ListCtrl.h" /* ---------------------------- CPWL_ListCtrl ---------------------------- */ CPWL_ListCtrl::CPWL_ListCtrl() : m_rcContent(0,0,0,0), m_ptScroll(0,0), m_fItemSpace(0.0f), m_fTopSpace(0.0f), m_fBottomSpace(0.0f) { } CPWL_ListCtrl::~CPWL_ListCtrl() { } void CPWL_ListCtrl::SetScrollPos(const CPDF_Point& point) { m_ptScroll = point; if (m_ptScroll.x < m_rcContent.left) m_ptScroll.x = m_rcContent.left; if (m_ptScroll.x > m_rcContent.right) m_ptScroll.x = m_rcContent.right; if (m_ptScroll.y > m_rcContent.top) m_ptScroll.y = m_rcContent.top; if (m_ptScroll.y < m_rcContent.bottom) m_ptScroll.y = m_rcContent.bottom; } CPDF_Point CPWL_ListCtrl::GetScrollPos() const { return m_ptScroll; } CPDF_Rect CPWL_ListCtrl::GetScrollArea() const { return m_rcContent; } void CPWL_ListCtrl::ResetFace() { ResetAll(FALSE, 0); } void CPWL_ListCtrl::ResetContent(FX_INT32 nStart) { if (nStart < 0) nStart = 0; if (nStart >= 0 && nStart < m_aChildren.GetSize()) ResetAll(TRUE, nStart); } FX_FLOAT CPWL_ListCtrl::GetContentsHeight(FX_FLOAT fLimitWidth) { FX_FLOAT fRet = m_fTopSpace; FX_FLOAT fBorderWidth = (FX_FLOAT)this->GetBorderWidth(); if (fLimitWidth > fBorderWidth* 2) { for (FX_INT32 i=0,sz=m_aChildren.GetSize(); i<sz; i++) { if (CPWL_Wnd* pChild = m_aChildren.GetAt(i)) { FX_FLOAT fLeft = pChild->GetItemLeftMargin(); FX_FLOAT fRight = pChild->GetItemRightMargin(); fRet += pChild->GetItemHeight(fLimitWidth - fBorderWidth* 2 - fLeft - fRight); fRet += m_fItemSpace; } } fRet -= m_fItemSpace; } fRet += m_fBottomSpace; return fRet; } void CPWL_ListCtrl::ResetAll(FX_BOOL bMove, FX_INT32 nStart) { CPDF_Rect rcClient = GetClientRect(); FX_FLOAT fWidth = rcClient.Width(); FX_FLOAT fy = 0.0f - m_fTopSpace; if (nStart-1 >= 0 && nStart-1 < m_aChildren.GetSize()) if (CPWL_Wnd* pChild = m_aChildren.GetAt(nStart-1)) fy = pChild->GetWindowRect().bottom - m_fItemSpace; for (FX_INT32 i=nStart,sz=m_aChildren.GetSize(); i<sz; i++) { if (CPWL_Wnd* pChild = m_aChildren.GetAt(i)) { FX_FLOAT fLeft = pChild->GetItemLeftMargin(); FX_FLOAT fRight = pChild->GetItemRightMargin(); pChild->SetChildMatrix( CPDF_Matrix(1,0,0,1, rcClient.left - m_ptScroll.x, rcClient.top - m_ptScroll.y) ); if (bMove) { FX_FLOAT fItemHeight = pChild->GetItemHeight(fWidth - fLeft - fRight); pChild->Move(CPDF_Rect(fLeft, fy-fItemHeight, fWidth - fRight, fy), TRUE, FALSE); fy -= fItemHeight; fy -= m_fItemSpace; } } } fy += m_fItemSpace; fy -= m_fBottomSpace; if (bMove) { m_rcContent.left = 0; m_rcContent.top = 0; m_rcContent.right = fWidth; m_rcContent.bottom = fy; } } void CPWL_ListCtrl::SetItemSpace(FX_FLOAT fSpace) { m_fItemSpace = fSpace; } void CPWL_ListCtrl::SetTopSpace(FX_FLOAT fSpace) { m_fTopSpace = fSpace; } void CPWL_ListCtrl::SetBottomSpace(FX_FLOAT fSpace) { m_fBottomSpace = fSpace; } void CPWL_ListCtrl::RePosChildWnd() { ResetFace(); } void CPWL_ListCtrl::DrawChildAppearance(CFX_RenderDevice* pDevice, CPDF_Matrix* pUser2Device) { pDevice->SaveState(); CPDF_Rect rcClient = GetClientRect(); CPDF_Rect rcTemp = rcClient; pUser2Device->TransformRect(rcTemp); FX_RECT rcClip((FX_INT32)rcTemp.left, (FX_INT32)rcTemp.bottom, (FX_INT32)rcTemp.right, (FX_INT32)rcTemp.top); pDevice->SetClip_Rect(&rcClip); for (FX_INT32 i=0,sz=m_aChildren.GetSize(); i<sz; i++) { if (CPWL_Wnd * pChild = m_aChildren.GetAt(i)) { CPDF_Rect rcChild = pChild->ChildToParent(pChild->GetWindowRect()); if (!(rcChild.top < rcClient.bottom || rcChild.bottom > rcClient.top)) { CPDF_Matrix mt = pChild->GetChildMatrix(); if (mt.IsIdentity()) { pChild->DrawAppearance(pDevice,pUser2Device); } else { mt.Concat(*pUser2Device); pChild->DrawAppearance(pDevice,&mt); } } } } pDevice->RestoreState(); } FX_INT32 CPWL_ListCtrl::GetItemIndex(CPWL_Wnd* pItem) { for (FX_INT32 i=0, sz=m_aChildren.GetSize(); i<sz; i++) { if (pItem == m_aChildren.GetAt(i)) return i; } return -1; } CPDF_Point CPWL_ListCtrl::InToOut(const CPDF_Point& point) const { CPDF_Rect rcClient = GetClientRect(); return CPDF_Point(point.x + rcClient.left - m_ptScroll.x, point.y + rcClient.top - m_ptScroll.y); } CPDF_Point CPWL_ListCtrl::OutToIn(const CPDF_Point& point) const { CPDF_Rect rcClient = GetClientRect(); return CPDF_Point(point.x - rcClient.left + m_ptScroll.x, point.y - rcClient.top + m_ptScroll.y); } CPDF_Rect CPWL_ListCtrl::InToOut(const CPDF_Rect& rect) const { CPDF_Rect rcClient = GetClientRect(); return CPDF_Rect(rect.left + rcClient.left - m_ptScroll.x, rect.bottom + rcClient.top - m_ptScroll.y, rect.right + rcClient.left - m_ptScroll.x, rect.top + rcClient.top - m_ptScroll.y); } CPDF_Rect CPWL_ListCtrl::OutToIn(const CPDF_Rect& rect) const { CPDF_Rect rcClient = GetClientRect(); return CPDF_Rect(rect.left - rcClient.left + m_ptScroll.x, rect.bottom - rcClient.top + m_ptScroll.y, rect.right - rcClient.left + m_ptScroll.x, rect.top - rcClient.top + m_ptScroll.y); }
23.410569
94
0.667477
quanganh2627
603c304083c76ea484ec2b6a10fb55c0f0d38824
1,381
cc
C++
garnet/lib/ui/gfx/engine/duration_predictor.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
1
2019-04-21T18:02:26.000Z
2019-04-21T18:02:26.000Z
garnet/lib/ui/gfx/engine/duration_predictor.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
garnet/lib/ui/gfx/engine/duration_predictor.cc
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "garnet/lib/ui/gfx/engine/duration_predictor.h" #include <src/lib/fxl/logging.h> namespace scenic_impl { namespace gfx { DurationPredictor::DurationPredictor(size_t window_size, zx::duration initial_prediction) : kWindowSize(window_size), window_(kWindowSize, initial_prediction) { FXL_DCHECK(kWindowSize > 0); current_maximum_duration_index_ = kWindowSize - 1; } zx::duration DurationPredictor::GetPrediction() const { return window_[current_maximum_duration_index_]; } void DurationPredictor::InsertNewMeasurement(zx::duration duration) { // Move window forward. window_.push_front(duration); window_.pop_back(); ++current_maximum_duration_index_; if (current_maximum_duration_index_ >= kWindowSize) { // If old min went out of scope, find the new min. current_maximum_duration_index_ = 0; for (size_t i = 1; i < kWindowSize; ++i) { if (window_[i] > window_[current_maximum_duration_index_]) { current_maximum_duration_index_ = i; } } } else if (window_.front() >= window_[current_maximum_duration_index_]) { // Use newest possible maximum. current_maximum_duration_index_ = 0; } } } // namespace gfx } // namespace scenic_impl
31.386364
89
0.740768
zhangpf
603f43cdde744bc7f8046572508c2294a0231ee8
711
cpp
C++
vta/bundles/FCTest/vtaFCTestBundle.cpp
etri/nest-compiler
c6ac790ed12807f2e0855e3aa0170cb149dc237d
[ "Apache-2.0" ]
112
2020-12-16T07:05:39.000Z
2022-03-15T08:12:03.000Z
vta/bundles/FCTest/vtaFCTestBundle.cpp
etri/nest-compiler
c6ac790ed12807f2e0855e3aa0170cb149dc237d
[ "Apache-2.0" ]
1
2022-02-25T03:36:18.000Z
2022-02-25T05:01:43.000Z
vta/bundles/FCTest/vtaFCTestBundle.cpp
etri/nest-compiler
c6ac790ed12807f2e0855e3aa0170cb149dc237d
[ "Apache-2.0" ]
10
2021-01-08T01:36:26.000Z
2022-02-23T02:03:08.000Z
#include "vta/runtime.h" #include "vta/vtalib/include/Bundle/VTABundle.h" #include "vtaFCTestBundle.h" SymbolTableEntry symbolTableEntry[2]={{"inputP",0,2048,'1'},{"outP",2048,1000,'1'}}; BundleConfig vtaFCTestBundle_config = {2052000, 3048, 0, 64, 2, symbolTableEntry}; int vtaFCTestMainEntry(int8_t *constantWeight, int8_t *mutableWeight, int8_t *activations){ xlnk_reset(); int8_t* filterP = constantWeight + 0; int8_t* biasP = constantWeight + 2048000; int8_t* inputP = mutableWeight + 0; int8_t* outP = mutableWeight + 2048; fullyconnected(inputP, 1.0/8.000000, 0, filterP, 1.0/128.000000, 0, biasP, 1.0/1024.000000, 0, outP, 1.0/4.000000, 0, 1, 2048, 2048, 1000, 1, 1000, 1 ); return 0; }
41.823529
154
0.7173
etri
603fe78538b1cd7b86abaaf5c7c1d79049fa445a
5,710
cpp
C++
Tests/support/matrix_support.cpp
Freddan-67/V3DLib
dcefc24a9a399ee1f5d1aa5529f44d9fd2486929
[ "MIT" ]
44
2021-01-16T14:17:15.000Z
2022-03-11T19:53:59.000Z
Tests/support/matrix_support.cpp
RcCreeperTech/V3DLib
38eb8d55b8276de5cf703d8e13fb9b5f220c49f0
[ "MIT" ]
8
2021-01-16T17:52:02.000Z
2021-12-18T22:38:00.000Z
Tests/support/matrix_support.cpp
RcCreeperTech/V3DLib
38eb8d55b8276de5cf703d8e13fb9b5f220c49f0
[ "MIT" ]
7
2021-01-16T14:25:47.000Z
2022-02-03T16:34:45.000Z
#include "matrix_support.h" #include "../doctest.h" #include "Support/Helpers.h" // random_float() using namespace V3DLib; void compare_arrays(Float::Array2D &a, float const *b, float precision) { // Values empirically determined - the bigger the matrices, the less precise if (precision == -1.0f) { if (Platform::has_vc4()) { precision = 1.0e-3f; } else { precision = 2.5e-4f; // This value works for 640x640 matrices } } float max_diff = -1; for (int r = 0; r < a.rows(); r++) { for (int c = 0; c < a.columns(); c++) { float diff = abs(a[r][c] - b[r*a.columns() + c]); if (max_diff == -1 || max_diff < diff) { max_diff = diff; } } } INFO("Max diff: " << max_diff << ", precision: " << precision); for (int r = 0; r < a.rows(); r++) { for (int c = 0; c < a.columns(); c++) { INFO("r: " << r << ", c: " << c); //INFO("Result: " << a.dump()); INFO("result: " << a[r][c] << ", expected: " << b[r*a.columns() + c]); REQUIRE(abs(a[r][c] - b[r*a.columns() + c]) < precision); } } } /** * This is better than: * * REQUIRE(m1.result() == m2.result()); * * ....which has been known to fail incorrectly. */ void compare_arrays(Float::Array2D &a, Float::Array2D &b, float precision) { REQUIRE(a.rows() == b.rows()); REQUIRE(a.columns() == b.columns()); if ( precision == -1.0f) { //precision = 1.0e-4f; // for high precision sin/cos in kernels precision = 4.1e-1f; // for low precision sin/cos in vc4 kernels (yeah, it sucks) } for (int r = 0; r < a.rows(); ++r) { for (int c = 0; c < a.columns(); ++c) { INFO("(r, c): ( " << r << ", " << c << ")"); INFO(a[r][c] << " == " << b[r][c]); // <= for dealing with precision 0.0f REQUIRE(abs(a[r][c] - b[r][c]) <= precision); REQUIRE(abs(a[r][c] - b[r][c]) <= precision); } } } void compare_arrays(Complex::Array2D &a, Complex::Array2D &b, float precision) { REQUIRE(a.rows() == b.rows()); REQUIRE(a.columns() == b.columns()); if ( precision == -1.0f) { //precision = 1.0e-4f; // for high precision sin/cos in kernels precision = 4.0e-1f; // for low precision sin/cos in kernels } float max_diff_re = -1; float max_diff_im = -1; for (int r = 0; r < a.rows(); r++) { for (int c = 0; c < a.columns(); c++) { float diff_re = abs(a[r][c].re() - b[r][c].re()); if (max_diff_re == -1 || max_diff_re < diff_re) { max_diff_re = diff_re; } float diff_im = abs(a[r][c].im() - b[r][c].im()); if (max_diff_im == -1 || max_diff_im < diff_im) { max_diff_im = diff_im; } } } // Do an overall check if (max_diff_re <= precision && max_diff_im <= precision) { return; // All is well } INFO("Max diff re: " << max_diff_re << ", max diff im: " << max_diff_im << ", precision: " << precision); // Do a specific check to find the (r,c) coordinate where it goes wrong for (int r = 0; r < a.rows(); ++r) { for (int c = 0; c < a.columns(); ++c) { INFO("(r, c): ( " << r << ", " << c << ")"); INFO(a[r][c].dump() << " == " << b[r][c].dump()); // <= for dealing with precision 0.0f // REQUIRE(abs(a[r][c].magnitude() - b[r][c].magnitude()) <= precision); REQUIRE(abs(a[r][c].re() - b[r][c].re()) <= precision); REQUIRE(abs(a[r][c].im() - b[r][c].im()) <= precision); } } } void compare_arrays(std::vector<float> &a, float const *b) { float precision = 1e-4f; for (int r = 0; r < (int) a.size(); ++r) { REQUIRE(abs(a[r] - b[r]) < precision); } } void check_unitary(std::vector<float> &a, int dim) { for (int r = 0; r < dim; r++) { for (int c = 0; c < dim; c++) { INFO("rows: " << dim << ", (r,c): (" << r << ", " << c << ")"); int offset = r*dim + c; if (r == c) { REQUIRE(a[offset] == 1.0f); } else { REQUIRE(a[offset] == 0.0f); } } } } void check_unitary(Float::Array2D &a) { REQUIRE(a.rows() == a.columns()); for (int r = 0; r < a.rows(); r++) { for (int c = 0; c < a.columns(); c++) { INFO("rows: " << a.rows() << ", (r,c): (" << r << ", " << c << ")"); if (r == c) { REQUIRE(a[r][c] == 1.0f); } else { REQUIRE(a[r][c] == 0.0f); } } } } void fill_random(float *arr, int size) { for (int n = 0; n < size; n++) { arr[n] = random_float(); } } void fill_random(std::vector<float> &arr) { assert(!arr.empty()); fill_random(arr.data(), (int) arr.size()); } /** * Pre: dst properly initialized, matches with src */ void copy_array(Float::Array2D &dst, float const *src) { for (int r = 0; r < dst.rows(); r++) { for (int c = 0; c < dst.columns(); c++) { dst[r][c] = src[r*dst.columns() + c]; } } } void copy_array(Float::Array2D &dst, std::vector<float> const &src) { assert(!src.empty()); assert((int) src.size() == dst.rows()*dst.columns()); copy_array(dst, src.data()); } void copy_transposed(float *dst, float const *src, int rows, int columns) { for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { dst[c*rows + r] = src[r*columns + c]; } } } void copy_transposed(std::vector<float> &dst, std::vector<float> const &src, int rows, int columns) { copy_transposed(dst.data(), src.data(), rows, columns); } void compare_array_scalar(Float::Array2D &arr, float scalar) { for (int r = 0; r < arr.rows(); ++r) { for (int c = 0; c < arr.columns(); ++c) { INFO("r: " << r << ", c: " << c); INFO("result: " << arr[r][c] << ", expected: " << scalar); REQUIRE(arr[r][c] == scalar); } } }
26.073059
101
0.509282
Freddan-67
6041e1f3f7b63e83347fb38d839271d52df36c2a
8,928
cpp
C++
inference-engine/src/mkldnn_plugin/cpu_blocked_memory_desc.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
1
2021-03-16T17:40:26.000Z
2021-03-16T17:40:26.000Z
inference-engine/src/mkldnn_plugin/cpu_blocked_memory_desc.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
42
2020-11-23T08:09:57.000Z
2022-02-21T13:03:34.000Z
inference-engine/src/mkldnn_plugin/cpu_blocked_memory_desc.cpp
v-Golubev/openvino
26936d1fbb025c503ee43fe74593ee9d7862ab15
[ "Apache-2.0" ]
4
2021-04-02T08:48:38.000Z
2021-07-01T06:59:02.000Z
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "cpu_blocked_memory_desc.h" #include "mkldnn_memory.h" #include "utils/cpu_utils.hpp" using namespace MKLDNNPlugin; BlockedMemoryDesc::BlockedMemoryDesc(InferenceEngine::Precision prc, const std::vector<size_t>& dims) : MemoryDesc(dims, Blocked) , precision(prc) { order.resize(dims.size()); std::iota(order.begin(), order.end(), 0); blockedDims = dims; offsetPadding = 0; offsetPaddingToData.resize(dims.size(), 0); strides.resize(order.size()); strides[strides.size() - 1] = 1; for (size_t i = 2; i <= order.size(); i++) { strides[strides.size() - i] = strides[strides.size() - (i - 1)] * blockedDims[blockedDims.size() - (i - 1)]; } } BlockedMemoryDesc::BlockedMemoryDesc(InferenceEngine::Precision prc, const std::vector<size_t>& dims, const std::vector<size_t>& blockedDims, const std::vector<size_t>& order, size_t offsetPadding, const std::vector<size_t>& offsetPaddingToData, const std::vector<size_t>& strides) : MemoryDesc(dims, Blocked), precision(prc) { if (std::any_of(order.begin(), order.end(), [](size_t val) { return val == Shape::UNDEFINED_DIM; })) { IE_THROW() << "BlockedMemoryDesc do not support undefined order."; } if (std::any_of(blockedDims.begin() + dims.size(), blockedDims.end(), [](size_t val) { return val == Shape::UNDEFINED_DIM; })) { IE_THROW() << "BlockedMemoryDesc doesn't support undefined blockedDims."; } this->order = order; this->blockedDims = blockedDims; this->offsetPadding = offsetPadding; if (offsetPaddingToData.empty() && !order.empty()) { this->offsetPaddingToData.resize(order.size()); this->offsetPaddingToData[order.size() - 1] = 0; for (size_t i = 2; i <= order.size(); i++) { this->offsetPaddingToData[order.size() - i] = 0; } } else { this->offsetPaddingToData = offsetPaddingToData; } if (strides.empty() && !order.empty()) { if (std::any_of(this->blockedDims.begin(), this->blockedDims.end(), [](size_t val) { return val == Shape::UNDEFINED_DIM; })) { this->strides.resize(order.size(), Shape::UNDEFINED_DIM); } else { this->strides.resize(order.size()); this->strides[order.size() - 1] = 1; for (size_t i = 2; i <= order.size(); i++) { this->strides[order.size() - i] = this->strides[order.size() - (i - 1)] * this->blockedDims[blockedDims.size() - (i - 1)]; } } } else { this->strides = strides; } if (!everyone_is(this->order.size(), this->blockedDims.size(), this->offsetPaddingToData.size(), this->strides.size())) { IE_THROW() << "Order, blocked dims, offset padding to data and strides must have equals size"; } } bool BlockedMemoryDesc::isDefined() const { bool defined = true; defined = defined && std::none_of(blockedDims.cbegin(), blockedDims.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; }); defined = defined && std::none_of(strides.cbegin(), strides.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; }); defined = defined && std::none_of(order.cbegin(), order.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; }); defined = defined && std::none_of(offsetPaddingToData.cbegin(), offsetPaddingToData.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; }); defined = defined && offsetPadding != Shape::UNDEFINED_DIM; return defined; } bool BlockedMemoryDesc::isCompatible(const MemoryDesc& rhs) const { const MemoryDesc* pRhs = &rhs; if (auto blockingDesc = dynamic_cast<const BlockedMemoryDesc*>(pRhs)) { return isCompatible(*blockingDesc); } else if (auto mkldnnDesc = dynamic_cast<const MKLDNNMemoryDesc*>(pRhs)) { return mkldnnDesc->isCompatible(*this); } else { return false; } } bool BlockedMemoryDesc::isCompatible(const BlockedMemoryDesc& rhs) const { if (this->getShape() != rhs.getShape() || this->getPrecision() != rhs.getPrecision()) return false; if (!dimsEqualWeak(this->getBlockDims(), rhs.getBlockDims())) { return false; } if (!dimsEqualWeak(this->getOffsetPaddingToData(), rhs.getOffsetPaddingToData())) { return false; } // this check needed to avoid inserting unnecessary reorders if the memory is used in place and the batch size is equal to 1 size_t skipAxis = this->getShape().getRank() > 0 && this->getShape().getDims().front() == 1 ? 0 : Shape::UNDEFINED_DIM; //ignore batch axis if batch size == 1 if (!dimsEqualWeak(this->getStrides(), rhs.getStrides(), skipAxis)) { return false; } if (!dimsEqualWeak(this->getOrder(), rhs.getOrder())) { return false; } return dimsEqualWeak(this->getOffsetPadding(), rhs.getOffsetPadding()); } bool BlockedMemoryDesc::isCompatible(const MKLDNNMemoryDesc& rhs) const { return rhs.isCompatible(*this); } size_t BlockedMemoryDesc::getMemSizeImp() const { int64_t e_size = getOffsetPadding() + 1; // size in bytes (from begin of data to last element) for (int j = 0; j < getBlockDims().size(); j++) e_size += (getBlockDims()[j] - 1) * getStrides()[j]; e_size *= getPrecision() == InferenceEngine::Precision::BIN ? 1 : getPrecision().size(); return e_size; } size_t BlockedMemoryDesc::getOffset(const InferenceEngine::SizeVector& v) const { InferenceEngine::SizeVector off_v = v; size_t n_blocked_dims = order.size(); if (blockedDims.size() != n_blocked_dims || strides.size() != n_blocked_dims) { IE_THROW() << "Cannot calculate offset. Incorrect primitive descriptor!"; } InferenceEngine::SizeVector blockedShift(n_blocked_dims); for (size_t i = 1; i <= n_blocked_dims; i++) { blockedShift[n_blocked_dims - i] = off_v[order[n_blocked_dims - i]] % blockedDims[n_blocked_dims - i]; off_v[order[n_blocked_dims - i]] /= blockedDims[n_blocked_dims - i]; } size_t offset = getOffsetPadding(); for (size_t d = 0; d < n_blocked_dims; ++d) { const size_t p = blockedShift[d] + getOffsetPaddingToData()[d]; offset += p * strides[d]; } return offset; } size_t BlockedMemoryDesc::getElementOffset(size_t elemNumber) const { // TODO [DS]: rewrite to support dynamic shapes auto& dims = shape.getStaticDims(); size_t n_dims = dims.size(); InferenceEngine::SizeVector pos(n_dims); for (size_t rd = 1; rd <= n_dims; ++rd) { const size_t d = n_dims - rd; const size_t cur_dim = dims[d]; pos[d] = elemNumber % cur_dim; elemNumber /= cur_dim; } return getOffset(pos); } bool BlockedMemoryDesc::hasLayoutType(LayoutType layoutType) const { switch (layoutType) { case LayoutType::ncsp: return isPlainFormat(); case LayoutType::nspc: return isTailCFormat(); case LayoutType::nCsp8c: return isBlockedCFormat(8); case LayoutType::nCsp16c: return isBlockedCFormat(16); default: return false; } } bool BlockedMemoryDesc::isPlainFormat() const { if (shape.getRank() != order.size()) { return false; } for (size_t i = 0; i < order.size(); ++i) { if (order[i] != i) { return false; } } return true; } bool BlockedMemoryDesc::isBlockedCFormat(size_t blk_size) const { if ((order.size() - shape.getRank()) != 1) { return false; } for (size_t i = 0; i < order.size() - 1; ++i) { if (order[i] != i) { return false; } } if (order.back() != 1) { return false; } if (blockedDims.back() != blk_size) { return false; } return true; } bool BlockedMemoryDesc::isTailCFormat() const { if (shape.getRank() < 3) { return false; } if (shape.getRank() != order.size()) { return false; } if (!std::is_sorted(order.begin(), --order.end())) { return false; } if (order.back() != 1) { return false; } return true; } std::string BlockedMemoryDesc::serializeFormat() const { std::stringstream result; char startLetter = 'a'; std::unordered_map<size_t, size_t> mapAxisBlockSize; for (size_t i = shape.getRank(); i < order.size(); ++i) { mapAxisBlockSize.insert({order[i], blockedDims[i]}); } for (size_t i = 0; i < shape.getRank(); ++i) { char nextLetter = startLetter + order[i]; if (mapAxisBlockSize.count(i)) { nextLetter = toupper(nextLetter); } result << nextLetter; } for (auto& item : mapAxisBlockSize) { result << item.second << char(startLetter + item.first); } return result.str(); }
36
152
0.620408
uikilin100
60436c3bf19201796208b71626c01ccfc8cbd6b2
27,650
cpp
C++
src/gpe_editor/gpe_scene_tilemap_class.cpp
jaymicrocode/Game-Pencil-Engine
28501fdf21ad7b3ff2ac7912e6f7a988a9ace7e4
[ "MIT" ]
null
null
null
src/gpe_editor/gpe_scene_tilemap_class.cpp
jaymicrocode/Game-Pencil-Engine
28501fdf21ad7b3ff2ac7912e6f7a988a9ace7e4
[ "MIT" ]
null
null
null
src/gpe_editor/gpe_scene_tilemap_class.cpp
jaymicrocode/Game-Pencil-Engine
28501fdf21ad7b3ff2ac7912e6f7a988a9ace7e4
[ "MIT" ]
null
null
null
/* gpe_scene_tilemap_class.cpp This file is part of: GAME PENCIL ENGINE https://www.pawbyte.com/gamepencilengine Copyright (c) 2014-2020 Nathan Hurde, Chase Lee. Copyright (c) 2014-2020 PawByte LLC. Copyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page ) 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. -Game Pencil Engine <https://www.pawbyte.com/gamepencilengine> */ #include "gpe_scene_tilemap_class.h" GPE_SceneTile::GPE_SceneTile() { isLocked = false; branchType = gpe::branch_type::TILE; iconTexture = paw_gui_rsm->texture_add_filename( gpe::app_directory_name+"resources/gfx/iconpacks/fontawesome/table.png") ; tileTypeId = -1; tileIndexId = -1; tilesheetIndexId = -1; tileRect.x = 0; tileRect.y = 0; tileRect.w = 0; tileRect.h = 0; } GPE_SceneTile::~GPE_SceneTile() { } void GPE_SceneTile::add_typed_elements() { if( PANEL_INSPECTOR!=NULL ) { } } void GPE_SceneTile::render_branch() { } bool GPE_SceneTile::save_branch_data(std::ofstream * fileTarget, int nestedFoldersIn ) { return true; } GPE_SceneTileMap::GPE_SceneTileMap( std::string mapName, int x, int y, GPE_GeneralResourceContainer *pFolder ) { projectParentFolder = pFolder; if( projectParentFolder!=NULL) { tilesheetDropDown = new GPE_DropDown_Resouce_Menu( "Tilesheet",projectParentFolder->find_resource_from_name( gpe::resource_type_names[ gpe::resource_type_tilesheet]+"s"),-1,true ); tilesheetDropDown->set_width(192); tSPreviewer = new tilesheetPreviewer(); } else { tilesheetDropDown = NULL; tSPreviewer = NULL; } isLocked = false; set_position( x, y); branchType = gpe::branch_type::TILEMAP; iconTexture = paw_gui_rsm->texture_add_filename( gpe::app_directory_name+"resources/gfx/iconpacks/fontawesome/th.png") ; update_rectangle(&tsPlacementArea,0,0,0,0); tileWidth = gpe::tile_default_width; tileHeight = gpe::tile_default_height; tileAmountX = prevTileAmountX = 0; tileAmountY = prevTileAmountY = 0; xPosField->set_number( xPos ); xPosField->set_label("Map-XStart"); yPosField->set_number( yPos ); yPosField->set_label("Map-YStart"); fieldTileWidth = new gpe_text_widget_number( "32" ); fieldTileWidth->set_number( tileWidth ); fieldTileWidth->set_label("Tile Width"); fieldTileWidth->scale_width( 0.4 ); fieldTileHeight = new gpe_text_widget_number( "32" ); fieldTileHeight->set_number( tileHeight ); fieldTileHeight->set_label("Tile Height"); fieldTileHeight->scale_width( 0.4 ); fieldAmountX = new gpe_text_widget_number( "" ); fieldAmountX->set_number( tileAmountX ); fieldAmountX->set_label("Map Width"); fieldAmountX->scale_width( 0.4 ); fieldAmountY = new gpe_text_widget_number( "y-tile-amount" ); fieldAmountY->set_label("Map Height"); fieldAmountY->set_number( tileAmountY ); fieldAmountY->scale_width( 0.4 ); fillScene = new GPE_CheckBoxBasic("Fill Scene","Check to use remainder of scene" ); if( (int)mapName.size()==0 ) { name = "tilemap"; } else { set_name( mapName ); } } void GPE_SceneTileMap::add_typed_elements() { if( PANEL_INSPECTOR!=NULL ) { PANEL_INSPECTOR->add_gui_element( tilesheetDropDown, true ); PANEL_INSPECTOR->add_gui_element( fieldTileWidth, false ); PANEL_INSPECTOR->add_gui_element( fieldTileHeight, true ); PANEL_INSPECTOR->add_gui_element( fieldAmountX, false ); PANEL_INSPECTOR->add_gui_element( fieldAmountY, true ); PANEL_INSPECTOR->add_gui_element( fillScene, true ); } } GPE_SceneTileMap::~GPE_SceneTileMap() { if( tSPreviewer!=NULL) { delete tSPreviewer; tSPreviewer = NULL; } } bool GPE_SceneTileMap::build_intohtml5_file(std::ofstream * fileTarget, int leftTabAmount, GPE_GeneralResourceContainer * localResTypeController ) { if( localResTypeController == NULL ) { return false; } std::string nestedTabsStr = generate_tabs( leftTabAmount ); GPE_SceneTile * fSceneTile = NULL; GPE_GeneralResourceContainer * fTSToPlace = NULL; int maxTilesInLayer = (int)mapTiles.size(); for( int i = 0; i < maxTilesInLayer; i++) { fSceneTile = mapTiles.at(i); if( fSceneTile!=NULL &&fSceneTile->tilesheetIndexId>=0 && fSceneTile->tileIndexId>=0) { fTSToPlace = localResTypeController->find_resource_from_id(fSceneTile->tilesheetIndexId); if( fTSToPlace!=NULL) { *fileTarget << nestedTabsStr << "_scn_temp_layer.scnStartTiles.push( {tileNumber: " << stg_ex::int_to_string( i ) << ","; *fileTarget << "tileSheetId: " << stg_ex::int_to_string(fTSToPlace->exportBuildGlobalId) << ","; *fileTarget << "tileIndexId: " << stg_ex::int_to_string(fSceneTile->tileIndexId); *fileTarget << "}); \n"; } } } GPE_SceneBasicClass::build_intohtml5_file( fileTarget, leftTabAmount+1, localResTypeController); return true; } void GPE_SceneTileMap::calculate_size() { } void GPE_SceneTileMap::create_new_map(int newTX, int newTY,int ntileType ) { tileAmountX=newTX; tileAmountY=newTY; int newSize = tileAmountX*tileAmountY; if( mapTiles.size() >0 ) { for(std::vector<GPE_SceneTile*>::const_iterator it = mapTiles.begin(); it != mapTiles.end(); it++) { delete *it; } mapTiles.clear(); } GPE_SceneTile * newTile = NULL; for(int i=0; i<newSize; i++) { newTile = new GPE_SceneTile(); newTile->tileTypeId = ntileType; mapTiles.push_back(newTile); } xPosField->set_number( xPos ); yPosField->set_number( yPos ); fieldTileWidth->set_number( tileWidth ); fieldTileHeight->set_number( tileHeight ); fieldAmountX->set_number( tileAmountX ); fieldAmountY->set_number( tileAmountY ); gpe::error_log->report("Tile Map created."); } int GPE_SceneTileMap::get_map_size() { return (int)mapTiles.size(); } int GPE_SceneTileMap::get_xmax() { return xPos+tileWidth * tileAmountX; } int GPE_SceneTileMap::get_ymax() { return yPos+tileHeight * tileAmountY; } int GPE_SceneTileMap::get_sizex() { return tileAmountX; } int GPE_SceneTileMap::get_sizey() { return tileAmountY; } int GPE_SceneTileMap::get_tile_x( int xInPixels) { if( tileAmountX == 0 || tileWidth == 0) { return -1; } if( xInPixels > xPos ) { xInPixels-= xPos; if( xInPixels < tileWidth * tileAmountX ) { return xInPixels /tileWidth; } else { return tileAmountX; } } return -1; } int GPE_SceneTileMap::get_tile_y( int yInPixels) { if( tileAmountY == 0 || tileHeight == 0) { return -1; } if( yInPixels > yPos ) { yInPixels-= yPos; if( yInPixels < tileHeight * tileAmountY ) { return yInPixels /tileHeight; } else { return tileAmountY; } } return -1; } GPE_SceneTile* GPE_SceneTileMap::get_tile_at(int xIn, int yIn) { if( xIn >=0 && yIn >=0) { if( xIn < tileAmountX && yIn < tileAmountY) { int cTilePosition = xIn+ yIn*tileAmountX; if( cTilePosition >=0 && cTilePosition < (int)mapTiles.size() ) { return mapTiles.at(cTilePosition); } } } return NULL; } void GPE_SceneTileMap::process_elements() { GPE_SceneBasicClass::process_elements(); int previousTileSheetId = tilesheetDropDown->get_selected_id(); PANEL_TS_RESOURCE = GPE_DOCK->find_panel("Tilesheet"); if(PANEL_TS_RESOURCE!=NULL ) { if( tSPreviewer!=NULL ) { tSPreviewer->tileSheetToPreview = NULL; PANEL_TS_RESOURCE->clear_panel(); PANEL_TS_RESOURCE->add_gui_element(tilesheetDropDown,true); if( tilesheetDropDown!=NULL && tSPreviewer!=NULL ) { if( tilesheetDropDown->is_clicked() || previousTileSheetId != tilesheetDropDown->get_selected_id() ) { tileToPlaceX1 = 0; tileToPlaceY1 = 0; tileToPlaceX2 = 0; tileToPlaceY2 = 0; tilesToPlacePerRow = 0; tileIdsToPlace.clear(); tSPreviewer->reset_preview(true); } GPE_GeneralResourceContainer * tsTypeContainer = tilesheetDropDown->get_selected_container(); if( tsTypeContainer!=NULL) { tsRes = (tilesheetResource*) tsTypeContainer->get_held_resource(); tSPreviewer->tileSheetToPreview = tsRes->tilesheetInEditor; } tSPreviewer->set_width( PANEL_TS_RESOURCE->get_width()-GENERAL_GPE_GUI_PADDING ); tSPreviewer->set_height( PANEL_TS_RESOURCE->get_height()-GENERAL_GPE_GUI_PADDING-tilesheetDropDown->get_height() ); PANEL_TS_RESOURCE->add_gui_element(tSPreviewer,true); } PANEL_TS_RESOURCE->process_self( ); } } int sceneTileMouseX = 0; int sceneTileMouseY = 0; if( spm !=NULL ) { if( tileWidth > 0) { sceneTileMouseX = ( spm->mouseXPos - xPos) / tileWidth; } else { sceneTileMouseX = 0; } if( tileHeight > 0) { sceneTileMouseY = ( spm->mouseYPos - yPos) /tileHeight; } } else { return; } //if( shortcutButtonBar->get_tab_id() == SCENE_MODE_PLACE && mouseIsInScene && tSPreviewer!=NULL && !selectedLayerMap->isLocked ) if( tSPreviewer!=NULL && !isLocked && tSPreviewer!=NULL && spm->mouseInScene && spm->editMode == SCENE_MODE_PLACE ) { if( gpe::input->check_mouse_down( mb_left ) && tileWidth > 0 && tileHeight > 0 && (int)tSPreviewer->tilesIdsInPreview.size()>0 ) { //Place Tiles and Such if( tsRes!=NULL && tsRes->tilesheetInEditor!=NULL && tsRes->tilesheetInEditor->tsImage!=NULL) { //select tiles to place / place tiles / add tiles //if( RESOURCE_TO_DRAG==NULL && mouseIsInScene && sceneXScroll->is_scrolling()==false && sceneYScroll->is_scrolling()==false ) { GPE_SceneTile* fSceneTileToEdit = NULL; int tileRowItr = 0; int tilesItr= 0; int newTileX = 0, newTileY = 0; for( tilesItr = 0; tilesItr < (int)tSPreviewer->tilesIdsInPreview.size(); tilesItr++ ) { fSceneTileToEdit = get_tile_at(sceneTileMouseX+newTileX,sceneTileMouseY+newTileY); if( fSceneTileToEdit!=NULL) { fSceneTileToEdit->tileIndexId = tSPreviewer->tilesIdsInPreview.at(tilesItr); fSceneTileToEdit->tilesheetIndexId = tilesheetDropDown->get_selected_id(); fSceneTileToEdit->tileTypeId = 1; } else { // main_OVERLAY->update_tooltip("Unable to find scene tile to edit..."); } newTileX+=1; tileRowItr+=1; if( tileRowItr >= tSPreviewer->tilesToPlacePerRow) { tileRowItr = 0; newTileX = 0; newTileY+=1; } } } } } } //else if(shortcutButtonBar->get_tab_id() == SCENE_MODE_ERASE && mouseIsInScene && selectedLayerMap!=NULL && !selectedLayerMap->isLocked ) else if( !isLocked && gpe::input->check_mouse_down( mb_right ) && spm->mouseInScene && spm->editMode == SCENE_MODE_ERASE ) { //Remove Tiles / Delete Tiles //if( mouseIsInScene && sceneXScroll->is_scrolling()==false && sceneYScroll->is_scrolling()==false ) if( spm!=NULL ) { GPE_SceneTile* fSceneTileToEdit = NULL; fSceneTileToEdit = get_tile_at(sceneTileMouseX,sceneTileMouseY); if( fSceneTileToEdit!=NULL ) { fSceneTileToEdit->tileIndexId = -1; fSceneTileToEdit->tilesheetIndexId = -1; fSceneTileToEdit->tileTypeId = 1; } } } } void GPE_SceneTileMap::resize_tilemap( int newTX, int newTY,int ntileType) { if( (newTX!=tileAmountX || newTY!=tileAmountY )&& newTX>0 && newTY>0) { int newSize = newTX*newTY; GPE_SceneTile *newTile = NULL; GPE_SceneTile *prevTile = NULL; int i, j; std::vector <GPE_SceneTile*> tempMapTiles; for( i=0; i<(int)mapTiles.size(); i++) { prevTile = mapTiles[i]; newTile = new GPE_SceneTile(); if( prevTile!=NULL) { newTile->tileTypeId = ntileType; newTile->tileIndexId = prevTile->tileIndexId; newTile->tilesheetIndexId = prevTile->tilesheetIndexId; } tempMapTiles.push_back(newTile); } //destroys old map to be reborn later if( (int)mapTiles.size() >0 ) { for(std::vector<GPE_SceneTile*>::const_iterator it = mapTiles.begin(); it != mapTiles.end(); it++) { delete *it; } } mapTiles.clear(); gpe::error_log->report("Map cleared ("+ stg_ex::int_to_string((int)mapTiles.size() ) +")."); gpe::error_log->report("New Dimensions ("+ stg_ex::int_to_string(newTX) +" x "+ stg_ex::int_to_string(newTY)+" = "+ stg_ex::int_to_string(newSize)+"."); for( i=0; i<newSize; i++) { newTile = new GPE_SceneTile(); newTile->tileTypeId = ntileType; mapTiles.push_back(newTile); } gpe::error_log->report("Map resized ("+ stg_ex::int_to_string((int)mapTiles.size() ) +")."); //creates the tile layer with new dimensions all blanked out newTile = NULL; int iMaxPrevXTiles = std::max(newTX, tileAmountX); int jMaxPrevYTiles = std::max(newTY, tileAmountY); if( (int)tempMapTiles.size() >0 && (int)mapTiles.size() >0 ) { for( j=0; j<jMaxPrevYTiles; j++) { for( i=0; i<iMaxPrevXTiles; i++) { if( tileAmountX > i && tileAmountY > j) { prevTile = tempMapTiles.at(i+tileAmountX*j); } else { prevTile = NULL; } if( newTX > i && newTY > j) { newTile = mapTiles.at(i+newTX*j); } else { newTile = NULL; } if( prevTile!=NULL && newTile!=NULL) { newTile->tileTypeId = prevTile->tileIndexId; newTile->tileIndexId = prevTile->tileIndexId; newTile->tilesheetIndexId = prevTile->tilesheetIndexId; } } } } tileAmountX=newTX; tileAmountY=newTY; //destroys the temp map if( (int)tempMapTiles.size() >0 ) { for(std::vector<GPE_SceneTile*>::const_iterator itOld = tempMapTiles.begin(); itOld != tempMapTiles.end(); itOld++) { delete *itOld; } tempMapTiles.clear(); } xPosField->set_number( xPos ); yPosField->set_number( yPos ); fieldTileWidth->set_number( tileWidth ); fieldTileHeight->set_number( tileHeight ); fieldAmountX->set_number( tileAmountX ); fieldAmountY->set_number( tileAmountY ); gpe::error_log->report("Tile Map created."); gpe::error_log->report("Map updated after resize ("+ stg_ex::int_to_string((int)mapTiles.size() ) +")."); } } void GPE_SceneTileMap::set_map_size( int newW, int newH ) { if( tileWidth !=0 & tileHeight!=0 ) { int expectedNewSizeX = ceil( (float)newW/tileWidth ); int expectedNewSizeY = ceil( (float)newW/tileHeight ); if( prevTileAmountX < tileAmountX || prevTileAmountX < tileAmountY ) { resize_tilemap( expectedNewSizeX, expectedNewSizeY); } } } void GPE_SceneTileMap::render_branch() { //Avoid the time waste and don't continue if alpha is too low. if( branchAlpha!=NULL && branchAlpha->get_value() < 5) { return; } if( spm == NULL) { return; } if( spm->cSceneTstList!=NULL && tileWidth!=0 && tileHeight!=0 && spm->zoomValue!=0 ) { gpe::shape_rect foundTsRect; int cTileXPos = 0; int cTileYPos = 0; int i = 0; int j = 0; int foundTilePos = 0; int tileXStartPos = std::max(0, get_tile_x( spm->cameraFloorXPos )-2 ); int tileYStartPos = std::max(0, get_tile_y( spm->cameraFloorYPos )-2 ); int tileXEndPos = tileXStartPos + std::max(0,get_tile_x( ( spm->currentCamera->w / spm->zoomValue) ) ) +2; int tileYEndPos = tileYStartPos + std::max(0,get_tile_y( ( spm->currentCamera->h / spm->zoomValue) ) ) +2; if( tileXStartPos>=0 && tileXStartPos > tileXEndPos) { tileXEndPos = tileAmountX; } if( tileYStartPos>=0 && tileYStartPos > tileYEndPos) { tileYEndPos = tileAmountY; } GPE_SceneTile * fSceneTile = NULL; GPE_GeneralResourceContainer * foundTSResource = NULL; tilesheetResource * foundHeldTSRes = NULL; //gpe::error_log->report("Performing 1st loop"); for( i = tileXStartPos; i < tileAmountX; i++ ) { //gpe::error_log->report("Performing 2nd loop"); for( j = tileYStartPos; j < tileAmountY; j++) { fSceneTile = get_tile_at( i, j); if( fSceneTile!=NULL) { if( fSceneTile->tilesheetIndexId >= 0 && fSceneTile->tileIndexId >= 0 ) { foundTSResource = spm->cSceneTstList->find_resource_from_id(fSceneTile->tilesheetIndexId); if( foundTSResource!=NULL) { foundHeldTSRes = (tilesheetResource * )foundTSResource->get_held_resource(); if( foundHeldTSRes->tilesheetInEditor!=NULL ) { if( foundHeldTSRes->tilesheetInEditor->tsImage!=NULL && fSceneTile->tileIndexId < (int)foundHeldTSRes->tilesheetInEditor->tsRects.size() ) { cTileXPos = floor( (i*tileWidth ) * spm->zoomValue ) - spm->currentCamera->x * spm->zoomValue; cTileYPos = floor( (j*tileHeight ) * spm->zoomValue ) - spm->currentCamera->y * spm->zoomValue; foundTsRect = foundHeldTSRes->tilesheetInEditor->tsRects.at(fSceneTile->tileIndexId ); //if( check_collision(editorCameraRect,cTileXPos,cTileYPos,foundTsRect.w,foundTsRect.h) ) { foundHeldTSRes->tilesheetInEditor->tsImage->render_tex_scaled( cTileXPos,cTileYPos, spm->zoomValue,spm->zoomValue,&foundTsRect,branchColor->get_color(), branchAlpha->get_value() ); /*if( renderOutlines ) { gpe::gcanvas->render_rectangle( cTileXPos,cTileYPos, cTileXPos+ceil( (float)foundTsRect.w*spm->zoomValue),cTileYPos+ceil( (float)foundTsRect.h*spm->zoomValue ), c_red, true, 255 ); //render_text( cTileXPos,cTileYPos, stg_ex::int_to_string(fSceneTile->tilesheetIndexId)+"-"+ stg_ex::int_to_string(fSceneTile->tileIndexId),c_red,font_default,gpe::fa_left,gpe::fa_top, 255 ); } */ } } } } } } } //gpe::error_log->report("2nd loop completed"); } //gpe::error_log->report("1st loop completed"); //Previews tilesheet if selected GPE_GeneralResourceContainer * tsTypeContainer = tilesheetDropDown->get_selected_container(); if( tsTypeContainer!=NULL && spm->mouseInScene && spm->editMode == SCENE_MODE_PLACE && RESOURCE_TO_DRAG==NULL ) { tsRes = (tilesheetResource*) tsTypeContainer->get_held_resource(); if( tsRes!=NULL && tsRes->tilesheetInEditor!=NULL && tsRes->tilesheetInEditor->tsImage!=NULL) { //if( sceneXScroll->is_scrolling()==false && sceneYScroll->is_scrolling()==false ) { int sceneTileMouseX = spm->mouseXPos; int sceneTileMouseY = spm->mouseYPos; if( tileWidth!=0 &&tileHeight!=0) { sceneTileMouseX = sceneTileMouseX/tileWidth; sceneTileMouseX = (sceneTileMouseX *tileWidth); sceneTileMouseY = sceneTileMouseY/tileHeight; sceneTileMouseY = (sceneTileMouseY *tileHeight); } sceneTileMouseX = floor( (sceneTileMouseX*spm->zoomValue-spm->cameraFloorXPos * spm->zoomValue ) ); sceneTileMouseY = floor( (sceneTileMouseY*spm->zoomValue-spm->cameraFloorYPos * spm->zoomValue) ); if( isLocked ) { tSPreviewer->render_selection( sceneTileMouseX,sceneTileMouseY, NULL,NULL, spm->zoomValue, gpe::c_orangered ); } else if( sceneTileMouseX >=0 && sceneTileMouseY >=0 ) { tSPreviewer->render_selection( sceneTileMouseX,sceneTileMouseY,NULL,NULL,spm->zoomValue, gpe::c_white ); } /* else if( spm->mouseXPos < 0 || spm->mouseYPos < 0 || spm->mouseXPos > spm->tempRect->w || spm->mouseYPos > spm->tempRect->h ) { tSPreviewer->render_selection( sceneTileMouseX,sceneTileMouseY,NULL,NULL,true,spm->zoomValue, c_red ); } else { tSPreviewer->render_selection( sceneTileMouseX,sceneTileMouseY,NULL,NULL,true,spm->zoomValue,c_white); } */ } } } } GPE_SpecialMenu_Branch::render_branch(); } bool GPE_SceneTileMap::save_branch_data(std::ofstream * fileTarget, int nestedFoldersIn ) { if( fileTarget!=NULL && fileTarget->is_open() ) { std::string nestedTabsStr = generate_tabs( nestedFoldersIn ); *fileTarget << nestedTabsStr+ "[GPE_TileMap="; *fileTarget << stg_ex::int_to_string( tileWidth )+","; *fileTarget << stg_ex::int_to_string( tileHeight )+","; *fileTarget << stg_ex::int_to_string( tileAmountX )+","; *fileTarget << stg_ex::int_to_string( tileAmountY )+","; *fileTarget << stg_ex::int_to_string( xPos )+","; *fileTarget << stg_ex::int_to_string( yPos )+","; if( fillScene!=NULL) { *fileTarget << stg_ex::int_to_string( fillScene->is_clicked() )+","; } else { *fileTarget << "0,"; } if( (int)name.size() > 0 ) { *fileTarget << name +",,"; } else { *fileTarget << +"tilemap,,"; } *fileTarget << "]\n"; GPE_SceneBasicClass::save_branch_data( fileTarget, nestedFoldersIn+1 ); int maxTilesInMap = (int)mapTiles.size(); nestedTabsStr = generate_tabs( nestedFoldersIn+1 ); GPE_SceneTile * fSceneTile = NULL; for( int i = 0; i < maxTilesInMap; i++) { fSceneTile = mapTiles.at(i); if( fSceneTile!=NULL && fSceneTile->tilesheetIndexId > 0 && fSceneTile->tileIndexId >= 0 ) { *fileTarget << nestedTabsStr+ "GPE_SingleTile="; //This is the position of the tile in the tilemap *fileTarget << stg_ex::int_to_string( i )+","; *fileTarget << stg_ex::int_to_string( fSceneTile->tilesheetIndexId )+","; *fileTarget << stg_ex::int_to_string( fSceneTile->tileIndexId )+","; *fileTarget << stg_ex::int_to_string( fSceneTile->tileTypeId )+","; /* *fileTarget << fSceneTile->get_name() +",,"; //For later version I plan to add more data here... fSceneTile->save_branch_data( fileTarget, nestedFoldersIn+1 ); */ *fileTarget << "\n"; } } *fileTarget << nestedTabsStr+"[/GPE_TileMap]\n"; return true; } return false; }
37.213997
236
0.548897
jaymicrocode
60481535d06cdd537c08cc7621a16701f6263dcc
1,625
cc
C++
test/common/common/basic_resource_impl_test.cc
lopter-dbx/envoy
d342e96e7ba2319329838e799021838354e88118
[ "Apache-2.0" ]
218
2019-05-10T01:11:27.000Z
2022-01-12T07:12:59.000Z
test/common/common/basic_resource_impl_test.cc
lopter-dbx/envoy
d342e96e7ba2319329838e799021838354e88118
[ "Apache-2.0" ]
624
2020-10-19T12:21:29.000Z
2021-05-09T22:47:00.000Z
test/common/common/basic_resource_impl_test.cc
lopter-dbx/envoy
d342e96e7ba2319329838e799021838354e88118
[ "Apache-2.0" ]
93
2019-05-10T00:15:21.000Z
2021-10-14T09:32:30.000Z
#include <limits> #include "common/common/basic_resource_impl.h" #include "test/mocks/runtime/mocks.h" #include "gtest/gtest.h" using testing::NiceMock; using testing::Return; namespace Envoy { class BasicResourceLimitImplTest : public testing::Test { protected: NiceMock<Runtime::MockLoader> runtime_; }; TEST_F(BasicResourceLimitImplTest, NoArgsConstructorVerifyMax) { BasicResourceLimitImpl br; EXPECT_EQ(br.max(), std::numeric_limits<uint64_t>::max()); } TEST_F(BasicResourceLimitImplTest, VerifySetClearMax) { BasicResourceLimitImpl br(123); EXPECT_EQ(br.max(), 123); br.setMax(321); EXPECT_EQ(br.max(), 321); br.resetMax(); EXPECT_EQ(br.max(), std::numeric_limits<uint64_t>::max()); } TEST_F(BasicResourceLimitImplTest, IncDecCount) { BasicResourceLimitImpl br; EXPECT_EQ(br.count(), 0); br.inc(); EXPECT_EQ(br.count(), 1); br.inc(); br.inc(); EXPECT_EQ(br.count(), 3); br.dec(); EXPECT_EQ(br.count(), 2); br.decBy(2); EXPECT_EQ(br.count(), 0); } TEST_F(BasicResourceLimitImplTest, CanCreate) { BasicResourceLimitImpl br(2); EXPECT_TRUE(br.canCreate()); br.inc(); EXPECT_TRUE(br.canCreate()); br.inc(); EXPECT_FALSE(br.canCreate()); br.dec(); EXPECT_TRUE(br.canCreate()); br.dec(); } TEST_F(BasicResourceLimitImplTest, RuntimeMods) { BasicResourceLimitImpl br(1337, runtime_, "trololo"); EXPECT_CALL(runtime_.snapshot_, getInteger("trololo", 1337)).WillOnce(Return(555)); EXPECT_EQ(br.max(), 555); EXPECT_CALL(runtime_.snapshot_, getInteger("trololo", 1337)).WillOnce(Return(1337)); EXPECT_EQ(br.max(), 1337); } } // namespace Envoy
21.959459
86
0.714462
lopter-dbx
6048a7840f1b8305021db025815847a3fb0dba78
11,580
cpp
C++
applications/freezing_soil_application/custom_conditions/face_load_pressure.cpp
AndreaVoltan/MyKratos7.0
e977752722e8ef1b606f25618c4bf8fd04c434cc
[ "BSD-4-Clause" ]
2
2020-04-30T19:13:08.000Z
2021-04-14T19:40:47.000Z
applications/freezing_soil_application/custom_conditions/face_load_pressure.cpp
AndreaVoltan/MyKratos7.0
e977752722e8ef1b606f25618c4bf8fd04c434cc
[ "BSD-4-Clause" ]
1
2020-04-30T19:19:09.000Z
2020-05-02T14:22:36.000Z
applications/freezing_soil_application/custom_conditions/face_load_pressure.cpp
AndreaVoltan/MyKratos7.0
e977752722e8ef1b606f25618c4bf8fd04c434cc
[ "BSD-4-Clause" ]
1
2020-06-12T08:51:24.000Z
2020-06-12T08:51:24.000Z
/* ============================================================================== KratosR1StructuralApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel pooyan@cimne.upc.edu rrossi@cimne.upc.edu janosch.stascheit@rub.de nagel@sd.rub.de - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain - Ruhr-University Bochum, Institute for Structural Mechanics, Germany 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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. ============================================================================== */ /* ************************************************************************************** * * Last Modified by: $Author: mengmeng $ * Date: $Date: 2008-10-17 11:58:58 $ * Revision: $Revision: 1.1 $ * * ***************************************************************************************/ // System includes // External includes // Project includes #include "includes/define.h" #include "custom_conditions/face_load_pressure.h" #include "includes/variables.h" #include "freezing_soil_application.h" #include "utilities/math_utils.h" namespace Kratos { //---------------------- //----- PUBLIC ------- //---------------------- // Constructor //*********************************************************************************** FaceLoadPressure::FaceLoadPressure() {} //*********************************************************************************** FaceLoadPressure::FaceLoadPressure(IndexType NewId, GeometryType::Pointer pGeometry) : Condition(NewId, pGeometry) {} //*********************************************************************************** FaceLoadPressure::FaceLoadPressure(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties) : Condition(NewId, pGeometry, pProperties) {} //*********************************************************************************** Condition::Pointer FaceLoadPressure::Create(IndexType NewId, NodesArrayType const& ThisNodes, PropertiesType::Pointer pProperties) const { return Condition::Pointer(new FaceLoadPressure(NewId, GetGeometry().Create(ThisNodes), pProperties)); } // Destructor //*********************************************************************************** FaceLoadPressure::~FaceLoadPressure() {} //*********************************************************************************** void FaceLoadPressure::EquationIdVector(EquationIdVectorType& rResult, ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY unsigned int number_of_nodes = GetGeometry().size(); unsigned int dof = number_of_nodes * 3; if ( rResult.size() != dof ) rResult.resize( dof ); for ( unsigned int i = 0; i < number_of_nodes; i++ ) { int index = i * 3; rResult[index] = GetGeometry()[i].GetDof( DISPLACEMENT_X ).EquationId(); rResult[index+1] = GetGeometry()[i].GetDof( DISPLACEMENT_Y ).EquationId(); rResult[index+2] = GetGeometry()[i].GetDof( DISPLACEMENT_Z ).EquationId(); } KRATOS_CATCH( "" ) } //*********************************************************************************** void FaceLoadPressure::GetDofList(DofsVectorType& ElementalDofList, ProcessInfo& rCurrentProcessInfo) { ElementalDofList.resize(0); for ( unsigned int i = 0; i < GetGeometry().size(); i++ ) { ElementalDofList.push_back( GetGeometry()[i].pGetDof( DISPLACEMENT_X ) ); ElementalDofList.push_back( GetGeometry()[i].pGetDof( DISPLACEMENT_Y ) ); ElementalDofList.push_back( GetGeometry()[i].pGetDof( DISPLACEMENT_Z ) ); } } //*********************************************************************************** void FaceLoadPressure::CalculateRightHandSide(VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo) { //calculation flags bool CalculateStiffnessMatrixFlag = false; bool CalculateResidualVectorFlag = true; MatrixType temp = Matrix(); CalculateAll(temp, rRightHandSideVector, rCurrentProcessInfo, CalculateStiffnessMatrixFlag, CalculateResidualVectorFlag); } //*********************************************************************************** void FaceLoadPressure::CalculateLocalSystem(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo) { //calculation flags bool CalculateStiffnessMatrixFlag = true; bool CalculateResidualVectorFlag = true; CalculateAll(rLeftHandSideMatrix, rRightHandSideVector, rCurrentProcessInfo, CalculateStiffnessMatrixFlag, CalculateResidualVectorFlag); } //*********************************************************************************** void FaceLoadPressure::MassMatrix(MatrixType& rMassMatrix, ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY rMassMatrix.resize(0,0,false); KRATOS_CATCH("") } //*********************************************************************************** void FaceLoadPressure::DampMatrix(MatrixType& rDampMatrix, ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY rDampMatrix.resize(0,0,false); KRATOS_CATCH("") } //*********************************************************************************** void FaceLoadPressure::GetValuesVector(Vector& values, int Step) { unsigned int number_of_nodes = GetGeometry().size(); unsigned int MatSize = number_of_nodes * 3; if (values.size() != MatSize) values.resize(MatSize); for (unsigned int i=0;i<number_of_nodes;i++) { const array_1d<double, 3>& disp = GetGeometry()[i].FastGetSolutionStepValue( DISPLACEMENT, Step ); unsigned int index = i * 3; values[index] = disp[0]; values[index+1] = disp[1]; values[index+2] = disp[2]; } } //---------------------- //----- PRIVATE ------ //---------------------- //*********************************************************************************** void FaceLoadPressure::CalculateAll(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, const ProcessInfo& rCurrentProcessInfo, bool CalculateStiffnessMatrixFlag, bool CalculateResidualVectorFlag) { KRATOS_TRY const unsigned int number_of_nodes = GetGeometry().size(); unsigned int MatSize = number_of_nodes * 3; const unsigned int dim = 3; //resizing as needed the LHS if (CalculateStiffnessMatrixFlag == true) //calculation of the matrix is required { if (rLeftHandSideMatrix.size1() != MatSize) rLeftHandSideMatrix.resize(MatSize,MatSize,false); noalias(rLeftHandSideMatrix) = ZeroMatrix(MatSize,MatSize); //resetting LHS } //resizing as needed the RHS if (CalculateResidualVectorFlag == true) //calculation of the matrix is required { if (rRightHandSideVector.size() != MatSize) rRightHandSideVector.resize(MatSize); rRightHandSideVector = ZeroVector(MatSize); //resetting RHS } //reading integration points and local gradients const GeometryType::IntegrationPointsArrayType& integration_points = GetGeometry().IntegrationPoints(); const GeometryType::ShapeFunctionsGradientsType& DN_DeContainer = GetGeometry().ShapeFunctionsLocalGradients(); const Matrix& Ncontainer = GetGeometry().ShapeFunctionsValues(); //calculating actual jacobian GeometryType::JacobiansType J; J = GetGeometry().Jacobian(J); // for ( unsigned int n = 0; n < number_of_nodes; n++ ) // std::cout << "+++ node "<<n<<": face_load= "<<( GetGeometry()[n] ).GetSolutionStepValue( FACE_LOAD_PRESSURE )<<" +++" << std::endl; //auxiliary terms for (unsigned int PointNumber=0; PointNumber<integration_points.size(); PointNumber++) { Vector Load( 3 ); noalias( Load ) = ZeroVector( 3 ); Vector temp( 3 ); for ( unsigned int n = 0; n < number_of_nodes; n++ ) { // noalias( temp ) = ( GetGeometry()[n] ).GetSolutionStepValue( FACE_LOAD_PRESSURE ); // for ( unsigned int i = 0; i < 3; i++ ) // Load( i ) += temp( i ) * Ncontainer( PointNumber, n ); Load[0] += ( GetGeometry()[n] ).FastGetSolutionStepValue( FACE_LOAD_PRESSURE_X ) * Ncontainer( PointNumber, n ); Load[1] += ( GetGeometry()[n] ).FastGetSolutionStepValue( FACE_LOAD_PRESSURE_Y ) * Ncontainer( PointNumber, n ); Load[2] += ( GetGeometry()[n] ).FastGetSolutionStepValue( FACE_LOAD_PRESSURE_Z ) * Ncontainer( PointNumber, n ); } // if ( PointNumber == 1 ) // std::cout << "CONDITION ### FaceLoadPressure: load= " << Load << std::endl; double IntegrationWeight = GetGeometry().IntegrationPoints()[PointNumber].Weight(); //to be replaced by the formulation in Face3D Vector t1 = ZeroVector( 3 );//first tangential vector Vector t2 = ZeroVector( 3 );//second tangential vector for ( unsigned int n = 0; n < number_of_nodes; n++ ) { t1[0] += GetGeometry().GetPoint( n ).X0() * DN_DeContainer[PointNumber]( n, 0 ); t1[1] += GetGeometry().GetPoint( n ).Y0() * DN_DeContainer[PointNumber]( n, 0 ); t1[2] += GetGeometry().GetPoint( n ).Z0() * DN_DeContainer[PointNumber]( n, 0 ); t2[0] += GetGeometry().GetPoint( n ).X0() * DN_DeContainer[PointNumber]( n, 1 ); t2[1] += GetGeometry().GetPoint( n ).Y0() * DN_DeContainer[PointNumber]( n, 1 ); t2[2] += GetGeometry().GetPoint( n ).Z0() * DN_DeContainer[PointNumber]( n, 1 ); } //calculating normal Vector v3 = ZeroVector( 3 ); v3[0] = t1[1] * t2[2] - t1[2] * t2[1]; v3[1] = t1[2] * t2[0] - t1[0] * t2[2]; v3[2] = t1[0] * t2[1] - t1[1] * t2[0]; double dA = sqrt( v3[0] * v3[0] + v3[1] * v3[1] + v3[2] * v3[2] ); // RIGHT HAND SIDE VECTOR if ( CalculateResidualVectorFlag == true ) //calculation of the matrix is required { for ( unsigned int prim = 0; prim < number_of_nodes; prim++ ) for ( unsigned int i = 0; i < 3; i++ ) rRightHandSideVector( prim*dim + i ) += Ncontainer( PointNumber, prim ) * Load( i ) * IntegrationWeight * dA; } } KRATOS_CATCH("") } } // Namespace Kratos.
41.505376
211
0.589292
AndreaVoltan
60490e8223ed24a6d95cc69636b5a15321481d1b
1,940
cpp
C++
comm/sender_test.cpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
7
2019-04-09T16:25:49.000Z
2021-12-07T10:29:52.000Z
comm/sender_test.cpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
null
null
null
comm/sender_test.cpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
4
2019-08-07T07:43:27.000Z
2021-05-21T07:54:14.000Z
#include "glog/logging.h" #include "gtest/gtest.h" #include "comm/sender.hpp" #include <iostream> #include <vector> namespace minips { namespace { class TestSender : public testing::Test { public: TestSender() {} ~TestSender() {} protected: void SetUp() {} void TearDown() {} }; class FakeMailbox : public AbstractMailbox { public: virtual int Send(const Message &msg) override { to_send_.Push(msg); return -1; } void WaitAndPop(Message *msg) { to_send_.WaitAndPop(msg); } private: ThreadsafeQueue<Message> to_send_; }; TEST_F(TestSender, StartStop) { FakeMailbox mailbox; Sender sender(&mailbox); sender.Start(); sender.Stop(); } TEST_F(TestSender, Send) { FakeMailbox mailbox; Sender sender(&mailbox); sender.Start(); auto *send_queue = sender.GetMessageQueue(); // Msg Message msg; msg.meta.sender = 123; msg.meta.recver = 0; msg.meta.model_id = 0; msg.meta.flag = Flag::kGet; third_party::SArray<Key> keys{1}; third_party::SArray<float> vals{0.1}; msg.AddData(keys); msg.AddData(vals); // Push the firstbmsg send_queue->Push(msg); Message res; mailbox.WaitAndPop(&res); EXPECT_EQ(res.meta.sender, msg.meta.sender); // Push the second msg msg.meta.sender = 543; send_queue->Push(msg); mailbox.WaitAndPop(&res); EXPECT_EQ(res.meta.sender, msg.meta.sender); sender.Stop(); } } // namespace } // namespace minips
24.25
59
0.495876
RickAi
6049e827e03267426651bb93dc2981591c5369c9
1,602
hpp
C++
src/Cajita.hpp
sfogerty/Cajita
6126509050f73c58614c9ae340015dd96ea4dfe7
[ "BSD-3-Clause" ]
20
2019-07-26T15:24:51.000Z
2020-02-29T01:40:33.000Z
src/Cajita.hpp
sfogerty/Cajita
6126509050f73c58614c9ae340015dd96ea4dfe7
[ "BSD-3-Clause" ]
26
2019-07-29T16:17:03.000Z
2020-06-09T18:27:37.000Z
src/Cajita.hpp
sfogerty/Cajita
6126509050f73c58614c9ae340015dd96ea4dfe7
[ "BSD-3-Clause" ]
6
2019-07-24T21:42:10.000Z
2020-04-10T12:05:50.000Z
/**************************************************************************** * Copyright (c) 2019-2020 by the Cajita authors * * All rights reserved. * * * * This file is part of the Cajita library. Cajita is distributed under a * * BSD 3-clause license. For the licensing terms see the LICENSE file in * * the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef CAJITA_HPP #define CAJITA_HPP #include <Cajita_Array.hpp> #include <Cajita_BovWriter.hpp> #include <Cajita_Config.hpp> #include <Cajita_GlobalGrid.hpp> #include <Cajita_GlobalMesh.hpp> #include <Cajita_Halo.hpp> #include <Cajita_IndexSpace.hpp> #include <Cajita_Interpolation.hpp> #include <Cajita_LocalGrid.hpp> #include <Cajita_LocalMesh.hpp> #include <Cajita_ManualPartitioner.hpp> #include <Cajita_MpiTraits.hpp> #include <Cajita_Partitioner.hpp> #include <Cajita_ReferenceStructuredSolver.hpp> #include <Cajita_Splines.hpp> #include <Cajita_Types.hpp> #include <Cajita_UniformDimPartitioner.hpp> #include <Cajita_Version.hpp> #ifdef CAJITA_HAVE_HYPRE #include <Cajita_HypreStructuredSolver.hpp> #endif #ifdef CAJITA_HAVE_HEFFTE #include <Cajita_FastFourierTransform.hpp> #endif #endif // end CAJITA_HPP
37.255814
78
0.555556
sfogerty
604ca4120540c41f055cc079e5f7346f1eafdfdf
6,177
cpp
C++
windows/wrapper/impl_org_webRtc_RTCRemoteOutboundRtpStreamStats.cpp
kevinhartman/webrtc-apis
c95bc4b8515bfb0920f3694ccba34ee5e2f63692
[ "BSD-3-Clause" ]
null
null
null
windows/wrapper/impl_org_webRtc_RTCRemoteOutboundRtpStreamStats.cpp
kevinhartman/webrtc-apis
c95bc4b8515bfb0920f3694ccba34ee5e2f63692
[ "BSD-3-Clause" ]
null
null
null
windows/wrapper/impl_org_webRtc_RTCRemoteOutboundRtpStreamStats.cpp
kevinhartman/webrtc-apis
c95bc4b8515bfb0920f3694ccba34ee5e2f63692
[ "BSD-3-Clause" ]
null
null
null
// Generated by zsLibEventingTool #include "impl_org_webRtc_RTCRemoteOutboundRtpStreamStats.h" using ::zsLib::String; using ::zsLib::Optional; using ::zsLib::Any; using ::zsLib::AnyPtr; using ::zsLib::AnyHolder; using ::zsLib::Promise; using ::zsLib::PromisePtr; using ::zsLib::PromiseWithHolder; using ::zsLib::PromiseWithHolderPtr; using ::zsLib::eventing::SecureByteBlock; using ::zsLib::eventing::SecureByteBlockPtr; using ::std::shared_ptr; using ::std::weak_ptr; using ::std::make_shared; using ::std::list; using ::std::set; using ::std::map; // borrow definitions from class ZS_DECLARE_TYPEDEF_PTR(wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::WrapperImplType, WrapperImplType); ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::WrapperType, WrapperType); //------------------------------------------------------------------------------ wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::RTCRemoteOutboundRtpStreamStats() noexcept { } //------------------------------------------------------------------------------ wrapper::org::webRtc::RTCRemoteOutboundRtpStreamStatsPtr wrapper::org::webRtc::RTCRemoteOutboundRtpStreamStats::wrapper_create() noexcept { auto pThis = make_shared<wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats>(); pThis->thisWeak_ = pThis; return pThis; } //------------------------------------------------------------------------------ wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::~RTCRemoteOutboundRtpStreamStats() noexcept { thisWeak_.reset(); } //------------------------------------------------------------------------------ ::zsLib::Time wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_timestamp() noexcept { ::zsLib::Time result {}; return result; } //------------------------------------------------------------------------------ Optional< wrapper::org::webRtc::RTCStatsType > wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_statsType() noexcept { Optional< wrapper::org::webRtc::RTCStatsType > result {}; return result; } //------------------------------------------------------------------------------ String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_statsTypeOther() noexcept { String result {}; return result; } //------------------------------------------------------------------------------ String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_id() noexcept { String result {}; return result; } //------------------------------------------------------------------------------ Optional< uint32_t > wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_ssrc() noexcept { Optional< uint32_t > result {}; return result; } //------------------------------------------------------------------------------ String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_kind() noexcept { String result {}; return result; } //------------------------------------------------------------------------------ String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_transportId() noexcept { String result {}; return result; } //------------------------------------------------------------------------------ String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_codecId() noexcept { String result {}; return result; } //------------------------------------------------------------------------------ unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_firCount() noexcept { unsigned long result {}; return result; } //------------------------------------------------------------------------------ unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_pliCount() noexcept { unsigned long result {}; return result; } //------------------------------------------------------------------------------ unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_nackCount() noexcept { unsigned long result {}; return result; } //------------------------------------------------------------------------------ unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_sliCount() noexcept { unsigned long result {}; return result; } //------------------------------------------------------------------------------ unsigned long long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_qpSum() noexcept { unsigned long long result {}; return result; } //------------------------------------------------------------------------------ unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_packetsSent() noexcept { unsigned long result {}; return result; } //------------------------------------------------------------------------------ unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_packetsDiscardedOnSend() noexcept { unsigned long result {}; return result; } //------------------------------------------------------------------------------ unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_fecPacketsSent() noexcept { unsigned long result {}; return result; } //------------------------------------------------------------------------------ unsigned long long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_bytesSent() noexcept { unsigned long long result {}; return result; } //------------------------------------------------------------------------------ unsigned long long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_bytesDiscardedOnSend() noexcept { unsigned long long result {}; return result; } //------------------------------------------------------------------------------ String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_localId() noexcept { String result {}; return result; } //------------------------------------------------------------------------------ ::zsLib::Time wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_remoteTimestamp() noexcept { ::zsLib::Time result {}; return result; }
33.032086
137
0.535697
kevinhartman
604d76204206a3460fb5f812df71aad5d4412b2d
4,433
hpp
C++
NWNXLib/API/API/CNWSPlaceable.hpp
nwnstuff/unified
2da1201fdded07235f3d2809a3215315140d19da
[ "MIT" ]
null
null
null
NWNXLib/API/API/CNWSPlaceable.hpp
nwnstuff/unified
2da1201fdded07235f3d2809a3215315140d19da
[ "MIT" ]
null
null
null
NWNXLib/API/API/CNWSPlaceable.hpp
nwnstuff/unified
2da1201fdded07235f3d2809a3215315140d19da
[ "MIT" ]
null
null
null
#pragma once #include "nwn_api.hpp" #include "CExoString.hpp" #include "CExoLocString.hpp" #include "CExoArrayList.hpp" #include "Vector.hpp" #include "CResRef.hpp" #include "CNWSObject.hpp" #ifdef NWN_API_PROLOGUE NWN_API_PROLOGUE(CNWSPlaceable) #endif struct CNWSObjectActionNode; struct CResStruct; struct CNWSArea; struct CNWSItem; struct CItemRepository; struct CResGFF; typedef int BOOL; typedef uint32_t OBJECT_ID; struct CNWSPlaceable : CNWSObject { CExoLocString m_sLocName; CExoString m_sDisplayName; int32_t m_nUpdateDisplayNameSeq; uint16_t m_nAppearance; CExoLocString m_sDescription; CExoString m_sDescriptionOverride; int32_t m_nFactionId; CResRef m_cDialog; uint8_t m_nType; BOOL m_bGroundPile; OBJECT_ID m_oidSittingCreature; uint8_t m_nHardness; float m_fBearing; BOOL m_bLocked; CExoString m_sKeyName; CExoString m_sKeyRequiredFeedbackMessage; BOOL m_bKeyRequired; BOOL m_bAutoRemoveKey; uint8_t m_nOpenLockDC; uint8_t m_nCloseLockDC; OBJECT_ID m_oidTrapCreator; uint8_t m_nTrapDetectionDC; BOOL m_bTrapFlag; uint8_t m_nDisarmDC; BOOL m_bDisarmable; BOOL m_bDetectable; BOOL m_bOneShot; BOOL m_bRecoverable; BOOL m_bFlagged; uint8_t m_nBaseType; BOOL m_bTrapIsActive; int32_t m_nTrapFaction; CExoString m_sScripts[16]; uint8_t m_nFortSave; uint8_t m_nWillSave; uint8_t m_nReflexSave; CExoArrayList<OBJECT_ID> m_poidCreatures; BOOL m_bHasInventory; BOOL m_bUseable; BOOL m_bPickable; BOOL m_bLockable; BOOL m_bDieWhenEmpty; uint32_t m_nOpenCount; int32_t m_nStaticObjectPosition; OBJECT_ID m_oidLootCreature; BOOL m_bIsBodyBag; uint32_t m_nLastHeartbeatScriptCalendarDay; uint32_t m_nLastHeartbeatScriptTimeOfDay; OBJECT_ID m_oidLastOpened; OBJECT_ID m_oidLastClosed; OBJECT_ID m_oidLastUser; OBJECT_ID m_oidLastDefaultClickedBy; OBJECT_ID m_oidLastTriggered; OBJECT_ID m_oidLastDisarmed; OBJECT_ID m_oidLastLocked; OBJECT_ID m_oidLastUnlocked; CItemRepository * m_pcItemRepository; uint16_t m_nRepositoryArrayIndex; uint16_t m_nItemContainerArrayIndex; OBJECT_ID m_oidCurrentItemContainer; Vector m_pvActionPoints[2]; CResRef m_cTemplateResRef; CExoString m_szPortalInfo; uint32_t m_nEffectSpellId; BOOL m_bLightIsOn; BOOL m_bLightStateChange; uint8_t m_nBodyBag; BOOL m_bStaticObject; BOOL m_bNeverMakeIntoStaticObject; virtual CNWSPlaceable * AsNWSPlaceable(); CNWSPlaceable(OBJECT_ID oidId = 0x7f000000); ~CNWSPlaceable(); void AddToArea(CNWSArea * pArea, float fX, float fY, float fZ, BOOL bRunScripts = true); void RemoveFromArea(); void SetOrientation(Vector vOrientation); void AIUpdate(); void DoDamage(int32_t nDamage); void EventHandler(uint32_t nEventId, OBJECT_ID nCallerObjectId, void * pScript, uint32_t nCalendarDay, uint32_t nTimeOfDay); BOOL LoadPlaceable(CResGFF * pRes, CResStruct * cPlaceableStruct, CExoString * pTag = nullptr); BOOL LoadFromTemplate(CResRef cResRef, CExoString * pTag = nullptr); BOOL LoadBodyBag(uint16_t nAppearance); BOOL SavePlaceable(CResGFF * pRes, CResStruct * pStruct, BOOL bSaveOIDs); void PostProcess(); BOOL AcquireItem(CNWSItem * * pItem, OBJECT_ID oidPossessor = 0x7f000000, uint8_t x = 0xff, uint8_t y = 0xff, BOOL bDisplayFeedback = true); BOOL RemoveItem(CNWSItem * pItem, BOOL bSetPossessor = true); uint32_t AcquireItemsFromObject(OBJECT_ID oidObject, BOOL bAcquireDroppablesOnly = true); void OpenInventory(OBJECT_ID oidOpener); void CloseInventory(OBJECT_ID oidCloser, BOOL bUpdatePlayer = true); void DropItemsIntoArea(); Vector GetNearestActionPoint(const Vector & vPosition); BOOL AddCastSpellActions(uint32_t nSpellId, int32_t nMetaType, Vector vTargetLocation, OBJECT_ID oidTarget, BOOL bFake = false, uint8_t nProjectilePathType = 0); uint32_t AIActionCastSpell(CNWSObjectActionNode * pNode); BOOL GetLightIsOn(); void SetLightIsOn(BOOL b); uint16_t GetBodyBagAppearance(); uint32_t GetItemCount(BOOL bDroppableOnly = true); void ClosePlaceableForAllPlayers(); void CalculateActionPoints(); #ifdef NWN_CLASS_EXTENSION_CNWSPlaceable NWN_CLASS_EXTENSION_CNWSPlaceable #endif }; #ifdef NWN_API_EPILOGUE NWN_API_EPILOGUE(CNWSPlaceable) #endif
31.439716
165
0.765847
nwnstuff
604e5692484977e3ff4b257224d809d9f5e9acf6
197
cpp
C++
templates/== libraryName ==/src/library_main.cpp
julian-becker/slush-cmake-library
5511f2276853545b366a34bdda48885f6b2b956b
[ "MIT" ]
null
null
null
templates/== libraryName ==/src/library_main.cpp
julian-becker/slush-cmake-library
5511f2276853545b366a34bdda48885f6b2b956b
[ "MIT" ]
null
null
null
templates/== libraryName ==/src/library_main.cpp
julian-becker/slush-cmake-library
5511f2276853545b366a34bdda48885f6b2b956b
[ "MIT" ]
null
null
null
#include <<%= libraryName %>/export.h> #include <iostream> <%= LIBRARYNAME %>_API int <%= libraryName %>_api() { std::cout << "hello from <%= libraryName %>" << std::endl; return 12345; }
21.888889
62
0.598985
julian-becker
604ff12d561cded190e636446b8a0ca555384546
14,457
cpp
C++
src/toolkits/feature_engineering/dict_transform_utils.cpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
src/toolkits/feature_engineering/dict_transform_utils.cpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
src/toolkits/feature_engineering/dict_transform_utils.cpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <toolkits/feature_engineering/dict_transform_utils.hpp> #include <core/data/flexible_type/flexible_type.hpp> #include <core/data/sframe/gl_sarray.hpp> namespace turi { /** Index keys come up in a lot of places, e.g. vectors. This deals * with that. (Also good to have it as it's own function in case * we want to update it later on). */ static inline flexible_type get_index_key(const flex_int& key) { return flexible_type(key).to<flex_string>(); }; /** The recursion function to actually add everything to the rest of * new dictionary. * * out -- the final dictionary. * key -- the current key. May be modified. * v -- the value to add to the dictionary. * separator -- the separator string. * undefined_string -- what to call undefined values. * process_image_value -- how to process images. * process_datetime_value -- how to process datetime values. */ GL_HOT_FLATTEN static void _to_flat_dict_recursion( flex_dict& out, flex_string& key, const flexible_type& v, const flex_string& separator, const flex_string& undefined_string, const std::function<flexible_type(const flex_image&)>& process_image_value, const std::function<flexible_type(const flex_date_time&)>& process_datetime_value, size_t depth) { // You probably hit errors before this in other areas of the code, // e.g. flexible type destructors. //////////////////////////////////////////////////////////////////////////////// /** Checks to error out if we go too deep. */ static constexpr size_t MAX_RECURSION_DEPTH = 64; // Where we recurse on the value, along with error checking as well. auto recurse_on_value = [&](const flexible_type& recurse_v) GL_GCC_ONLY(GL_HOT_INLINE) { auto depth_overflow_error = [&]() GL_GCC_ONLY(GL_COLD_NOINLINE) { // Check to make sure we haven't reached our recursion depth limit. std::ostringstream ss; ss << "Maximum nested depth in dictionary of " << MAX_RECURSION_DEPTH << " exceeded in flattening dictionary/list. " << "This is not the type of deep learning we are used to." << std::endl; throw std::runtime_error(ss.str()); }; if(depth > MAX_RECURSION_DEPTH) { depth_overflow_error(); } _to_flat_dict_recursion(out, key, recurse_v, separator, undefined_string, process_image_value, process_datetime_value, depth + 1); }; //////////////////////////////////////////////////////////////////////////////// /** Add a new sub-key to the current key string. Put this in a * central place so that all the different paths have a consistent * way of handling the key. */ auto add_to_key_string = [&](const flexible_type& key_v) { // Add in the separator if needed. if(key.size() != 0) { key.append(separator); } // Write out the key switch(v.get_type()) { case flex_type_enum::STRING: { key.append(key_v.get<flex_string>()); break; } case flex_type_enum::UNDEFINED: { key.append(undefined_string); break; } case flex_type_enum::INTEGER: { flex_string s = get_index_key(key_v.get<flex_int>()); key.append(s); break; } default: { flex_string s = key_v.to<flex_string>(); key.append(s); break; } } }; //////////////////////////////////////////////////////////////////////////////// // Now, handle the value. size_t base_key_size = key.size(); switch(v.get_type()) { case flex_type_enum::INTEGER: case flex_type_enum::FLOAT: { out.push_back({key, v}); break; } case flex_type_enum::DICT: { const flex_dict& d = v.get<flex_dict>(); for(const auto& p : d) { add_to_key_string(p.first); recurse_on_value(p.second); key.resize(base_key_size); } break; } case flex_type_enum::UNDEFINED: case flex_type_enum::STRING: { add_to_key_string(v); out.push_back({key, 1}); key.resize(base_key_size); break; } case flex_type_enum::LIST: { const flex_list& fl = v.get<flex_list>(); for(size_t i = 0; i < fl.size(); ++i) { add_to_key_string(i); recurse_on_value(fl[i]); key.resize(base_key_size); } break; } case flex_type_enum::VECTOR: { const flex_vec& fv = v.get<flex_vec>(); for(size_t i = 0; i < fv.size(); ++i) { add_to_key_string(i); out.push_back({key, fv[i]}); key.resize(base_key_size); } break; } case flex_type_enum::IMAGE: { flexible_type ft_out = process_image_value(v.get<flex_image>()); ASSERT_MSG(ft_out.get_type() != flex_type_enum::IMAGE, "Handling function for image types returned an image type."); if(ft_out.get_type() != flex_type_enum::UNDEFINED) { recurse_on_value(ft_out); } break; } case flex_type_enum::DATETIME: { flexible_type ft_out = process_datetime_value(v.get<flex_date_time>()); ASSERT_MSG(ft_out.get_type() != flex_type_enum::DATETIME, "Handling function for datetime types returned an datetime type."); if(ft_out.get_type() != flex_type_enum::UNDEFINED) { recurse_on_value(ft_out); } break; } case flex_type_enum::ND_VECTOR: { log_and_throw(std::string("Flexible type case currently unsupported: ND_VECTOR")); ASSERT_UNREACHABLE(); } default: { log_and_throw(std::string("Flexible type case not recognized")); ASSERT_UNREACHABLE(); } } } /** Flattens any types to a non-nested dictionary of (string key : * numeric value) pairs. Each nested key is a concatenation of the * keys in the separation with sep_char separating them. For * example, if sep_char = ".", then * * {"a" : {"b" : 1}, "c" : 2} * * becomes * * {"a.b" : 1, "c" : 2}. * * - List and vector elements are handled by converting the index of * the appropriate element to a string. * * - String values are handled by treating them as a single * {"string_value" : 1} pair. * * - numeric values in the original are translated into a {"0" : * value} dict. * * - FLEX_UNDEFINED values are handled by replacing them with the * string contents of `undefined_string`. * * - image and datetime types are handled by calling * process_image_value and process_datetime_value. These * functions must either throw an exception, which propegates up, * return any other flexible type (e.g. dict, list, vector, etc.), * or return FLEX_UNDEFINED, in which case that value is ignored. * */ GL_HOT flex_dict to_flat_dict( const flexible_type& input, const flex_string& separator, const flex_string& undefined_string, std::function<flexible_type(const flex_image&)> process_image_value, std::function<flexible_type(const flex_date_time&)> process_datetime_value) { //////////////////////////////////////////////////////////////////////////////// // Some utility functions used everywhere -- done here to keep // things organized and make sure errors are processed correctly. //////////////////////////////////////////////////////////////////////////////// /** Based on the input type, we do some processing. */ switch(input.get_type()) { case flex_type_enum::DICT: { bool need_to_flatten = false; for(const auto& p : input.get<flex_dict>()) { if(p.first.get_type() != flex_type_enum::STRING) { need_to_flatten = true; } if(p.second.get_type() != flex_type_enum::FLOAT && p.second.get_type() != flex_type_enum::INTEGER) { need_to_flatten = true; } if(need_to_flatten) { break; } } // If we don't need to flatten it, then don't. if(!need_to_flatten) { return input.get<flex_dict>(); } else { break; } } case flex_type_enum::LIST: { // This will be flattened later on, as it could be arbitrarily // recursive. break; } case flex_type_enum::VECTOR: { // Vectors are changed to a dictionary of {"0" : v[0], "1" : v[1], ...}. const flex_vec& v = input.get<flex_vec>(); flex_dict _out(v.size()); for(size_t i = 0; i < v.size(); ++i) { _out[i] = {get_index_key(i), v[i]}; } return _out; } case flex_type_enum::STRING: { return flex_dict{ {input, 1} }; } case flex_type_enum::INTEGER: case flex_type_enum::FLOAT: { return flex_dict{ {get_index_key(0), input} }; } case flex_type_enum::IMAGE: { // This can recurse a maximum of once, as the return value of // process_image_value cannot be an image or datetime type, // and this is the only place we recurse. return to_flat_dict(process_image_value(input), separator, undefined_string, process_image_value, process_datetime_value); } case flex_type_enum::DATETIME: { // This can recurse a maximum of once, as the return value of // process_datetime_value cannot be an image or datetime type, // and this is the only place we recurse. return to_flat_dict(process_datetime_value(input), separator, undefined_string, process_image_value, process_datetime_value); } case flex_type_enum::UNDEFINED: { return flex_dict{ {undefined_string, 1} }; } case flex_type_enum::ND_VECTOR: { log_and_throw(std::string("Flexible type case currently unsupported: ND_VECTOR")); ASSERT_UNREACHABLE(); } default: { log_and_throw(std::string("Flexible type case not recognized")); ASSERT_UNREACHABLE(); } } //////////////////////////////////////////////////////////////////////////////// // Reserve the output container. flex_dict out; out.reserve(input.size()); // The current key. flex_string key = ""; key.reserve(256); _to_flat_dict_recursion(out, key, input, separator, undefined_string, process_image_value, process_datetime_value, 0); return out; } //////////////////////////////////////////////////////////////////////////////// static std::function<flexible_type(const flex_image&)> _get_image_handler( const std::string& image_policy) { if(image_policy == "error") { return [](const flex_image&) -> flexible_type { log_and_throw("Image types are not allowed when flattening dictionaries."); }; } else if (image_policy == "ignore") { return [](const flex_image&) -> flexible_type { return FLEX_UNDEFINED; }; } else { log_and_throw("At this time, only \"error\" and \"ignore\" are " "implemented for handling of image types."); return [](const flex_image&) -> flexible_type { return FLEX_UNDEFINED; }; } } static std::function<flexible_type(const flex_date_time&)> _get_datetime_handler( const std::string& datetime_policy) { if(datetime_policy == "error") { return [](const flex_date_time&) -> flexible_type { log_and_throw("Datetime types are not allowed when flattening dictionaries."); }; } else if (datetime_policy == "ignore") { return [](const flex_date_time&) -> flexible_type { return FLEX_UNDEFINED; }; } else { log_and_throw("At this time, only \"error\" and \"ignore\" are " "implemented for handling of datetime types."); return [](const flex_date_time&) -> flexible_type { return FLEX_UNDEFINED; }; } } /** Flattens any types to a non-nested dictionary of (string key : * numeric value) pairs. Each nested key is a concatenation of the * keys in the separation with sep_char separating them. For * example, if sep_char = ".", then * * {"a" : {"b" : 1}, "c" : 2} * * becomes * * {"a.b" : 1, "c" : 2}. * * - List and vector elements are handled by converting the index of * the appropriate element to a string. * * - String values are handled by treating them as a single * {"string_value" : 1} pair. * * - numeric values in the original are translated into a {"0" : * value} dict. * * - FLEX_UNDEFINED values are handled by replacing them with the * string contents of `undefined_string`. * * - image and datetime types are handled by calling * process_image_value and process_datetime_value. These * functions must either throw an exception, which propegates up, * return any other flexible type (e.g. dict, list, vector, etc.), * or return FLEX_UNDEFINED, in which case that value is ignored. * */ EXPORT flex_dict to_flat_dict(const flexible_type& input, const flex_string& separator, const flex_string& undefined_string, const std::string& image_policy, const std::string& datetime_policy) { return to_flat_dict(input, separator, undefined_string, _get_image_handler(image_policy), _get_datetime_handler(datetime_policy)); } /** Performs dictionary flattening on an SArray. */ EXPORT gl_sarray to_sarray_of_flat_dictionaries(gl_sarray input, const flex_string& sep, const flex_string& undefined_string, const std::string& image_policy, const std::string& datetime_policy) { auto image_handler = _get_image_handler(image_policy); auto datetime_handler = _get_datetime_handler(datetime_policy); std::function<flexible_type(const flexible_type& dt)> flatten_it = [=](const flexible_type& x) -> flexible_type GL_GCC_ONLY(GL_HOT_FLATTEN) { return to_flat_dict(x, sep, undefined_string, image_handler, datetime_handler); }; return input.apply(flatten_it, flex_type_enum::DICT); } }
32.414798
90
0.60552
Bpowers4
6050123017fabbb197c8363977751b1a3c29ea58
12,208
hpp
C++
include/etl/op/dim_view.hpp
wichtounet/etl
8cc5b7eaf56f1d9f9f78d337d64339731ffe2a94
[ "MIT" ]
210
2015-02-13T11:40:45.000Z
2022-01-21T21:46:42.000Z
include/etl/op/dim_view.hpp
wichtounet/etl
8cc5b7eaf56f1d9f9f78d337d64339731ffe2a94
[ "MIT" ]
5
2017-01-31T18:12:48.000Z
2020-07-16T15:18:00.000Z
include/etl/op/dim_view.hpp
wichtounet/etl
8cc5b7eaf56f1d9f9f78d337d64339731ffe2a94
[ "MIT" ]
25
2016-11-26T16:32:56.000Z
2021-07-20T02:08:51.000Z
//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief dim_view expression implementation */ #pragma once namespace etl { /*! * \brief View that shows one dimension of a matrix * \tparam T The type of expression on which the view is made * \tparam D The dimension to show */ template <typename T, size_t D> struct dim_view { static_assert(D == 1 || D == 2, "Invalid dimension"); using sub_type = T; ///< The sub type using value_type = value_t<sub_type>; ///< The value contained in the expression using memory_type = memory_t<sub_type>; ///< The memory acess type using const_memory_type = const_memory_t<sub_type>; ///< The const memory access type using return_type = return_helper<sub_type, decltype(std::declval<sub_type>()(0, 0))>; ///< The type returned by the view using const_return_type = const_return_helper<sub_type, decltype(std::declval<sub_type>()(0, 0))>; ///< The const type return by the view private: T sub; ///< The Sub expression const size_t i; ///< The index friend struct etl_traits<dim_view>; public: /*! * \brief Construct a new dim_view over the given sub expression * \param sub The sub expression * \param i The sub index */ dim_view(sub_type sub, size_t i) : sub(sub), i(i) {} /*! * \brief Returns the element at the given index * \param j The index * \return a reference to the element at the given index. */ const_return_type operator[](size_t j) const { if (D == 1) { return sub(i, j); } else { //D == 2 return sub(j, i); } } /*! * \brief Returns the element at the given index * \param j The index * \return a reference to the element at the given index. */ return_type operator[](size_t j) { if (D == 1) { return sub(i, j); } else { //D == 2 return sub(j, i); } } /*! * \brief Returns the value at the given index * This function never has side effects. * \param j The index * \return the value at the given index. */ value_type read_flat(size_t j) const noexcept { if (D == 1) { return sub(i, j); } else { //D == 2 return sub(j, i); } } /*! * \brief Returns the element at the given index * \param j The index * \return a reference to the element at the given index. */ const_return_type operator()(size_t j) const { if (D == 1) { return sub(i, j); } else { //D == 2 return sub(j, i); } } /*! * \brief Returns the element at the given index * \param j The index * \return a reference to the element at the given index. */ return_type operator()(size_t j) { if (D == 1) { return sub(i, j); } else { //D == 2 return sub(j, i); } } /*! * \brief Test if this expression aliases with the given expression * \param rhs The other expression to test * \return true if the two expressions aliases, false otherwise */ template <typename E> bool alias(const E& rhs) const noexcept { return sub.alias(rhs); } /*! * \brief Returns a pointer to the first element in memory. * \return a pointer tot the first element in memory. */ memory_type memory_start() noexcept { static_assert(is_dma<T> && D == 1, "This expression does not have direct memory access"); return sub.memory_start() + i * subsize(sub); } /*! * \brief Returns a pointer to the first element in memory. * \return a pointer tot the first element in memory. */ const_memory_type memory_start() const noexcept { static_assert(is_dma<T> && D == 1, "This expression does not have direct memory access"); return sub.memory_start() + i * subsize(sub); } /*! * \brief Returns a pointer to the past-the-end element in memory. * \return a pointer tot the past-the-end element in memory. */ memory_type memory_end() noexcept { static_assert(is_dma<T> && D == 1, "This expression does not have direct memory access"); return sub.memory_start() + (i + 1) * subsize(sub); } /*! * \brief Returns a pointer to the past-the-end element in memory. * \return a pointer tot the past-the-end element in memory. */ const_memory_type memory_end() const noexcept { static_assert(is_dma<T> && D == 1, "This expression does not have direct memory access"); return sub.memory_start() + (i + 1) * subsize(sub); } // Assignment functions /*! * \brief Assign to the given left-hand-side expression * \param lhs The expression to which assign */ template <typename L> void assign_to(L&& lhs) const { std_assign_evaluate(*this, lhs); } /*! * \brief Add to the given left-hand-side expression * \param lhs The expression to which assign */ template <typename L> void assign_add_to(L&& lhs) const { std_add_evaluate(*this, lhs); } /*! * \brief Sub from the given left-hand-side expression * \param lhs The expression to which assign */ template <typename L> void assign_sub_to(L&& lhs) const { std_sub_evaluate(*this, lhs); } /*! * \brief Multiply the given left-hand-side expression * \param lhs The expression to which assign */ template <typename L> void assign_mul_to(L&& lhs) const { std_mul_evaluate(*this, lhs); } /*! * \brief Divide the given left-hand-side expression * \param lhs The expression to which assign */ template <typename L> void assign_div_to(L&& lhs) const { std_div_evaluate(*this, lhs); } /*! * \brief Modulo the given left-hand-side expression * \param lhs The expression to which assign */ template <typename L> void assign_mod_to(L&& lhs) const { std_mod_evaluate(*this, lhs); } // Internals /*! * \brief Apply the given visitor to this expression and its descendants. * \param visitor The visitor to apply */ void visit(detail::evaluator_visitor& visitor) const { sub.visit(visitor); } /*! * \brief Ensures that the GPU memory is allocated and that the GPU memory * is up to date (to undefined value). */ void ensure_cpu_up_to_date() const { // Need to ensure sub value sub.ensure_cpu_up_to_date(); } /*! * \brief Copy back from the GPU to the expression memory if * necessary. */ void ensure_gpu_up_to_date() const { // Need to ensure both LHS and RHS sub.ensure_gpu_up_to_date(); } /*! * \brief Print a representation of the view on the given stream * \param os The output stream * \param v The view to print * \return the output stream */ friend std::ostream& operator<<(std::ostream& os, const dim_view& v) { return os << "dim[" << D << "](" << v.sub << ", " << v.i << ")"; } }; /*! * \brief Specialization for dim_view */ template <typename T, size_t D> struct etl_traits<etl::dim_view<T, D>> { using expr_t = etl::dim_view<T, D>; ///< The expression type using sub_expr_t = std::decay_t<T>; ///< The sub expression type using value_type = typename etl_traits<sub_expr_t>::value_type; ///< The value type static constexpr bool is_etl = true; ///< Indicates if the type is an ETL expression static constexpr bool is_transformer = false; ///< Indicates if the type is a transformer static constexpr bool is_view = true; ///< Indicates if the type is a view static constexpr bool is_magic_view = false; ///< Indicates if the type is a magic view static constexpr bool is_fast = etl_traits<sub_expr_t>::is_fast; ///< Indicates if the expression is fast static constexpr bool is_linear = false; ///< Indicates if the expression is linear static constexpr bool is_thread_safe = etl_traits<sub_expr_t>::is_thread_safe; ///< Indicates if the expression is thread safe static constexpr bool is_value = false; ///< Indicates if the expression is of value type static constexpr bool is_direct = etl_traits<sub_expr_t>::is_direct && D == 1; ///< Indicates if the expression has direct memory access static constexpr bool is_generator = false; ///< Indicates if the expression is a generator static constexpr bool is_padded = false; ///< Indicates if the expression is padded static constexpr bool is_aligned = false; ///< Indicates if the expression is padded static constexpr bool is_temporary = etl_traits<sub_expr_t>::is_temporary; ///< Indicates if the exxpression needs a evaluator visitor static constexpr bool gpu_computable = false; ///< Indicates if the expression can be computed on GPU static constexpr order storage_order = etl_traits<sub_expr_t>::storage_order; ///< The expression's storage order /*! * \brief Indicates if the expression is vectorizable using the * given vector mode * \tparam V The vector mode */ template <vector_mode_t V> static constexpr bool vectorizable = false; /*! * \brief Returns the size of the given expression * \param v The expression to get the size for * \returns the size of the given expression */ static size_t size(const expr_t& v) { if (D == 1) { return etl_traits<sub_expr_t>::dim(v.sub, 1); } else { return etl_traits<sub_expr_t>::dim(v.sub, 0); } } /*! * \brief Returns the dth dimension of the given expression * \param v The expression * \param d The dimension to get * \return The dth dimension of the given expression */ static size_t dim(const expr_t& v, [[maybe_unused]] size_t d) { cpp_assert(d == 0, "Invalid dimension"); return size(v); } /*! * \brief Returns the size of an expression of this fast type. * \returns the size of an expression of this fast type. */ static constexpr size_t size() { return D == 1 ? etl_traits<sub_expr_t>::template dim<1>() : etl_traits<sub_expr_t>::template dim<0>(); } /*! * \brief Returns the D2th dimension of an expression of this type * \tparam D2 The dimension to get * \return the D2th dimension of an expression of this type */ template <size_t D2> static constexpr size_t dim() { static_assert(D2 == 0, "Invalid dimension"); return size(); } /*! * \brief Returns the number of expressions for this type * \return the number of dimensions of this type */ static constexpr size_t dimensions() { return 1; } /*! * \brief Estimate the complexity of computation * \return An estimation of the complexity of the expression */ static constexpr int complexity() noexcept { return -1; } }; } //end of namespace etl
34.88
147
0.574132
wichtounet
60502ce5ecedb8247b8c3662268eb535d64305b6
715
cpp
C++
cpp/student/student.cpp
shauryachawla/misc
e50eb7c8979f9b3f7ecc43464cf7ccc91bf4d0bb
[ "MIT" ]
null
null
null
cpp/student/student.cpp
shauryachawla/misc
e50eb7c8979f9b3f7ecc43464cf7ccc91bf4d0bb
[ "MIT" ]
null
null
null
cpp/student/student.cpp
shauryachawla/misc
e50eb7c8979f9b3f7ecc43464cf7ccc91bf4d0bb
[ "MIT" ]
1
2019-10-07T08:22:09.000Z
2019-10-07T08:22:09.000Z
#include "student.h" #include <iostream> using namespace std; void Student::input (void) { cout << "\n\nRoll No: "; cin >> rollno; cout << "Name: "; cin.ignore(); cin.getline(name, 20); cout << "MARKS" << endl; cout << "Phy: "; cin >> marks[phy]; cout << "Chem: "; cin >> marks[chem]; cout << "Math: "; cin >> marks[math]; } void Student::output (void) { cout << "\n\nRoll No: " << rollno << endl; cout << "Name: " << name << endl; cout << "MARKS" << endl << "Phy: " << marks[phy] << endl << "Chem: " << marks[chem] << endl << "Math: " << marks[math]; } float Student::totalMarks (void) { return (marks[phy] + marks[chem] + marks[math]); }
24.655172
60
0.513287
shauryachawla
60537596a9774a77332ba1d40d430a02f2ebe5f8
1,573
cc
C++
Mu2eG4/src/Mu2eUniverse.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
null
null
null
Mu2eG4/src/Mu2eUniverse.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
Mu2eG4/src/Mu2eUniverse.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
// // Umbrela for the the Mu2e G4 world classes // // $Id: Mu2eUniverse.cc,v 1.2 2012/11/19 23:03:49 genser Exp $ // $Author: genser $ // $Date: 2012/11/19 23:03:49 $ // // Original author Rob Kutschke // // // C++ includes #include <iostream> #include <vector> #include <iomanip> // Framework includes #include "art/Framework/Services/Registry/ServiceHandle.h" #include "cetlib_except/exception.h" // Mu2e includes #include "G4Helper/inc/G4Helper.hh" #include "Mu2eG4/inc/Mu2eUniverse.hh" // G4 includes #include "G4PhysicalVolumeStore.hh" using namespace std; namespace mu2e { Mu2eUniverse::Mu2eUniverse(): _geom(*(art::ServiceHandle<GeometryService>())), _config(_geom.config()), _helper(&(*(art::ServiceHandle<G4Helper>()))) {} // beware of the order of initialization/declarations Mu2eUniverse::~Mu2eUniverse(){ } // Convert to base units for all of the items in the vector. void Mu2eUniverse::setUnits( vector<double>& V, G4double unit ){ for ( vector<double>::iterator b=V.begin(), e=V.end(); b!=e; ++b){ *b *= unit; } } // A helper function for debugging. Print a subset of the physical volume store. void Mu2eUniverse::printPhys() { G4PhysicalVolumeStore* pstore = G4PhysicalVolumeStore::GetInstance(); int n(0); for ( std::vector<G4VPhysicalVolume*>::const_iterator i=pstore->begin(); i!=pstore->end(); i++){ cout << "Physical Volume: " << setw(5) << n++ << (*i)->GetName() << endl; if ( n > 25 ) break; } } } // end namespace mu2e
24.578125
100
0.643357
bonventre
6053fa76062bcfa303e9dd3acb1fc387dfd2057d
3,570
cpp
C++
Source/Source/Common/SO3World/Src/KNpcOrderList.cpp
uvbs/FullSource
07601c5f18d243fb478735b7bdcb8955598b9a90
[ "MIT" ]
2
2018-07-26T07:58:14.000Z
2019-05-31T14:32:18.000Z
Jx3Full/Source/Source/Common/SO3World/Src/KNpcOrderList.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
null
null
null
Jx3Full/Source/Source/Common/SO3World/Src/KNpcOrderList.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
5
2021-02-03T10:25:39.000Z
2022-02-23T07:08:37.000Z
#include "stdafx.h" #include "KMath.h" #include "Global.h" #include "KNpcOrderList.h" using namespace std; BOOL KNpcOrderManager::Init() { BOOL bResult = false; int nRetCode = false; ITabFile* piTabFile = NULL; char szFileName[MAX_PATH]; int nTableHeight = 0; snprintf(szFileName, MAX_PATH, "%s/NpcOrder/%s", SETTING_DIR, "OrderList.tab"); szFileName[MAX_PATH - 1] = '\0'; piTabFile = g_OpenTabFile(szFileName); if (!piTabFile) { KGLogPrintf(KGLOG_ERR, "[KNpcOrderManager] Failed to open tab file: \"%s\".\n", szFileName); goto Exit0; } nTableHeight = piTabFile->GetHeight(); KGLOG_PROCESS_ERROR(nTableHeight >= 1); for (int i = 0; i < nTableHeight - 1; ++i) { KORDER Order; DWORD dwID = 0; float fZoom = 0.0f; nRetCode = piTabFile->GetInteger(2 + i, "ID", 0, (int*)&dwID); KGLOG_PROCESS_ERROR(nRetCode == 1); nRetCode = piTabFile->GetString(2 + i, "File", "", szFileName, MAX_PATH); KGLOG_PROCESS_ERROR(nRetCode == 1); nRetCode = piTabFile->GetFloat(2 + i, "Zoom", 0.0f, &fZoom); KGLOG_PROCESS_ERROR(nRetCode == 1); KGLOG_PROCESS_ERROR(fZoom != 0.0f); nRetCode = LoadOrder(Order, szFileName, fZoom); KGLOG_PROCESS_ERROR(nRetCode); m_OrderList[dwID] = Order; } bResult = true; Exit0: if (!bResult) { m_OrderList.clear(); } KG_COM_RELEASE(piTabFile); return bResult; } void KNpcOrderManager::UnInit() { m_OrderList.clear(); } const KORDER* KNpcOrderManager::GetOrder(DWORD dwID) { KORDER_LIST::iterator it = m_OrderList.find(dwID); if (it == m_OrderList.end()) return NULL; return &it->second; } BOOL KNpcOrderManager::LoadOrder(KORDER& rOrder, const char cszFileName[], float fZoom) { BOOL bResult = false; int nRetCode = false; ITabFile* piTabFile = NULL; char szFullName[MAX_PATH]; int nTableHeight = 0; snprintf(szFullName, MAX_PATH, "%s/NpcOrder/%s", SETTING_DIR, cszFileName); szFullName[MAX_PATH - 1] = '\0'; piTabFile = g_OpenTabFile(szFullName); if (!piTabFile) { KGLogPrintf(KGLOG_ERR, "[KNpcOrderManager] Failed to open tab file: \"%s\".\n", szFullName); goto Exit0; } nTableHeight = piTabFile->GetHeight(); KGLOG_PROCESS_ERROR(nTableHeight > 1); for (int i = 0; i < nTableHeight - 1; ++i) { int nIndex = 0; float fRadius = 0.0f; float fAngel = 0.0f; KORDER_NODE Node; nRetCode = piTabFile->GetInteger(2 + i, "Index", 0, &nIndex); KG_PROCESS_ERROR(nRetCode == 1); nRetCode = piTabFile->GetFloat(2 + i, "Radius", 0, &fRadius); KG_PROCESS_ERROR(nRetCode == 1); nRetCode = piTabFile->GetFloat(2 + i, "Angel", 0, &fAngel); KG_PROCESS_ERROR(nRetCode == 1); KG_PROCESS_ERROR(nIndex == i + 1); Node.nRadius = (int)(fRadius * fZoom); Node.nAngel = (int)(fAngel * DIRECTION_COUNT / (2 * SO3WORLD_PI)); if (Node.nAngel < 0) { Node.nAngel += DIRECTION_COUNT; } KGLOG_PROCESS_ERROR(Node.nAngel < DIRECTION_COUNT); rOrder.push_back(Node); } bResult = true; Exit0: KG_COM_RELEASE(piTabFile); return bResult; }
27.890625
101
0.566387
uvbs
60568d7eeac972c43eb899da7ac15d571144af92
507
cc
C++
src/samplers/SamplerFattal/bimage/btest.cc
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
44
2018-01-09T19:56:29.000Z
2022-03-03T06:38:54.000Z
src/samplers/SamplerFattal/bimage/btest.cc
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
16
2018-01-29T18:01:42.000Z
2022-03-31T07:01:09.000Z
src/samplers/SamplerFattal/bimage/btest.cc
FrancoisGaits/utk
8c408dd79635f98c46ed075c098f15e23972aad0
[ "BSD-2-Clause-FreeBSD" ]
12
2018-03-14T00:24:14.000Z
2022-03-03T06:40:07.000Z
#include "bimage.hh" #include <math.h> #include <fstream> #include <stdlib.h> #include <iostream> using namespace std; int main(int argc, char* argv[]){ BImage image(257,256) ; image.clear(255,255,255) ; image.text(10,10,"abc ABC 123 @$%& ][{}.,:") ; // fghijklmnopquvwxyz") ; for(int i = 0 ; i < 16 ; i++) { for(int j = 2 ; j < 8 ; j++) cout << (char)(j*16+i) << "\t" ; cout << endl ; } image.writeImage("a.bmp") ; image.show() ; //image.close() ; return 0 ; }
16.354839
74
0.540434
FrancoisGaits
6056ab2add72b1ec078a0e58df3d0eee5dafb44f
53,420
cpp
C++
tools/dumpce/dumpce.cpp
tizenorg/external.icu
5b69033400476be749862631609f60bd7daaacd7
[ "ICU" ]
3
2016-03-25T14:11:57.000Z
2021-08-24T19:46:11.000Z
tools/dumpce/dumpce.cpp
tizenorg/external.icu
5b69033400476be749862631609f60bd7daaacd7
[ "ICU" ]
null
null
null
tools/dumpce/dumpce.cpp
tizenorg/external.icu
5b69033400476be749862631609f60bd7daaacd7
[ "ICU" ]
2
2018-01-18T04:38:16.000Z
2019-05-29T02:20:44.000Z
/******************************************************************** * COPYRIGHT: * Copyright (C) 2001-2011 IBM, Inc. All Rights Reserved. * ********************************************************************/ /******************************************************************************** * * File dumpce.cpp * * Modification History: * Name Date Description * synwee May 31 2001 Creation * ********************************************************************************* */ /** * This program outputs the collation elements used for a requested tailoring. * * Usage: * dumpce options... please check main function. */ #include <unicode/utypes.h> #include <unicode/ucol.h> #include <unicode/uloc.h> #include <unicode/ucoleitr.h> #include <unicode/uchar.h> #include <unicode/uscript.h> #include <unicode/utf16.h> #include <unicode/putil.h> #include <unicode/ustring.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "ucol_tok.h" #include "cstring.h" #include "uoptions.h" #include "ucol_imp.h" #include <unicode/ures.h> #include <unicode/uniset.h> #include <unicode/usetiter.h> /** * Command line option variables. * These global variables are set according to the options specified on the * command line by the user. */ static UOption options[]={ /* 00 */ UOPTION_HELP_H, /* 01 */ UOPTION_HELP_QUESTION_MARK, /* 02 */ {"locale", NULL, NULL, NULL, 'l', UOPT_REQUIRES_ARG, 0}, /* 03 */ {"serialize", NULL, NULL, NULL, 'z', UOPT_NO_ARG, 0}, /* 04 */ UOPTION_DESTDIR, /* 05 */ UOPTION_SOURCEDIR, /* 06 */ {"attribute", NULL, NULL, NULL, 'a', UOPT_REQUIRES_ARG, 0}, /* 07 */ {"rule", NULL, NULL, NULL, 'r', UOPT_REQUIRES_ARG, 0}, /* 08 */ {"normalization", NULL, NULL, NULL, 'n', UOPT_REQUIRES_ARG, 0}, /* 09 */ {"scripts", NULL, NULL, NULL, 't', UOPT_NO_ARG, 0}, /* 10 */ {"reducehan", NULL, NULL, NULL, 'e', UOPT_NO_ARG, 0}, /* 11 */ UOPTION_VERBOSE, /* 12 */ {"wholescripts", NULL, NULL, NULL, 'W', UOPT_NO_ARG, 0} }; /** * Collator used in this program */ static UCollator *COLLATOR_; /** * Output strea, used in this program */ static FILE *OUTPUT_; static UColAttributeValue ATTRIBUTE_[UCOL_ATTRIBUTE_COUNT] = { UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT, }; typedef struct { int value; char *name; } EnumNameValuePair; static const EnumNameValuePair ATTRIBUTE_NAME_[] = { {UCOL_FRENCH_COLLATION, "UCOL_FRENCH_COLLATION"}, {UCOL_ALTERNATE_HANDLING, "UCOL_ALTERNATE_HANDLING"}, {UCOL_CASE_FIRST, "UCOL_CASE_FIRST"}, {UCOL_CASE_LEVEL, "UCOL_CASE_LEVEL"}, {UCOL_NORMALIZATION_MODE, "UCOL_NORMALIZATION_MODE|UCOL_DECOMPOSITION_MODE"}, {UCOL_STRENGTH, "UCOL_STRENGTH"}, {UCOL_HIRAGANA_QUATERNARY_MODE, "UCOL_HIRAGANA_QUATERNARY_MODE"}, {UCOL_NUMERIC_COLLATION, "UCOL_NUMERIC_COLLATION"}, NULL }; static const EnumNameValuePair ATTRIBUTE_VALUE_[] = { {UCOL_PRIMARY, "UCOL_PRIMARY"}, {UCOL_SECONDARY, "UCOL_SECONDARY"}, {UCOL_TERTIARY, "UCOL_TERTIARY|UCOL_DEFAULT_STRENGTH"}, {UCOL_QUATERNARY, "UCOL_QUATERNARY"}, {UCOL_IDENTICAL, "UCOL_IDENTICAL"}, {UCOL_OFF, "UCOL_OFF"}, {UCOL_ON, "UCOL_ON"}, {UCOL_SHIFTED, "UCOL_SHIFTED"}, {UCOL_NON_IGNORABLE, "UCOL_NON_IGNORABLE"}, {UCOL_LOWER_FIRST, "UCOL_LOWER_FIRST"}, {UCOL_UPPER_FIRST, "UCOL_UPPER_FIRST"}, NULL }; typedef struct { UChar ch[32]; int count; // number of codepoint UBool tailored; } ScriptElement; /** * Writes the hexadecimal of a null-terminated array of codepoints into a * file * @param f UFILE instance to store * @param c codepoints array */ void serialize(FILE *f, const UChar *c) { UChar cp = *(c ++); fprintf(f, " %04x", cp); while (*c != 0) { cp = *(c ++); fprintf(f, " %04x", cp); } } /** * Writes the hexadecimal of a non-null-terminated array of codepoints into a * file * @param f UFILE instance to store * @param c codepoints array * @param l codepoints array length */ void serialize(FILE *f, const UChar *c, int l) { int count = 1; UChar cp = *(c ++); fprintf(f, " %04x", cp); while (count < l) { cp = *(c ++); fprintf(f, " %04x", cp); count ++; } } /** * Sets the iterator to the argument string and outputs the collation elements. * @param f file output stream * @param iter collation element iterator */ void serialize(FILE *f, UCollationElements *iter) { UChar *codepoint = iter->iteratordata_.string; // unlikely that sortkeys will be over this size uint8_t sortkey[64]; uint8_t *psortkey = sortkey; int sortkeylength = 0; if (iter->iteratordata_.flags & UCOL_ITER_HASLEN) { serialize(f, codepoint, iter->iteratordata_.endp - codepoint); sortkeylength = ucol_getSortKey(iter->iteratordata_.coll, codepoint, iter->iteratordata_.endp - codepoint, sortkey, 64); } else { serialize(f, codepoint); sortkeylength = ucol_getSortKey(iter->iteratordata_.coll, codepoint, -1, sortkey, 64); } if (options[11].doesOccur) { serialize(stdout, codepoint); fprintf(stdout, "\n"); } fprintf(f, "; "); UErrorCode error = U_ZERO_ERROR; uint32_t ce = ucol_next(iter, &error); if (U_FAILURE(error)) { fprintf(f, "Error retrieving collation elements\n"); return; } while (TRUE) { fprintf(f, "["); if (UCOL_PRIMARYORDER(ce) != 0) { fprintf(f, "%04x", UCOL_PRIMARYORDER(ce)); } fprintf(f, ","); if (UCOL_SECONDARYORDER(ce) != 0) { fprintf(f, " %02x", UCOL_SECONDARYORDER(ce)); } fprintf(f, ","); if (UCOL_TERTIARYORDER(ce) != 0) { fprintf(f, " %02x", UCOL_TERTIARYORDER(ce)); } fprintf(f, "] "); ce = ucol_next(iter, &error); if (ce == UCOL_NULLORDER) { break; } if (U_FAILURE(error)) { fprintf(stdout, "Error retrieving collation elements"); return; } } if (sortkeylength > 64) { fprintf(f, "Sortkey exceeds pre-allocated size"); } fprintf(f, "["); while (TRUE) { fprintf(f, "%02x", *psortkey); psortkey ++; if ((*psortkey) == 0) { break; } fprintf(f, " "); } fprintf(f, "]\n"); } /** * Serializes the contraction within the given argument rule * @param f file output stream * @param r rule * @param rlen rule length * @param contractionsonly flag to indicate if only contractions are to be * output or all collation elements * @param iter iterator to iterate over collation elements */ void serialize(FILE *f, UChar *rule, int rlen, UBool contractiononly, UCollationElements *iter) { const UChar *current = NULL; uint32_t strength = 0; uint32_t chOffset = 0; uint32_t chLen = 0; uint32_t exOffset = 0; uint32_t exLen = 0; uint32_t prefixOffset = 0; uint32_t prefixLen = 0; uint8_t specs = 0; UBool rstart = TRUE; UColTokenParser src; UColOptionSet opts; UParseError parseError; UErrorCode error = U_ZERO_ERROR; src.opts = &opts; src.source = rule; src.current = rule; src.end = rule + rlen; src.extraCurrent = src.end; src.extraEnd = src.end + UCOL_TOK_EXTRA_RULE_SPACE_SIZE; while ((current = ucol_tok_parseNextToken(&src, rstart, &parseError, &error)) != NULL) { chOffset = src.parsedToken.charsOffset; chLen = src.parsedToken.charsLen; // contractions handled here if (!contractiononly || chLen > 1) { ucol_setText(iter, rule + chOffset, chLen, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error setting text in iterator\n"); return; } serialize(f, iter); } rstart = FALSE; } } /** * Prints the attribute values in the argument collator into the output stream * @param collator */ void outputAttribute(UCollator *collator, UErrorCode *error) { UColAttribute attribute = UCOL_FRENCH_COLLATION; while (attribute < UCOL_ATTRIBUTE_COUNT) { int count = 0; while (TRUE) { // getting attribute name if (ATTRIBUTE_NAME_[count].value == attribute) { fprintf(OUTPUT_, "%s = ", ATTRIBUTE_NAME_[count].name); break; } count ++; } count = 0; int attributeval = ucol_getAttribute(collator, attribute, error); if (U_FAILURE(*error)) { fprintf(stdout, "Failure in reading collator attribute\n"); return; } while (TRUE) { // getting attribute value if (ATTRIBUTE_VALUE_[count].value == attributeval) { fprintf(OUTPUT_, "%s\n", ATTRIBUTE_VALUE_[count].name); break; } count ++; } attribute = (UColAttribute)(attribute + 1); } } /** * Prints the normalization mode in the argument collator into the output stream * @param collator */ void outputNormalization(UCollator *collator) { UErrorCode status = U_ZERO_ERROR; int normmode = ucol_getAttribute(collator, UCOL_NORMALIZATION_MODE, &status); int count = 0; while (TRUE) { // getting attribute name if (ATTRIBUTE_VALUE_[count].value == normmode) { break; } count ++; } fprintf(OUTPUT_, "NORMALIZATION MODE = %s\n", ATTRIBUTE_VALUE_[count].name); } /** * Output the collation element belonging to the locale into a file * @param locale string * @param fullrules flag to indicate if only tailored collation elements are to * be output or all collation elements */ void serialize(const char *locale, UBool tailoredonly) { UErrorCode error = U_ZERO_ERROR; UChar str[128]; int strlen = 0; fprintf(OUTPUT_, "# This file contains the serialized collation elements\n"); fprintf(OUTPUT_, "# as of the collation version indicated below.\n"); fprintf(OUTPUT_, "# Data format: xxxx xxxx..; [yyyy, yy, yy] [yyyy, yy, yy] ... [yyyy, yy, yy] [zz zz..\n"); fprintf(OUTPUT_, "# where xxxx are codepoints in hexadecimals,\n"); fprintf(OUTPUT_, "# yyyyyyyy are the corresponding\n"); fprintf(OUTPUT_, "# collation elements in hexadecimals\n"); fprintf(OUTPUT_, "# and zz are the sortkey values in hexadecimals\n"); fprintf(OUTPUT_, "\n# Collator information\n"); fprintf(OUTPUT_, "\nLocale: %s\n", locale); fprintf(stdout, "Locale: %s\n", locale); UVersionInfo version; ucol_getVersion(COLLATOR_, version); fprintf(OUTPUT_, "Version number: %d.%d.%d.%d\n", version[0], version[1], version[2], version[3]); outputAttribute(COLLATOR_, &error); outputNormalization(COLLATOR_); UCollationElements *iter = ucol_openElements(COLLATOR_, str, strlen, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error creating iterator\n"); return; } if (!tailoredonly) { fprintf(OUTPUT_, "\n# Range of unicode characters\n\n"); UChar32 codepoint = 0; while (codepoint <= UCHAR_MAX_VALUE) { if (u_isdefined(codepoint)) { strlen = 0; UTF16_APPEND_CHAR_UNSAFE(str, strlen, codepoint); str[strlen] = 0; ucol_setText(iter, str, strlen, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error setting text in iterator\n"); return; } serialize(OUTPUT_, iter); } codepoint ++; } } UChar ucarules[0x10000]; UChar *rules; int32_t rulelength = 0; rules = ucarules; if (tailoredonly) { int32_t rulelength = 0; const UChar *temp = ucol_getRules(COLLATOR_, &rulelength); if (rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE > 0x10000) { rules = (UChar *)malloc(sizeof(UChar) * (rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE)); } memcpy(rules, temp, rulelength * sizeof(UChar)); rules[rulelength] = 0; fprintf(OUTPUT_, "\n# Tailorings\n\n"); serialize(OUTPUT_, rules, rulelength, FALSE, iter); if (rules != ucarules) { free(rules); } } else { rulelength = ucol_getRulesEx(COLLATOR_, UCOL_FULL_RULES, ucarules, 0x10000); if (rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE > 0x10000) { rules = (UChar *)malloc(sizeof(UChar) * (rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE)); rulelength = ucol_getRulesEx(COLLATOR_, UCOL_FULL_RULES, rules, rulelength); } fprintf(OUTPUT_, "\n# Contractions\n\n"); serialize(OUTPUT_, rules, rulelength, TRUE, iter); if (rules != ucarules) { free(rules); } } ucol_closeElements(iter); } /** * Sets the collator with the attribute values * @param collator * @param error status */ void setAttributes(UCollator *collator, UErrorCode *error) { int count = 0; while (count < UCOL_ATTRIBUTE_COUNT) { if (ATTRIBUTE_[count] != UCOL_DEFAULT) { ucol_setAttribute(collator, (UColAttribute)count, ATTRIBUTE_[count], error); if (U_FAILURE(*error)) { return; } } count ++; } } /** * Appends directory path with an ending seperator if necessary. * @param path with enough space to append one seperator * @return new directory path length */ int appendDirSeparator(char *dir) { int dirlength = strlen(dir); char dirending = dir[dirlength - 1]; if (dirending != U_FILE_SEP_CHAR) { dir[dirlength] = U_FILE_SEP_CHAR; dir[dirlength + 1] = 0; return dirlength + 1; } return dirlength; } /** * Output the collation element into a file */ void serialize() { char filename[128]; int dirlength = 0; if (options[4].doesOccur) { strcpy(filename, options[4].value); dirlength = appendDirSeparator(filename); } if (options[2].doesOccur) { const char *locale = (char *)options[2].value; int32_t localeindex = 0; if (strcmp(locale, "all") == 0) { if (options[4].doesOccur) { strcat(filename, "UCA.txt"); OUTPUT_ = fopen(filename, "w"); if (OUTPUT_ == NULL) { fprintf(stdout, "Cannot open file:%s\n", filename); return; } } fprintf(stdout, "UCA\n"); UErrorCode error = U_ZERO_ERROR; COLLATOR_ = ucol_open("en_US", &error); if (U_FAILURE(error)) { fprintf(stdout, "Collator creation failed:"); fprintf(stdout, u_errorName(error)); goto CLOSEUCA; return; } setAttributes(COLLATOR_, &error); if (U_FAILURE(error)) { fprintf(stdout, "Collator attribute setting failed:"); fprintf(stdout, u_errorName(error)); goto CLOSEUCA; return; } serialize("UCA", FALSE); CLOSEUCA : if (options[4].doesOccur) { filename[dirlength] = 0; fclose(OUTPUT_); } ucol_close(COLLATOR_); localeindex = ucol_countAvailable() - 1; fprintf(stdout, "Number of locales: %d\n", localeindex + 1); locale = ucol_getAvailable(localeindex); } while (TRUE) { UErrorCode error = U_ZERO_ERROR; COLLATOR_ = ucol_open(locale, &error); if (U_FAILURE(error)) { fprintf(stdout, "Collator creation failed:"); fprintf(stdout, u_errorName(error)); goto CLOSETAILOR; return; } setAttributes(COLLATOR_, &error); if (U_FAILURE(error)) { fprintf(stdout, "Collator attribute setting failed:"); fprintf(stdout, u_errorName(error)); goto CLOSETAILOR; return; } if (options[4].doesOccur) { strcat(filename, locale); strcat(filename, ".txt"); OUTPUT_ = fopen(filename, "w"); if (OUTPUT_ == NULL) { fprintf(stdout, "Cannot open file:%s\n", filename); return; } } if (options[3].doesOccur) { serialize(locale, TRUE); } ucol_close(COLLATOR_); CLOSETAILOR : if (options[4].doesOccur) { filename[dirlength] = 0; fclose(OUTPUT_); } localeindex --; if (localeindex < 0) { break; } locale = ucol_getAvailable(localeindex); } } if (options[7].doesOccur) { char inputfilename[128] = ""; // rules are to be used if (options[5].doesOccur) { strcpy(inputfilename, options[5].value); appendDirSeparator(inputfilename); } strcat(inputfilename, options[7].value); FILE *input = fopen(inputfilename, "r"); if (input == NULL) { fprintf(stdout, "Cannot open file:%s\n", filename); return; } char s[1024]; UChar rule[1024]; UChar *prule = rule; int size = 1024; // synwee TODO: make this part dynamic while (fscanf(input, "%[^\n]s", s) != EOF) { size -= u_unescape(s, prule, size); prule = prule + u_strlen(prule); } fclose(input); if (options[4].doesOccur) { strcat(filename, "Rules.txt"); OUTPUT_ = fopen(filename, "w"); if (OUTPUT_ == NULL) { fprintf(stdout, "Cannot open file:%s\n", filename); return; } } fprintf(stdout, "Rules\n"); UErrorCode error = U_ZERO_ERROR; UParseError parseError; COLLATOR_ = ucol_openRules(rule, u_strlen(rule), UCOL_DEFAULT, UCOL_DEFAULT_STRENGTH, &parseError, &error); if (U_FAILURE(error)) { fprintf(stdout, "Collator creation failed:"); fprintf(stdout, u_errorName(error)); goto CLOSERULES; return; } setAttributes(COLLATOR_, &error); if (U_FAILURE(error)) { fprintf(stdout, "Collator attribute setting failed:"); fprintf(stdout, u_errorName(error)); goto CLOSERULES; return; } serialize("Rule-based", TRUE); ucol_close(COLLATOR_); CLOSERULES : if (options[4].doesOccur) { filename[dirlength] = 0; fclose(OUTPUT_); } } } /** * Parse for enum values. * Note this only works for positive enum values. * @param enumarray array containing names of the enum values in string and * their corresponding value. * declared enum value. * @param str string to be parsed * @return corresponding integer enum value or -1 if value is not found. */ int parseEnums(const EnumNameValuePair enumarray[], const char *str) { const char *enumname = enumarray[0].name; int result = atoi(str); if (result == 0 && str[0] != '0') { while (strcmp(enumname, str) != 0) { // checking for multiple enum names sharing the same values enumname = strstr(enumname, str); if (enumname != NULL) { int size = strchr(enumname, '|') - enumname; if (size < 0) { size = strlen(enumname); } if (size == (int)strlen(str)) { return enumarray[result].value; } } result ++; if (&(enumarray[result]) == NULL) { return -1; } enumname = enumarray[result].name; } } return -1; } /** * Parser for attribute name value pair */ void parseAttributes() { char str[32]; const char *pname = options[6].value; const char *pend = options[6].value + strlen(options[6].value); const char *pvalue; while (pname < pend) { pvalue = strchr(pname, '='); if (pvalue == NULL) { fprintf(stdout, "No matching value found for attribute argument %s\n", pname); return; } int count = pvalue - pname; strncpy(str, pname, count); str[count] = 0; int name = parseEnums(ATTRIBUTE_NAME_, str); if (name == -1) { fprintf(stdout, "Attribute name not found: %s\n", str); return; } pvalue ++; // getting corresponding enum value pname = strchr(pvalue, ','); if (pname == NULL) { pname = pend; } count = pname - pvalue; strncpy(str, pvalue, count); str[count] = 0; int value = parseEnums(ATTRIBUTE_VALUE_, str); if (value == -1) { fprintf(stdout, "Attribute value not found: %s\n", str); return; } ATTRIBUTE_[name] = (UColAttributeValue)value; pname ++; } } /** * Checks if the locale argument is a base language * @param locale to be checked * @return TRUE if it is a base language */ inline UBool checkLocaleForLanguage(const char *locale) { return strlen(locale) <= 2; } /** * Converts a UChar array into its string form "xxxx xxxx" * @param ch array of UChar characters * @param count number of UChar characters */ void outputUChar(UChar ch[], int count) { for (int i = 0; i < count; i ++) { fprintf(OUTPUT_, "%04X ", ch[i]); } } /** * If it is a primary difference returns -1 or 1. * If it is a secondary difference returns -2 or 2. * If it is a tertiary difference returns -3 or 3. * If equals returns 0. */ int compareSortKey(const void *elem1, const void *elem2) { // compare the 2 script element sort key UChar *ch1 = ((ScriptElement *)elem1)->ch; UChar *ch2 = ((ScriptElement *)elem2)->ch; int size1 = ((ScriptElement *)elem1)->count; int size2 = ((ScriptElement *)elem2)->count; UErrorCode error = U_ZERO_ERROR; ucol_setStrength(COLLATOR_, UCOL_PRIMARY); int result = ucol_strcoll(COLLATOR_, ch1, size1, ch2, size2); if (result == 0) { ucol_setStrength(COLLATOR_, UCOL_SECONDARY); result = ucol_strcoll(COLLATOR_, ch1, size1, ch2, size2); if (result == 0) { ucol_setStrength(COLLATOR_, UCOL_TERTIARY); result = ucol_strcoll(COLLATOR_, ch1, size1, ch2, size2); if (result < 0) { return -3; } if (result > 0) { return 3; } } if (result < 0) { return -2; } if (result > 0) { return 2; } } return result; } /** * Output serialized script elements * @param element the element to output * @param compare the comparison with the previous element * @param expansion flags TRUE if element has an expansion */ void outputScriptElem(ScriptElement &element, int compare, UBool expansion) { switch (compare) { case 0: if (expansion) { fprintf(OUTPUT_, "<tr><td class='eq' title='["); } else { fprintf(OUTPUT_, "<tr><td class='q' title='["); } break; case -1: if (expansion) { fprintf(OUTPUT_, "<tr><td class='ep' title='["); } else { fprintf(OUTPUT_, "<tr><td class='p' title='["); } break; case -2: if (expansion) { fprintf(OUTPUT_, "<tr><td class='es' title='["); } else { fprintf(OUTPUT_, "<tr><td class='s' title='["); } break; default: if (expansion) { fprintf(OUTPUT_, "<tr><td class='et' title='["); } else { fprintf(OUTPUT_, "<tr><td class='t' title='["); } } uint8_t sortkey[32]; ucol_setStrength(COLLATOR_, UCOL_TERTIARY); ucol_getSortKey(COLLATOR_, element.ch, element.count, sortkey, 32); int i = 0; while (sortkey[i] != 0) { if (sortkey[i] == 1) { fprintf(OUTPUT_, " | "); } else { fprintf(OUTPUT_, "%02x", sortkey[i]); } i ++; } fprintf(OUTPUT_, "]'>"); UErrorCode error = U_ZERO_ERROR; char utf8[64]; UChar nfc[32]; int32_t length = unorm_normalize(element.ch, element.count, UNORM_NFC, 0, nfc, 32, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error normalizing contractions to NFC\n"); } u_strToUTF8(utf8, 64, &length, nfc, length, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error converting UChar to utf8\n"); return; } fprintf(OUTPUT_, "%s<br>", utf8); fprintf(OUTPUT_, "<tt>"); outputUChar(element.ch, element.count); if (compare == 0) { fprintf(OUTPUT_, "</tt></td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>Q</td><td>"); } else if (compare == -1) { fprintf(OUTPUT_, "</tt></td><td>P</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>"); } else if (compare == -2) { fprintf(OUTPUT_, "</tt></td><td>&nbsp;</td><td>S</td><td>&nbsp;</td><td>&nbsp;</td><td>"); } else if (compare == -3) { fprintf(OUTPUT_, "</tt></td><td>&nbsp;</td><td>&nbsp;</td><td>T</td><td>&nbsp;</td><td>"); } i = 0; while (i < element.count) { char str[128]; UChar32 codepoint; UTF_NEXT_CHAR(element.ch, i, element.count, codepoint); int32_t temp = u_charName(codepoint, U_UNICODE_CHAR_NAME, str, 128, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error getting character name\n"); return; } if (element.tailored) { fprintf(OUTPUT_, "<b>"); } fprintf(OUTPUT_, "%s", str); if (element.tailored) { fprintf(OUTPUT_, " *</b>"); } if (i < element.count) { fprintf(OUTPUT_, "<br>\n"); } } fprintf(OUTPUT_, "</td></tr>\n"); } /** * Checks if codepoint belongs to scripts * @param script list * @param scriptcount number of scripts * @param codepoint to test * @return TRUE if codepoint belongs to scripts */ UBool checkInScripts(UScriptCode script[], int scriptcount, UChar32 codepoint) { UErrorCode error = U_ZERO_ERROR; for (int i = 0; i < scriptcount; i ++) { if (script[i] == USCRIPT_HAN && options[10].doesOccur) { if ((codepoint >= 0x2E80 && codepoint <= 0x2EE4) || (codepoint >= 0x2A672 && codepoint <= 0x2A6D6)) { // reduce han return TRUE; } } else if (uscript_getScript(codepoint, &error) == script[i]) { return TRUE; } if (U_FAILURE(error)) { fprintf(stdout, "Error checking character in scripts\n"); return FALSE; } } return FALSE; } /** * Checks if the set of codepoints belongs to the script * @param script list * @param scriptcount number of scripts * @param scriptelem * @return TRUE if all codepoints belongs to the script */ inline UBool checkInScripts(UScriptCode script[], int scriptcount, ScriptElement scriptelem) { int i = 0; while (i < scriptelem.count) { UChar32 codepoint; UTF_NEXT_CHAR(scriptelem.ch, i, scriptelem.count, codepoint); UErrorCode error = U_ZERO_ERROR; if (checkInScripts(script, scriptcount, codepoint)) { return TRUE; } } return FALSE; } /** * Gets the script elements and contractions belonging to the script * @param elems output list * @param locale locale * @return number of script elements * Add by Richard */ int getScriptElementsFromExemplars(ScriptElement scriptelem[], const char* locale) { UErrorCode error = U_ZERO_ERROR; UChar32 codepoint = 0; UResourceBundle* ures = ures_open(NULL, locale, &error); if (U_FAILURE(error)) { fprintf(stdout, "Can not find resource bundle for locale: %s\n", locale); return -1; } int32_t length; const UChar* exemplarChars = ures_getStringByKey(ures, "ExemplarCharacters", &length, &error); if (U_FAILURE(error)) { fprintf(stdout, "Can not find ExemplarCharacters in resource bundle\n"); return -1; } UChar* upperChars = new UChar[length * 2]; if (upperChars == 0) { fprintf(stdout, "Memory error\n"); return -1; } int32_t destLength = u_strToUpper(upperChars, length * 2, exemplarChars, -1, locale, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error when u_strToUpper() \n"); return -1; } UChar* pattern = new UChar[length + destLength + 10]; UChar left[2] = {0x005b, 0x0}; UChar right[2] = {0x005d, 0x0}; pattern = u_strcpy(pattern, left); pattern = u_strcat(pattern, exemplarChars); pattern = u_strcat(pattern, upperChars); pattern = u_strcat(pattern, right); UnicodeSet * uniset = new UnicodeSet(UnicodeString(pattern), error); if (U_FAILURE(error)) { fprintf(stdout, "Can not open USet \n"); return -1; } UnicodeSetIterator* usetiter = new UnicodeSetIterator(*uniset); int32_t count = 0; while (usetiter -> next()) { if (usetiter -> isString()) { UnicodeString strItem = usetiter -> getString(); scriptelem[count].count = 0; for (int i = 0; i < strItem.length(); i++) { codepoint = strItem.char32At(i); UTF16_APPEND_CHAR_UNSAFE(scriptelem[count].ch, scriptelem[count].count, codepoint); scriptelem[count].tailored = FALSE; } } else { codepoint = usetiter -> getCodepoint(); scriptelem[count].count = 0; UTF16_APPEND_CHAR_UNSAFE(scriptelem[count].ch, scriptelem[count].count, codepoint); scriptelem[count].tailored = FALSE; } delete []pattern; count++; } delete []pattern; return count; } /** * Gets the script elements and contractions belonging to the script * @param script list * @param scriptcount number of scripts * @param elems output list * @return number of script elements */ int getScriptElements(UScriptCode script[], int scriptcount, ScriptElement scriptelem[]) { UErrorCode error = U_ZERO_ERROR; UChar32 codepoint = 0; int count = 0; while (codepoint <= UCHAR_MAX_VALUE) { if (checkInScripts(script, scriptcount, codepoint)) { scriptelem[count].count = 0; UTF16_APPEND_CHAR_UNSAFE(scriptelem[count].ch, scriptelem[count].count, codepoint); scriptelem[count].tailored = FALSE; count ++; } if (U_FAILURE(error)) { fprintf(stdout, "Error determining codepoint in script\n"); return -1; } codepoint ++; } const UChar *current = NULL; uint32_t strength = 0; uint32_t chOffset = 0; uint32_t chLen = 0; uint32_t exOffset = 0; uint32_t exLen = 0; uint32_t prefixOffset = 0; uint32_t prefixLen = 0; uint8_t specs = 0; UBool rstart = TRUE; UColTokenParser src; UColOptionSet opts; UParseError parseError; int32_t rulelength = ucol_getRulesEx(COLLATOR_, UCOL_FULL_RULES, NULL, 0); src.source = (UChar *)malloc(sizeof(UChar) * (rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE)); rulelength = ucol_getRulesEx(COLLATOR_, UCOL_FULL_RULES, src.source, rulelength); src.current = src.source; src.end = src.source + rulelength; src.extraCurrent = src.end; src.extraEnd = src.end + UCOL_TOK_EXTRA_RULE_SPACE_SIZE; src.opts = &opts; /* ucol_tok_parseNextToken(&src, &strength, &chOffset, &chLen, &exOffset, &exLen, &prefixOffset, &prefixLen, &specs, rstart, &parseError, &error) */ while ((current = ucol_tok_parseNextToken(&src, rstart, &parseError, &error)) != NULL) { // contractions handled here if (chLen > 1) { u_strncpy(scriptelem[count].ch, src.source + chOffset, chLen); scriptelem[count].count = chLen; if (checkInScripts(script, scriptcount, scriptelem[count])) { scriptelem[count].tailored = FALSE; count ++; } } rstart = FALSE; } if (U_FAILURE(error)) { fprintf(stdout, "Error parsing rules: %s\n", u_errorName(error)); } // rule might have been reallocated, so delete this instead free(src.source); return count; } int compareCodepoints(const void *elem1, const void *elem2) { UChar *ch1 = ((ScriptElement *)elem1)->ch; // key UChar *ch2 = ((ScriptElement *)elem2)->ch; ch1[((ScriptElement *)elem1)->count] = 0; ch2[((ScriptElement *)elem2)->count] = 0; // compare the 2 codepoints return u_strcmp(ch1, ch2); } UBool hasSubNFD(ScriptElement &se, ScriptElement &key) { UChar *ch1 = se.ch; UChar *ch2 = key.ch; // key ch1[se.count] = 0; ch2[key.count] = 0; // compare the 2 codepoints if (u_strstr(ch1, ch2) != NULL) { return TRUE; } // check the decomposition UChar norm[32]; UErrorCode error = U_ZERO_ERROR; int size = unorm_normalize(ch1, se.count, UNORM_NFD, 0, norm, 32, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error normalizing\n"); } if (u_strstr(norm, ch2) != NULL) { return TRUE; } return FALSE; } /** * Marks tailored elements * @param script list * @param scriptcount number of scripts * @param scriptelem script element list * @param scriptelemlength size of the script element list */ void markTailored(UScriptCode script[], int scriptcount, ScriptElement scriptelem[], int scriptelemlength) { int32_t rulelength; const UChar *rule = ucol_getRules(COLLATOR_, &rulelength); const UChar *current = NULL; uint32_t strength = 0; uint32_t chOffset = 0; uint32_t chLen = 0; uint32_t exOffset = 0; uint32_t exLen = 0; uint32_t prefixOffset = 0; uint32_t prefixLen = 0; uint8_t specs = 0; UBool rstart = TRUE; UColTokenParser src; UColOptionSet opts; UParseError parseError; src.opts = &opts; src.source = (UChar *)malloc( (rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE) * sizeof(UChar)); memcpy(src.source, rule, rulelength * sizeof(UChar)); src.current = src.source; src.end = (UChar *)src.source + rulelength; src.extraCurrent = src.end; src.extraEnd = src.end + UCOL_TOK_EXTRA_RULE_SPACE_SIZE; UErrorCode error = U_ZERO_ERROR; while ((current = ucol_tok_parseNextToken(&src, rstart, &parseError, &error)) != NULL) { if (chLen >= 1 && strength != UCOL_TOK_RESET) { // skipping the reset characters and non useful stuff. ScriptElement se; u_strncpy(se.ch, src.source + chOffset, chLen); se.count = chLen; if (checkInScripts(script, scriptcount, se)) { /* ScriptElement *tse = (ScriptElement *)bsearch(&se, scriptelem, scriptelemlength, sizeof(ScriptElement), compareCodepoints); */ for (int i = 0; i < scriptelemlength; i ++) { if (!scriptelem[i].tailored && hasSubNFD(scriptelem[i], se)) { scriptelem[i].tailored = TRUE; } } } } rstart = FALSE; } free(src.source); if (U_FAILURE(error)) { fprintf(stdout, "Error parsing rules\n"); } } /** * Checks if the collation iterator has more than 1 collation element * @parem coleiter collation element iterator * @return TRUE if collation iterator has more than 1 collation element */ UBool hasExpansions(UCollationElements *coleiter) { UErrorCode error = U_ZERO_ERROR; int32_t ce = ucol_next(coleiter, &error); int count = 0; if (U_FAILURE(error)) { fprintf(stdout, "Error getting next collation element\n"); } while (ce != UCOL_NULLORDER) { if ((UCOL_PRIMARYORDER(ce) != 0) && !isContinuation(ce)) { count ++; if (count == 2) { return TRUE; } } ce = ucol_next(coleiter, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error getting next collation element\n"); } } return FALSE; } /** * Prints the footer for index.html * @param file output file */ void outputHTMLFooter() { fprintf(OUTPUT_, "</table>\n"); fprintf(OUTPUT_, "</body>\n"); fprintf(OUTPUT_, "</html>\n"); } /** * Serialize the codepoints from start to end into an html file. * Arranging them into ascending collation order. * @param script code list * @param scriptcount number of scripts */ //void serializeScripts(UScriptCode script[], int scriptcount) //Richard void serializeScripts(UScriptCode script[], int scriptcount, const char* locale = NULL) { UErrorCode error = U_ZERO_ERROR; ScriptElement *scriptelem = (ScriptElement *)malloc(sizeof(ScriptElement) * 0x20000); if (scriptelem == NULL) { fprintf(stdout, "Memory error\n"); return; } int count = 0; if(locale) { count = getScriptElementsFromExemplars(scriptelem, locale); } else { count = getScriptElements(script, scriptcount, scriptelem); } // Sort script elements using Quicksort algorithm: qsort(scriptelem, count, sizeof(ScriptElement), compareCodepoints); markTailored(script, scriptcount, scriptelem, count); // Sort script elements using Quicksort algorithm: qsort(scriptelem, count, sizeof(ScriptElement), compareSortKey); UCollationElements* coleiter = ucol_openElements(COLLATOR_, scriptelem[0].ch, scriptelem[0].count, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error creating collation element iterator\n"); return; } outputScriptElem(scriptelem[0], -1, hasExpansions(coleiter)); for (int i = 0; i < count - 1; i ++) { ucol_setText(coleiter, scriptelem[i + 1].ch, scriptelem[i + 1].count, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error setting text in collation element iterator\n"); return; } outputScriptElem(scriptelem[i + 1], compareSortKey(scriptelem + i, scriptelem + i + 1), hasExpansions(coleiter)); } free(scriptelem); outputHTMLFooter(); } /** * Prints the header for the html * @param locale name * @param script * @param scriptcount number of scripts */ void outputHTMLHeader(const char *locale, UScriptCode script[], int scriptcount) { fprintf(OUTPUT_, "<html>\n"); fprintf(OUTPUT_, "<head>\n"); fprintf(OUTPUT_, "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"); fprintf(OUTPUT_, "<meta http-equiv=\"Content-Language\" content=\"en-us\">\n"); fprintf(OUTPUT_, "<link rel=\"stylesheet\" href=\"charts.css\" type=\"text/css\">\n"); fprintf(OUTPUT_, "<title>ICU Collation charts</title>\n"); fprintf(OUTPUT_, "<base target=\"main\">\n"); fprintf(OUTPUT_, "</head>\n"); fprintf(OUTPUT_, "<body bgcolor=#FFFFFF>\n"); fprintf(OUTPUT_, "<!--\n"); fprintf(OUTPUT_, "This file contains sorted characters in ascending order according to the locale stated\n"); fprintf(OUTPUT_, "If the character is in red, it is tailored in the collation rules.\n"); fprintf(OUTPUT_, "Background colours have certain meanings:\n"); fprintf(OUTPUT_, "White - equals the previous character\n"); fprintf(OUTPUT_, "dark blue - primary greater than the previous character\n"); fprintf(OUTPUT_, "blue - secondary greater than the previous character\n"); fprintf(OUTPUT_, "light blue - tertiary greater than the previous character\n"); fprintf(OUTPUT_, "--!>\n"); fprintf(OUTPUT_, "<table border=0>\n"); UChar displayname[64]; UErrorCode error = U_ZERO_ERROR; int32_t size = uloc_getDisplayName(locale, "en_US", displayname, 64, &error); char utf8displayname[128]; if (U_FAILURE(error)) { utf8displayname[0] = 0; } else { int32_t utf8size = 0; u_strToUTF8(utf8displayname, 128, &utf8size, displayname, size, &error); } fprintf(OUTPUT_, "<tr><th>Locale</th><td class='noborder'>%s</td></tr>\n", utf8displayname); fprintf(OUTPUT_, "<tr><th>Script(s)</th>"); fprintf(OUTPUT_, "<td class='noborder'>"); for (int i = 0; i < scriptcount; i ++) { fprintf(OUTPUT_, "%s", uscript_getName(script[i])); if (i + 1 != scriptcount) { fprintf(OUTPUT_, ", "); } } fprintf(OUTPUT_, "</td></tr>\n"); fprintf(OUTPUT_, "<tr><th>Rules</th><td class='noborder'><a href=\"http://dev.icu-project.org/cgi-bin/viewcvs.cgi/*checkout*/icu/source/data/coll/%s.txt\">%s.txt</a></td></tr>\n", locale, locale); UVersionInfo version; ucol_getVersion(COLLATOR_, version); fprintf(OUTPUT_, "<tr><th>Collator version</th><td class='noborder'>%d.%d.%d.%d</td></tr>\n", version[0], version[1], version[2], version[3]); UColAttribute attr = UCOL_FRENCH_COLLATION; while (attr < UCOL_ATTRIBUTE_COUNT) { UColAttributeValue value = ucol_getAttribute(COLLATOR_, attr, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error getting attribute\n"); return; } if (value != UCOL_DEFAULT) { if (attr == UCOL_FRENCH_COLLATION && value != UCOL_OFF) { fprintf(OUTPUT_, "<tr><th>French Collation</th><td class='noborder'>on, code %d</td></tr>\n", value); } if (attr == UCOL_ALTERNATE_HANDLING && value != UCOL_NON_IGNORABLE) { fprintf(OUTPUT_, "<tr><th>Alternate Handling</th><td class='noborder'>shifted, code%d</td></tr>\n", value); } if (attr == UCOL_CASE_FIRST && value != UCOL_OFF) { fprintf(OUTPUT_, "<tr><th>Case First</th><td class='noborder'>on, code %d</td></tr>\n", value); } if (attr == UCOL_CASE_LEVEL && value != UCOL_OFF) { fprintf(OUTPUT_, "<tr><th>Case Level</th><td class='noborder'>on, code %d</td></tr>\n", value); } if (attr == UCOL_NORMALIZATION_MODE && value != UCOL_OFF) { fprintf(OUTPUT_, "<tr><th>Normalization</th><td class='noborder'>on, code %d</td></tr>\n", value); } if (attr == UCOL_STRENGTH && value != UCOL_TERTIARY) { fprintf(OUTPUT_, "<tr><th>Strength</th><td class='noborder'>code %d</td></tr>\n", value); } if (attr == UCOL_HIRAGANA_QUATERNARY_MODE && value != UCOL_OFF) { fprintf(OUTPUT_, "<tr><th>Hiragana Quaternary</th><td class='noborder'>on, code %d</td></tr>\n", value); } } attr = (UColAttribute)(attr + 1); } // Get UNIX-style time and display as number and string. time_t ltime; time( &ltime ); fprintf(OUTPUT_, "<tr><th>Date Generated</th><td class='noborder'>%s</td></tr>", ctime(&ltime)); fprintf(OUTPUT_, "</table>\n"); fprintf(OUTPUT_, "<p><a href=help.html>How to read the table</a><br>\n"); fprintf(OUTPUT_, "<a href=http://www.jtcsv.com/cgi-bin/icu-bugs/ target=new>Submit a bug</a></p>\n"); fprintf(OUTPUT_, "\n<table>\n"); fprintf(OUTPUT_, "\n<tr><th>Codepoint</th><th>P</th><th>S</th><th>T</th><th>Q</th><th>Name</th></tr>\n"); } /** * Prints the header for index.html * @param file output file */ void outputListHTMLHeader(FILE *file) { fprintf(file, "<html>\n"); fprintf(file, "<head>\n"); fprintf(file, "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"); fprintf(file, "<meta http-equiv=\"Content-Language\" content=\"en-us\">\n"); fprintf(file, "<title>ICU Collation Charts</title>\n"); fprintf(file, "<base target=\"main\">\n"); fprintf(file, "</head>\n"); fprintf(file, "<body bgcolor=#FFFFFF>\n"); fprintf(file, "<h2 align=center>ICU Collation Charts</h2>\n"); fprintf(file, "<p align=center>\n"); fprintf(file, "<a href=http://www.unicode.org/charts/collation/ target=new>UCA Charts</a><br>"); } /** * Prints the footer for index.html * @param file output file */ void outputListHTMLFooter(FILE *file) { fprintf(file, "</p>\n"); //fprintf(file, "<center><image src=http://oss.software.ibm.com/icu/images/w24.gif></center>\n"); fprintf(file, "</body>\n"); fprintf(file, "</html>\n"); } /** * Gets all scripts and serialize their codepoints into an html file. */ void serializeScripts() { char filename[128]; int dirlength = 0; if (options[4].doesOccur) { strcpy(filename, options[4].value); dirlength = appendDirSeparator(filename); } else { filename[0] = 0; } const char *locale; int32_t localelist = 0; int32_t localesize; localesize = ucol_countAvailable(); locale = ucol_getAvailable(localelist); strcat(filename, "list.html"); FILE *list = fopen(filename, "w"); filename[dirlength] = 0; if (list == NULL) { fprintf(stdout, "Cannot open file: %s\n", filename); return; } outputListHTMLHeader(list); fprintf(list, "<blockquote>\n"); while (TRUE) { UErrorCode error = U_ZERO_ERROR; COLLATOR_ = ucol_open(locale, &error); if (U_FAILURE(error)) { fprintf(stdout, "Collator creation failed:"); fprintf(stdout, u_errorName(error)); break; } if ((error != U_USING_FALLBACK_WARNING && // not tailored error != U_USING_DEFAULT_WARNING) || checkLocaleForLanguage(locale)) { fprintf(list, "<a href=%s.html>%s</a> ", locale, locale); setAttributes(COLLATOR_, &error); if (U_FAILURE(error)) { fprintf(stdout, "Collator attribute setting failed:"); fprintf(stdout, u_errorName(error)); break; } UScriptCode scriptcode[32]; uint32_t scriptcount = uscript_getCode(locale, scriptcode, 32, &error); if (U_FAILURE(error)) { fprintf(stdout, "Error getting lcale scripts\n"); break; } strcat(filename, locale); strcat(filename, ".html"); OUTPUT_ = fopen(filename, "w"); if (OUTPUT_ == NULL) { fprintf(stdout, "Cannot open file:%s\n", filename); break; } outputHTMLHeader(locale, scriptcode, scriptcount); fprintf(stdout, "%s\n", locale); if(options[12].doesOccur) { // use whole scripts serializeScripts(scriptcode, scriptcount); } else { // use exemplar chars serializeScripts(scriptcode, scriptcount, locale); } fclose(OUTPUT_); } ucol_close(COLLATOR_); filename[dirlength] = 0; localelist ++; if (localelist == localesize) { break; } locale = ucol_getAvailable(localelist); } fprintf(list, "<br><a href=help.html>help</a><br>"); fprintf(list, "</blockquote>\n"); outputListHTMLFooter(list); fclose(list); } /** * Main -- process command line, read in and pre-process the test file, * call other functions to do the actual tests. */ int main(int argc, char *argv[]) { argc = u_parseArgs(argc, argv, sizeof(options)/sizeof(options[0]), options); // error handling, printing usage message if (argc < 0) { fprintf(stdout, "error in command line argument: "); fprintf(stdout, argv[-argc]); fprintf(stdout, "\n"); } if (argc < 0 || options[0].doesOccur || options[1].doesOccur) { fprintf(stdout, "Usage: dumpce options...\n" "--help\n" " Display this message.\n" "--locale name|all\n" " ICU locale to use. Default is en_US\n" "--serialize\n" " Serializes the collation elements in -locale or all locales available and outputs them into --outputdir/locale_ce.txt\n" "--destdir dir_name\n" " Path for outputing the serialized collation elements. Defaults to stdout if no defined\n" "--sourcedir dir_name\n" " Path for the input rule file for collation\n" "--attribute name=value,name=value...\n" " Pairs of attribute names and values for setting\n" "--rule filename\n" " Name of file containing the collation rules.\n" "--normalizaton mode\n" " UNormalizationMode mode to be used.\n" "--scripts\n" " Codepoints from all scripts are sorted and serialized.\n" "--reducehan\n" " Only 200 Han script characters will be displayed with the use of --scripts.\n" "--wholescripts\n" " Show collation order for whole scripts instead of just for exemplar characters of a locale\n\n"); fprintf(stdout, "Example to generate *.txt files : dumpce --serialize --locale af --destdir /temp --attribute UCOL_STRENGTH=UCOL_DEFAULT_STRENGTH,4=17\n\n"); fprintf(stdout, "Example to generate *.html files for oss web display: dumpce --scripts --destdir /temp --reducehan\n"); return argc < 0 ? U_ILLEGAL_ARGUMENT_ERROR : U_ZERO_ERROR; } OUTPUT_ = stdout; if (options[6].doesOccur) { fprintf(stdout, "attributes %s\n", options[6].value); parseAttributes(); } if (options[3].doesOccur) { serialize(); } if (options[9].doesOccur) { serializeScripts(); } return 0; }
33.40838
200
0.549495
tizenorg
605757c835aa09d53b965180a09441a30458a1b2
12,800
cpp
C++
NOLF/ClientShellDLL/FolderWeapons.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
38
2019-09-16T14:46:42.000Z
2022-03-10T20:28:10.000Z
NOLF/ClientShellDLL/FolderWeapons.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
39
2019-08-12T01:35:33.000Z
2022-02-28T16:48:16.000Z
NOLF/ClientShellDLL/FolderWeapons.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
6
2019-09-17T12:49:18.000Z
2022-03-10T20:28:12.000Z
// FolderWeapons.cpp: implementation of the CFolderWeapons class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "FolderWeapons.h" #include "FolderCommands.h" #include "MissionData.h" #include "MissionMgr.h" #include "ClientRes.h" #include "InterfaceMgr.h" #include "GameClientShell.h" extern CGameClientShell* g_pGameClientShell; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CFolderWeapons::CFolderWeapons() { } CFolderWeapons::~CFolderWeapons() { } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::Build // // PURPOSE: Build the folder // // ----------------------------------------------------------------------- // LTBOOL CFolderWeapons::Build() { CreateTitle(IDS_TITLE_WEAPONS); LTBOOL success = CBaseSelectionFolder::Build(); return success; } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::IsAvailable // // PURPOSE: Check to see if there any selections to be made here // // ----------------------------------------------------------------------- // LTBOOL CFolderWeapons::IsAvailable() { int missionNum = g_pInterfaceMgr->GetMissionData()->GetMissionNum(); MISSION* pMission = g_pMissionMgr->GetMission(missionNum); return (pMission->nNumWeapons != 0); } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::OnFocus // // PURPOSE: Handle gaining or losing focus // // ----------------------------------------------------------------------- // void CFolderWeapons::OnFocus(LTBOOL bFocus) { if (bFocus) { UseBack(LTTRUE); SetContinue(); m_szModel[0] = '\0'; m_szSkin[0] = '\0'; BuildWeaponsList(); SetSelection(kNoSelection); } else { SetSelection(kNoSelection); SaveWeaponData(); ClearWeaponsList(); } CBaseSelectionFolder::OnFocus(bFocus); } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::BuildWeaponsList // // PURPOSE: Create the list of weapons // // ----------------------------------------------------------------------- // void CFolderWeapons::BuildWeaponsList() { //get info from MissionMgr CMissionData *pData = g_pInterfaceMgr->GetMissionData(); int missionNum = pData->GetMissionNum(); MISSION* pMission = g_pMissionMgr->GetMission(missionNum); CPlayerStats* pStats = g_pInterfaceMgr->GetPlayerStats(); m_nNumSlots = pMission->nNumWeapons; if (m_nNumSlots == -1 || m_nNumSlots > MAX_SELECTION_SLOTS) m_nNumSlots = MAX_SELECTION_SLOTS; //no choices allowed... don't go here if (m_nNumSlots <= 0) return; int nWID = WMGR_INVALID_ID; WEAPON* pWeapon = LTNULL; for (int i=0; i< pMission->nNumRequiredWeapons; i++) { nWID = pMission->aRequiredWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); AddToSlot(nWID,pWeapon->nNameId,LTTRUE); } for (i=0; i< pMission->nNumOneTimeWeapons; i++) { nWID = pMission->aOneTimeWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); AddToSlot(nWID,pWeapon->nNameId,LTTRUE); } int numCurrWeapons = pData->GetNumWeapons(); if (numCurrWeapons) { CWeaponData* currWeapons[255]; WEAPON* pWeapon = LTNULL; numCurrWeapons = pData->GetWeapons(currWeapons,255); for (i=0; i< numCurrWeapons; i++) { nWID = currWeapons[i]->m_nID; pWeapon = g_pWeaponMgr->GetWeapon(nWID); if (pWeapon && !pWeapon->IsAGadget()) AddToSlot(nWID,pWeapon->nNameId,LTFALSE); } } else { for (i=0; i< pMission->nNumDefaultWeapons; i++) { nWID = pMission->aDefaultWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); AddToSlot(nWID,pWeapon->nNameId,LTFALSE); } } for (i=0; i< pMission->nNumAllowedWeapons; i++) { nWID = pMission->aAllowedWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); AddItem(nWID,pWeapon->nNameId); } int numWeapons = g_pWeaponMgr->GetNumWeapons(); for (i=0; i < numWeapons; i++) { pWeapon = g_pWeaponMgr->GetWeapon(i); AMMO *pAmmo = g_pWeaponMgr->GetAmmo(pWeapon->nDefaultAmmoType); if (pStats->CanUseWeapon(i) && !pWeapon->IsAGadget() && pAmmo->eInstDamageType != DT_MELEE) { AddItem(i,pWeapon->nNameId); } } for (i=0; i< pMission->nNumDeniedWeapons; i++) { nWID = pMission->aDeniedWeapons[i]; RemoveFromSlot(nWID); RemoveItem(nWID); } int nNumSelectable = (int)m_controlArray.GetSize(); int nNumFree = m_nNumSlots - m_nSlotsFilled; if (nNumFree > nNumSelectable) { nNumFree = nNumSelectable; m_nNumSlots = m_nSlotsFilled + nNumFree; while (m_controlArray.GetSize()) { nNumFree--; CLTGUICtrl *pCtrl = GetControl(0); if (pCtrl) { int nWID = pCtrl->GetParam1(); WEAPON* pWeapon = g_pWeaponMgr->GetWeapon(nWID); ItemToSlot(nWID,pWeapon->nNameId); } } } for (i=0;i < nNumFree;i++) { AddEmptySlot(); } return; } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::UpdateSelection // // PURPOSE: Show info based on current selection // // ----------------------------------------------------------------------- // LTBOOL CFolderWeapons::UpdateSelection() { LTBOOL bChanged = CBaseSelectionFolder::UpdateSelection(); if (bChanged) { CLTGUICtrl *pCtrl = GetControl(m_nLastListItem); int weaponId = pCtrl->GetParam1(); WEAPON* pWeapon = g_pWeaponMgr->GetWeapon(weaponId); if (pWeapon) { m_pName->RemoveAll(); m_pName->AddString(pWeapon->nNameId); m_pDescription->SetString(pWeapon->nDescriptionId); SAFE_STRCPY(m_szModel, pWeapon->szInterfaceModel); SAFE_STRCPY(m_szSkin, pWeapon->szInterfaceSkin); VEC_COPY(m_vOffset, pWeapon->vInterfaceOffset); m_fScale = pWeapon->fInterfaceScale; CreateModelSFX(); } } return bChanged; } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::ClearWeaponsList // // PURPOSE: Remove all of the controls // // ----------------------------------------------------------------------- // void CFolderWeapons::ClearWeaponsList() { // Terminate the ctrls RemoveFree(); ClearSlots(); ClearSelection(); } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::SaveWeaponData // // PURPOSE: Save the players selections // // ----------------------------------------------------------------------- // void CFolderWeapons::SaveWeaponData() { CMissionData *pData = g_pInterfaceMgr->GetMissionData(); pData->ClearWeapons(); if (m_bSaveSelection) { for (int slot = 0; slot < m_nSlotsFilled; slot++) { CLTGUICtrl *pCtrl = GetControl(m_nFirstSlot - slot); if (pCtrl && (int)pCtrl->GetParam1() != kEmptySlot) pData->AddWeapon(pCtrl->GetParam1()); } } } // ----------------------------------------------------------------------- // // // ROUTINE: CFolderWeapons::OnCommand // // PURPOSE: Handle activation of items // // ----------------------------------------------------------------------- // uint32 CFolderWeapons::OnCommand(uint32 dwCommand, uint32 dwParam1, uint32 dwParam2) { switch (dwCommand) { case FOLDER_CMD_SELECT_SLOT: { if (dwParam2) { g_pInterfaceMgr->RequestInterfaceSound(IS_NO_SELECT); return 0; } int nWID = (int)dwParam1; WEAPON *pWeapon = g_pWeaponMgr->GetWeapon(nWID); SlotToItem(nWID,pWeapon->nNameId); return 1; } break; case FOLDER_CMD_SELECT_ITEM: { int nWID = (int)dwParam1; WEAPON *pWeapon = g_pWeaponMgr->GetWeapon(nWID); ItemToSlot(nWID,pWeapon->nNameId); return 1; } break; case FOLDER_CMD_CONTINUE: { if (m_pContinue->GetHelpID() == IDS_HELP_START) { int missionNum = g_pInterfaceMgr->GetMissionData()->GetMissionNum(); g_pGameClientShell->StartMission(missionNum); return 1; } } break; } return CBaseSelectionFolder::OnCommand(dwCommand,dwParam1,dwParam2); } HSTRING CFolderWeapons::GetHelpString(uint32 dwHelpId, int nControlIndex) { WEAPON* pWeapon = LTNULL; char pStr[512] = ""; //slots are fixed controls so count negatively ( 0 > first > last ) int nLastSlot = (m_nFirstSlot - m_nNumSlots) + 1; if (nControlIndex >= 0 || (nControlIndex <= m_nFirstSlot && nControlIndex >= nLastSlot)) { CLTGUICtrl *pCtrl = GetControl(nControlIndex); int weaponId = pCtrl->GetParam1(); if (weaponId == kEmptySlot) return CBaseSelectionFolder::GetHelpString(dwHelpId,nControlIndex); pWeapon = g_pWeaponMgr->GetWeapon(weaponId); if (!pWeapon) return CBaseSelectionFolder::GetHelpString(dwHelpId,nControlIndex); int nameId = pWeapon->nNameId; HSTRING hTemp = g_pLTClient->FormatString(nameId); char *pName = g_pLTClient->GetStringData(hTemp); if (nControlIndex < 0) { //over a slot if (pCtrl->GetParam2()) { sprintf(pStr,"%s %s",pName,m_sRequiredStr); } else if (nControlIndex < 0) { sprintf(pStr,"%s %s",m_sUnselectStr,pName); } } else { sprintf(pStr,"%s %s",m_sSelectStr,pName); } g_pLTClient->FreeString(hTemp); HSTRING hStr = g_pLTClient->CreateString(pStr); return hStr; } else return CBaseSelectionFolder::GetHelpString(dwHelpId,nControlIndex); } void CFolderWeapons::SetContinue() { int nHelp = LTNULL; eFolderID eNext = GetNextSelectionFolder(FOLDER_ID_WEAPONS,&nHelp); if (eNext != FOLDER_ID_NONE) { UseContinue(eNext,nHelp); } else { UseContinue(g_pInterfaceMgr->GetMainFolder(),IDS_HELP_START,IDS_START_MISSION); } } void CFolderWeapons::CreateModelSFX() { // no model = no SFX if (!strlen(m_szModel)) return; HOBJECT hCamera = g_pGameClientShell->GetInterfaceCamera(); if (!hCamera) return; BSCREATESTRUCT bcs; LTVector vPos, vU, vR, vF, vTemp, vScale(1.0f,1.0f,1.0f); LTRotation rRot; g_pLTClient->GetObjectPos(hCamera, &vPos); g_pLTClient->GetObjectRotation(hCamera, &rRot); g_pLTClient->GetRotationVectors(&rRot, &vU, &vR, &vF); g_pLTClient->RotateAroundAxis(&rRot, &vU, MATH_HALFPI); g_pLTClient->RotateAroundAxis(&rRot, &vR, -0.3f); VEC_MULSCALAR(vScale, vScale, m_fScale); LTVector vModPos = g_pLayoutMgr->GetFolderCustomVector((eFolderID)m_nFolderID,"ModelPos"); VEC_ADD(vModPos,vModPos,m_vOffset); VEC_MULSCALAR(vTemp, vF, vModPos.z); VEC_MULSCALAR(vTemp, vTemp, 1);//g_pInterfaceResMgr->GetXRatio()); VEC_ADD(vPos, vPos, vTemp); VEC_MULSCALAR(vTemp, vR, vModPos.x); VEC_ADD(vPos, vPos, vTemp); VEC_MULSCALAR(vTemp, vU, vModPos.y); VEC_ADD(vPos, vPos, vTemp); VEC_COPY(bcs.vPos, vPos); bcs.rRot = rRot; VEC_COPY(bcs.vInitialScale, vScale); VEC_COPY(bcs.vFinalScale, vScale); VEC_SET(bcs.vInitialColor, 1.0f, 1.0f, 1.0f); VEC_SET(bcs.vFinalColor, 1.0f, 1.0f, 1.0f); bcs.bUseUserColors = LTTRUE; bcs.pFilename = m_szModel; bcs.pSkin = m_szSkin; bcs.dwFlags = FLAG_VISIBLE | FLAG_FOGDISABLE | FLAG_NOLIGHT; bcs.nType = OT_MODEL; bcs.fInitialAlpha = 1.0f; bcs.fFinalAlpha = 1.0f; bcs.fLifeTime = 1000000.0f; if (m_ModelSFX.Init(&bcs)) { m_ModelSFX.CreateObject(g_pLTClient); g_pInterfaceMgr->AddInterfaceSFX(&m_ModelSFX, IFX_NORMAL); m_fSFXRot = g_pLayoutMgr->GetFolderCustomFloat((eFolderID)m_nFolderID,"ModelRotSpeed"); } } void CFolderWeapons::RemoveInterfaceSFX() { CBaseSelectionFolder::RemoveInterfaceSFX(); g_pInterfaceMgr->RemoveInterfaceSFX(&m_ModelSFX); m_ModelSFX.Term(); } void CFolderWeapons::UpdateInterfaceSFX() { CBaseSelectionFolder::UpdateInterfaceSFX(); if (m_ModelSFX.GetObject()) { LTFLOAT spin = g_pGameClientShell->GetFrameTime() * m_fSFXRot; LTVector vU, vR, vF; LTRotation rRot; g_pLTClient->GetObjectRotation(m_ModelSFX.GetObject(), &rRot); g_pLTClient->GetRotationVectors(&rRot, &vU, &vR, &vF); g_pLTClient->RotateAroundAxis(&rRot, &vU, spin); g_pLTClient->SetObjectRotation(m_ModelSFX.GetObject(),&rRot); } } void CFolderWeapons::SkipOutfitting() { CMissionData *pData = g_pInterfaceMgr->GetMissionData(); int missionNum = pData->GetMissionNum(); MISSION* pMission = g_pMissionMgr->GetMission(missionNum); pData->ClearWeapons(); int nWID = WMGR_INVALID_ID; WEAPON* pWeapon = LTNULL; for (int i=0; i< pMission->nNumRequiredWeapons; i++) { nWID = pMission->aRequiredWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); pData->AddWeapon(nWID); } for (i=0; i< pMission->nNumOneTimeWeapons; i++) { nWID = pMission->aOneTimeWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); pData->AddWeapon(nWID); } for (i=0; i< pMission->nNumDefaultWeapons; i++) { nWID = pMission->aDefaultWeapons[i]; pWeapon = g_pWeaponMgr->GetWeapon(nWID); pData->AddWeapon(nWID); } }
24.380952
97
0.624766
haekb
605779aec247a93cff658e28eff006079d781e70
30,481
cpp
C++
Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/unitTestOneWayDopplerPartials.cpp
sebranchett/tudat
24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44
[ "BSD-3-Clause" ]
null
null
null
Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/unitTestOneWayDopplerPartials.cpp
sebranchett/tudat
24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44
[ "BSD-3-Clause" ]
null
null
null
Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/unitTestOneWayDopplerPartials.cpp
sebranchett/tudat
24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2019, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. * */ #define BOOST_TEST_MAIN #include <limits> #include <string> #include <vector> #include <boost/test/unit_test.hpp> #include <boost/make_shared.hpp> #include <boost/lambda/lambda.hpp> #include "Tudat/Basics/testMacros.h" #include "Tudat/InputOutput/basicInputOutput.h" #include "Tudat/External/SpiceInterface/spiceInterface.h" #include "Tudat/SimulationSetup/EstimationSetup/createObservationModel.h" #include "Tudat/Astrodynamics/ObservationModels/oneWayDopplerObservationModel.h" #include "Tudat/Astrodynamics/OrbitDetermination/EstimatableParameters/constantRotationRate.h" #include "Tudat/SimulationSetup/EstimationSetup/createObservationPartials.h" #include "Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/numericalObservationPartial.h" #include "Tudat/SimulationSetup/EnvironmentSetup/createGroundStations.h" #include "Tudat/SimulationSetup/EnvironmentSetup/defaultBodies.h" #include "Tudat/Mathematics/BasicMathematics/numericalDerivative.h" #include "Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/observationPartialTestFunctions.h" namespace tudat { namespace unit_tests { BOOST_AUTO_TEST_SUITE( test_one_way_observation_partials) Eigen::Vector3d computeUnitVectorToReceiverFromTransmitterState( const Eigen::Vector3d receiverPosition, const std::function< Eigen::Vector6d( const double ) > transmitterStateFunction, const double evaluationTime ) { return ( receiverPosition - transmitterStateFunction( evaluationTime ).segment( 0, 3 ) ).normalized( ); } Eigen::Vector3d computeUnitVectorToReceiverFromReceiverState( const std::function< Eigen::Vector6d( const double ) > receiverStateFunction, const Eigen::Vector3d transmitterPosition, const double evaluationTime ) { return ( receiverStateFunction( evaluationTime ).segment( 0, 3 ) - transmitterPosition ).normalized( ); } Eigen::VectorXd getProperTimeRateInVectorForm( std::shared_ptr< DopplerProperTimeRateInterface > properTimeRateCalculator, const std::vector< double >& linkEndTimes, const std::vector< Eigen::Matrix< double, 6, 1 > >& linkEndStates, const LinkEndType linkEndAssociatedWithTime ) { return ( Eigen::Vector1d( ) << properTimeRateCalculator->getOberverProperTimeDeviation( linkEndTimes, linkEndStates ) ).finished( ); } //! Test partial derivatives of one-way doppler observable, using general test suite of observation partials. BOOST_AUTO_TEST_CASE( testOneWayDopplerPartials ) { using namespace tudat::gravitation; using namespace tudat::gravitation; using namespace tudat::ephemerides; using namespace tudat::observation_models; using namespace tudat::simulation_setup; using namespace tudat::spice_interface; using namespace tudat::observation_partials; using namespace tudat::estimatable_parameters; // Define and create ground stations. std::vector< std::pair< std::string, std::string > > groundStations; groundStations.resize( 2 ); groundStations[ 0 ] = std::make_pair( "Earth", "Graz" ); groundStations[ 1 ] = std::make_pair( "Mars", "MSL" ); // Test ancilliary functions { double nominalEvaluationTime = 1.1E7; // Create environment NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, false ); // Set link ends for observation model LinkEnds linkEnds; linkEnds[ transmitter ] = groundStations[ 1 ]; linkEnds[ receiver ] = groundStations[ 0 ]; // Create transmitter/receriver state functions std::function< Eigen::Vector6d( const double ) > transmitterStateFunction = getLinkEndCompleteEphemerisFunction< double, double >( linkEnds[ transmitter ], bodyMap ); std::function< Eigen::Vector6d( const double ) > receiverStateFunction = getLinkEndCompleteEphemerisFunction< double, double >( linkEnds[ receiver ], bodyMap ); // Define (independent!) transmission/reception times double transmissionTime = nominalEvaluationTime; double receptionTime = nominalEvaluationTime + 1.0E3; // Compute associated states Eigen::Vector6d nominalTransmitterState = transmitterStateFunction( transmissionTime ); Eigen::Vector6d nominalReceiverState = receiverStateFunction( receptionTime ); Eigen::Vector3d nominalVectorToReceiver = ( nominalReceiverState - nominalTransmitterState ).segment( 0, 3 ); double timePerturbation = 100.0; // Partials for fixed receiver { // Compute numerical derivative of transmitter state for acceleration) Eigen::Vector6d numericalStateDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( transmitterStateFunction, transmissionTime, timePerturbation, numerical_derivatives::order8 ); // Compute unit vector derivative numerically std::function< Eigen::Vector3d( const double ) > unitVectorFunction = std::bind( &computeUnitVectorToReceiverFromTransmitterState, nominalReceiverState.segment( 0, 3 ), transmitterStateFunction, std::placeholders::_1 ); Eigen::Vector3d numericalUnitVectorDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( unitVectorFunction, transmissionTime, timePerturbation, numerical_derivatives::order8 ); // Compute projected velocoty vector derivative numerically std::function< double( const double) > projectedVelocityFunction = std::bind( &calculateLineOfSightVelocityAsCFractionFromTransmitterStateFunction< double, double >, nominalReceiverState.segment( 0, 3 ), transmitterStateFunction, std::placeholders::_1 ); double numericalProjectedVelocityDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( projectedVelocityFunction, transmissionTime, timePerturbation, numerical_derivatives::order8 ); // Compute analytical partial derivatives Eigen::Vector3d analyticalUnitVectorDerivative = -computePartialOfUnitVectorWrtLinkEndTime( nominalVectorToReceiver, nominalVectorToReceiver.normalized( ), nominalVectorToReceiver.norm( ), nominalTransmitterState.segment( 3, 3 ) ); double analyticalProjectedVelocityDerivative = computePartialOfProjectedLinkEndVelocityWrtAssociatedTime( nominalVectorToReceiver, nominalTransmitterState.segment( 3, 3 ), nominalTransmitterState.segment( 3, 3 ), numericalStateDerivative.segment( 3, 3 ), false ); for( unsigned int i = 0; i < 3; i++ ) { BOOST_CHECK_SMALL( std::fabs( analyticalUnitVectorDerivative( i ) - numericalUnitVectorDerivative( i ) ), 1.0E-16 ); } BOOST_CHECK_SMALL( std::fabs( analyticalProjectedVelocityDerivative / physical_constants::SPEED_OF_LIGHT - numericalProjectedVelocityDerivative ), 1.0E-21 ); } // Partials for fixed transmitter { // Compute numerical derivative of receiver state for acceleration) Eigen::Vector6d numericalStateDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( receiverStateFunction, receptionTime, timePerturbation, numerical_derivatives::order8 ); // Compute unit vector derivative numerically std::function< Eigen::Vector3d( const double ) > unitVectorFunction = std::bind( &computeUnitVectorToReceiverFromReceiverState, receiverStateFunction, nominalTransmitterState.segment( 0, 3 ), std::placeholders::_1 ); Eigen::Vector3d numericalUnitVectorDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( unitVectorFunction, receptionTime, timePerturbation, numerical_derivatives::order8 ); // Compute projected velocoty vector derivative numerically std::function< double( const double) > projectedVelocityFunction = std::bind( &calculateLineOfSightVelocityAsCFractionFromReceiverStateFunction< double, double >, receiverStateFunction, nominalTransmitterState.segment( 0, 3 ), std::placeholders::_1 ); double numericalProjectedVelocityDerivative = numerical_derivatives::computeCentralDifferenceFromFunction( projectedVelocityFunction, receptionTime, timePerturbation, numerical_derivatives::order8 ); // Compute analytical partial derivatives Eigen::Vector3d analyticalUnitVectorDerivative = computePartialOfUnitVectorWrtLinkEndTime( nominalVectorToReceiver, nominalVectorToReceiver.normalized( ), nominalVectorToReceiver.norm( ), nominalReceiverState.segment( 3, 3 ) ); double analyticalProjectedVelocityDerivative = computePartialOfProjectedLinkEndVelocityWrtAssociatedTime( nominalVectorToReceiver, nominalReceiverState.segment( 3, 3 ), nominalReceiverState.segment( 3, 3 ),\ numericalStateDerivative.segment( 3, 3 ), true ); for( unsigned int i = 0; i < 3; i++ ) { BOOST_CHECK_SMALL( std::fabs( analyticalUnitVectorDerivative( i ) - numericalUnitVectorDerivative( i ) ), 1.0E-18 ); } BOOST_CHECK_SMALL( std::fabs( analyticalProjectedVelocityDerivative / physical_constants::SPEED_OF_LIGHT - numericalProjectedVelocityDerivative ), 1.0E-22 ); } } // Test partials with constant ephemerides (allows test of position partials) { // Create environment NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, true ); // Set link ends for observation model LinkEnds linkEnds; linkEnds[ transmitter ] = groundStations[ 1 ]; linkEnds[ receiver ] = groundStations[ 0 ]; for( unsigned int estimationCase = 0; estimationCase < 3; estimationCase ++ ) { std::cout << "Case " << estimationCase << std::endl; // Generate one-way doppler model std::shared_ptr< ObservationModel< 1 > > oneWayDopplerModel; std::vector< std::string > perturbingBodies; perturbingBodies.push_back( "Earth" ); if( estimationCase == 0 ) { oneWayDopplerModel = observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< observation_models::ObservationSettings >( observation_models::one_way_doppler, std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >( perturbingBodies ) ), bodyMap ); } else { oneWayDopplerModel = observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< OneWayDopplerObservationSettings > ( std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >( perturbingBodies ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Mars" ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Earth" ) ), bodyMap ); } // Create parameter objects. std::shared_ptr< EstimatableParameterSet< double > > fullEstimatableParameterSet; Eigen::VectorXd parameterPerturbationMultipliers = Eigen::Vector4d::Constant( 1.0 ); if( estimationCase < 2 ) { fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7 ); } else { fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7, true ); parameterPerturbationMultipliers( 2 ) = 1.0E-4; } testObservationPartials< 1 >( oneWayDopplerModel, bodyMap, fullEstimatableParameterSet, linkEnds, one_way_doppler, 1.0E-5, true, true, 10.0, parameterPerturbationMultipliers ); std::cout << "Case " << estimationCase << std::endl; } } // Test partials with real ephemerides (without test of position partials) { // Create environment NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, false ); // Set link ends for observation model LinkEnds linkEnds; linkEnds[ transmitter ] = groundStations[ 1 ]; linkEnds[ receiver ] = groundStations[ 0 ]; for( unsigned int estimationCase = 0; estimationCase < 3; estimationCase ++ ) { std::cout << "Rates: " << estimationCase << std::endl; // Generate one-way doppler model std::shared_ptr< ObservationModel< 1 > > oneWayDopplerModel; std::vector< std::string > perturbingBodies; perturbingBodies.push_back( "Earth" ); if( estimationCase == 0 ) { oneWayDopplerModel = observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< observation_models::ObservationSettings >( observation_models::one_way_doppler, std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >( perturbingBodies ) ), bodyMap ); } else { oneWayDopplerModel = observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< OneWayDopplerObservationSettings > ( std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >( perturbingBodies ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Mars" ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Earth" ) ), bodyMap ); } // Create parameter objects. std::shared_ptr< EstimatableParameterSet< double > > fullEstimatableParameterSet; Eigen::VectorXd parameterPerturbationMultipliers = Eigen::Vector4d::Constant( 1.0 ); if( estimationCase < 2 ) { fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7 ); } else { fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7, true ); parameterPerturbationMultipliers( 2 ) = 1.0E-4; } testObservationPartials< 1 >( oneWayDopplerModel, bodyMap, fullEstimatableParameterSet, linkEnds, one_way_doppler, 1.0E-4, false, true, 1.0, parameterPerturbationMultipliers ); } } // Test partials with constant ephemerides (allows test of position partials) { // Create environment NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, true, 1000000.0 ); // Set link ends for observation model (Mars to Earth) LinkEnds linkEnds; linkEnds[ transmitter ] = groundStations[ 1 ]; linkEnds[ receiver ] = groundStations[ 0 ]; // Create one-way doppler model std::shared_ptr< OneWayDopplerObservationModel< > > oneWayDopplerModel = std::dynamic_pointer_cast< OneWayDopplerObservationModel< > >( observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< OneWayDopplerObservationSettings > ( std::shared_ptr< LightTimeCorrectionSettings >( ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Earth" ), std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Mars" ) ), bodyMap ) ); // Extract proper time calculators std::shared_ptr< DopplerProperTimeRateInterface > receiverProperTimeRateCalculator = oneWayDopplerModel->getReceiverProperTimeRateCalculator( ); std::shared_ptr< DopplerProperTimeRateInterface > transmitterProperTimeRateCalculator = oneWayDopplerModel->getTransmitterProperTimeRateCalculator( ); // Create parameter objects. std::shared_ptr< EstimatableParameterSet< double > > fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7 ); // Create partials for Doppler with proper time rates std::map< LinkEnds, std::shared_ptr< ObservationModel< 1 > > > observationModelList; observationModelList[ linkEnds ] = oneWayDopplerModel; std::map< LinkEnds, std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > > dopplerPartials = createOneWayDopplerPartials( observationModelList, bodyMap, fullEstimatableParameterSet ); // Retrieve scaling objects and partials with proper time std::shared_ptr< OneWayDopplerScaling > partialScalingObject = std::dynamic_pointer_cast< OneWayDopplerScaling >( dopplerPartials.begin( )->second.second ); std::shared_ptr< OneWayDopplerProperTimeComponentScaling > transmitterProperTimePartials = partialScalingObject->getTransmitterProperTimePartials( ); std::shared_ptr< OneWayDopplerProperTimeComponentScaling > receiverProperTimePartials = partialScalingObject->getReceiverProperTimePartials( ); std::shared_ptr< OneWayDopplerPartial > earthStatePartial = std::dynamic_pointer_cast< OneWayDopplerPartial >( ( dopplerPartials.begin( )->second.first ).begin( )->second ); std::shared_ptr< OneWayDopplerPartial > marsStatePartial = std::dynamic_pointer_cast< OneWayDopplerPartial >( ( ++( ( dopplerPartials.begin( )->second.first ).begin( ) ) )->second ); // Compute nominal observation with proper time double observationTime = 1.1E7; std::vector< double > linkEndTimes; std::vector< Eigen::Vector6d > linkEndStates; LinkEndType referenceLinkEnd = transmitter; Eigen::VectorXd nominalObservable = oneWayDopplerModel->computeIdealObservationsWithLinkEndData( observationTime, referenceLinkEnd, linkEndTimes, linkEndStates ); // Compute partials with proper time. partialScalingObject->update( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > earthStatePartialOutput = earthStatePartial->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > marsStatePartialOutput = marsStatePartial->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); // Compute numerical proper time rate partials and compare to analytical results { std::function< Eigen::VectorXd( const double ) > transmitterProperTimeRateFunction = std::bind( &getProperTimeRateInVectorForm, transmitterProperTimeRateCalculator, linkEndTimes, linkEndStates, referenceLinkEnd ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtMarsPosition = calculatePartialWrtConstantBodyState( "Earth", bodyMap, Eigen::Vector3d::Constant( 1000.0E3 ), transmitterProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtEarthPosition = calculatePartialWrtConstantBodyState( "Mars", bodyMap, Eigen::Vector3d::Constant( 1000.0E3 ), transmitterProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtMarsVelocity = calculatePartialWrtConstantBodyVelocity( "Earth", bodyMap, Eigen::Vector3d::Constant( 1.0E0 ), transmitterProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtEarthVelocity = calculatePartialWrtConstantBodyVelocity( "Mars", bodyMap, Eigen::Vector3d::Constant( 1.0E0 ), transmitterProperTimeRateFunction, 1.1E7, 1 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( transmitterProperTimePartials->getPositionScalingFactor( transmitter ) ), numericalTransmitterProperTimePartialsWrtMarsPosition, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( transmitterProperTimePartials->getPositionScalingFactor( receiver ) ), numericalTransmitterProperTimePartialsWrtEarthPosition, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( transmitterProperTimePartials->getVelocityScalingFactor( transmitter ) ), numericalTransmitterProperTimePartialsWrtMarsVelocity, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( transmitterProperTimePartials->getVelocityScalingFactor( receiver ) ), numericalTransmitterProperTimePartialsWrtEarthVelocity, 1.0E-6 ); std::function< Eigen::VectorXd( const double ) > receiverProperTimeRateFunction = std::bind( &getProperTimeRateInVectorForm, receiverProperTimeRateCalculator, linkEndTimes, linkEndStates, referenceLinkEnd ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtMarsPosition = calculatePartialWrtConstantBodyState( "Earth", bodyMap, Eigen::Vector3d::Constant( 10000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtEarthPosition = calculatePartialWrtConstantBodyState( "Mars", bodyMap, Eigen::Vector3d::Constant( 10000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtMarsVelocity = calculatePartialWrtConstantBodyVelocity( "Earth", bodyMap, Eigen::Vector3d::Constant( 1000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 ); Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtEarthVelocity = calculatePartialWrtConstantBodyVelocity( "Mars", bodyMap, Eigen::Vector3d::Constant( 1000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( receiverProperTimePartials->getPositionScalingFactor( receiver ) ), numericalReceiverProperTimePartialsWrtEarthPosition, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( receiverProperTimePartials->getPositionScalingFactor( transmitter ) ), numericalReceiverProperTimePartialsWrtMarsPosition, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( receiverProperTimePartials->getVelocityScalingFactor( transmitter ) ), numericalReceiverProperTimePartialsWrtMarsVelocity, 1.0E-6 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( receiverProperTimePartials->getVelocityScalingFactor( receiver ) ), numericalReceiverProperTimePartialsWrtEarthVelocity, 1.0E-6 ); } // Create one-way doppler model without proper time rates std::shared_ptr< OneWayDopplerObservationModel< > > oneWayDopplerModelWithoutProperTime = std::dynamic_pointer_cast< OneWayDopplerObservationModel< > >( observation_models::ObservationModelCreator< 1, double, double >::createObservationModel( linkEnds, std::make_shared< ObservationSettings > ( one_way_doppler, std::shared_ptr< LightTimeCorrectionSettings >( ) ), bodyMap ) ); // Create partials for Doppler without proper time rates observationModelList.clear( ); observationModelList[ linkEnds ] = oneWayDopplerModelWithoutProperTime; std::map< LinkEnds, std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > > dopplerPartialsWithoutProperTime = createOneWayDopplerPartials( observationModelList, bodyMap, fullEstimatableParameterSet ); // Retrieve partial object without proper time std::shared_ptr< OneWayDopplerScaling > partialScalingObjectWithoutProperTime = std::dynamic_pointer_cast< OneWayDopplerScaling >( dopplerPartialsWithoutProperTime.begin( )->second.second ); std::shared_ptr< OneWayDopplerPartial > earthStatePartialWithoutProperTime = std::dynamic_pointer_cast< OneWayDopplerPartial >( ( dopplerPartialsWithoutProperTime.begin( )->second.first ).begin( )->second ); std::shared_ptr< OneWayDopplerPartial > marsStatePartialWithoutProperTime = std::dynamic_pointer_cast< OneWayDopplerPartial >( ( ++( ( dopplerPartialsWithoutProperTime.begin( )->second.first ).begin( ) ) )->second ); // Compute nominal observation without proper time std::vector< double > linkEndTimesWithoutProperTime; std::vector< Eigen::Vector6d > linkEndStatesWithoutProperTime; Eigen::VectorXd nominalObservableWithoutProperTime = oneWayDopplerModelWithoutProperTime->computeIdealObservationsWithLinkEndData( observationTime, referenceLinkEnd, linkEndTimesWithoutProperTime, linkEndStatesWithoutProperTime ); // Compute partials with proper time. partialScalingObjectWithoutProperTime->update( linkEndStatesWithoutProperTime, linkEndTimesWithoutProperTime, referenceLinkEnd, nominalObservableWithoutProperTime ); std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > earthStatePartialOutputWithoutProperTime = earthStatePartialWithoutProperTime->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > marsStatePartialOutputWithoutProperTime = marsStatePartialWithoutProperTime->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable ); Eigen::MatrixXd partialWrtEarthState = earthStatePartialOutput.at( 0 ).first; Eigen::MatrixXd partialWrtEarthStateWithoutProperTime = earthStatePartialOutputWithoutProperTime.at( 0 ).first; Eigen::MatrixXd partialWrtMarsState = marsStatePartialOutput.at( 0 ).first; Eigen::MatrixXd partialWrtMarsStateWithoutProperTime = marsStatePartialOutputWithoutProperTime.at( 0 ).first; Eigen::MatrixXd properTimePartialWrtMarsPosition = transmitterProperTimePartials->getPositionScalingFactor( transmitter ); Eigen::MatrixXd properTimePartialWrtEarthPosition = receiverProperTimePartials->getPositionScalingFactor( receiver ); Eigen::MatrixXd properTimePartialWrtMarsVelocity = transmitterProperTimePartials->getVelocityScalingFactor( transmitter ); Eigen::MatrixXd properTimePartialWrtEarthVelocity = receiverProperTimePartials->getVelocityScalingFactor( receiver ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( ( partialWrtMarsState - partialWrtMarsStateWithoutProperTime ).block( 0, 0, 1, 3 ) ), properTimePartialWrtMarsPosition, 1.0E-9 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( -( partialWrtEarthState - partialWrtEarthStateWithoutProperTime ).block( 0, 0, 1, 3 ) ), properTimePartialWrtEarthPosition, 1.0E-9 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( ( partialWrtMarsState - partialWrtMarsStateWithoutProperTime ).block( 0, 3, 1, 3 ) ), properTimePartialWrtMarsVelocity, 1.0E-8 ); TUDAT_CHECK_MATRIX_CLOSE_FRACTION( ( -( partialWrtEarthState - partialWrtEarthStateWithoutProperTime ).block( 0, 3, 1, 3 ) ), properTimePartialWrtEarthVelocity, 1.0E-8 ); } } BOOST_AUTO_TEST_SUITE_END( ) } // namespace unit_tests } // namespace tudat
56.973832
153
0.661658
sebranchett
6058ab2b2f86f8c0d1e8094850e835a5c8767413
1,845
cpp
C++
C++/InfoArena/Arhiva probleme/Grarb/main.cpp
Nicu-Ducal/Competitive-Programming
c84126a4cb701b0764664db490b7e594495c8592
[ "MIT" ]
null
null
null
C++/InfoArena/Arhiva probleme/Grarb/main.cpp
Nicu-Ducal/Competitive-Programming
c84126a4cb701b0764664db490b7e594495c8592
[ "MIT" ]
null
null
null
C++/InfoArena/Arhiva probleme/Grarb/main.cpp
Nicu-Ducal/Competitive-Programming
c84126a4cb701b0764664db490b7e594495c8592
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; template <typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; } template <typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; } using i64 = long long int; const int INF = INT_MAX, MOD = 1e9 + 7; const double EPS = 1e-9, PI = acos(-1); const int dx[] = {0, 0, 0, -1, 1, -1, 1, 1, -1}; const int dy[] = {0, -1, 1, 0, 0, -1, 1, -1, 1}; struct Graph { vector<vector<int>> adj; vector<bool> marked; vector<int> parent, level; int n, m; Graph(int _n = 0) { init(_n); } void init(int _n) { n = _n; adj.resize(n + 1); marked.resize(n + 1, false); } void addEdge(int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } int solve() { int ans = 0; for (int node = 1; node <= n; node++) { if (not marked[node]) { dfs(node); ans++; } } return ans - 1; } void dfs(int node) { marked[node] = true; for (auto nei: adj[node]) if (not marked[nei]) dfs(nei); } }; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); /// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); ifstream cin("grarb.in"); ofstream cout("grarb.out"); int n, m; cin >> n >> m; Graph g(n); g.m = m; for (int i = 1; i <= m; i++) { int u, v; cin >> u >> v; g.addEdge(u, v); } int add = g.solve(); int rem = m + add - (n - 1); cout << rem << "\n" << add << "\n"; return 0; }
24.6
171
0.476423
Nicu-Ducal
6058ccad1acc11ed529ce45cad4b23b357cf5c98
14,597
cc
C++
test/unit/energy_comparison/weibel_driver.cc
HPCL/vpic
4b9dbb714f1d521fda0af69a29495ebfa5d4634c
[ "Unlicense" ]
2
2017-04-21T00:33:05.000Z
2021-02-13T06:06:53.000Z
test/unit/energy_comparison/weibel_driver.cc
HPCL/vpic
4b9dbb714f1d521fda0af69a29495ebfa5d4634c
[ "Unlicense" ]
null
null
null
test/unit/energy_comparison/weibel_driver.cc
HPCL/vpic
4b9dbb714f1d521fda0af69a29495ebfa5d4634c
[ "Unlicense" ]
null
null
null
//#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #define CATCH_CONFIG_RUNNER // We will provide a custom main #include "catch.hpp" // TODO: this import may ultimately be a bad idea, but it lets you paste an input deck in... #include "deck/wrapper.h" #include "src/species_advance/species_advance.h" #include "src/vpic/vpic.h" #include "compare_energies.h" begin_globals { double energies_interval; double fields_interval; double ehydro_interval; double ihydro_interval; double eparticle_interval; double iparticle_interval; double restart_interval; }; std::string energy_file_name = "./energies"; std::string energy_gold_file_name = EXPAND_AND_STRINGIFY( GOLD_ENERGY_FILE ); void vpic_simulation::user_diagnostics() { dump_energies(energy_file_name.c_str(), 1); } begin_initialization { // AKA: //void //vpic_simulation::user_initialization( int num_cmdline_arguments, //char ** cmdline_argument ) //{ // At this point, there is an empty grid and the random number generator is // seeded with the rank. The grid, materials, species need to be defined. // Then the initial non-zero fields need to be loaded at time level 0 and the // particles (position and momentum both) need to be loaded at time level 0. // Arguments can be passed from the command line to the input deck // if( num_cmdline_arguments!=3 ) { // sim_log( "Usage: " << cmdline_argument[0] << " mass_ratio seed" ); // abort(0); // } seed_entropy(1); //seed_entropy( atoi( cmdline_argument[2] ) ); // Diagnostic messages can be passed written (usually to stderr) sim_log( "Computing simulation parameters"); // Define the system of units for this problem (natural units) //double L = 1; // Length normalization (sheet thickness) double de = 1; // Length normalization (electron inertial length) double ec = 1; // Charge normalization double me = 1; // Mass normalization double c = 1; // Speed of light double eps0 = 1; // Permittivity of space // Physics parameters double mi_me = 1836; //25; //atof(cmdline_argument[1]); // Ion mass / electron mass double vthe = 0.25/sqrt(2.0); //0.0424264068711; //0.424264068711; // Electron thermal velocity double vthi = 0.25/sqrt(2.0); //0.0424264068711; //0.424264068711; // Ion thermal velocity double vthex =0.05/sqrt(2.0); //0.0141421356237; // 0.141421356237; // Electron thermal velocity in x-direction. double vthix =0.05/sqrt(2.0); //0.0141421356237; // 0.141421356237;Ion thermal velocity in x-direction. double n0 = 1.0; // Background plasma density double b0 = 0.0; // In plane magnetic field. double tauwpe = 200000; // simulation wpe's to run // Numerical parameters double topology_x = nproc(); // Number of domains in x, y, and z double topology_y = 1; double topology_z = 1; // For load balance, best to keep "1" or "2" for Harris sheet double Lx = 2.09439510239320; //4.62*de; //6.7*de; //10.0*de; // How big should the box be in the x direction double Ly = 1; //0.0721875*de; // How big should the box be in the y direction double Lz = 1; //0.0721875*de; // How big should the box be in the z direction double nx = 16; //64; //64; //32; // Global resolution in the x direction double ny = 1; // Global resolution in the y direction double nz = 1; //32; // Global resolution in the z direction double nppc = 200; //800; //200; //2048; //1024; //128; // Average number of macro particles per cell (both species combined!) double cfl_req = 0.99f; //0.99; // How close to Courant should we try to run double wpedt_max = 0.36; // How big a timestep is allowed if Courant is not too restrictive double damp = 0.0; // Level of radiation damping // Derived quantities double mi = me*mi_me; // Ion mass double wpe = c/de; // electron plasma frequency double wpi = wpe/sqrt(mi_me); // ion plasma frequency double di = c/wpi; // ion inertial length double hx = Lx/nx; double hy = Ly/ny; double hz = Lz/nz; double Npe = n0*Ly*Lz*Lx; // Number physical electrons. double Npi = Npe; // Number of physical ions in box double Ne = nppc*nx*ny*nz; // total macro electrons in box Ne = trunc_granular(Ne,nproc()); double Ni = Ne; // Total macro ions in box double we = Npe/Ne; // Weight of a macro electron double wi = Npi/Ni; // Weight of a macro ion // Determine the timestep double dg = courant_length(Lx,Ly,Lz,nx,ny,nz); // Courant length double dt = cfl_req*dg/c; // Courant limited time step // printf("in harris.cxx: dt=%.7f\n", dt); // exit(1); if( wpe*dt>wpedt_max ) dt=wpedt_max/wpe; // Override time step if plasma frequency limited //////////////////////////////////////// // Setup high level simulation parmeters num_step = 700; //4000; // int(tauwpe/(wpe*dt)); status_interval = 0; //2000; sync_shared_interval = 0; //status_interval; clean_div_e_interval = 0; //turn off cleaning (GY)//status_interval; clean_div_b_interval = 0; //status_interval; //(GY) global->energies_interval = 1; //status_interval; global->fields_interval = status_interval; global->ehydro_interval = status_interval; global->ihydro_interval = status_interval; global->eparticle_interval = status_interval; // Do not dump global->iparticle_interval = status_interval; // Do not dump global->restart_interval = status_interval; // Do not dump /////////////////////////// // Setup the space and time // Setup basic grid parameters define_units( c, eps0 ); define_timestep( dt ); grid->dx = hx; grid->dy = hy; grid->dz = hz; grid->dt = dt; grid->cvac = c; //grid->damp = damp; // Parition a periodic box among the processors sliced uniformly along y // define_periodic_grid( -0.5*Lx, 0, 0, // Low corner // 0.5*Lx, Ly, Lz, // High corner // nx, ny, nz, // Resolution // 1, nproc(), 1 ); // Topology define_periodic_grid( 0, -0.5*Ly, -0.5*Lz, // Low corner Lx, 0.5*Ly, 0.5*Lz, // High corner nx, ny, nz, // Resolution topology_x, topology_y, topology_z); // Topology // printf("in harris.cxx: g->neighbor[6*265]=%jd\n", grid->neighbor[6*265]); // Override some of the boundary conditions to put a particle reflecting // perfect electrical conductor on the -x and +x boundaries // set_domain_field_bc( BOUNDARY(-1,0,0), pec_fields ); // set_domain_field_bc( BOUNDARY( 1,0,0), pec_fields ); // set_domain_particle_bc( BOUNDARY(-1,0,0), reflect_particles ); // set_domain_particle_bc( BOUNDARY( 1,0,0), reflect_particles ); define_material( "vacuum", 1 ); // Note: define_material defaults to isotropic materials with mu=1,sigma=0 // Tensor electronic, magnetic and conductive materials are supported // though. See "shapes" for how to define them and assign them to regions. // Also, space is initially filled with the first material defined. // If you pass NULL to define field array, the standard field array will // be used (if damp is not provided, no radiation damping will be used). define_field_array( NULL, damp ); //////////////////// // Setup the species // Allow 50% more local_particles in case of non-uniformity // VPIC will pick the number of movers to use for each species // Both species use out-of-place sorting // species_t * ion = define_species( "ion", ec, mi, 1.5*Ni/nproc(), -1, 40, 1 ); // species_t * electron = define_species( "electron", -ec, me, 1.5*Ne/nproc(), -1, 20, 1 ); //species_t *electron = define_species("electron",-ec,me,2.4*Ne/nproc(),-1,25,0); //species_t *ion = define_species("ion", ec,mi,2.4*Ne/nproc(),-1,25,0); species_t *electron = define_species("electron",-ec,me,2.4*Ne/nproc(),-1,0,0); //turn off sorting (GY) species_t *ion = define_species("ion", ec,mi,2.4*Ne/nproc(),-1,0,0); //(GY) /////////////////////////////////////////////////// // Log diagnostic information about this simulation sim_log( "***********************************************" ); sim_log ( "mi/me = " << mi_me ); sim_log ( "tauwpe = " << tauwpe ); sim_log ( "num_step = " << num_step ); sim_log ( "Lx/di = " << Lx/di ); sim_log ( "Lx/de = " << Lx/de ); sim_log ( "Ly/di = " << Ly/di ); sim_log ( "Ly/de = " << Ly/de ); sim_log ( "Lz/di = " << Lz/di ); sim_log ( "Lz/de = " << Lz/de ); sim_log ( "nx = " << nx ); sim_log ( "ny = " << ny ); sim_log ( "nz = " << nz ); sim_log ( "damp = " << damp ); sim_log ( "courant = " << c*dt/dg ); sim_log ( "nproc = " << nproc () ); sim_log ( "nppc = " << nppc ); sim_log ( " b0 = " << b0 ); sim_log ( " di = " << di ); sim_log ( " Ne = " << Ne ); sim_log ( "total # of particles = " << 2*Ne ); sim_log ( "dt*wpe = " << wpe*dt ); sim_log ( "dx/de = " << Lx/(de*nx) ); sim_log ( "dy/de = " << Ly/(de*ny) ); sim_log ( "dz/de = " << Lz/(de*nz) ); sim_log ( "dx/debye = " << (Lx/nx)/(vthe/wpe) ); sim_log ( "n0 = " << n0 ); sim_log ( "vthi/c = " << vthi/c ); sim_log ( "vthe/c = " << vthe/c ); sim_log( "" ); //////////////////////////// // Load fields and particles // sim_log( "Loading fields" ); // set_region_field( everywhere, 0, 0, 0, // Electric field // 0, -sn*b0*tanh(x/L), cs*b0*tanh(x/L) ); // Magnetic field // Note: everywhere is a region that encompasses the entire simulation // In general, regions are specied as logical equations (i.e. x>0 && x+y<2) sim_log( "Loading particles" ); // Do a fast load of the particles //seed_rand( rng_seed*nproc() + rank() ); //Generators desynchronized double xmin = grid->x0 , xmax = grid->x0+(grid->dx)*(grid->nx); double ymin = grid->y0 , ymax = grid->y0+(grid->dy)*(grid->ny); double zmin = grid->z0 , zmax = grid->z0+(grid->dz)*(grid->nz); sim_log( "-> Uniform Bi-Maxwellian" ); double n1,n2,n3; repeat ( Ne/nproc() ) { double x = uniform( rng(0), xmin, xmax ); double y = uniform( rng(0), ymin, ymax ); double z = uniform( rng(0), zmin, zmax ); n1 = normal(rng(0),0,vthex); n2 = normal(rng(0),0,vthe ); n3 = normal(rng(0),0,vthe ); inject_particle( electron, x, y, z, n1, n2, n3,we, 0, 0); n1 = normal(rng(0),0,vthix); n2 = normal(rng(0),0,vthi ); n3 = normal(rng(0),0,vthi ); inject_particle( ion, x, y, z, n1, n2, n3,wi, 0 ,0 ); } sim_log( "Finished loading particles" ); //exit(1); // Upon completion of the initialization, the following occurs: // - The synchronization error (tang E, norm B) is computed between domains // and tang E / norm B are synchronized by averaging where discrepancies // are encountered. // - The initial divergence error of the magnetic field is computed and // one pass of cleaning is done (for good measure) // - The bound charge density necessary to give the simulation an initially // clean divergence e is computed. // - The particle momentum is uncentered from u_0 to u_{-1/2} // - The user diagnostics are called on the initial state // - The physics loop is started // // The physics loop consists of: // - Advance particles from x_0,u_{-1/2} to x_1,u_{1/2} // - User particle injection at x_{1-age}, u_{1/2} (use inject_particles) // - User current injection (adjust field(x,y,z).jfx, jfy, jfz) // - Advance B from B_0 to B_{1/2} // - Advance E from E_0 to E_1 // - User field injection to E_1 (adjust field(x,y,z).ex,ey,ez,cbx,cby,cbz) // - Advance B from B_{1/2} to B_1 // - (periodically) Divergence clean electric field // - (periodically) Divergence clean magnetic field // - (periodically) Synchronize shared tang e and norm b // - Increment the time step // - Call user diagnostics // - (periodically) Print a status message } TEST_CASE( "Check if Weibel gives correct energy (within tol)", "[energy]" ) { // Before we run this, we must make sure we remove the energy file std::ofstream ofs; ofs.open(energy_file_name, std::ofstream::out | std::ofstream::trunc); ofs.close(); // Init and run sim vpic_simulation simulation = vpic_simulation(); // TODO: We should do this in a safer manner simulation.initialize( 0, NULL ); while( simulation.advance() ); simulation.finalize(); if( world_rank==0 ) log_printf( "normal exit\n" ); std::cout << "Comparing " << energy_file_name << " to " << energy_gold_file_name << std::endl; // Compare energies to make sure everything worked out OK (within 1%) const unsigned short e_mask = 0b0000001110; const unsigned short b_mask = 0b0001110000; const unsigned short particle_mask = 0b011000000; SECTION("e_field") { // Test the sum of the e_field REQUIRE( test_utils::compare_energies(energy_file_name, energy_gold_file_name, 0.3, e_mask, test_utils::FIELD_ENUM::Sum, 1, "Weibel.e.out") ); } SECTION("b_field") { // Test the sum of the b_field REQUIRE( test_utils::compare_energies(energy_file_name, energy_gold_file_name, 0.03, b_mask, test_utils::FIELD_ENUM::Sum, 1, "Weibel.b.out") ); } SECTION("particle_energy") { // Test particle energies individually REQUIRE( test_utils::compare_energies(energy_file_name, energy_gold_file_name, 0.01, particle_mask, test_utils::FIELD_ENUM::Sum, 1, "Weibel.p.out") ); } } begin_particle_injection { // No particle injection for this simulation } begin_current_injection { // No current injection for this simulation } begin_field_injection { // No field injection for this simulation } begin_particle_collisions{ // No collisions for this simulation } // Manually implement catch main int main( int argc, char* argv[] ) { // Setup boot_services( &argc, &argv ); int result = Catch::Session().run( argc, argv ); // clean-up... halt_services(); return result; }
37.048223
136
0.611975
HPCL
605a0f65f0e1e368456e7ba5d78f1c7b313fe66f
2,205
hpp
C++
includes/Fox/Lexer/Token.hpp
Pierre-vh/Fox
ab3d9a5b3c409b5611840c477abef989830ea571
[ "MIT" ]
17
2019-01-17T22:41:11.000Z
2020-08-27T03:39:07.000Z
includes/Fox/Lexer/Token.hpp
Pierre-vh/Moonshot
ab3d9a5b3c409b5611840c477abef989830ea571
[ "MIT" ]
null
null
null
includes/Fox/Lexer/Token.hpp
Pierre-vh/Moonshot
ab3d9a5b3c409b5611840c477abef989830ea571
[ "MIT" ]
2
2019-06-30T19:07:10.000Z
2019-12-26T17:30:17.000Z
//----------------------------------------------------------------------------// // Part of the Fox project, licensed under the MIT license. // See LICENSE.txt in the project root for license information. // File : Token.hpp // Author : Pierre van Houtryve //----------------------------------------------------------------------------// // This file contains the Token class and TokenKind enum. //----------------------------------------------------------------------------// #pragma once #include "Fox/AST/Identifier.hpp" #include "Fox/Common/FoxTypes.hpp" #include "Fox/Common/SourceLoc.hpp" #include "Fox/Common/LLVM.hpp" #include "llvm/ADT/SmallVector.h" #include <cstddef> #include <iosfwd> namespace fox { class ASTContext; class DiagnosticEngine; class SourceManager; /// TokenKind /// The different kind of tokens that exist enum class TokenKind : std::uint8_t { #define TOKEN(ID) ID, #include "TokenKinds.def" }; /// Token /// Provides information about a lexed token: its string, location and kind. struct Token { public: using Kind = TokenKind; /// Creates an invalid token Token() = default; /// Creates a normal token Token(Kind kind, string_view str, SourceRange range); /// \returns true if this token's kind != TokenKind::Invalid bool isValid() const; /// \returns true if this token is the EOF token bool isEOF() const; /// \returns isValid() operator bool() const; /// \returns true if this token's kind matches "kind" bool is(Kind kind) const; /// dumps this token's data to out (without loc info) void dump(std::ostream& out) const; /// dumps this token's data to out (with loc info) void dump(std::ostream& out, SourceManager& srcMgr, bool printFileName) const; /// The SourceRange of this token const SourceRange range; /// A string-view (in the file's buffer) of this token. const string_view str; /// The Kind of token this is const Kind kind = Kind::Invalid; }; /// A Vector of Tokens. using TokenVector = SmallVector<Token, 4>; }
30.625
81
0.570975
Pierre-vh
605c71ebb028d6055653a9c1781de822a64e3e9b
47,941
cpp
C++
src/build_vehicle_gui.cpp
trademarks/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
8
2016-10-21T09:01:43.000Z
2021-05-31T06:32:14.000Z
src/build_vehicle_gui.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
null
null
null
src/build_vehicle_gui.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
4
2017-05-16T00:15:58.000Z
2020-08-06T01:46:31.000Z
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file build_vehicle_gui.cpp GUI for building vehicles. */ #include "stdafx.h" #include "engine_base.h" #include "engine_func.h" #include "station_base.h" #include "articulated_vehicles.h" #include "textbuf_gui.h" #include "command_func.h" #include "company_func.h" #include "vehicle_gui.h" #include "newgrf_engine.h" #include "newgrf_text.h" #include "group.h" #include "string_func.h" #include "strings_func.h" #include "window_func.h" #include "date_func.h" #include "vehicle_func.h" #include "widgets/dropdown_func.h" #include "engine_gui.h" #include "cargotype.h" #include "core/geometry_func.hpp" #include "table/strings.h" /** * Get the height of a single 'entry' in the engine lists. * @param type the vehicle type to get the height of * @return the height for the entry */ uint GetEngineListHeight(VehicleType type) { return max<uint>(FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM, GetVehicleHeight(type)); } enum BuildVehicleWidgets { BUILD_VEHICLE_WIDGET_CAPTION, BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN, BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN, BUILD_VEHICLE_WIDGET_LIST, BUILD_VEHICLE_WIDGET_SCROLLBAR, BUILD_VEHICLE_WIDGET_PANEL, BUILD_VEHICLE_WIDGET_BUILD, BUILD_VEHICLE_WIDGET_BUILD_SEL, BUILD_VEHICLE_WIDGET_RENAME, BUILD_VEHICLE_WIDGET_END }; static const NWidgetPart _nested_build_vehicle_widgets[] = { NWidget(NWID_HORIZONTAL), NWidget(WWT_CLOSEBOX, COLOUR_GREY), NWidget(WWT_CAPTION, COLOUR_GREY, BUILD_VEHICLE_WIDGET_CAPTION), SetDataTip(STR_WHITE_STRING, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS), NWidget(WWT_SHADEBOX, COLOUR_GREY), NWidget(WWT_STICKYBOX, COLOUR_GREY), EndContainer(), NWidget(WWT_PANEL, COLOUR_GREY), NWidget(NWID_HORIZONTAL), NWidget(NWID_VERTICAL), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0), NWidget(NWID_SPACER), SetFill(1, 1), EndContainer(), NWidget(NWID_VERTICAL), NWidget(WWT_DROPDOWN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA), NWidget(WWT_DROPDOWN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_FILTER_CRITERIA), EndContainer(), EndContainer(), EndContainer(), /* Vehicle list. */ NWidget(NWID_HORIZONTAL), NWidget(WWT_MATRIX, COLOUR_GREY, BUILD_VEHICLE_WIDGET_LIST), SetResize(1, 1), SetFill(1, 0), SetDataTip(0x101, STR_NULL), SetScrollbar(BUILD_VEHICLE_WIDGET_SCROLLBAR), NWidget(NWID_VSCROLLBAR, COLOUR_GREY, BUILD_VEHICLE_WIDGET_SCROLLBAR), EndContainer(), /* Panel with details. */ NWidget(WWT_PANEL, COLOUR_GREY, BUILD_VEHICLE_WIDGET_PANEL), SetMinimalSize(240, 122), SetResize(1, 0), EndContainer(), /* Build/rename buttons, resize button. */ NWidget(NWID_HORIZONTAL), NWidget(NWID_SELECTION, INVALID_COLOUR, BUILD_VEHICLE_WIDGET_BUILD_SEL), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_BUILD), SetResize(1, 0), SetFill(1, 0), EndContainer(), NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_RENAME), SetResize(1, 0), SetFill(1, 0), NWidget(WWT_RESIZEBOX, COLOUR_GREY), EndContainer(), }; /** Special cargo filter criteria */ static const CargoID CF_ANY = CT_NO_REFIT; ///< Show all vehicles independent of carried cargo (i.e. no filtering) static const CargoID CF_NONE = CT_INVALID; ///< Show only vehicles which do not carry cargo (e.g. train engines) static bool _internal_sort_order; ///< false = descending, true = ascending static byte _last_sort_criteria[] = {0, 0, 0, 0}; static bool _last_sort_order[] = {false, false, false, false}; static CargoID _last_filter_criteria[] = {CF_ANY, CF_ANY, CF_ANY, CF_ANY}; /** * Determines order of engines by engineID * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineNumberSorter(const EngineID *a, const EngineID *b) { int r = ListPositionOfEngine(*a) - ListPositionOfEngine(*b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by introduction date * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineIntroDateSorter(const EngineID *a, const EngineID *b) { const int va = Engine::Get(*a)->intro_date; const int vb = Engine::Get(*b)->intro_date; const int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by name * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineNameSorter(const EngineID *a, const EngineID *b) { static EngineID last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE }; static char last_name[2][64] = { "\0", "\0" }; const EngineID va = *a; const EngineID vb = *b; if (va != last_engine[0]) { last_engine[0] = va; SetDParam(0, va); GetString(last_name[0], STR_ENGINE_NAME, lastof(last_name[0])); } if (vb != last_engine[1]) { last_engine[1] = vb; SetDParam(0, vb); GetString(last_name[1], STR_ENGINE_NAME, lastof(last_name[1])); } int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting). /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by reliability * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineReliabilitySorter(const EngineID *a, const EngineID *b) { const int va = Engine::Get(*a)->reliability; const int vb = Engine::Get(*b)->reliability; const int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by purchase cost * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineCostSorter(const EngineID *a, const EngineID *b) { Money va = Engine::Get(*a)->GetCost(); Money vb = Engine::Get(*b)->GetCost(); int r = ClampToI32(va - vb); /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by speed * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineSpeedSorter(const EngineID *a, const EngineID *b) { int va = Engine::Get(*a)->GetDisplayMaxSpeed(); int vb = Engine::Get(*b)->GetDisplayMaxSpeed(); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by power * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EnginePowerSorter(const EngineID *a, const EngineID *b) { int va = Engine::Get(*a)->GetPower(); int vb = Engine::Get(*b)->GetPower(); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by tractive effort * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineTractiveEffortSorter(const EngineID *a, const EngineID *b) { int va = Engine::Get(*a)->GetDisplayMaxTractiveEffort(); int vb = Engine::Get(*b)->GetDisplayMaxTractiveEffort(); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by running costs * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EngineRunningCostSorter(const EngineID *a, const EngineID *b) { Money va = Engine::Get(*a)->GetRunningCost(); Money vb = Engine::Get(*b)->GetRunningCost(); int r = ClampToI32(va - vb); /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of engines by running costs * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL EnginePowerVsRunningCostSorter(const EngineID *a, const EngineID *b) { const Engine *e_a = Engine::Get(*a); const Engine *e_b = Engine::Get(*b); /* Here we are using a few tricks to get the right sort. * We want power/running cost, but since we usually got higher running cost than power and we store the result in an int, * we will actually calculate cunning cost/power (to make it more than 1). * Because of this, the return value have to be reversed as well and we return b - a instead of a - b. * Another thing is that both power and running costs should be doubled for multiheaded engines. * Since it would be multipling with 2 in both numerator and denumerator, it will even themselves out and we skip checking for multiheaded. */ Money va = (e_a->GetRunningCost()) / max(1U, (uint)e_a->GetPower()); Money vb = (e_b->GetRunningCost()) / max(1U, (uint)e_b->GetPower()); int r = ClampToI32(vb - va); /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /* Train sorting functions */ /** * Determines order of train engines by capacity * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL TrainEngineCapacitySorter(const EngineID *a, const EngineID *b) { const RailVehicleInfo *rvi_a = RailVehInfo(*a); const RailVehicleInfo *rvi_b = RailVehInfo(*b); int va = GetTotalCapacityOfArticulatedParts(*a) * (rvi_a->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1); int vb = GetTotalCapacityOfArticulatedParts(*b) * (rvi_b->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /** * Determines order of train engines by engine / wagon * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL TrainEnginesThenWagonsSorter(const EngineID *a, const EngineID *b) { int val_a = (RailVehInfo(*a)->railveh_type == RAILVEH_WAGON ? 1 : 0); int val_b = (RailVehInfo(*b)->railveh_type == RAILVEH_WAGON ? 1 : 0); int r = val_a - val_b; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /* Road vehicle sorting functions */ /** * Determines order of road vehicles by capacity * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL RoadVehEngineCapacitySorter(const EngineID *a, const EngineID *b) { int va = GetTotalCapacityOfArticulatedParts(*a); int vb = GetTotalCapacityOfArticulatedParts(*b); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /* Ship vehicle sorting functions */ /** * Determines order of ships by capacity * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL ShipEngineCapacitySorter(const EngineID *a, const EngineID *b) { const Engine *e_a = Engine::Get(*a); const Engine *e_b = Engine::Get(*b); int va = e_a->GetDisplayDefaultCapacity(); int vb = e_b->GetDisplayDefaultCapacity(); int r = va - vb; /* Use EngineID to sort instead since we want consistent sorting */ if (r == 0) return EngineNumberSorter(a, b); return _internal_sort_order ? -r : r; } /* Aircraft sorting functions */ /** * Determines order of aircraft by cargo * @param *a first engine to compare * @param *b second engine to compare * @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal */ static int CDECL AircraftEngineCargoSorter(const EngineID *a, const EngineID *b) { const Engine *e_a = Engine::Get(*a); const Engine *e_b = Engine::Get(*b); uint16 mail_a, mail_b; int va = e_a->GetDisplayDefaultCapacity(&mail_a); int vb = e_b->GetDisplayDefaultCapacity(&mail_b); int r = va - vb; if (r == 0) { /* The planes have the same passenger capacity. Check mail capacity instead */ r = mail_a - mail_b; if (r == 0) { /* Use EngineID to sort instead since we want consistent sorting */ return EngineNumberSorter(a, b); } } return _internal_sort_order ? -r : r; } static EngList_SortTypeFunction * const _sorter[][11] = {{ /* Trains */ &EngineNumberSorter, &EngineCostSorter, &EngineSpeedSorter, &EnginePowerSorter, &EngineTractiveEffortSorter, &EngineIntroDateSorter, &EngineNameSorter, &EngineRunningCostSorter, &EnginePowerVsRunningCostSorter, &EngineReliabilitySorter, &TrainEngineCapacitySorter, }, { /* Road vehicles */ &EngineNumberSorter, &EngineCostSorter, &EngineSpeedSorter, &EnginePowerSorter, &EngineTractiveEffortSorter, &EngineIntroDateSorter, &EngineNameSorter, &EngineRunningCostSorter, &EnginePowerVsRunningCostSorter, &EngineReliabilitySorter, &RoadVehEngineCapacitySorter, }, { /* Ships */ &EngineNumberSorter, &EngineCostSorter, &EngineSpeedSorter, &EngineIntroDateSorter, &EngineNameSorter, &EngineRunningCostSorter, &EngineReliabilitySorter, &ShipEngineCapacitySorter, }, { /* Aircraft */ &EngineNumberSorter, &EngineCostSorter, &EngineSpeedSorter, &EngineIntroDateSorter, &EngineNameSorter, &EngineRunningCostSorter, &EngineReliabilitySorter, &AircraftEngineCargoSorter, }}; static const StringID _sort_listing[][12] = {{ /* Trains */ STR_SORT_BY_ENGINE_ID, STR_SORT_BY_COST, STR_SORT_BY_MAX_SPEED, STR_SORT_BY_POWER, STR_SORT_BY_TRACTIVE_EFFORT, STR_SORT_BY_INTRO_DATE, STR_SORT_BY_NAME, STR_SORT_BY_RUNNING_COST, STR_SORT_BY_POWER_VS_RUNNING_COST, STR_SORT_BY_RELIABILITY, STR_SORT_BY_CARGO_CAPACITY, INVALID_STRING_ID }, { /* Road vehicles */ STR_SORT_BY_ENGINE_ID, STR_SORT_BY_COST, STR_SORT_BY_MAX_SPEED, STR_SORT_BY_POWER, STR_SORT_BY_TRACTIVE_EFFORT, STR_SORT_BY_INTRO_DATE, STR_SORT_BY_NAME, STR_SORT_BY_RUNNING_COST, STR_SORT_BY_POWER_VS_RUNNING_COST, STR_SORT_BY_RELIABILITY, STR_SORT_BY_CARGO_CAPACITY, INVALID_STRING_ID }, { /* Ships */ STR_SORT_BY_ENGINE_ID, STR_SORT_BY_COST, STR_SORT_BY_MAX_SPEED, STR_SORT_BY_INTRO_DATE, STR_SORT_BY_NAME, STR_SORT_BY_RUNNING_COST, STR_SORT_BY_RELIABILITY, STR_SORT_BY_CARGO_CAPACITY, INVALID_STRING_ID }, { /* Aircraft */ STR_SORT_BY_ENGINE_ID, STR_SORT_BY_COST, STR_SORT_BY_MAX_SPEED, STR_SORT_BY_INTRO_DATE, STR_SORT_BY_NAME, STR_SORT_BY_RUNNING_COST, STR_SORT_BY_RELIABILITY, STR_SORT_BY_CARGO_CAPACITY, INVALID_STRING_ID }}; /** Cargo filter functions */ static bool CDECL CargoFilter(const EngineID *eid, const CargoID cid) { if (cid == CF_ANY) return true; uint32 refit_mask = GetUnionOfArticulatedRefitMasks(*eid, true); return (cid == CF_NONE ? refit_mask == 0 : HasBit(refit_mask, cid)); } static GUIEngineList::FilterFunction * const _filter_funcs[] = { &CargoFilter, }; static int DrawCargoCapacityInfo(int left, int right, int y, EngineID engine, bool refittable) { CargoArray cap = GetCapacityOfArticulatedParts(engine); for (CargoID c = 0; c < NUM_CARGO; c++) { if (cap[c] == 0) continue; SetDParam(0, c); SetDParam(1, cap[c]); SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY); DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY); y += FONT_HEIGHT_NORMAL; /* Only show as refittable once */ refittable = false; } return y; } /* Draw rail wagon specific details */ static int DrawRailWagonPurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi) { const Engine *e = Engine::Get(engine_number); /* Purchase cost */ SetDParam(0, e->GetCost()); DrawString(left, right, y, STR_PURCHASE_INFO_COST); y += FONT_HEIGHT_NORMAL; /* Wagon weight - (including cargo) */ uint weight = e->GetDisplayWeight(); SetDParam(0, weight); uint cargo_weight = (e->CanCarryCargo() ? CargoSpec::Get(e->GetDefaultCargoType())->weight * e->GetDisplayDefaultCapacity() >> 4 : 0); SetDParam(1, cargo_weight + weight); DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT); y += FONT_HEIGHT_NORMAL; /* Wagon speed limit, displayed if above zero */ if (_settings_game.vehicle.wagon_speed_limits) { uint max_speed = e->GetDisplayMaxSpeed(); if (max_speed > 0) { SetDParam(0, max_speed); DrawString(left, right, y, STR_PURCHASE_INFO_SPEED); y += FONT_HEIGHT_NORMAL; } } /* Running cost */ if (rvi->running_cost_class != INVALID_PRICE) { SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; } return y; } /* Draw locomotive specific details */ static int DrawRailEnginePurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi) { const Engine *e = Engine::Get(engine_number); /* Purchase Cost - Engine weight */ SetDParam(0, e->GetCost()); SetDParam(1, e->GetDisplayWeight()); DrawString(left, right, y, STR_PURCHASE_INFO_COST_WEIGHT); y += FONT_HEIGHT_NORMAL; /* Max speed - Engine power */ SetDParam(0, e->GetDisplayMaxSpeed()); SetDParam(1, e->GetPower()); DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER); y += FONT_HEIGHT_NORMAL; /* Max tractive effort - not applicable if old acceleration or maglev */ if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && GetRailTypeInfo(rvi->railtype)->acceleration_type != 2) { SetDParam(0, e->GetDisplayMaxTractiveEffort()); DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE); y += FONT_HEIGHT_NORMAL; } /* Running cost */ if (rvi->running_cost_class != INVALID_PRICE) { SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; } /* Powered wagons power - Powered wagons extra weight */ if (rvi->pow_wag_power != 0) { SetDParam(0, rvi->pow_wag_power); SetDParam(1, rvi->pow_wag_weight); DrawString(left, right, y, STR_PURCHASE_INFO_PWAGPOWER_PWAGWEIGHT); y += FONT_HEIGHT_NORMAL; } return y; } /* Draw road vehicle specific details */ static int DrawRoadVehPurchaseInfo(int left, int right, int y, EngineID engine_number) { const Engine *e = Engine::Get(engine_number); if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) { /* Purchase Cost */ SetDParam(0, e->GetCost()); DrawString(left, right, y, STR_PURCHASE_INFO_COST); y += FONT_HEIGHT_NORMAL; /* Road vehicle weight - (including cargo) */ int16 weight = e->GetDisplayWeight(); SetDParam(0, weight); uint cargo_weight = CargoSpec::Get(e->GetDefaultCargoType())->weight * GetTotalCapacityOfArticulatedParts(engine_number) / 16; SetDParam(1, cargo_weight + weight); DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT); y += FONT_HEIGHT_NORMAL; /* Max speed - Engine power */ SetDParam(0, e->GetDisplayMaxSpeed()); SetDParam(1, e->GetPower()); DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER); y += FONT_HEIGHT_NORMAL; /* Max tractive effort */ SetDParam(0, e->GetDisplayMaxTractiveEffort()); DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE); y += FONT_HEIGHT_NORMAL; } else { /* Purchase cost - Max speed */ SetDParam(0, e->GetCost()); SetDParam(1, e->GetDisplayMaxSpeed()); DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED); y += FONT_HEIGHT_NORMAL; } /* Running cost */ SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; return y; } /* Draw ship specific details */ static int DrawShipPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable) { const Engine *e = Engine::Get(engine_number); /* Purchase cost - Max speed */ SetDParam(0, e->GetCost()); SetDParam(1, e->GetDisplayMaxSpeed()); DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED); y += FONT_HEIGHT_NORMAL; /* Cargo type + capacity */ SetDParam(0, e->GetDefaultCargoType()); SetDParam(1, e->GetDisplayDefaultCapacity()); SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY); DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY); y += FONT_HEIGHT_NORMAL; /* Running cost */ SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; return y; } /* Draw aircraft specific details */ static int DrawAircraftPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable) { const Engine *e = Engine::Get(engine_number); CargoID cargo = e->GetDefaultCargoType(); /* Purchase cost - Max speed */ SetDParam(0, e->GetCost()); SetDParam(1, e->GetDisplayMaxSpeed()); DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED); y += FONT_HEIGHT_NORMAL; /* Cargo capacity */ uint16 mail_capacity; uint capacity = e->GetDisplayDefaultCapacity(&mail_capacity); if (mail_capacity > 0) { SetDParam(0, cargo); SetDParam(1, capacity); SetDParam(2, CT_MAIL); SetDParam(3, mail_capacity); DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_CAPACITY); } else { /* Note, if the default capacity is selected by the refit capacity * callback, then the capacity shown is likely to be incorrect. */ SetDParam(0, cargo); SetDParam(1, capacity); SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY); DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY); } y += FONT_HEIGHT_NORMAL; /* Running cost */ SetDParam(0, e->GetRunningCost()); DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST); y += FONT_HEIGHT_NORMAL; return y; } /** * Display additional text from NewGRF in the purchase information window * @param left Left border of text bounding box * @param right Right border of text bounding box * @param y Top border of text bounding box * @param engine Engine to query the additional purchase information for * @return Bottom border of text bounding box */ static uint ShowAdditionalText(int left, int right, int y, EngineID engine) { uint16 callback = GetVehicleCallback(CBID_VEHICLE_ADDITIONAL_TEXT, 0, 0, engine, NULL); if (callback == CALLBACK_FAILED) return y; /* STR_BLACK_STRING is used to start the string with {BLACK} */ SetDParam(0, GetGRFStringID(GetEngineGRFID(engine), 0xD000 + callback)); PrepareTextRefStackUsage(0); uint result = DrawStringMultiLine(left, right, y, INT32_MAX, STR_BLACK_STRING); StopTextRefStackUsage(); return result; } /** * Draw the purchase info details of a vehicle at a given location. * @param left,right,y location where to draw the info * @param engine_number the engine of which to draw the info of * @return y after drawing all the text */ int DrawVehiclePurchaseInfo(int left, int right, int y, EngineID engine_number) { const Engine *e = Engine::Get(engine_number); YearMonthDay ymd; ConvertDateToYMD(e->intro_date, &ymd); bool refittable = IsArticulatedVehicleRefittable(engine_number); bool articulated_cargo = false; switch (e->type) { default: NOT_REACHED(); case VEH_TRAIN: if (e->u.rail.railveh_type == RAILVEH_WAGON) { y = DrawRailWagonPurchaseInfo(left, right, y, engine_number, &e->u.rail); } else { y = DrawRailEnginePurchaseInfo(left, right, y, engine_number, &e->u.rail); } articulated_cargo = true; break; case VEH_ROAD: y = DrawRoadVehPurchaseInfo(left, right, y, engine_number); articulated_cargo = true; break; case VEH_SHIP: y = DrawShipPurchaseInfo(left, right, y, engine_number, refittable); break; case VEH_AIRCRAFT: y = DrawAircraftPurchaseInfo(left, right, y, engine_number, refittable); break; } if (articulated_cargo) { /* Cargo type + capacity, or N/A */ int new_y = DrawCargoCapacityInfo(left, right, y, engine_number, refittable); if (new_y == y) { SetDParam(0, CT_INVALID); SetDParam(2, STR_EMPTY); DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY); y += FONT_HEIGHT_NORMAL; } else { y = new_y; } } /* Draw details that apply to all types except rail wagons. */ if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) { /* Design date - Life length */ SetDParam(0, ymd.year); SetDParam(1, e->GetLifeLengthInDays() / DAYS_IN_LEAP_YEAR); DrawString(left, right, y, STR_PURCHASE_INFO_DESIGNED_LIFE); y += FONT_HEIGHT_NORMAL; /* Reliability */ SetDParam(0, ToPercent16(e->reliability)); DrawString(left, right, y, STR_PURCHASE_INFO_RELIABILITY); y += FONT_HEIGHT_NORMAL; } /* Additional text from NewGRF */ y = ShowAdditionalText(left, right, y, engine_number); if (refittable) y = ShowRefitOptionsList(left, right, y, engine_number); return y; } /** * Engine drawing loop * @param type Type of vehicle (VEH_*) * @param l The left most location of the list * @param r The right most location of the list * @param y The top most location of the list * @param eng_list What engines to draw * @param min where to start in the list * @param max where in the list to end * @param selected_id what engine to highlight as selected, if any * @param show_count Whether to show the amount of engines or not * @param selected_group the group to list the engines of */ void DrawEngineList(VehicleType type, int l, int r, int y, const GUIEngineList *eng_list, uint16 min, uint16 max, EngineID selected_id, bool show_count, GroupID selected_group) { static const int sprite_widths[] = { 60, 60, 76, 67 }; static const int sprite_y_offsets[] = { -1, -1, -2, -2 }; /* Obligatory sanity checks! */ assert((uint)type < lengthof(sprite_widths)); assert_compile(lengthof(sprite_y_offsets) == lengthof(sprite_widths)); assert(max <= eng_list->Length()); bool rtl = _current_text_dir == TD_RTL; int step_size = GetEngineListHeight(type); int sprite_width = sprite_widths[type]; int sprite_x = (rtl ? r - sprite_width / 2 : l + sprite_width / 2) - 1; int sprite_y_offset = sprite_y_offsets[type] + step_size / 2; int text_left = l + (rtl ? WD_FRAMERECT_LEFT : sprite_width); int text_right = r - (rtl ? sprite_width : WD_FRAMERECT_RIGHT); int normal_text_y_offset = (step_size - FONT_HEIGHT_NORMAL) / 2; int small_text_y_offset = step_size - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1; for (; min < max; min++, y += step_size) { const EngineID engine = (*eng_list)[min]; /* Note: num_engines is only used in the autoreplace GUI, so it is correct to use _local_company here. */ const uint num_engines = GetGroupNumEngines(_local_company, selected_group, engine); SetDParam(0, engine); DrawString(text_left, text_right, y + normal_text_y_offset, STR_ENGINE_NAME, engine == selected_id ? TC_WHITE : TC_BLACK); DrawVehicleEngine(l, r, sprite_x, y + sprite_y_offset, engine, (show_count && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(engine, _local_company)); if (show_count) { SetDParam(0, num_engines); DrawString(text_left, text_right, y + small_text_y_offset, STR_TINY_BLACK_COMA, TC_FROMSTRING, SA_RIGHT); } } } struct BuildVehicleWindow : Window { VehicleType vehicle_type; union { RailTypeByte railtype; RoadTypes roadtypes; } filter; bool descending_sort_order; byte sort_criteria; bool listview_mode; EngineID sel_engine; EngineID rename_engine; GUIEngineList eng_list; CargoID cargo_filter[NUM_CARGO + 2]; ///< Available cargo filters; CargoID or CF_ANY or CF_NONE StringID cargo_filter_texts[NUM_CARGO + 3]; ///< Texts for filter_cargo, terminated by INVALID_STRING_ID byte cargo_filter_criteria; ///< Selected cargo filter int details_height; ///< Minimal needed height of the details panels (found so far). Scrollbar *vscroll; BuildVehicleWindow(const WindowDesc *desc, TileIndex tile, VehicleType type) : Window() { this->vehicle_type = type; this->window_number = tile == INVALID_TILE ? (int)type : tile; this->sel_engine = INVALID_ENGINE; this->sort_criteria = _last_sort_criteria[type]; this->descending_sort_order = _last_sort_order[type]; switch (type) { default: NOT_REACHED(); case VEH_TRAIN: this->filter.railtype = (tile == INVALID_TILE) ? RAILTYPE_END : GetRailType(tile); break; case VEH_ROAD: this->filter.roadtypes = (tile == INVALID_TILE) ? ROADTYPES_ALL : GetRoadTypes(tile); case VEH_SHIP: case VEH_AIRCRAFT: break; } this->listview_mode = (this->window_number <= VEH_END); this->CreateNestedTree(desc); this->vscroll = this->GetScrollbar(BUILD_VEHICLE_WIDGET_SCROLLBAR); /* If we are just viewing the list of vehicles, we do not need the Build button. * So we just hide it, and enlarge the Rename buton by the now vacant place. */ if (this->listview_mode) this->GetWidget<NWidgetStacked>(BUILD_VEHICLE_WIDGET_BUILD_SEL)->SetDisplayedPlane(SZSP_NONE); NWidgetCore *widget = this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_LIST); widget->tool_tip = STR_BUY_VEHICLE_TRAIN_LIST_TOOLTIP + type; widget = this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_BUILD); widget->widget_data = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_BUTTON + type; widget->tool_tip = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_TOOLTIP + type; widget = this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_RENAME); widget->widget_data = STR_BUY_VEHICLE_TRAIN_RENAME_BUTTON + type; widget->tool_tip = STR_BUY_VEHICLE_TRAIN_RENAME_TOOLTIP + type; this->details_height = ((this->vehicle_type == VEH_TRAIN) ? 10 : 9) * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM; this->FinishInitNested(desc, tile == INVALID_TILE ? (int)type : tile); this->owner = (tile != INVALID_TILE) ? GetTileOwner(tile) : _local_company; this->eng_list.ForceRebuild(); this->GenerateBuildList(); // generate the list, since we need it in the next line /* Select the first engine in the list as default when opening the window */ if (this->eng_list.Length() > 0) this->sel_engine = this->eng_list[0]; } /** Populate the filter list and set the cargo filter criteria. */ void SetCargoFilterArray() { uint filter_items = 0; /* Add item for disabling filtering. */ this->cargo_filter[filter_items] = CF_ANY; this->cargo_filter_texts[filter_items] = STR_PURCHASE_INFO_ALL_TYPES; filter_items++; /* Add item for vehicles not carrying anything, e.g. train engines. * This could also be useful for eyecandy vehicles of other types, but is likely too confusing for joe, */ if (this->vehicle_type == VEH_TRAIN) { this->cargo_filter[filter_items] = CF_NONE; this->cargo_filter_texts[filter_items] = STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE; filter_items++; } /* Collect available cargo types for filtering. */ const CargoSpec *cs; FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) { this->cargo_filter[filter_items] = cs->Index(); this->cargo_filter_texts[filter_items] = cs->name; filter_items++; } /* Terminate the filter list. */ this->cargo_filter_texts[filter_items] = INVALID_STRING_ID; /* If not found, the cargo criteria will be set to all cargos. */ this->cargo_filter_criteria = 0; /* Find the last cargo filter criteria. */ for (uint i = 0; i < filter_items; i++) { if (this->cargo_filter[i] == _last_filter_criteria[this->vehicle_type]) { this->cargo_filter_criteria = i; break; } } this->eng_list.SetFilterFuncs(_filter_funcs); this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY); } void OnInit() { this->SetCargoFilterArray(); } /** Filter the engine list against the currently selected cargo filter */ void FilterEngineList() { this->eng_list.Filter(this->cargo_filter[this->cargo_filter_criteria]); if (0 == this->eng_list.Length()) { // no engine passed through the filter, invalidate the previously selected engine this->sel_engine = INVALID_ENGINE; } else if (!this->eng_list.Contains(this->sel_engine)) { // previously selected engine didn't pass the filter, select the first engine of the list this->sel_engine = this->eng_list[0]; } } /** Filter a single engine */ bool FilterSingleEngine(EngineID eid) { CargoID filter_type = this->cargo_filter[this->cargo_filter_criteria]; return (filter_type == CF_ANY || CargoFilter(&eid, filter_type)); } /* Figure out what train EngineIDs to put in the list */ void GenerateBuildTrainList() { EngineID sel_id = INVALID_ENGINE; int num_engines = 0; int num_wagons = 0; this->filter.railtype = (this->listview_mode) ? RAILTYPE_END : GetRailType(this->window_number); this->eng_list.Clear(); /* Make list of all available train engines and wagons. * Also check to see if the previously selected engine is still available, * and if not, reset selection to INVALID_ENGINE. This could be the case * when engines become obsolete and are removed */ const Engine *e; FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) { EngineID eid = e->index; const RailVehicleInfo *rvi = &e->u.rail; if (this->filter.railtype != RAILTYPE_END && !HasPowerOnRail(rvi->railtype, this->filter.railtype)) continue; if (!IsEngineBuildable(eid, VEH_TRAIN, _local_company)) continue; /* Filter now! So num_engines and num_wagons is valid */ if (!FilterSingleEngine(eid)) continue; *this->eng_list.Append() = eid; if (rvi->railveh_type != RAILVEH_WAGON) { num_engines++; } else { num_wagons++; } if (eid == this->sel_engine) sel_id = eid; } this->sel_engine = sel_id; /* make engines first, and then wagons, sorted by ListPositionOfEngine() */ _internal_sort_order = false; EngList_Sort(&this->eng_list, TrainEnginesThenWagonsSorter); /* and then sort engines */ _internal_sort_order = this->descending_sort_order; EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], 0, num_engines); /* and finally sort wagons */ EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], num_engines, num_wagons); } /* Figure out what road vehicle EngineIDs to put in the list */ void GenerateBuildRoadVehList() { EngineID sel_id = INVALID_ENGINE; this->eng_list.Clear(); const Engine *e; FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) { EngineID eid = e->index; if (!IsEngineBuildable(eid, VEH_ROAD, _local_company)) continue; if (!HasBit(this->filter.roadtypes, HasBit(EngInfo(eid)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD)) continue; *this->eng_list.Append() = eid; if (eid == this->sel_engine) sel_id = eid; } this->sel_engine = sel_id; } /* Figure out what ship EngineIDs to put in the list */ void GenerateBuildShipList() { EngineID sel_id = INVALID_ENGINE; this->eng_list.Clear(); const Engine *e; FOR_ALL_ENGINES_OF_TYPE(e, VEH_SHIP) { EngineID eid = e->index; if (!IsEngineBuildable(eid, VEH_SHIP, _local_company)) continue; *this->eng_list.Append() = eid; if (eid == this->sel_engine) sel_id = eid; } this->sel_engine = sel_id; } /* Figure out what aircraft EngineIDs to put in the list */ void GenerateBuildAircraftList() { EngineID sel_id = INVALID_ENGINE; this->eng_list.Clear(); const Station *st = this->listview_mode ? NULL : Station::GetByTile(this->window_number); /* Make list of all available planes. * Also check to see if the previously selected plane is still available, * and if not, reset selection to INVALID_ENGINE. This could be the case * when planes become obsolete and are removed */ const Engine *e; FOR_ALL_ENGINES_OF_TYPE(e, VEH_AIRCRAFT) { EngineID eid = e->index; if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_company)) continue; /* First VEH_END window_numbers are fake to allow a window open for all different types at once */ if (!this->listview_mode && !CanVehicleUseStation(eid, st)) continue; *this->eng_list.Append() = eid; if (eid == this->sel_engine) sel_id = eid; } this->sel_engine = sel_id; } /* Generate the list of vehicles */ void GenerateBuildList() { if (!this->eng_list.NeedRebuild()) return; switch (this->vehicle_type) { default: NOT_REACHED(); case VEH_TRAIN: this->GenerateBuildTrainList(); this->eng_list.Compact(); this->eng_list.RebuildDone(); return; // trains should not reach the last sorting case VEH_ROAD: this->GenerateBuildRoadVehList(); break; case VEH_SHIP: this->GenerateBuildShipList(); break; case VEH_AIRCRAFT: this->GenerateBuildAircraftList(); break; } this->FilterEngineList(); _internal_sort_order = this->descending_sort_order; EngList_Sort(&this->eng_list, _sorter[this->vehicle_type][this->sort_criteria]); this->eng_list.Compact(); this->eng_list.RebuildDone(); } void OnClick(Point pt, int widget, int click_count) { switch (widget) { case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING: this->descending_sort_order ^= true; _last_sort_order[this->vehicle_type] = this->descending_sort_order; this->eng_list.ForceRebuild(); this->SetDirty(); break; case BUILD_VEHICLE_WIDGET_LIST: { uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, BUILD_VEHICLE_WIDGET_LIST); size_t num_items = this->eng_list.Length(); this->sel_engine = (i < num_items) ? this->eng_list[i] : INVALID_ENGINE; this->SetDirty(); if (click_count > 1 && !this->listview_mode) this->OnClick(pt, BUILD_VEHICLE_WIDGET_BUILD, 1); break; } case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN: { // Select sorting criteria dropdown menu uint32 hidden_mask = 0; /* Disable sorting by power or tractive effort when the original acceleration model for road vehicles is being used. */ if (this->vehicle_type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) { SetBit(hidden_mask, 3); // power SetBit(hidden_mask, 4); // tractive effort SetBit(hidden_mask, 8); // power by running costs } /* Disable sorting by tractive effort when the original acceleration model for trains is being used. */ if (this->vehicle_type == VEH_TRAIN && _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) { SetBit(hidden_mask, 4); // tractive effort } ShowDropDownMenu(this, _sort_listing[this->vehicle_type], this->sort_criteria, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN, 0, hidden_mask); break; } case BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN: // Select cargo filtering criteria dropdown menu ShowDropDownMenu(this, this->cargo_filter_texts, this->cargo_filter_criteria, BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN, 0, 0); break; case BUILD_VEHICLE_WIDGET_BUILD: { EngineID sel_eng = this->sel_engine; if (sel_eng != INVALID_ENGINE) { CommandCallback *callback = (this->vehicle_type == VEH_TRAIN && RailVehInfo(sel_eng)->railveh_type == RAILVEH_WAGON) ? CcBuildWagon : CcBuildPrimaryVehicle; DoCommandP(this->window_number, sel_eng, 0, GetCmdBuildVeh(this->vehicle_type), callback); } break; } case BUILD_VEHICLE_WIDGET_RENAME: { EngineID sel_eng = this->sel_engine; if (sel_eng != INVALID_ENGINE) { this->rename_engine = sel_eng; SetDParam(0, sel_eng); ShowQueryString(STR_ENGINE_NAME, STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type, MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS); } break; } } } /** * Some data on this window has become invalid. * @param data Information about the changed data. * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details. */ virtual void OnInvalidateData(int data = 0, bool gui_scope = true) { if (!gui_scope) return; /* When switching to original acceleration model for road vehicles, clear the selected sort criteria if it is not available now. */ if (this->vehicle_type == VEH_ROAD && _settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL && this->sort_criteria > 7) { this->sort_criteria = 0; _last_sort_criteria[VEH_ROAD] = 0; } this->eng_list.ForceRebuild(); } virtual void SetStringParameters(int widget) const { switch (widget) { case BUILD_VEHICLE_WIDGET_CAPTION: if (this->vehicle_type == VEH_TRAIN && !this->listview_mode) { const RailtypeInfo *rti = GetRailTypeInfo(this->filter.railtype); SetDParam(0, rti->strings.build_caption); } else { SetDParam(0, (this->listview_mode ? STR_VEHICLE_LIST_AVAILABLE_TRAINS : STR_BUY_VEHICLE_TRAIN_ALL_CAPTION) + this->vehicle_type); } break; case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN: SetDParam(0, _sort_listing[this->vehicle_type][this->sort_criteria]); break; case BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN: SetDParam(0, this->cargo_filter_texts[this->cargo_filter_criteria]); } } virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) { switch (widget) { case BUILD_VEHICLE_WIDGET_LIST: resize->height = GetEngineListHeight(this->vehicle_type); size->height = 3 * resize->height; break; case BUILD_VEHICLE_WIDGET_PANEL: size->height = this->details_height; break; case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING: { Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data); d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better. d.height += padding.height; *size = maxdim(*size, d); break; } } } virtual void DrawWidget(const Rect &r, int widget) const { switch (widget) { case BUILD_VEHICLE_WIDGET_LIST: DrawEngineList(this->vehicle_type, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, &this->eng_list, this->vscroll->GetPosition(), min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->eng_list.Length()), this->sel_engine, false, DEFAULT_GROUP); break; case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING: this->DrawSortButtonState(BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING, this->descending_sort_order ? SBS_DOWN : SBS_UP); break; } } virtual void OnPaint() { this->GenerateBuildList(); this->vscroll->SetCount(this->eng_list.Length()); this->DrawWidgets(); if (!this->IsShaded()) { int needed_height = this->details_height; /* Draw details panels. */ if (this->sel_engine != INVALID_ENGINE) { NWidgetBase *nwi = this->GetWidget<NWidgetBase>(BUILD_VEHICLE_WIDGET_PANEL); int text_end = DrawVehiclePurchaseInfo(nwi->pos_x + WD_FRAMETEXT_LEFT, nwi->pos_x + nwi->current_x - WD_FRAMETEXT_RIGHT, nwi->pos_y + WD_FRAMERECT_TOP, this->sel_engine); needed_height = max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM); } if (needed_height != this->details_height) { // Details window are not high enough, enlarge them. int resize = needed_height - this->details_height; this->details_height = needed_height; this->ReInit(0, resize); return; } } } virtual void OnQueryTextFinished(char *str) { if (str == NULL) return; DoCommandP(0, this->rename_engine, 0, CMD_RENAME_ENGINE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN_TYPE + this->vehicle_type), NULL, str); } virtual void OnDropdownSelect(int widget, int index) { switch (widget) { case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN: if (this->sort_criteria != index) { this->sort_criteria = index; _last_sort_criteria[this->vehicle_type] = this->sort_criteria; this->eng_list.ForceRebuild(); } break; case BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN: // Select a cargo filter criteria if (this->cargo_filter_criteria != index) { this->cargo_filter_criteria = index; _last_filter_criteria[this->vehicle_type] = this->cargo_filter[this->cargo_filter_criteria]; /* deactivate filter if criteria is 'Show All', activate it otherwise */ this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY); this->eng_list.ForceRebuild(); } break; } this->SetDirty(); } virtual void OnResize() { this->vscroll->SetCapacityFromWidget(this, BUILD_VEHICLE_WIDGET_LIST); this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START); } }; static const WindowDesc _build_vehicle_desc( WDP_AUTO, 240, 268, WC_BUILD_VEHICLE, WC_NONE, WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION, _nested_build_vehicle_widgets, lengthof(_nested_build_vehicle_widgets) ); void ShowBuildVehicleWindow(TileIndex tile, VehicleType type) { /* We want to be able to open both Available Train as Available Ships, * so if tile == INVALID_TILE (Available XXX Window), use 'type' as unique number. * As it always is a low value, it won't collide with any real tile * number. */ uint num = (tile == INVALID_TILE) ? (int)type : tile; assert(IsCompanyBuildableVehicleType(type)); DeleteWindowById(WC_BUILD_VEHICLE, num); new BuildVehicleWindow(&_build_vehicle_desc, tile, type); }
34.739855
301
0.728208
trademarks
605e265b864bd9d680900d13c2b8b4d4909505c8
1,320
hpp
C++
src/FrozenWasteland.hpp
miRackModular/FrozenWasteland
2e21f41cb121c2a4036b509a26061bf7981d4d9a
[ "CC0-1.0" ]
null
null
null
src/FrozenWasteland.hpp
miRackModular/FrozenWasteland
2e21f41cb121c2a4036b509a26061bf7981d4d9a
[ "CC0-1.0" ]
null
null
null
src/FrozenWasteland.hpp
miRackModular/FrozenWasteland
2e21f41cb121c2a4036b509a26061bf7981d4d9a
[ "CC0-1.0" ]
null
null
null
#include "rack.hpp" using namespace rack; extern Plugin *pluginInstance; extern Model *modelBPMLFO; extern Model *modelBPMLFO2; extern Model *modelBPMLFOPhaseExpander; extern Model *modelDamianLillard; extern Model *modelEverlastingGlottalStopper; extern Model *modelHairPick; extern Model *modelLissajousLFO; extern Model *modelMrBlueSky; extern Model *modelTheOneRingModulator; extern Model *modelPhasedLockedLoop; extern Model *modelPortlandWeather; extern Model *modelProbablyNote; //extern Model *modelProbablyNoteArabic; extern Model *modelProbablyNoteBP; //extern Model *modelProbablyNoteIndian; extern Model *modelPNChordExpander; extern Model *modelQuadAlgorithmicRhythm; extern Model *modelQARGrooveExpander; extern Model *modelQARProbabilityExpander; extern Model *modelQuantussyCell; extern Model *modelSeedsOfChange; extern Model *modelSeedsOfChangeCVExpander; extern Model *modelSeedsOfChangeGateExpander; extern Model *modelStringTheory; extern Model *modelRouletteLFO; extern Model *modelSeriouslySlowLFO; extern Model *modelVoxInhumana; extern Model *modelVoxInhumanaExpander; extern Model *modelCDCSeriouslySlowLFO; namespace old { extern Model *modelLissajousLFO_old; extern Model *modelRouletteLFO_old; extern Model *modelQuadGolombRulerRhythm_old; extern Model *modelQuadEuclideanRhythm_old; }
30
45
0.852273
miRackModular
605e4b58ca412594170dcd9f6562cfb13e8dde7f
3,025
ipp
C++
implement/oglplus/enums/precision_type_def.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/oglplus/enums/precision_type_def.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
implement/oglplus/enums/precision_type_def.ipp
jnbrq/oglplus
2e072e91292643e0871565ae5147584403846290
[ "BSL-1.0" ]
null
null
null
// File implement/oglplus/enums/precision_type_def.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/precision_type.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2017 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif #if defined GL_LOW_FLOAT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined LowFloat # pragma push_macro("LowFloat") # undef LowFloat OGLPLUS_ENUM_CLASS_VALUE(LowFloat, GL_LOW_FLOAT) # pragma pop_macro("LowFloat") # else OGLPLUS_ENUM_CLASS_VALUE(LowFloat, GL_LOW_FLOAT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_MEDIUM_FLOAT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined MediumFloat # pragma push_macro("MediumFloat") # undef MediumFloat OGLPLUS_ENUM_CLASS_VALUE(MediumFloat, GL_MEDIUM_FLOAT) # pragma pop_macro("MediumFloat") # else OGLPLUS_ENUM_CLASS_VALUE(MediumFloat, GL_MEDIUM_FLOAT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_HIGH_FLOAT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined HighFloat # pragma push_macro("HighFloat") # undef HighFloat OGLPLUS_ENUM_CLASS_VALUE(HighFloat, GL_HIGH_FLOAT) # pragma pop_macro("HighFloat") # else OGLPLUS_ENUM_CLASS_VALUE(HighFloat, GL_HIGH_FLOAT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_LOW_INT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined LowInt # pragma push_macro("LowInt") # undef LowInt OGLPLUS_ENUM_CLASS_VALUE(LowInt, GL_LOW_INT) # pragma pop_macro("LowInt") # else OGLPLUS_ENUM_CLASS_VALUE(LowInt, GL_LOW_INT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_MEDIUM_INT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined MediumInt # pragma push_macro("MediumInt") # undef MediumInt OGLPLUS_ENUM_CLASS_VALUE(MediumInt, GL_MEDIUM_INT) # pragma pop_macro("MediumInt") # else OGLPLUS_ENUM_CLASS_VALUE(MediumInt, GL_MEDIUM_INT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #if defined GL_HIGH_INT # ifdef OGLPLUS_LIST_NEEDS_COMMA OGLPLUS_ENUM_CLASS_COMMA # endif # if defined HighInt # pragma push_macro("HighInt") # undef HighInt OGLPLUS_ENUM_CLASS_VALUE(HighInt, GL_HIGH_INT) # pragma pop_macro("HighInt") # else OGLPLUS_ENUM_CLASS_VALUE(HighInt, GL_HIGH_INT) # endif # ifndef OGLPLUS_LIST_NEEDS_COMMA # define OGLPLUS_LIST_NEEDS_COMMA 1 # endif #endif #ifdef OGLPLUS_LIST_NEEDS_COMMA # undef OGLPLUS_LIST_NEEDS_COMMA #endif
26.077586
62
0.798347
jnbrq
60652138789f318acbf8aaba47d8cf518ef89802
1,121
hh
C++
include/trick/MTV.hh
dexueyang/trick-dup0
2d5d5502fa896d3c42eda40ce0ee45e98ec35463
[ "NASA-1.3" ]
null
null
null
include/trick/MTV.hh
dexueyang/trick-dup0
2d5d5502fa896d3c42eda40ce0ee45e98ec35463
[ "NASA-1.3" ]
null
null
null
include/trick/MTV.hh
dexueyang/trick-dup0
2d5d5502fa896d3c42eda40ce0ee45e98ec35463
[ "NASA-1.3" ]
3
2021-06-22T11:02:39.000Z
2021-10-21T00:58:00.000Z
#ifndef MTV_HH #define MTV_HH #include <string> #include "trick/IPPythonEvent.hh" namespace Trick { class MTV { public: MTV() ; Trick::IPPythonEvent dummy_event ; /**< trick_io(*io) trick_units(--) */ Trick::IPPythonEvent ** mtv_list ; /**< trick_io(*io) trick_units(--) */ /** Count of user events to be displayed by mtv.\n */ unsigned int mtv_count ; /**< trick_io(*io) trick_units(--) */ /** Running count of last new event or event deletion, so mtv knows when to update.\n */ int mtv_update_ticker; /**< trick_io(*io) trick_units(--) */ int add_event ( Trick::IPPythonEvent * in_event ) ; int delete_event ( Trick::IPPythonEvent * in_event ) ; Trick::IPPythonEvent * get_event ( std::string event_name ) ; int send_event_data() ; } ; } int mtv_add_event(Trick::IPPythonEvent * in_event) ; int mtv_delete_event(Trick::IPPythonEvent * in_event) ; Trick::IPPythonEvent * mtv_get_event(std::string event_name) ; int mtv_send_event_data() ; #endif
26.690476
96
0.607493
dexueyang
60671f89364864ec9dea61361a7a3a8f7fe65f6a
1,822
hpp
C++
DDMallocDetector/MallocDetector/Classes/detector/MallocCollectorHelper.hpp
djs66256/DDMallocDetector
f719cdb7abbd8c9590c0fdb68361b943c1674adf
[ "BSD-2-Clause" ]
10
2018-04-08T16:37:17.000Z
2021-07-13T11:04:38.000Z
DDMallocDetector/MallocDetector/Classes/detector/MallocCollectorHelper.hpp
djs66256/DDMallocDetector
f719cdb7abbd8c9590c0fdb68361b943c1674adf
[ "BSD-2-Clause" ]
null
null
null
DDMallocDetector/MallocDetector/Classes/detector/MallocCollectorHelper.hpp
djs66256/DDMallocDetector
f719cdb7abbd8c9590c0fdb68361b943c1674adf
[ "BSD-2-Clause" ]
2
2019-02-13T09:21:41.000Z
2021-07-13T11:04:41.000Z
// // MallocCollectorHelper.hpp // cfunction // // Created by hzduanjiashun on 2018/3/28. // Copyright © 2018年 Daniel. All rights reserved. // #ifndef MallocCollectorHelper_hpp #define MallocCollectorHelper_hpp #include <stdio.h> #include <memory> #include <malloc/malloc.h> #include "MallocMemory.hpp" namespace MD { namespace CollectorDefault { template <class _S> struct CollectorChecker { static int64_t max() { return 1024*1024; } static void overflow(_S* storage) { } }; } template <class _S, class _I, class _C = CollectorDefault::CollectorChecker<_S>> class Collector { public: typedef _S storage_type; typedef _I item_type; typedef _C checker_type; Collector(storage_type* s) : s_(s) { i_.start(); } Collector& setZone(malloc_zone_t *z) { i_.zone = z; return *this; } Collector& setAction(Action act) { i_.action = act; return *this; } Collector& setSize(std::int64_t size) { i_.size = size; return *this; } Collector& set(malloc_zone_t *z, Action act, std::int64_t size) { i_.zone = z; i_.action = act; i_.size = size; return *this; } ~Collector() { i_.stop(); int64_t cnt = s_->collect(std::move(i_)); if (cnt > checker_type::max()) { checker_type::overflow(s_); } } private: storage_type* s_; item_type i_; }; } #endif /* MallocCollectorHelper_hpp */
22.775
84
0.502195
djs66256
6068bfd22ae93d26a163098241f831908c014575
6,504
cxx
C++
PMD/anal/AliPMDOfflineCalibTask.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
PMD/anal/AliPMDOfflineCalibTask.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
PMD/anal/AliPMDOfflineCalibTask.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /************************************ * AliPMD offline calibration task * * Satyajit Jena, IIT Bombay * sjena@cern.ch * Fri Feb 12 13:30:19 IST 2010 * ************************************/ #include "TChain.h" #include "TList.h" #include "TFile.h" #include "TTree.h" #include "TH1F.h" #include "TCanvas.h" #include "AliAnalysisTask.h" #include "AliAnalysisManager.h" #include "AliVEvent.h" #include "AliESD.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "TObjArray.h" #include "AliPMDOfflineCalibTask.h" ClassImp(AliPMDOfflineCalibTask) //________________________________________________________________________ AliPMDOfflineCalibTask::AliPMDOfflineCalibTask(const char *name) : AliAnalysisTaskSE(name), fListOfHistos(0), fPmdCalibAdcP(0), fPmdCalibAdcC(0), fPmdCalibEntP(0), fPmdCalibEntC(0), fNEvents(0), fSelectedTrigger(new TObjArray()), fRejected(kTRUE) { // Constructor DefineOutput(1, TList::Class()); } //________________________________________________________________________ void AliPMDOfflineCalibTask::UserCreateOutputObjects() { fListOfHistos = new TList(); fNEvents = new TH1I("hNEvents","Events Statistic", 3, 0, 5); fPmdCalibAdcP = new TH1F("fPmdCalibAdcP", "PMD Calibration ADC fill for PRE", 234795, 0, 234795); fPmdCalibAdcP->GetYaxis()->SetTitle("ADC"); fPmdCalibAdcP->GetXaxis()->SetTitle("Cells in SMN-ROW-COL"); fPmdCalibAdcC = new TH1F("fPmdCalibAdcC", "PMD Calibration ADC fill for CPV", 234795, 0, 234795); fPmdCalibAdcC->GetYaxis()->SetTitle("ADC"); fPmdCalibAdcC->GetXaxis()->SetTitle("Cells in SMN-ROW-COL"); fPmdCalibEntP = new TH1F("fPmdCalibEntP", "PMD Calibration Entries fill for PRE", 234795, 0, 234795); fPmdCalibEntP->GetYaxis()->SetTitle("Frequescy"); fPmdCalibEntP->GetXaxis()->SetTitle("Cells in SMN-ROW-COL"); fPmdCalibEntC = new TH1F("fPmdCalibEntC", "PMD Calibration Entries fill for CPV", 234795, 0, 234795); fPmdCalibEntC->GetYaxis()->SetTitle("Frequescy "); fPmdCalibEntC->GetXaxis()->SetTitle("Cells in SMN-ROW-COL"); fListOfHistos->Add(fPmdCalibAdcP); fListOfHistos->Add(fPmdCalibAdcC); fListOfHistos->Add(fPmdCalibEntP); fListOfHistos->Add(fPmdCalibEntC); fListOfHistos->Add(fNEvents); } //________________________________________________________________________ void AliPMDOfflineCalibTask::UserExec(Option_t *) { AliVEvent *event = InputEvent(); if (!event) { Printf("ERROR: Could not retrieve event"); return; } fNEvents->Fill(1); AliESDEvent* pmdesd = dynamic_cast<AliESDEvent*>(event); if(!pmdesd) return; fNEvents->Fill(2); Bool_t pass = kTRUE; Int_t numberOfTriggerSelected = fSelectedTrigger->GetEntriesFast(); if(fRejected) { pass = kTRUE; for(Int_t k = 0; k < numberOfTriggerSelected; k++) { const TObjString *const obString = (TObjString*)fSelectedTrigger->At(k); const TString tString = obString->GetString(); if(pmdesd->IsTriggerClassFired((const char*)tString)) { pass = kFALSE; } } } else { pass = kFALSE; for(Int_t k = 0; k < numberOfTriggerSelected; k++) { const TObjString *const obString=(TObjString*)fSelectedTrigger->At(k); const TString tString = obString->GetString(); if(pmdesd->IsTriggerClassFired((const char*)tString)) { pass = kTRUE; } } } if(!pass) { PostData(1, fListOfHistos); return; } fNEvents->Fill(3); Int_t npmdcl = pmdesd->GetNumberOfPmdTracks(); if(npmdcl < 1) fNEvents->Fill(4); while (npmdcl--) { AliESDPmdTrack *pmdtr = pmdesd->GetPmdTrack(npmdcl); Int_t det = pmdtr->GetDetector(); Int_t smn = pmdtr->GetSmn(); Float_t adc = pmdtr->GetClusterADC(); Float_t sTag = pmdtr->GetClusterSigmaX(); Float_t sRowCol = pmdtr->GetClusterSigmaY(); Float_t rc = smn*10000 + sRowCol; if(adc > 1200.) continue; if(sTag > 999. && sTag < 1000.) { if(det == 0) { fPmdCalibAdcP->Fill(rc,adc); fPmdCalibEntP->Fill(rc); } else if(det == 1) { fPmdCalibAdcC->Fill(rc,adc); fPmdCalibEntC->Fill(rc); } } } PostData(1, fListOfHistos); } //________________________________________________________________________ void AliPMDOfflineCalibTask::Terminate(Option_t *) { fListOfHistos = dynamic_cast<TList*>(GetOutputData(1)); fPmdCalibAdcP = dynamic_cast<TH1F*>(fListOfHistos->At(0)); if(!fPmdCalibAdcP) { printf("ERROR: No ADC File Generated for PMD-PRE "); return; } fPmdCalibAdcC = dynamic_cast<TH1F*>(fListOfHistos->At(1)); if(!fPmdCalibAdcC) { printf("ERROR: No ADC File Generated for PMD-CPV "); return; } fPmdCalibEntP = dynamic_cast<TH1F*>(fListOfHistos->At(2)); if(!fPmdCalibEntP) { printf("ERROR: No Entry File Generated for PMD-PRE "); printf(" No fhXyPRE "); return; } fPmdCalibEntC = dynamic_cast<TH1F*>(fListOfHistos->At(3)); if(!fPmdCalibEntC) { printf("ERROR: No Entry File Generated for PMD-CPV "); return; } fNEvents = dynamic_cast<TH1I*>(fListOfHistos->At(4)); if(!fNEvents) { printf("ERROR: No Entry File Generated for Event Counter "); return; } Info("AliPMDOfflineCalibTask","PMD offline Calibration Successfully finished"); }
29.165919
103
0.628998
AllaMaevskaya
60695c9676c50e738917c4abd03ecb8d3dd5beea
671
cpp
C++
Excercises_Source/2.Bitfields.cpp
ChenpoHU/C-Excercies_OOP
b009b5a8da82fda6b3918f9f77b1d62ad0a1f876
[ "MIT" ]
null
null
null
Excercises_Source/2.Bitfields.cpp
ChenpoHU/C-Excercies_OOP
b009b5a8da82fda6b3918f9f77b1d62ad0a1f876
[ "MIT" ]
null
null
null
Excercises_Source/2.Bitfields.cpp
ChenpoHU/C-Excercies_OOP
b009b5a8da82fda6b3918f9f77b1d62ad0a1f876
[ "MIT" ]
null
null
null
#include <iostream> struct BitFieldStruct { unsigned int a : 4; unsigned int b : 3; }; int main() { BitFieldStruct x; x.a = 06; x.b = x.a | 3; // | bitwise OR, || logical OR ; & bitwise AND, && logicalwise AND std::cout << x.a << '\n' << std::endl;// converted to unsigned and then displayed std::cout << x.b << '\n' << std::endl;// converted to unsigned and then displayed } // 0 1 1 is 3 // 1 1 0 is 6 bitwise OR of 3 and 6 is: // 1 1 1 is 7 //may save space but cost time in comparison to byte alignment // bitwise logical // OR | || //AND & && //XOR ^ != //NEG ~ !
25.807692
83
0.520119
ChenpoHU
606a40d66e7f65605f06cce15bba65817f404485
1,240
cpp
C++
extras/lib_info/SdFat_Gre/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp
UTSAAH/Dhwani-HA_Library
f182d8b6571d48b1e506637684844eb12e0a791c
[ "MIT" ]
181
2019-09-20T15:49:09.000Z
2022-03-23T01:27:29.000Z
Transmitters/Old Version/X_CTRL_STM32F4xx/X_CTRL_GUN/Libraries/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp
DogDod/X-CTRL
683ffe3b40222e1da6ff156b6595c691cd09fec1
[ "MIT" ]
7
2020-03-06T19:37:07.000Z
2020-05-05T20:33:32.000Z
Transmitters/Old Version/X_CTRL_STM32F4xx/X_CTRL_GUN/Libraries/SdFat/examples/LowLatencyLoggerMPU6050/UserFunctions.cpp
DogDod/X-CTRL
683ffe3b40222e1da6ff156b6595c691cd09fec1
[ "MIT" ]
75
2019-10-25T02:53:27.000Z
2022-03-23T01:25:00.000Z
// User data functions. Modify these functions for your data items. #include "UserTypes.h" #include "Wire.h" #include "I2Cdev.h" #include "MPU6050.h" //------------------------------------------------------------------------------ MPU6050 mpu; static uint32_t startMicros; // Acquire a data record. void acquireData(data_t* data) { data->time = micros(); mpu.getMotion6(&data->ax, &data->ay, &data->az, &data->gx, &data->gy, &data->gz); } // setup AVR I2C void userSetup() { #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE Wire.begin(); Wire.setClock(400000); #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE Fastwire::setup(400, true); #endif mpu.initialize(); } // Print a data record. void printData(Print* pr, data_t* data) { if (startMicros == 0) { startMicros = data->time; } pr->print(data->time- startMicros); pr->write(','); pr->print(data->ax); pr->write(','); pr->print(data->ay); pr->write(','); pr->print(data->az); pr->write(','); pr->print(data->gx); pr->write(','); pr->print(data->gy); pr->write(','); pr->println(data->gz); } // Print data header. void printHeader(Print* pr) { startMicros = 0; pr->println(F("micros,ax,ay,az,gx,gy,gz")); }
23.846154
80
0.592742
UTSAAH
606cea24b8145cd4923cac5f70c31f32aef2378f
5,886
hpp
C++
src/Utils/Constantes.hpp
brunograssano/SuperMarioBros-Honguitos
f945e434bc317a6d8c8d682b1042d8a385929156
[ "MIT" ]
4
2021-02-21T17:12:46.000Z
2021-02-25T20:36:27.000Z
src/Utils/Constantes.hpp
brunograssano/SuperMarioBros-Honguitos
f945e434bc317a6d8c8d682b1042d8a385929156
[ "MIT" ]
null
null
null
src/Utils/Constantes.hpp
brunograssano/SuperMarioBros-Honguitos
f945e434bc317a6d8c8d682b1042d8a385929156
[ "MIT" ]
2
2021-02-20T19:49:33.000Z
2021-02-25T20:35:22.000Z
#ifndef TP_TALLER_DE_PROGRAMACION_FIUBA_CONSTANTES_HPP #define TP_TALLER_DE_PROGRAMACION_FIUBA_CONSTANTES_HPP #include <stdint.h> const int ANCHO_FONDO = 8177; #define VALOR_POR_DEFECTO_ANCHO 800 #define VALOR_POR_DEFECTO_ALTO 600 #define TIEMPO_ESPERA_GAME_LOOP 5 #define IZQUIERDA 1 #define DERECHA 2 #define ARRIBA 3 #define ABAJO 4 #define MAX_CONEXIONES 4 #define SIN_JUGAR (-1) #define LARGO_IP 20 //=======================================================// //==================== COLISIONES =======================// #define COLISION_ID_MARIO "Mario" #define COLISION_ID_KOOPA "Koopa" #define COLISION_ID_GOOMBA "Goomba" #define COLISION_ID_MONEDA "Moneda" #define COLISION_ID_LADRILLO "Ladrillo" #define COLISION_ID_SORPRESA "Sorpresa" #define COLISION_ID_FLOR "Flor" #define COLISION_ID_MONEDA_FLOTANTE "Moneda flotante" #define COLISION_ID_BOLA_DE_FUEGO "Bola de fuego" #define COLISION_ID_CHISPA "Chispa" #define COLISION_ID_NADA "Nada" #define COLISION_ID_PLATAFORMA "Plataforma" #define COLISION_ID_PIEZA_TUBERIA "Pieza tuberia" //=======================================================// //====================== MEDIDAS ========================// const int PUNTOS_KOOPA = 1000; const int PUNTOS_GOOMBA = 500; const int PUNTOS_POR_MONEDA = 50; const int ANCHO_POZO = 200, ALTO_POZO = 65; const int ALTO_MARIO = 80, ANCHO_MARIO = 40, ALTO_MARIO_AGACHADO = 55; const int ALTO_ENEMIGOS = 40, ANCHO_ENEMIGOS = 40; const int RANGO_EXTRA_ENEMIGOS = ANCHO_ENEMIGOS*2; const int LARGO_BLOQUE = 40; const int LARGO_MONEDA = 40; const int ALTO_FLOR = 40, ANCHO_FLOR = 40; const int ALTO_BOLA = 20, ANCHO_BOLA = 20; const int ALTO_CHISPA = 44, ANCHO_CHISPA = 64; const int ALTO_TUBERIA_CHICA = 90, ANCHO_TUBERIA_CHICA = 90; const int ALTO_TUBERIA_GRANDE = ALTO_TUBERIA_CHICA*2, ANCHO_TUBERIA_GRANDE = ANCHO_TUBERIA_CHICA*2; const uint8_t SIN_MODIFICADOR = 0, MODIFICADOR_FUEGO = 1; #define TUBERIA_CHICA 0 #define TUBERIA_GRANDE 1 #define COLORES_BLOQUES_POSIBLES 7 #define ESTADOS_BLOQUE 5 #define ESTADOS_MONEDA 4 #define ESTADOS_GOOMBA 3 #define COLORES_GOOMBA_POSIBLES 4 #define ESTADOS_KOOPA 6 #define COLORES_KOOPA_POSIBLES 5 //=======================================================// //====================== ENTIDADES ======================// const uint8_t NADA = 0; const uint8_t GOOMBA = 1; const uint8_t KOOPA = 2; const uint8_t BOLA_DE_FUEGO = 3; const uint8_t CHISPA = 4; const uint8_t FLOR = 5; const uint8_t MONEDA_FLOTANTE = 6; const uint8_t MONEDA = 7; const uint8_t BLOQUE = 8; const uint8_t TUBERIA = 9; const uint8_t POZO = 10; const uint8_t FONDO_POZO = 11; const uint8_t MARIO_RECORTE = 12; const int ENEMIGOS_RECORTE = 12; const int EFECTOS_RECORTE = 13; //=======================================================// //====================== TEXTURAS =======================// #define CLAVE_TEXTURA_POZO "Pozo" #define CLAVE_TEXTURA_MONEDA "Moneda" #define CLAVE_TEXTURA_FONDO_INICIO "FondoInicio" #define CLAVE_TEXTURA_TITULO "Titulo" #define CLAVE_TEXTURA_GAMEOVER "FondoGameOver" #define CLAVE_TEXTURA_COFFIN_MARIO "Coffin" #define CLAVE_TEXTURA_TUBERIAS "Tuberia" #define CLAVE_TEXTURA_CORAZON "Corazon" #define CLAVE_TEXTURA_BOLA_DE_FUEGO "BolaDeFuego" #define CLAVE_TEXTURA_CHISPA "Chispa" #define CLAVE_TEXTURA_FLOR "Flor" #define CLAVE_TEXTURA_MONEDA_FLOTANTE "MonedaFlotante" #define CLAVE_TEXTURA_BLOQUES "Bloques" #define CLAVE_TEXTURA_GOOMBA "Goombas" #define CLAVE_TEXTURA_KOOPAS "Koopas" #define CLAVE_TEXTURA_PEACH_SALTANDO "PeachSaltando" #define CLAVE_TEXTURA_TOAD_SALTANDO "ToadSaltando" #define CLAVE_TEXTURA_YOSHI_SALTANDO "YoshiSaltando" #define CLAVE_TEXTURA_MARIO_SALTANDO "MarioSaltando" #define CLAVE_TEXTURA_FONDO_POZO "FondoPozo" //=======================================================// //====================== MUSICA =========================// #define MUSICA_VICTORIA "resources/Musica/MusicaVictoria.mp3" #define MUSICA_GAMEOVER "resources/Musica/CoffinDance8Bits.mp3" #define MUSICA_INICIO "resources/Musica/MusicaInicio.mp3" #define MUSICA_NIVEL1 "resources/Musica/TemaNivel1.mp3" #define MUSICA_MODO_DIEGO "resources/Musica/LiveisLife.mp3" //=======================================================// //====================== SONIDOS ========================// const uint8_t NO_SONAR = 0; const uint8_t SONIDO_SALTO = 1; const uint8_t SONIDO_AGARRAR_MONEDA = 2; const uint8_t SONIDO_MATAR_GOOMBA = 3; const uint8_t SONIDO_MATAR_KOOPA = 4; const uint8_t SONIDO_APARECE_FLOR = 5; const uint8_t SONIDO_AGARRA_POWERUP = 6; const uint8_t SONIDO_MORIR = 7; const uint8_t SONIDO_LANZAR_BOLA_DE_FUEGO = 8; const uint8_t SONIDO_LANZAR_CHISPA = 9; const uint8_t SONIDO_REBOTE_BOLA_DE_FUEGO = 10; const uint8_t SONIDO_EXPLOSION_BOLA_DE_FUEGO = 11; const uint8_t SONIDO_LLEGAR_A_LA_META = 12; #define DIRECCION_SONIDO_SALTO "resources/Musica/EfectosSonido/EfectoSalto.wav" #define DIRECCION_SONIDO_AGARRAR_MONEDA "resources/Musica/EfectosSonido/AgarrarMoneda.wav" #define DIRECCION_SONIDO_MUERTE_GOOMBA "resources/Musica/EfectosSonido/MarioMataGoomba.wav" #define DIRECCION_SONIDO_MUERTE_KOOPA "resources/Musica/EfectosSonido/MarioPisaKoopa.wav" #define DIRECCION_SONIDO_APARECE_PLANTA "resources/Musica/EfectosSonido/AparecePlanta.wav" #define DIRECCION_SONIDO_MARIO_AGARRA_HONGO "resources/Musica/EfectosSonido/MarioAgarraHongo.wav" #define DIRECCION_SONIDO_MARIO_MUERE "resources/Musica/EfectosSonido/MarioMorir.wav" #define DIRECCION_SONIDO_MARIO_LANZA_FUEGO "resources/Musica/EfectosSonido/MarioLanzaFuego.wav" #define DIRECCION_SONIDO_CHISPA "resources/Musica/EfectosSonido/Chispazo.wav" #define DIRECCION_SONIDO_REBOTE "resources/Musica/EfectosSonido/ReboteBolaDeFuego.wav" #define DIRECCION_SONIDO_EXPLOSION "resources/Musica/EfectosSonido/ExplosionBolaDeFuego.wav" #define DIRECCION_SONIDO_PASAR_NIVEL "resources/Musica/EfectosSonido/PasarDeNivel.wav" #endif //TP_TALLER_DE_PROGRAMACION_FIUBA_CONSTANTES_HPP
39.503356
99
0.74227
brunograssano
606ffb194da6ff4a1ca462fd0eaf631574c13785
1,074
cpp
C++
math/normal3.cpp
masrtis/eyebeam
a9ea111c7958838c19c0b26ea1961f119b4f91f1
[ "MIT" ]
null
null
null
math/normal3.cpp
masrtis/eyebeam
a9ea111c7958838c19c0b26ea1961f119b4f91f1
[ "MIT" ]
4
2020-12-13T14:55:24.000Z
2021-03-10T01:47:36.000Z
math/normal3.cpp
masrtis/eyebeam
a9ea111c7958838c19c0b26ea1961f119b4f91f1
[ "MIT" ]
null
null
null
#include "normal3.h" #include <cmath> #include <ostream> namespace eyebeam { Normal3 operator+(const Normal3& lhs, const Normal3& rhs) { auto result(lhs); result += rhs; return result; } Normal3 operator-(const Normal3& lhs, const Normal3& rhs) { auto result(lhs); result -= rhs; return result; } Normal3 operator*(const Normal3& lhs, float rhs) { auto result(lhs); result *= rhs; return result; } Normal3 operator*(float lhs, const Normal3& rhs) { auto result(rhs); result *= lhs; return result; } Normal3 operator/(const Normal3& lhs, float rhs) { auto result(lhs); result /= rhs; return result; } float length(const Normal3& normal) { return std::sqrt(lengthSquared(normal)); } void normalize(Normal3& normal) { normal /= length(normal); } Normal3 norm(Normal3 normal) { normalize(normal); return normal; } std::ostream& operator<<(std::ostream& os, const Normal3& out) { os << "(" << out.x() << ", " << out.y() << ", " << out.z() << ")"; return os; } } // namespace eyebeam
16.029851
70
0.623836
masrtis
6072d2fe54028b06e9ebadf3c78dda234ef29f64
15,068
cpp
C++
http/gzip_mem.cpp
hdsy/public
20ee6559ba4f84a2356785fc53b54c1a4dcdf354
[ "Apache-2.0" ]
null
null
null
http/gzip_mem.cpp
hdsy/public
20ee6559ba4f84a2356785fc53b54c1a4dcdf354
[ "Apache-2.0" ]
null
null
null
http/gzip_mem.cpp
hdsy/public
20ee6559ba4f84a2356785fc53b54c1a4dcdf354
[ "Apache-2.0" ]
1
2020-05-10T23:42:34.000Z
2020-05-10T23:42:34.000Z
#include <stdio.h> #include <zlib.h> #include <string.h> #include <stdlib.h> #include "gzip_mem.h" #define OF(args) args #define OS_CODE 3 // unix #if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 #else # define DEF_MEM_LEVEL MAX_MEM_LEVEL #endif /* default memLevel */ #define Z_BUFSIZE 16384 #define ALLOC(size) malloc( size ) #define TRYFREE(p) free( p ) static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */ /* gzip flag byte */ #define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */ #define HEAD_CRC 0x02 /* bit 1 set: header CRC present */ #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */ #define ORIG_NAME 0x08 /* bit 3 set: original file name present */ #define COMMENT 0x10 /* bit 4 set: file comment present */ #define RESERVED 0xE0 /* bits 5..7: reserved */ typedef int ( * XGZFILE_PROC_READ )( void* user_cb , void* , int len ); typedef int ( * XGZFILE_PROC_WRITE )( void* user_cb , const void* , int len ); typedef struct xmem_gzstream { z_stream stream; int z_err; /* error code for last stream operation */ int z_eof; /* set if end of input file */ XGZFILE_PROC_READ proc_read ; XGZFILE_PROC_WRITE proc_write; void* user_cb ; Byte *inbuf; /* input buffer */ Byte *outbuf; /* output buffer */ uLong crc; /* crc32 of uncompressed data */ char *msg; /* error message */ int transparent; /* 1 if input file is not a .gz file */ char mode; /* 'w' or 'r' */ long startpos; /* start of compressed data in file (header skipped) */ } xmem_gzstream; static int get_byte OF((xmem_gzstream *s)); static int check_header OF((xmem_gzstream *s)); /*! return bytes of read. */ static int destroy OF((xmem_gzstream *s)); static void putLong OF((xmem_gzstream *s , uLong x)); static uLong getLong OF((xmem_gzstream *s)); xmem_gzstream* XGZFILE_open( XGZFILE_PROC_READ proc_read , XGZFILE_PROC_WRITE proc_write , void* user_cb , int create_flag , int level ) { int err; int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */ static Byte simpleheader[] = { 0x1f, 0x8b, Z_DEFLATED , 0 , 0 , 0 , 0 , 0 , 0 , OS_CODE }; xmem_gzstream *s; if( (create_flag&&!proc_write) || (!create_flag&&!proc_read) ) return Z_NULL; s = (xmem_gzstream *)ALLOC( sizeof(xmem_gzstream) ); if( !s ) return Z_NULL; s->stream.zalloc = (alloc_func)0; s->stream.zfree = (free_func)0; s->stream.opaque = (voidpf)0; s->stream.next_in = s->inbuf = Z_NULL; s->stream.next_out = s->outbuf = Z_NULL; s->stream.avail_in = s->stream.avail_out = 0; s->proc_read = proc_read ; s->proc_write = proc_write; s->user_cb = user_cb ; s->z_err = Z_OK; s->z_eof = 0; s->crc = crc32(0L, Z_NULL, 0); s->msg = NULL; s->transparent = 0; s->mode = create_flag ? 'w' : 'r'; if( create_flag ) { err = deflateInit2(&(s->stream), level, Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy); s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); if (err != Z_OK || s->outbuf == Z_NULL) { return destroy(s), (xmem_gzstream*)Z_NULL; } } else { s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); err = inflateInit2(&(s->stream), -MAX_WBITS); if (err != Z_OK || s->inbuf == Z_NULL) { return destroy(s), (xmem_gzstream*)Z_NULL; } } s->stream.avail_out = Z_BUFSIZE; if( create_flag ) { s->proc_write( s->user_cb , simpleheader , 10 ); s->startpos = 10L; } else { s->startpos = check_header(s); } return (xmem_gzstream*)s; } int XGZFILE_read ( xmem_gzstream* file , void* buf , int len ) { xmem_gzstream *s = (xmem_gzstream*)file; Bytef *start = (Bytef*)buf; /* starting point for crc computation */ Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */ if( !s || s->mode != 'r' ) return Z_STREAM_ERROR; if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1; if (s->z_err == Z_STREAM_END) return 0; /* -1 */ next_out = (Byte*)buf; s->stream.next_out = (Bytef*)buf; s->stream.avail_out = len; while (s->stream.avail_out != 0) { if (s->transparent) { /* Copy first the lookahead bytes: */ uInt n = s->stream.avail_in; if (n > s->stream.avail_out) n = s->stream.avail_out; if (n > 0) { memcpy(s->stream.next_out, s->stream.next_in, n); next_out += n; s->stream.next_out = next_out; s->stream.next_in += n; s->stream.avail_out -= n; s->stream.avail_in -= n; } if (s->stream.avail_out > 0) { s->stream.avail_out -= s->proc_read( s->user_cb , next_out , s->stream.avail_out ); } len -= s->stream.avail_out; s->stream.total_in += (uLong)len; s->stream.total_out += (uLong)len; if (len == 0) s->z_eof = 1; return (int)len; } if (s->stream.avail_in == 0 && !s->z_eof) { /* errno = 0; */ s->stream.avail_in = s->proc_read( s->user_cb , s->inbuf , Z_BUFSIZE ); if (s->stream.avail_in == 0) { s->z_eof = 1; } s->stream.next_in = s->inbuf; } s->z_err = inflate(&(s->stream), Z_NO_FLUSH); if (s->z_err == Z_STREAM_END) { /* Check CRC and original size */ s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); start = s->stream.next_out; if (getLong(s) != s->crc) { s->z_err = Z_DATA_ERROR; } else { (void)getLong(s); /* The uncompressed length returned by above getlong() may * be different from s->stream.total_out) in case of * concatenated .gz files. Check for such files: */ check_header(s); if (s->z_err == Z_OK) { uLong total_in = s->stream.total_in; uLong total_out = s->stream.total_out; inflateReset(&(s->stream)); s->stream.total_in = total_in; s->stream.total_out = total_out; s->crc = crc32(0L, Z_NULL, 0); } } } if (s->z_err != Z_OK || s->z_eof) break; } s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); return len - s->stream.avail_out ; } int XGZFILE_write( xmem_gzstream* file , const void* buf , int len ) { xmem_gzstream *s = (xmem_gzstream*)file; if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR; s->stream.next_in = (Bytef*)buf; s->stream.avail_in = len; while (s->stream.avail_in != 0) { if (s->stream.avail_out == 0) { s->stream.next_out = s->outbuf; if( s->proc_write( s->user_cb , s->outbuf , Z_BUFSIZE ) != Z_BUFSIZE ) { s->z_err = Z_ERRNO; break; } s->stream.avail_out = Z_BUFSIZE; } s->z_err = deflate(&(s->stream), Z_NO_FLUSH); if (s->z_err != Z_OK) break; } s->crc = crc32(s->crc, (const Bytef *)buf, len); return (int)(len - s->stream.avail_in); } int XGZFILE_flush( xmem_gzstream* file , int flush ) { xmem_gzstream *s = (xmem_gzstream*)file; uInt len; int done = 0; if( !s || s->mode != 'w' ) return Z_STREAM_ERROR; s->stream.avail_in = 0; /* should be zero already anyway */ for (;;) { len = Z_BUFSIZE - s->stream.avail_out; if (len != 0) { if( s->proc_write( s->user_cb , s->outbuf , len ) != (int)len ) { s->z_err = Z_ERRNO; return Z_ERRNO; } s->stream.next_out = s->outbuf; s->stream.avail_out = Z_BUFSIZE; } if (done) break; s->z_err = deflate(&(s->stream), flush); /* Ignore the second of two consecutive flushes: */ if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; /* deflate has finished flushing only when it hasn't used up * all the available space in the output buffer: */ done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; } return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; } int XGZFILE_eof ( xmem_gzstream* file ) { xmem_gzstream *s = (xmem_gzstream*)file; return (s == NULL || s->mode != 'r') ? 0 : s->z_eof; } int XGZFILE_close( xmem_gzstream* file ) { int err; xmem_gzstream *s = (xmem_gzstream*)file; if (s == NULL) return Z_STREAM_ERROR; if (s->mode == 'w') { err = XGZFILE_flush (file, Z_FINISH); if (err != Z_OK) return destroy((xmem_gzstream*)file); putLong (s , s->crc); putLong (s , s->stream.total_in); } return destroy((xmem_gzstream*)file); } static int get_byte (xmem_gzstream *s) { if (s->z_eof) return -1; if (s->stream.avail_in == 0) { /* errno = 0; */ s->stream.avail_in = s->proc_read( s->user_cb , s->inbuf , Z_BUFSIZE ); if (s->stream.avail_in == 0) { s->z_eof = 1; return -1; } s->stream.next_in = s->inbuf; } s->stream.avail_in--; return *(s->stream.next_in)++; } static void putLong (xmem_gzstream *s, uLong x) { int n; char ch; for (n = 0; n < 4; n++) { ch = (char)(x & 0xff); s->proc_write( s->user_cb , &ch , 1 ); x >>= 8; } } static uLong getLong (xmem_gzstream *s) { uLong x = (uLong)get_byte(s); int c; x += ((uLong)get_byte(s))<<8; x += ((uLong)get_byte(s))<<16; c = get_byte(s); if (c == -1) s->z_err = Z_DATA_ERROR; x += ((uLong)c)<<24; return x; } static int destroy (xmem_gzstream *s) { int err = Z_OK; if (!s) return Z_STREAM_ERROR; TRYFREE(s->msg); if (s->stream.state != NULL) { if (s->mode == 'w') { err = deflateEnd(&(s->stream)); } else if (s->mode == 'r') { err = inflateEnd(&(s->stream)); } } if (s->z_err < 0) err = s->z_err; TRYFREE(s->inbuf); TRYFREE(s->outbuf); TRYFREE(s); return err; } static int check_header (xmem_gzstream *s) /*! return bytes of read. */ { int method; /* method byte */ int flags; /* flags byte */ uInt len; int c; int lenret; int ch; /* Check the gzip magic header */ for (len = 0; len < 2; len++) { c = get_byte(s); if (c != gz_magic[len]) { if (len != 0) s->stream.avail_in++, s->stream.next_in--; if (c != -1) { s->stream.avail_in++, s->stream.next_in--; s->transparent = 1; } s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END; return len; } } lenret = 2; method = get_byte(s); if( method != -1 ) ++lenret; flags = get_byte(s); if( flags != -1 ) ++lenret; if (method != Z_DEFLATED || (flags & RESERVED) != 0) { s->z_err = Z_DATA_ERROR; return lenret; } /* Discard time, xflags and OS code: */ for (len = 0; len < 6; len++) { ch = get_byte(s); if( ch != -1 ) ++lenret; else { s->z_err = Z_DATA_ERROR; return lenret; } } if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ ch = get_byte(s); if( ch != -1 ) ++lenret; len = ch; ch = get_byte(s); if( ch != -1 ) ++lenret; len += ((uInt)ch)<<8; /* len is garbage if -1 but the loop below will quit anyway */ while (len-- != 0 && get_byte(s) != -1) ++lenret; } if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ while ((c = get_byte(s)) != 0 && c != -1) ++lenret; } if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ while ((c = get_byte(s)) != 0 && c != -1) ++lenret; } if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ for (len = 0; len < 2; len++) if( get_byte(s) != -1 ) ++lenret; } s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; return lenret; } typedef unsigned char XU8; static XU8 z_input[] = { 0x1F,0x8B,0x08,0x08,0x59,0x96,0x9C,0x46,0x00,0x03,0x74,0x35,0x00,0x2B,0xC9,0xC8 ,0x2C,0x56,0x00,0xA2,0x44,0x85,0x92,0xD4,0xE2,0x12,0x85,0xB4,0xCC,0x9C,0x54,0x5E ,0xAE,0x12,0x4C,0x41,0x00,0x9A,0xA3,0x62,0x77,0x28,0x00,0x00,0x00 }; static XU8 x_text[] = { 0x74,0x68,0x69,0x73,0x20,0x69,0x73,0x20,0x61,0x20,0x74,0x65,0x73,0x74,0x20,0x66 ,0x69,0x6C,0x65,0x0D,0x0A,0x74,0x68,0x69,0x73,0x20,0x69,0x73,0x20,0x61,0x20,0x74 ,0x65,0x73,0x74,0x20,0x66,0x69,0x6C,0x65 }; const static string * pstring = NULL; /* static int X_test_read( void* user_cb , void* buff , int len ) { if( *(int*)user_cb >= sizeof( z_input ) || len <= 0 ) return 0; if( len > (int)(sizeof( z_input ) - *(int*)user_cb) ) len = sizeof( z_input ) - *(int*)user_cb; memcpy( buff , z_input + *(int*)user_cb , len ); *(int*)user_cb += len; return len; } //*/ static int X_test_read( void* user_cb , void* buff , int len ) { if(pstring == NULL) return 0; if( *(int*)user_cb >= pstring->size() || len <= 0 ) return 0; if( len > (int)(pstring->size() - *(int*)user_cb) ) len = pstring->size() - *(int*)user_cb; memcpy( buff , pstring->data() + *(int*)user_cb , len ); *(int*)user_cb += len; return len; } /* int main() { int off = 0 , len; XU8 buff[100]; xmem_gzstream* strm = XGZFILE_open( X_test_read , NULL , &off , 0 , -1 ); len = XGZFILE_read( strm , buff , sizeof( buff ) ); XGZFILE_close( strm ); if( len != sizeof( x_text ) || memcmp( x_text , buff , len ) ) printf( "error\n" ); return 0; } //*/ string GUnzip(const string & zip_mem) { int off = 0 , len; XU8 buff[1024] ; memset(buff,0,sizeof(buff)); string res; pstring = &zip_mem; xmem_gzstream* strm = XGZFILE_open( X_test_read , NULL , &off , 0 , -1 ); while(len = XGZFILE_read( strm , buff , sizeof( buff ) )) { res.append((char *)buff,len); memset(buff,0,sizeof(buff)); } XGZFILE_close( strm ); return res; }
29.837624
88
0.521503
hdsy
6075b9bf5c04375251eb250f9f00a81da9c255f0
1,683
cc
C++
RecoParticleFlow/PFClusterTools/src/Utils.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoParticleFlow/PFClusterTools/src/Utils.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
RecoParticleFlow/PFClusterTools/src/Utils.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "RecoParticleFlow/PFClusterTools/interface/Utils.h" #include <stdio.h> #include <math.h> #include <regex.h> #include <glob.h> #include "TCanvas.h" #include "TVector3.h" using namespace std; using namespace pftools; bool Utils::StringMatch(const char* str, const char* pattern) { int status; regex_t re; if( regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0 ) return false; status = regexec(&re, str, (size_t)0, NULL, 0); regfree(&re); if (status != 0) return false; return true; } TCanvas* Utils::DivideCanvas( TCanvas *cv, int nPads ) { if( !cv ) return 0; if( nPads<=1 ) return cv; int sqnP = (unsigned int) (sqrt( nPads )); int nC = sqnP; int nL = sqnP; while( nC*nL < nPads ) if( nC < nL ) nC++; else nL++; cv->Divide( nC, nL, 0.005, 0.005, 0 ); return cv; } vector<string> Utils::Glob(const char* pattern) { glob_t globbuf; globbuf.gl_offs = 2; glob(pattern, GLOB_TILDE|GLOB_BRACE|GLOB_MARK, NULL, &globbuf); vector<string> results; for(unsigned i=0; i<globbuf.gl_pathc; i++) { results.push_back(globbuf.gl_pathv[i]); } globfree(&globbuf); return results; } string Utils::Date() { string date("date +%d%b%Y_%H%M%S"); FILE *in = popen(date.c_str(), "r"); char result[100]; if(fscanf(in,"%s",result) != EOF) { return string(result); } else return string(""); } TVector3 Utils::VectorEPRtoXYZ( const TVector3& posepr ) { TVector3 posxyz(1,1,1); // to be called before a SetMag posxyz.SetMag( posepr.Z() ); double theta = 2*atan( exp( - posepr.X() ) ); posxyz.SetTheta( theta ); posxyz.SetPhi( posepr.Y() ); return posxyz; }
20.035714
65
0.628045
pasmuss
6078c16e5ce080020fc7292bdd4928bd5b127f9a
2,473
cc
C++
RecoLocalCalo/EcalRecProducers/plugins/EcalUncalibRecHitWorkerMaxSample.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoLocalCalo/EcalRecProducers/plugins/EcalUncalibRecHitWorkerMaxSample.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoLocalCalo/EcalRecProducers/plugins/EcalUncalibRecHitWorkerMaxSample.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/** \class EcalMaxSampleUncalibRecHitProducer * produce ECAL uncalibrated rechits from dataframes * * \author G. Franzoni, E. Di Marco * */ #include "RecoLocalCalo/EcalRecProducers/plugins/EcalUncalibRecHitWorkerMaxSample.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/EcalDigi/interface/EcalDigiCollections.h" #include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h" #include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include <FWCore/ParameterSet/interface/ConfigurationDescriptions.h> #include <FWCore/ParameterSet/interface/ParameterSetDescription.h> #include <FWCore/ParameterSet/interface/EmptyGroupDescription.h> #include <cmath> #include <iomanip> #include <iostream> #include <vector> EcalUncalibRecHitWorkerMaxSample::EcalUncalibRecHitWorkerMaxSample(const edm::ParameterSet& ps, edm::ConsumesCollector& c) : EcalUncalibRecHitWorkerRunOneDigiBase(ps, c) {} void EcalUncalibRecHitWorkerMaxSample::set(const edm::EventSetup& es) {} bool EcalUncalibRecHitWorkerMaxSample::run(const edm::Event& evt, const EcalDigiCollection::const_iterator& itdg, EcalUncalibratedRecHitCollection& result) { DetId detid(itdg->id()); if (detid.subdetId() == EcalBarrel) { result.push_back(ebAlgo_.makeRecHit(*itdg, nullptr, nullptr, nullptr, nullptr)); } else { result.push_back(eeAlgo_.makeRecHit(*itdg, nullptr, nullptr, nullptr, nullptr)); } return true; } edm::ParameterSetDescription EcalUncalibRecHitWorkerMaxSample::getAlgoDescription() { edm::ParameterSetDescription psd; return psd; //.addNode(std::unique_ptr<edm::ParameterDescriptionNode>(new edm::EmptyGroupDescription())); } #include "FWCore/Framework/interface/MakerMacros.h" #include "RecoLocalCalo/EcalRecProducers/interface/EcalUncalibRecHitWorkerFactory.h" DEFINE_EDM_PLUGIN(EcalUncalibRecHitWorkerFactory, EcalUncalibRecHitWorkerMaxSample, "EcalUncalibRecHitWorkerMaxSample"); #include "RecoLocalCalo/EcalRecProducers/interface/EcalUncalibRecHitFillDescriptionWorkerFactory.h" DEFINE_EDM_PLUGIN(EcalUncalibRecHitFillDescriptionWorkerFactory, EcalUncalibRecHitWorkerMaxSample, "EcalUncalibRecHitWorkerMaxSample");
40.540984
120
0.756571
ckamtsikis
607a96483c9d37a6152bba71eb234421ceeb2172
5,936
cpp
C++
src/athena/MemoryWriter.cpp
encounter/athena
6adba82abd8b7f48e6eca9f74361d0c605bc9ec8
[ "MIT" ]
null
null
null
src/athena/MemoryWriter.cpp
encounter/athena
6adba82abd8b7f48e6eca9f74361d0c605bc9ec8
[ "MIT" ]
null
null
null
src/athena/MemoryWriter.cpp
encounter/athena
6adba82abd8b7f48e6eca9f74361d0c605bc9ec8
[ "MIT" ]
null
null
null
#include "athena/MemoryWriter.hpp" #include <cstdio> #include <cstring> #ifdef HW_RVL #include <malloc.h> #endif // HW_RVL namespace athena::io { MemoryWriter::MemoryWriter(atUint8* data, atUint64 length, bool takeOwnership) : m_data(data), m_length(length), m_bufferOwned(takeOwnership) { if (!data) { atError(fmt("data cannot be NULL")); setError(); return; } } MemoryWriter::~MemoryWriter() { if (m_bufferOwned) delete m_data; m_data = nullptr; m_length = 0; } MemoryCopyWriter::MemoryCopyWriter(atUint8* data, atUint64 length) { m_data = data; m_length = length; m_position = 0; m_bufferOwned = false; if (length == 0) { atError(fmt("length cannot be 0")); setError(); return; } m_dataCopy.reset(new atUint8[length]); m_data = m_dataCopy.get(); if (data) memmove(m_data, data, length); } MemoryCopyWriter::MemoryCopyWriter(std::string_view filename) { m_filepath = filename; m_length = 0x10; m_position = 0; m_dataCopy.reset(new atUint8[m_length]); m_data = m_dataCopy.get(); m_bufferOwned = false; if (!m_data) { atError(fmt("Could not allocate memory!")); setError(); return; } } void MemoryWriter::seek(atInt64 position, SeekOrigin origin) { switch (origin) { case SeekOrigin::Begin: if (position < 0) { atError(fmt("Position outside stream bounds")); setError(); return; } if ((atUint64)position > m_length) { atError(fmt("data exceeds available buffer space")); setError(); return; } m_position = position; break; case SeekOrigin::Current: if ((((atInt64)m_position + position) < 0)) { atError(fmt("Position outside stream bounds")); setError(); return; } if (m_position + position > m_length) { atError(fmt("data exceeds available buffer space")); setError(); return; } m_position += position; break; case SeekOrigin::End: if (((atInt64)m_length - position) < 0) { atError(fmt("Position outside stream bounds")); setError(); return; } if ((atUint64)position > m_length) { atError(fmt("data exceeds available buffer space")); setError(); return; } m_position = m_length - position; break; } } void MemoryCopyWriter::seek(atInt64 position, SeekOrigin origin) { switch (origin) { case SeekOrigin::Begin: if (position < 0) { atError(fmt("Position outside stream bounds")); setError(); return; } if ((atUint64)position > m_length) resize(position); m_position = position; break; case SeekOrigin::Current: if ((((atInt64)m_position + position) < 0)) { atError(fmt("Position outside stream bounds")); setError(); return; } if (m_position + position > m_length) resize(m_position + position); m_position += position; break; case SeekOrigin::End: if (((atInt64)m_length - position) < 0) { atError(fmt("Position outside stream bounds")); setError(); return; } if ((atUint64)position > m_length) resize(position); m_position = m_length - position; break; } } void MemoryWriter::setData(atUint8* data, atUint64 length, bool takeOwnership) { if (m_bufferOwned) delete m_data; m_data = data; m_length = length; m_position = 0; m_bufferOwned = takeOwnership; } void MemoryCopyWriter::setData(const atUint8* data, atUint64 length) { m_dataCopy.reset(new atUint8[length]); m_data = m_dataCopy.get(); memmove(m_data, data, length); m_length = length; m_position = 0; m_bufferOwned = false; } atUint8* MemoryWriter::data() const { atUint8* ret = new atUint8[m_length]; memset(ret, 0, m_length); memmove(ret, m_data, m_length); return ret; } void MemoryWriter::save(std::string_view filename) { if (filename.empty() && m_filepath.empty()) { atError(fmt("No file specified, cannot save.")); setError(); return; } if (!filename.empty()) { m_filepath = filename; } std::unique_ptr<FILE, decltype(&std::fclose)> out{std::fopen(m_filepath.c_str(), "wb"), std::fclose}; if (!out) { atError(fmt("Unable to open file '{}'"), m_filepath); setError(); return; } atUint64 done = 0; atUint64 blocksize = BLOCKSZ; do { if (blocksize > m_length - done) { blocksize = m_length - done; } const atInt64 ret = std::fwrite(m_data + done, 1, blocksize, out.get()); if (ret < 0) { atError(fmt("Error writing data to disk")); setError(); return; } if (ret == 0) { break; } done += blocksize; } while (done < m_length); } void MemoryWriter::writeUBytes(const atUint8* data, atUint64 length) { if (!data) { atError(fmt("data cannnot be NULL")); setError(); return; } if (m_position + length > m_length) { atError(fmt("data length exceeds available buffer space")); setError(); return; } memmove(reinterpret_cast<atInt8*>(m_data + m_position), data, length); m_position += length; } void MemoryCopyWriter::writeUBytes(const atUint8* data, atUint64 length) { if (!data) { atError(fmt("data cannnot be NULL")); setError(); return; } if (m_position + length > m_length) resize(m_position + length); memmove(reinterpret_cast<atInt8*>(m_data + m_position), data, length); m_position += length; } void MemoryCopyWriter::resize(atUint64 newSize) { if (newSize < m_length) { atError(fmt("New size cannot be less to the old size.")); return; } // Allocate and copy new buffer auto newArray = std::make_unique<atUint8[]>(newSize); if (m_dataCopy) { std::memmove(newArray.get(), m_dataCopy.get(), m_length); } m_dataCopy = std::move(newArray); // Swap the pointer and size out for the new ones. m_data = m_dataCopy.get(); m_length = newSize; } } // namespace athena::io
21.585455
103
0.635782
encounter
607dfe415a7df668b437c3650c3805edc55c2547
16,550
cc
C++
jni/sources/modules/rtp_rtcp/source/forward_error_correction_internal.cc
guo19941204/c-jni
866a2bc3f1148824e1a5c270fdf452888cb06d2b
[ "MIT" ]
null
null
null
jni/sources/modules/rtp_rtcp/source/forward_error_correction_internal.cc
guo19941204/c-jni
866a2bc3f1148824e1a5c270fdf452888cb06d2b
[ "MIT" ]
null
null
null
jni/sources/modules/rtp_rtcp/source/forward_error_correction_internal.cc
guo19941204/c-jni
866a2bc3f1148824e1a5c270fdf452888cb06d2b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/rtp_rtcp/source/forward_error_correction_internal.h" #include <cassert> #include <cstring> #include "modules/rtp_rtcp/source/fec_private_tables_random.h" #include "modules/rtp_rtcp/source/fec_private_tables_bursty.h" namespace { // Allow for different modes of protection for packets in UEP case. enum ProtectionMode { kModeNoOverlap, kModeOverlap, kModeBiasFirstPacket, }; /** * Fits an input mask (subMask) to an output mask. * The mask is a matrix where the rows are the FEC packets, * and the columns are the source packets the FEC is applied to. * Each row of the mask is represented by a number of mask bytes. * * \param[in] numMaskBytes The number of mask bytes of output mask. * \param[in] numSubMaskBytes The number of mask bytes of input mask. * \param[in] numRows The number of rows of the input mask. * \param[in] subMask A pointer to hold the input mask, of size * [0, numRows * numSubMaskBytes] * \param[out] packetMask A pointer to hold the output mask, of size * [0, x * numMaskBytes], where x >= numRows. */ void FitSubMask(int numMaskBytes, int numSubMaskBytes, int numRows, const uint8_t* subMask, uint8_t* packetMask) { if (numMaskBytes == numSubMaskBytes) { memcpy(packetMask, subMask, numRows * numSubMaskBytes); } else { for (int i = 0; i < numRows; i++) { int pktMaskIdx = i * numMaskBytes; int pktMaskIdx2 = i * numSubMaskBytes; for (int j = 0; j < numSubMaskBytes; j++) { packetMask[pktMaskIdx] = subMask[pktMaskIdx2]; pktMaskIdx++; pktMaskIdx2++; } } } } /** * Shifts a mask by number of columns (bits), and fits it to an output mask. * The mask is a matrix where the rows are the FEC packets, * and the columns are the source packets the FEC is applied to. * Each row of the mask is represented by a number of mask bytes. * * \param[in] numMaskBytes The number of mask bytes of output mask. * \param[in] numSubMaskBytes The number of mask bytes of input mask. * \param[in] numColumnShift The number columns to be shifted, and * the starting row for the output mask. * \param[in] endRow The ending row for the output mask. * \param[in] subMask A pointer to hold the input mask, of size * [0, (endRowFEC - startRowFec) * numSubMaskBytes] * \param[out] packetMask A pointer to hold the output mask, of size * [0, x * numMaskBytes], where x >= endRowFEC. */ // TODO (marpan): This function is doing three things at the same time: // shift within a byte, byte shift and resizing. // Split up into subroutines. void ShiftFitSubMask(int numMaskBytes, int resMaskBytes, int numColumnShift, int endRow, const uint8_t* subMask, uint8_t* packetMask) { // Number of bit shifts within a byte const int numBitShifts = (numColumnShift % 8); const int numByteShifts = numColumnShift >> 3; // Modify new mask with sub-mask21. // Loop over the remaining FEC packets. for (int i = numColumnShift; i < endRow; i++) { // Byte index of new mask, for row i and column resMaskBytes, // offset by the number of bytes shifts int pktMaskIdx = i * numMaskBytes + resMaskBytes - 1 + numByteShifts; // Byte index of subMask, for row i and column resMaskBytes int pktMaskIdx2 = (i - numColumnShift) * resMaskBytes + resMaskBytes - 1; uint8_t shiftRightCurrByte = 0; uint8_t shiftLeftPrevByte = 0; uint8_t combNewByte = 0; // Handle case of numMaskBytes > resMaskBytes: // For a given row, copy the rightmost "numBitShifts" bits // of the last byte of subMask into output mask. if (numMaskBytes > resMaskBytes) { shiftLeftPrevByte = (subMask[pktMaskIdx2] << (8 - numBitShifts)); packetMask[pktMaskIdx + 1] = shiftLeftPrevByte; } // For each row i (FEC packet), shift the bit-mask of the subMask. // Each row of the mask contains "resMaskBytes" of bytes. // We start from the last byte of the subMask and move to first one. for (int j = resMaskBytes - 1; j > 0; j--) { // Shift current byte of sub21 to the right by "numBitShifts". shiftRightCurrByte = subMask[pktMaskIdx2] >> numBitShifts; // Fill in shifted bits with bits from the previous (left) byte: // First shift the previous byte to the left by "8-numBitShifts". shiftLeftPrevByte = (subMask[pktMaskIdx2 - 1] << (8 - numBitShifts)); // Then combine both shifted bytes into new mask byte. combNewByte = shiftRightCurrByte | shiftLeftPrevByte; // Assign to new mask. packetMask[pktMaskIdx] = combNewByte; pktMaskIdx--; pktMaskIdx2--; } // For the first byte in the row (j=0 case). shiftRightCurrByte = subMask[pktMaskIdx2] >> numBitShifts; packetMask[pktMaskIdx] = shiftRightCurrByte; } } } // namespace namespace webrtc { namespace internal { PacketMaskTable::PacketMaskTable(FecMaskType fec_mask_type, int num_media_packets) : fec_mask_type_(InitMaskType(fec_mask_type, num_media_packets)), fec_packet_mask_table_(InitMaskTable(fec_mask_type_)) { } // Sets |fec_mask_type_| to the type of packet mask selected. The type of // packet mask selected is based on |fec_mask_type| and |numMediaPackets|. // If |numMediaPackets| is larger than the maximum allowed by |fec_mask_type| // for the bursty type, then the random type is selected. FecMaskType PacketMaskTable::InitMaskType(FecMaskType fec_mask_type, int num_media_packets) { // The mask should not be bigger than |packetMaskTbl|. assert(num_media_packets <= static_cast<int>(sizeof(kPacketMaskRandomTbl) / sizeof(*kPacketMaskRandomTbl))); switch (fec_mask_type) { case kFecMaskRandom: { return kFecMaskRandom; } case kFecMaskBursty: { int max_media_packets = static_cast<int>(sizeof(kPacketMaskBurstyTbl) / sizeof(*kPacketMaskBurstyTbl)); if (num_media_packets > max_media_packets) { return kFecMaskRandom; } else { return kFecMaskBursty; } } } assert(false); return kFecMaskRandom; } // Returns the pointer to the packet mask tables corresponding to type // |fec_mask_type|. const uint8_t*** PacketMaskTable::InitMaskTable(FecMaskType fec_mask_type) { switch (fec_mask_type) { case kFecMaskRandom: { return kPacketMaskRandomTbl; } case kFecMaskBursty: { return kPacketMaskBurstyTbl; } } assert(false); return kPacketMaskRandomTbl; } // Remaining protection after important (first partition) packet protection void RemainingPacketProtection(int numMediaPackets, int numFecRemaining, int numFecForImpPackets, int numMaskBytes, ProtectionMode mode, uint8_t* packetMask, const PacketMaskTable& mask_table) { if (mode == kModeNoOverlap) { // subMask21 const int lBit = (numMediaPackets - numFecForImpPackets) > 16 ? 1 : 0; const int resMaskBytes = (lBit == 1) ? kMaskSizeLBitSet : kMaskSizeLBitClear; const uint8_t* packetMaskSub21 = mask_table.fec_packet_mask_table() [numMediaPackets - numFecForImpPackets - 1] [numFecRemaining - 1]; ShiftFitSubMask(numMaskBytes, resMaskBytes, numFecForImpPackets, (numFecForImpPackets + numFecRemaining), packetMaskSub21, packetMask); } else if (mode == kModeOverlap || mode == kModeBiasFirstPacket) { // subMask22 const uint8_t* packetMaskSub22 = mask_table.fec_packet_mask_table() [numMediaPackets - 1][numFecRemaining - 1]; FitSubMask(numMaskBytes, numMaskBytes, numFecRemaining, packetMaskSub22, &packetMask[numFecForImpPackets * numMaskBytes]); if (mode == kModeBiasFirstPacket) { for (int i = 0; i < numFecRemaining; i++) { int pktMaskIdx = i * numMaskBytes; packetMask[pktMaskIdx] = packetMask[pktMaskIdx] | (1 << 7); } } } else { assert(false); } } // Protection for important (first partition) packets void ImportantPacketProtection(int numFecForImpPackets, int numImpPackets, int numMaskBytes, uint8_t* packetMask, const PacketMaskTable& mask_table) { const int lBit = numImpPackets > 16 ? 1 : 0; const int numImpMaskBytes = (lBit == 1) ? kMaskSizeLBitSet : kMaskSizeLBitClear; // Get subMask1 from table const uint8_t* packetMaskSub1 = mask_table.fec_packet_mask_table() [numImpPackets - 1][numFecForImpPackets - 1]; FitSubMask(numMaskBytes, numImpMaskBytes, numFecForImpPackets, packetMaskSub1, packetMask); } // This function sets the protection allocation: i.e., how many FEC packets // to use for numImp (1st partition) packets, given the: number of media // packets, number of FEC packets, and number of 1st partition packets. int SetProtectionAllocation(int numMediaPackets, int numFecPackets, int numImpPackets) { // TODO (marpan): test different cases for protection allocation: // Use at most (allocPar * numFecPackets) for important packets. float allocPar = 0.5; int maxNumFecForImp = allocPar * numFecPackets; int numFecForImpPackets = (numImpPackets < maxNumFecForImp) ? numImpPackets : maxNumFecForImp; // Fall back to equal protection in this case if (numFecPackets == 1 && (numMediaPackets > 2 * numImpPackets)) { numFecForImpPackets = 0; } return numFecForImpPackets; } // Modification for UEP: reuse the off-line tables for the packet masks. // Note: these masks were designed for equal packet protection case, // assuming random packet loss. // Current version has 3 modes (options) to build UEP mask from existing ones. // Various other combinations may be added in future versions. // Longer-term, we may add another set of tables specifically for UEP cases. // TODO (marpan): also consider modification of masks for bursty loss cases. // Mask is characterized as (#packets_to_protect, #fec_for_protection). // Protection factor defined as: (#fec_for_protection / #packets_to_protect). // Let k=numMediaPackets, n=total#packets, (n-k)=numFecPackets, m=numImpPackets. // For ProtectionMode 0 and 1: // one mask (subMask1) is used for 1st partition packets, // the other mask (subMask21/22, for 0/1) is for the remaining FEC packets. // In both mode 0 and 1, the packets of 1st partition (numImpPackets) are // treated equally important, and are afforded more protection than the // residual partition packets. // For numImpPackets: // subMask1 = (m, t): protection = t/(m), where t=F(k,n-k,m). // t=F(k,n-k,m) is the number of packets used to protect first partition in // subMask1. This is determined from the function SetProtectionAllocation(). // For the left-over protection: // Mode 0: subMask21 = (k-m,n-k-t): protection = (n-k-t)/(k-m) // mode 0 has no protection overlap between the two partitions. // For mode 0, we would typically set t = min(m, n-k). // Mode 1: subMask22 = (k, n-k-t), with protection (n-k-t)/(k) // mode 1 has protection overlap between the two partitions (preferred). // For ProtectionMode 2: // This gives 1st packet of list (which is 1st packet of 1st partition) more // protection. In mode 2, the equal protection mask (which is obtained from // mode 1 for t=0) is modified (more "1s" added in 1st column of packet mask) // to bias higher protection for the 1st source packet. // Protection Mode 2 may be extended for a sort of sliding protection // (i.e., vary the number/density of "1s" across columns) across packets. void UnequalProtectionMask(int numMediaPackets, int numFecPackets, int numImpPackets, int numMaskBytes, uint8_t* packetMask, const PacketMaskTable& mask_table) { // Set Protection type and allocation // TODO (marpan): test/update for best mode and some combinations thereof. ProtectionMode mode = kModeOverlap; int numFecForImpPackets = 0; if (mode != kModeBiasFirstPacket) { numFecForImpPackets = SetProtectionAllocation(numMediaPackets, numFecPackets, numImpPackets); } int numFecRemaining = numFecPackets - numFecForImpPackets; // Done with setting protection type and allocation // // Generate subMask1 // if (numFecForImpPackets > 0) { ImportantPacketProtection(numFecForImpPackets, numImpPackets, numMaskBytes, packetMask, mask_table); } // // Generate subMask2 // if (numFecRemaining > 0) { RemainingPacketProtection(numMediaPackets, numFecRemaining, numFecForImpPackets, numMaskBytes, mode, packetMask, mask_table); } } void GeneratePacketMasks(int numMediaPackets, int numFecPackets, int numImpPackets, bool useUnequalProtection, const PacketMaskTable& mask_table, uint8_t* packetMask) { assert(numMediaPackets > 0); assert(numFecPackets <= numMediaPackets && numFecPackets > 0); assert(numImpPackets <= numMediaPackets && numImpPackets >= 0); int lBit = numMediaPackets > 16 ? 1 : 0; const int numMaskBytes = (lBit == 1) ? kMaskSizeLBitSet : kMaskSizeLBitClear; // Equal-protection for these cases if (!useUnequalProtection || numImpPackets == 0) { // Retrieve corresponding mask table directly:for equal-protection case. // Mask = (k,n-k), with protection factor = (n-k)/k, // where k = numMediaPackets, n=total#packets, (n-k)=numFecPackets. memcpy(packetMask, mask_table.fec_packet_mask_table()[numMediaPackets - 1] [numFecPackets - 1], numFecPackets * numMaskBytes); } else //UEP case { UnequalProtectionMask(numMediaPackets, numFecPackets, numImpPackets, numMaskBytes, packetMask, mask_table); } // End of UEP modification } //End of GetPacketMasks } // namespace internal } // namespace webrtc
37.871854
82
0.602115
guo19941204
607e0486d7f8a1727ef97f5885bec89a799311c6
21,702
cc
C++
chrome/browser/external_protocol/external_protocol_policy_browsertest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/external_protocol/external_protocol_policy_browsertest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/external_protocol/external_protocol_policy_browsertest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/values.h" #include "chrome/browser/external_protocol/auto_launch_protocols_policy_handler.h" #include "chrome/browser/external_protocol/external_protocol_handler.h" #include "chrome/browser/policy/policy_test_utils.h" #include "chrome/browser/ui/browser.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/policy_constants.h" #include "content/public/test/browser_test.h" #include "url/gurl.h" #include "url/origin.h" namespace policy { class ExternalProtocolPolicyBrowserTest : public PolicyTest {}; IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsMalformedPolicy) { const char kWildcardOrigin[] = "*"; const char kExampleScheme[] = "custom"; url::Origin test_origin = url::Origin::Create(GURL("https://example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); // Single dictionary for this test case, but erroneously not embedded // in a list. base::DictionaryValue protocol_origins_map; // Set a protocol list with a matching protocol. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set origins list with a wildcard origin matching pattern. base::ListValue origins; origins.Append(kWildcardOrigin); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map.Clone(), nullptr); UpdateProviderPolicy(policies); block_state = ExternalProtocolHandler::GetBlockState( kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsNullInitiatingOrigin) { const char kWildcardOrigin[] = "*"; const char kExampleScheme[] = "custom"; base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an origins list with the wildcard origin matching pattern. base::ListValue origins; origins.Append(kWildcardOrigin); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); // Calling GetBlockState with a null initiating_origin should // return UNKNOWN. ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, nullptr, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsEmptyOriginList) { const char kExampleScheme[] = "custom"; url::Origin test_origin = url::Origin::Create(GURL("https://example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol list with a matching protocol. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an empty origins list. base::ListValue origins; protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); block_state = ExternalProtocolHandler::GetBlockState( kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsWildcardOriginList) { const char kWildcardOrigin[] = "*"; const char kExampleScheme[] = "custom"; base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol to match the test. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an origins list with the wildcard origin matching pattern. base::ListValue origins; origins.Append(kWildcardOrigin); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); url::Origin test_origin = url::Origin::Create(GURL("https://example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsInvalidProtocols) { const char kInvalidProtocol1[] = "custom:"; const char kInvalidProtocol2[] = "custom://"; const char kInvalidProtocol3[] = "custom//"; const char kWildcardOrigin[] = "*"; const char kExampleScheme[] = "custom"; base::ListValue protocol_origins_map_list; // Three dictionaries in the list for this test case. base::DictionaryValue protocol_origins_map1; base::DictionaryValue protocol_origins_map2; base::DictionaryValue protocol_origins_map3; // Set invalid protocols, each with the wildcard origin matching pattern. protocol_origins_map1.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kInvalidProtocol1); base::ListValue origins1; origins1.Append(kWildcardOrigin); protocol_origins_map1.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins1)); protocol_origins_map_list.Append(std::move(protocol_origins_map1)); protocol_origins_map2.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kInvalidProtocol2); base::ListValue origins2; origins2.Append(kWildcardOrigin); protocol_origins_map2.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins2)); protocol_origins_map_list.Append(std::move(protocol_origins_map2)); protocol_origins_map3.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kInvalidProtocol3); base::ListValue origins3; origins3.Append(kWildcardOrigin); protocol_origins_map3.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins3)); protocol_origins_map_list.Append(std::move(protocol_origins_map3)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); url::Origin test_origin = url::Origin::Create(GURL("https://example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsOriginPatternWithMissingScheme) { const char kExampleScheme[] = "custom"; const char kHost[] = "www.example.test"; base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol to match the test. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an origins list with an origin matching pattern that matches but is // only the host name. base::ListValue origins; origins.Append(kHost); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); // Test that secure origin matches. url::Origin test_origin = url::Origin::Create(GURL("https://www.example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state); // Test that insecure origin matches. test_origin = url::Origin::Create(GURL("http://www.example.test")); block_state = ExternalProtocolHandler::GetBlockState( kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state); // Test that different origin does not match. test_origin = url::Origin::Create(GURL("http://www.other.test")); block_state = ExternalProtocolHandler::GetBlockState( kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsOriginPatternWithExactHostname) { const char kExampleScheme[] = "custom"; const char kExactHostName[] = ".www.example.test"; base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol to match the test. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an origins list with an origin matching pattern that matches exactly // but has no scheme. base::ListValue origins; origins.Append(kExactHostName); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); // Test that secure origin matches. url::Origin test_origin = url::Origin::Create(GURL("https://www.example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state); // Test that insecure origin matches. test_origin = url::Origin::Create(GURL("http://www.example.test")); block_state = ExternalProtocolHandler::GetBlockState( kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state); // Test that different origin does not match. test_origin = url::Origin::Create(GURL("http://www.other.test")); block_state = ExternalProtocolHandler::GetBlockState( kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsOriginPatternWithParentDomain) { const char kExampleScheme[] = "custom"; const char kParentDomain[] = "example.test"; base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol to match the test. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an origins list with an origin matching pattern that is the parent // domain but should match subdomains. base::ListValue origins; origins.Append(kParentDomain); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); // Test that a subdomain matches. url::Origin test_origin = url::Origin::Create(GURL("https://www.example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsOriginPatternWithWildcardOrigin) { const char kExampleScheme[] = "custom"; const char kProtocolWithWildcardHostname[] = "https://*"; base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol to match the test. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an origins list with an origin matching pattern that matches the scheme // and all hosts. base::ListValue origins; origins.Append(kProtocolWithWildcardHostname); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); // Test that secure origin matches. url::Origin test_origin = url::Origin::Create(GURL("https://www.example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state); // Test that insecure origin does not match. test_origin = url::Origin::Create(GURL("http://www.example.test")); block_state = ExternalProtocolHandler::GetBlockState( kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsOriginPatternWithFullOrigin) { const char kExampleScheme[] = "custom"; const char kFullOrigin[] = "https://www.example.test:443"; base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol to match the test. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an origins list with an origin matching pattern that matches the full // origin exactly. base::ListValue origins; origins.Append(kFullOrigin); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); // Test that default HTTPS port 443 matches. url::Origin test_origin = url::Origin::Create(GURL("https://www.example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state); // Test that explicit port 443 matches. test_origin = url::Origin::Create(GURL("https://www.example.test:443")); block_state = ExternalProtocolHandler::GetBlockState( kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state); // Test that explicit other port does not match. test_origin = url::Origin::Create(GURL("https://www.example.test:8080")); block_state = ExternalProtocolHandler::GetBlockState( kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsOriginPatternWithExactParentDomain) { const char kExampleScheme[] = "custom"; const char kExactParentDomain[] = ".example.com"; base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol to match the test. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an origins list with an origin matching pattern that doesn't match // because it is a parent domain that does not match subdomains. base::ListValue origins; origins.Append(kExactParentDomain); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); url::Origin test_origin = url::Origin::Create(GURL("https://www.example.test")); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest, AutoLaunchProtocolsOriginPatternWithPath) { const char kExampleScheme[] = "custom"; const char kFullUrlWithPath[] = "https://example.test/home.html"; base::ListValue protocol_origins_map_list; // Single dictionary in the list for this test case. base::DictionaryValue protocol_origins_map; // Set a protocol to match the test. protocol_origins_map.SetStringKey( AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme); // Set an origins list with an origin matching pattern that doesn't match // because it contains a [/path] element. base::ListValue origins; origins.Append(kFullUrlWithPath); protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey, std::move(origins)); protocol_origins_map_list.Append(std::move(protocol_origins_map)); PolicyMap policies; policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, protocol_origins_map_list.Clone(), nullptr); UpdateProviderPolicy(policies); url::Origin test_origin = url::Origin::Create(GURL(kFullUrlWithPath)); ExternalProtocolHandler::BlockState block_state = ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin, browser()->profile()); EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state); } } // namespace policy
46.174468
82
0.736568
zealoussnow
607e300251eb0aac876c03dad8357a69e4656472
17,436
cpp
C++
external_libs/pgenlib/pgenlibr.cpp
tedyun/regenie
6d31b5165e098a08ff575e5a36c0cb6219247cc6
[ "MIT" ]
null
null
null
external_libs/pgenlib/pgenlibr.cpp
tedyun/regenie
6d31b5165e098a08ff575e5a36c0cb6219247cc6
[ "MIT" ]
null
null
null
external_libs/pgenlib/pgenlibr.cpp
tedyun/regenie
6d31b5165e098a08ff575e5a36c0cb6219247cc6
[ "MIT" ]
null
null
null
/* * * File obtained from pgenlibr R library: * https://github.com/chrchang/plink-ng/tree/master/2.0/pgenlibr * * License info obtained from DESCRIPTION file: * https://github.com/chrchang/plink-ng/blob/master/2.0/pgenlibr/DESCRIPTION * ----------------------------------------------------- Package: pgenlibr Type: Package Title: PLINK 2 Binary (.pgen) Reader Version: 0.2 Date: 2019-07-10 Author: Christopher Chang Maintainer: Christopher Chang <chrchang@alumni.caltech.edu> Description: A thin wrapper over PLINK 2's core libraries which provides an R interface for reading .pgen files. A minimal .pvar loader is also included. License: LGPL (>= 3) Imports: Rcpp (>= 1.0.1) LinkingTo: Rcpp * ----------------------------------------------------- * Modified by Joelle Mbatchou - June 29 2020 * - removed functions that were for R * - split file to header (added link to several standard C++ libraries) * - modified remaining functions to be fully C/C++ compatible * * This file remains under LGPL v3 license (license is in same directory as this file) */ #include "pgenlibr.h" PgenReader::PgenReader() : _info_ptr(nullptr), //_allele_idx_offsetsp(nullptr), //_nonref_flagsp(nullptr), _state_ptr(nullptr) { } PgenReader::~PgenReader() { Close(); } void PgenReader::Load(std::string filename, uint32_t cur_sample_ct, std::vector<int> sample_subset_1based) { if (_info_ptr) { Close(); } _info_ptr = static_cast<plink2::PgenFileInfo*>(malloc(sizeof(plink2::PgenFileInfo))); if (!_info_ptr) { fprintf(stderr,"Out of memory"); exit(-1); } plink2::PreinitPgfi(_info_ptr); uint32_t cur_variant_ct = UINT32_MAX; const char* fname = filename.c_str(); plink2::PgenHeaderCtrl header_ctrl; uintptr_t pgfi_alloc_cacheline_ct; char errstr_buf[plink2::kPglErrstrBufBlen]; if (PgfiInitPhase1(fname, cur_variant_ct, cur_sample_ct, 0, &header_ctrl, _info_ptr, &pgfi_alloc_cacheline_ct, errstr_buf) != plink2::kPglRetSuccess) { fprintf(stderr, "%s\n", &(errstr_buf[7])); exit(-1); } const uint32_t raw_variant_ct = _info_ptr->raw_variant_ct; if (header_ctrl & 0x30) { fprintf(stderr,"Storing of allele count information is not supported (only bi-allelic variants should be present)."); exit(-1); // no need to zero-initialize this //_allele_idx_offsetsp = plink2::CreateRefcountedWptr(raw_variant_ct + 1); //_info_ptr->allele_idx_offsets = _allele_idx_offsetsp->p; // _info_ptr->max_allele_ct updated by PgfiInitPhase2() in this case } _info_ptr->max_allele_ct = 2; if ((header_ctrl & 0xc0) == 0xc0) { fprintf(stderr,"Tracking og reference alleles in header is not supported."); exit(-1); // todo: load this in pvar, to enable consistency check. we use a // (manually implemented) shared_ptr in preparation for this. //const uintptr_t raw_variant_ctl = plink2::DivUp(raw_variant_ct, plink2::kBitsPerWord); // no need to zero-initialize this //_nonref_flagsp = plink2::CreateRefcountedWptr(raw_variant_ctl + 1); //_info_ptr->nonref_flags = _nonref_flagsp->p; } const uint32_t file_sample_ct = _info_ptr->raw_sample_ct; unsigned char* pgfi_alloc = nullptr; if (plink2::cachealigned_malloc(pgfi_alloc_cacheline_ct * plink2::kCacheline, &pgfi_alloc)) { fprintf(stderr,"Out of memory"); exit(-1); } uint32_t max_vrec_width; uintptr_t pgr_alloc_cacheline_ct; if (PgfiInitPhase2(header_ctrl, 1, 0, 0, 0, raw_variant_ct, &max_vrec_width, _info_ptr, pgfi_alloc, &pgr_alloc_cacheline_ct, errstr_buf)) { if (pgfi_alloc && (!_info_ptr->vrtypes)) { plink2::aligned_free(pgfi_alloc); } fprintf(stderr,"%s\n", &(errstr_buf[7])); exit(-1); } if ((!_allele_idx_offsetsp) && (_info_ptr->gflags & 4)) { // Note that it's safe to be ignorant of multiallelic variants when // phase and dosage info aren't present; GetAlleleCt() then always returns // 2 when that isn't actually true, and all ALTs are treated as if they // were ALT1, but otherwise everything works properly. fprintf(stderr,"Multiallelic variants and phase/dosage info simultaneously present; pvar required in this case"); exit(-1); } _state_ptr = static_cast<plink2::PgenReader*>(malloc(sizeof(plink2::PgenReader))); if (!_state_ptr) { fprintf(stderr,"Out of memory"); exit(-1); } plink2::PreinitPgr(_state_ptr); plink2::PgrSetFreadBuf(nullptr, _state_ptr); const uintptr_t pgr_alloc_main_byte_ct = pgr_alloc_cacheline_ct * plink2::kCacheline; const uintptr_t sample_subset_byte_ct = plink2::DivUp(file_sample_ct, plink2::kBitsPerVec) * plink2::kBytesPerVec; const uintptr_t cumulative_popcounts_byte_ct = plink2::DivUp(file_sample_ct, plink2::kBitsPerWord * plink2::kInt32PerVec) * plink2::kBytesPerVec; const uintptr_t genovec_byte_ct = plink2::DivUp(file_sample_ct, plink2::kNypsPerVec) * plink2::kBytesPerVec; const uintptr_t ac_byte_ct = plink2::RoundUpPow2(file_sample_ct * sizeof(plink2::AlleleCode), plink2::kBytesPerVec); const uintptr_t ac2_byte_ct = plink2::RoundUpPow2(file_sample_ct * 2 * sizeof(plink2::AlleleCode), plink2::kBytesPerVec); uintptr_t multiallelic_hc_byte_ct = 0; if (_info_ptr->max_allele_ct != 2) { multiallelic_hc_byte_ct = 2 * sample_subset_byte_ct + ac_byte_ct + ac2_byte_ct; } const uintptr_t dosage_main_byte_ct = plink2::DivUp(file_sample_ct, (2 * plink2::kInt32PerVec)) * plink2::kBytesPerVec; unsigned char* pgr_alloc; if (plink2::cachealigned_malloc(pgr_alloc_main_byte_ct + (2 * plink2::kPglNypTransposeBatch + 5) * sample_subset_byte_ct + cumulative_popcounts_byte_ct + (1 + plink2::kPglNypTransposeBatch) * genovec_byte_ct + multiallelic_hc_byte_ct + dosage_main_byte_ct + plink2::kPglBitTransposeBufbytes + 4 * (plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8), &pgr_alloc)) { fprintf(stderr,"Out of memory"); exit(-1); } plink2::PglErr reterr = PgrInit(fname, max_vrec_width, _info_ptr, _state_ptr, pgr_alloc); if (reterr != plink2::kPglRetSuccess) { if (!plink2::PgrGetFreadBuf(_state_ptr)) { plink2::aligned_free(pgr_alloc); } sprintf(errstr_buf, "PgrInit() error %d", static_cast<int>(reterr)); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } unsigned char* pgr_alloc_iter = &(pgr_alloc[pgr_alloc_main_byte_ct]); _subset_include_vec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _subset_include_interleaved_vec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); #ifdef USE_AVX2 _subset_include_interleaved_vec[-3] = 0; _subset_include_interleaved_vec[-2] = 0; #endif _subset_include_interleaved_vec[-1] = 0; _subset_cumulative_popcounts = reinterpret_cast<uint32_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[cumulative_popcounts_byte_ct]); _pgv.genovec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[genovec_byte_ct]); if (multiallelic_hc_byte_ct) { _pgv.patch_01_set = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.patch_01_vals = reinterpret_cast<plink2::AlleleCode*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[ac_byte_ct]); _pgv.patch_10_set = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.patch_10_vals = reinterpret_cast<plink2::AlleleCode*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[ac2_byte_ct]); } else { _pgv.patch_01_set = nullptr; _pgv.patch_01_vals = nullptr; _pgv.patch_10_set = nullptr; _pgv.patch_10_vals = nullptr; } _pgv.phasepresent = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.phaseinfo = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.dosage_present = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]); _pgv.dosage_main = reinterpret_cast<uint16_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[dosage_main_byte_ct]); if (sample_subset_1based.size() > 0) { SetSampleSubsetInternal(sample_subset_1based); } else { _subset_size = file_sample_ct; } pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglBitTransposeBufbytes]); _multivar_vmaj_geno_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * genovec_byte_ct]); _multivar_vmaj_phasepresent_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * sample_subset_byte_ct]); _multivar_vmaj_phaseinfo_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * sample_subset_byte_ct]); _multivar_smaj_geno_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 4]); _multivar_smaj_phaseinfo_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8]); _multivar_smaj_phasepresent_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter); // pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8]); } uint32_t PgenReader::GetRawSampleCt() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return _info_ptr->raw_sample_ct; } uint32_t PgenReader::GetSubsetSize() const { return _subset_size; } uint32_t PgenReader::GetVariantCt() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return _info_ptr->raw_variant_ct; } uint32_t PgenReader::GetAlleleCt(uint32_t variant_idx) const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } if (variant_idx >= _info_ptr->raw_variant_ct) { char errstr_buf[256]; sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } if (!_allele_idx_offsetsp) { return 2; } fprintf(stderr,"Error: only bi-allelic variants are supported"); exit(-1); //const uintptr_t* allele_idx_offsets = _allele_idx_offsetsp->p; //return allele_idx_offsets[variant_idx + 1] - allele_idx_offsets[variant_idx]; } uint32_t PgenReader::GetMaxAlleleCt() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return _info_ptr->max_allele_ct; } bool PgenReader::HardcallPhasePresent() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return ((_info_ptr->gflags & plink2::kfPgenGlobalHardcallPhasePresent) != 0); } // added by J.Mbatchou (09/22/20) to check if dosages are present in PGEN file bool PgenReader::DosagePresent() const { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } return ((_info_ptr->gflags & plink2::kfPgenGlobalDosagePresent) != 0); } static const int32_t kGenoRInt32Quads[1024] ALIGNV16 = QUAD_TABLE256(0, 1, 2, -3); void PgenReader::ReadIntHardcalls(std::vector<int>& buf, int variant_idx, int allele_idx) { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) { char errstr_buf[256]; sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } if (buf.size() != _subset_size) { char errstr_buf[256]; sprintf(errstr_buf, "buf has wrong length (%" PRIdPTR "; %u expected)", buf.size(), _subset_size); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::PglErr reterr = PgrGet1(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec); if (reterr != plink2::kPglRetSuccess) { char errstr_buf[256]; sprintf(errstr_buf, "PgrGet1() error %d", static_cast<int>(reterr)); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::GenoarrLookup256x4bx4(_pgv.genovec, kGenoRInt32Quads, _subset_size, &buf[0]); } static const double kGenoRDoublePairs[32] ALIGNV16 = PAIR_TABLE16(0.0, 1.0, 2.0, -3.0); void PgenReader::ReadHardcalls(std::vector<double>& buf, int variant_idx, int allele_idx) { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) { char errstr_buf[256]; sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } if (buf.size() != _subset_size) { char errstr_buf[256]; sprintf(errstr_buf, "buf has wrong length (%" PRIdPTR "; %u expected)", buf.size(), _subset_size); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::PglErr reterr = PgrGet1(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec); if (reterr != plink2::kPglRetSuccess) { char errstr_buf[256]; sprintf(errstr_buf, "PgrGet1() error %d", static_cast<int>(reterr)); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::GenoarrLookup16x8bx2(_pgv.genovec, kGenoRDoublePairs, _subset_size, &buf[0]); } void PgenReader::Read(std::vector<double>& buf, int variant_idx, int allele_idx) { if (!_info_ptr) { fprintf(stderr,"pgen is closed"); exit(-1); } if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) { char errstr_buf[256]; sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } if (buf.size() != _subset_size) { char errstr_buf[256]; sprintf(errstr_buf, "buf has wrong length (%" PRIdPTR "; %u expected)", buf.size(), _subset_size); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } uint32_t dosage_ct; plink2::PglErr reterr = PgrGet1D(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, &dosage_ct); if (reterr != plink2::kPglRetSuccess) { char errstr_buf[256]; sprintf(errstr_buf, "PgrGet1D() error %d", static_cast<int>(reterr)); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::Dosage16ToDoubles(kGenoRDoublePairs, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, _subset_size, dosage_ct, &buf[0]); } void PgenReader::Close() { // don't bother propagating file close errors for now if (_info_ptr) { //CondReleaseRefcountedWptr(&_allele_idx_offsetsp); //CondReleaseRefcountedWptr(&_nonref_flagsp); if (_info_ptr->vrtypes) { plink2::aligned_free(_info_ptr->vrtypes); } plink2::PglErr reterr = plink2::kPglRetSuccess; plink2::CleanupPgfi(_info_ptr, &reterr); free(_info_ptr); _info_ptr = nullptr; } if (_state_ptr) { plink2::PglErr reterr = plink2::kPglRetSuccess; plink2::CleanupPgr(_state_ptr, &reterr); if (PgrGetFreadBuf(_state_ptr)) { plink2::aligned_free(PgrGetFreadBuf(_state_ptr)); } free(_state_ptr); _state_ptr = nullptr; } _subset_size = 0; } void PgenReader::SetSampleSubsetInternal(std::vector<int>& sample_subset_1based) { const uint32_t raw_sample_ct = _info_ptr->raw_sample_ct; const uint32_t raw_sample_ctv = plink2::DivUp(raw_sample_ct, plink2::kBitsPerVec); const uint32_t raw_sample_ctaw = raw_sample_ctv * plink2::kWordsPerVec; uintptr_t* sample_include = _subset_include_vec; plink2::ZeroWArr(raw_sample_ctaw, sample_include); const uint32_t subset_size = sample_subset_1based.size(); if (subset_size == 0) { fprintf(stderr,"Empty sample_subset is not currently permitted"); exit(-1); } uint32_t sample_uidx = sample_subset_1based[0] - 1; uint32_t idx = 0; uint32_t next_uidx; while (1) { if (sample_uidx >= raw_sample_ct) { char errstr_buf[256]; sprintf(errstr_buf, "sample number out of range (%d; must be 1..%u)", static_cast<int>(sample_uidx + 1), raw_sample_ct); fprintf(stderr,"%s\n", errstr_buf); exit(-1); } plink2::SetBit(sample_uidx, sample_include); if (++idx == subset_size) { break; } next_uidx = sample_subset_1based[idx] - 1; // prohibit this since it implies that the caller expects genotypes to be // returned in a different order if (next_uidx <= sample_uidx) { fprintf(stderr,"sample_subset is not in strictly increasing order"); exit(-1); } sample_uidx = next_uidx; } plink2::FillInterleavedMaskVec(sample_include, raw_sample_ctv, _subset_include_interleaved_vec); const uint32_t raw_sample_ctl = plink2::DivUp(raw_sample_ct, plink2::kBitsPerWord); plink2::FillCumulativePopcounts(sample_include, raw_sample_ctl, _subset_cumulative_popcounts); plink2::PgrSetSampleSubsetIndex(_subset_cumulative_popcounts, _state_ptr, &_subset_index); _subset_size = subset_size; }
41.81295
382
0.71708
tedyun
607eb76c427464a3e63567d4b48312bd5c8f70a5
1,335
hh
C++
gecode/string/find.hh
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
1
2021-05-26T13:27:00.000Z
2021-05-26T13:27:00.000Z
gecode/string/find.hh
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
gecode/string/find.hh
ramadini/gecode
ff0d261486a67f66895850a771f161bfa8bf9839
[ "MIT-feh" ]
null
null
null
#ifndef __GECODE_STRING_FIND_HH__ #define __GECODE_STRING_FIND_HH__ namespace Gecode { namespace String { /** * \brief %Propagator for string find. * */ class Find : public MixTernaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND> { protected: using MixTernaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND> ::x0; using MixTernaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND> ::x1; using MixTernaryPropagator<StringView, PC_STRING_DOM, StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND> ::x2; /// Constructor for cloning \a p Find(Space& home, Find& p); /// Constructor for posting Find(Home home, StringView, StringView, Gecode::Int::IntView); public: /// Copy propagator during cloning virtual Actor* copy(Space& home); /// Perform propagation virtual ExecStatus propagate(Space& home, const ModEventDelta& med); /// Post propagator for \f n = find(x, y) \f$ static ExecStatus post(Home, StringView, StringView, Gecode::Int::IntView); }; }} #include <gecode/string/int/find.hpp> #endif
32.560976
79
0.697378
ramadini
60800365b8156a58de2c7956ce2151c151a87257
4,152
cc
C++
src/core/ext/transport/chttp2/client/insecure/channel_create.cc
mnuck/grpc
d5b1f9809202bf2338f94a9e1c07bc511b42d67d
[ "Apache-2.0" ]
91
2018-11-24T05:33:58.000Z
2022-03-16T05:58:05.000Z
src/core/ext/transport/chttp2/client/insecure/channel_create.cc
mnuck/grpc
d5b1f9809202bf2338f94a9e1c07bc511b42d67d
[ "Apache-2.0" ]
11
2019-06-02T23:50:17.000Z
2022-02-04T23:58:56.000Z
src/core/ext/transport/chttp2/client/insecure/channel_create.cc
mnuck/grpc
d5b1f9809202bf2338f94a9e1c07bc511b42d67d
[ "Apache-2.0" ]
18
2018-11-24T10:35:29.000Z
2021-04-22T07:22:10.000Z
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include <grpc/grpc.h> #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/string_util.h> #include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/client_channel/resolver_registry.h" #include "src/core/ext/transport/chttp2/client/chttp2_connector.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/channel.h" static void client_channel_factory_ref( grpc_client_channel_factory* cc_factory) {} static void client_channel_factory_unref( grpc_client_channel_factory* cc_factory) {} static grpc_subchannel* client_channel_factory_create_subchannel( grpc_client_channel_factory* cc_factory, const grpc_subchannel_args* args) { grpc_connector* connector = grpc_chttp2_connector_create(); grpc_subchannel* s = grpc_subchannel_create(connector, args); grpc_connector_unref(connector); return s; } static grpc_channel* client_channel_factory_create_channel( grpc_client_channel_factory* cc_factory, const char* target, grpc_client_channel_type type, const grpc_channel_args* args) { if (target == nullptr) { gpr_log(GPR_ERROR, "cannot create channel with NULL target name"); return nullptr; } // Add channel arg containing the server URI. grpc_core::UniquePtr<char> canonical_target = grpc_core::ResolverRegistry::AddDefaultPrefixIfNeeded(target); grpc_arg arg = grpc_channel_arg_string_create((char*)GRPC_ARG_SERVER_URI, canonical_target.get()); const char* to_remove[] = {GRPC_ARG_SERVER_URI}; grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove(args, to_remove, 1, &arg, 1); grpc_channel* channel = grpc_channel_create(target, new_args, GRPC_CLIENT_CHANNEL, nullptr); grpc_channel_args_destroy(new_args); return channel; } static const grpc_client_channel_factory_vtable client_channel_factory_vtable = {client_channel_factory_ref, client_channel_factory_unref, client_channel_factory_create_subchannel, client_channel_factory_create_channel}; static grpc_client_channel_factory client_channel_factory = { &client_channel_factory_vtable}; /* Create a client channel: Asynchronously: - resolve target - connect to it (trying alternatives as presented) - perform handshakes */ grpc_channel* grpc_insecure_channel_create(const char* target, const grpc_channel_args* args, void* reserved) { grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE( "grpc_insecure_channel_create(target=%s, args=%p, reserved=%p)", 3, (target, args, reserved)); GPR_ASSERT(reserved == nullptr); // Add channel arg containing the client channel factory. grpc_arg arg = grpc_client_channel_factory_create_channel_arg(&client_channel_factory); grpc_channel_args* new_args = grpc_channel_args_copy_and_add(args, &arg, 1); // Create channel. grpc_channel* channel = client_channel_factory_create_channel( &client_channel_factory, target, GRPC_CLIENT_CHANNEL_TYPE_REGULAR, new_args); // Clean up. grpc_channel_args_destroy(new_args); return channel != nullptr ? channel : grpc_lame_client_channel_create( target, GRPC_STATUS_INTERNAL, "Failed to create client channel"); }
39.169811
80
0.729046
mnuck
60850ff8061079e361d38c3d4c9eb8eefb3caf0d
9,397
cpp
C++
osquery/events/darwin/fsevents.cpp
justintime32/osquery
721dd1ed624b25738c2471dae617d7868df8fb0d
[ "BSD-3-Clause" ]
1
2018-10-30T03:58:24.000Z
2018-10-30T03:58:24.000Z
osquery/events/darwin/fsevents.cpp
justintime32/osquery
721dd1ed624b25738c2471dae617d7868df8fb0d
[ "BSD-3-Clause" ]
null
null
null
osquery/events/darwin/fsevents.cpp
justintime32/osquery
721dd1ed624b25738c2471dae617d7868df8fb0d
[ "BSD-3-Clause" ]
2
2020-09-23T04:49:23.000Z
2022-03-29T17:32:31.000Z
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <fnmatch.h> #include <boost/filesystem.hpp> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/tables.h> #include "osquery/events/darwin/fsevents.h" /** * @brief FSEvents needs a real/absolute path for watches. * * When adding a subscription, FSEvents will resolve a depth of recursive * symlinks. Increasing the max will make tolerance to odd setups more robust * but introduce additional latency during startup. */ #define FSEVENTS_MAX_SYMLINK_DEPTH 5 namespace fs = boost::filesystem; namespace osquery { std::map<FSEventStreamEventFlags, std::string> kMaskActions = { {kFSEventStreamEventFlagItemChangeOwner, "ATTRIBUTES_MODIFIED"}, {kFSEventStreamEventFlagItemXattrMod, "ATTRIBUTES_MODIFIED"}, {kFSEventStreamEventFlagItemInodeMetaMod, "ATTRIBUTES_MODIFIED"}, {kFSEventStreamEventFlagItemCreated, "CREATED"}, {kFSEventStreamEventFlagItemRemoved, "DELETED"}, {kFSEventStreamEventFlagItemModified, "UPDATED"}, {kFSEventStreamEventFlagItemRenamed, "MOVED_TO"}, {kFSEventStreamEventFlagMustScanSubDirs, "COLLISION_WITHIN"}, {kFSEventStreamEventFlagUnmount, "UNMOUNTED"}, {kFSEventStreamEventFlagRootChanged, "ROOT_CHANGED"}, }; REGISTER(FSEventsEventPublisher, "event_publisher", "fsevents"); void FSEventsSubscriptionContext::requireAction(const std::string& action) { for (const auto& bit : kMaskActions) { if (action == bit.second) { mask = mask & bit.first; } } } void FSEventsEventPublisher::restart() { if (run_loop_ == nullptr) { return; } // Remove any existing stream. stop(); // Build paths as CFStrings { WriteLock lock(mutex_); if (paths_.empty()) { // There are no paths to watch. paths_.insert("/dev/null"); } std::vector<CFStringRef> cf_paths; for (const auto& path : paths_) { auto cf_path = CFStringCreateWithCString( nullptr, path.c_str(), kCFStringEncodingUTF8); cf_paths.push_back(cf_path); } // The FSEvents watch takes a CFArrayRef auto watch_list = CFArrayCreate(nullptr, reinterpret_cast<const void**>(&cf_paths[0]), cf_paths.size(), &kCFTypeArrayCallBacks); // Set stream flags. auto flags = kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagWatchRoot; if (no_defer_) { flags |= kFSEventStreamCreateFlagNoDefer; } if (no_self_) { flags |= kFSEventStreamCreateFlagIgnoreSelf; } // Create the FSEvent stream. stream_ = FSEventStreamCreate(nullptr, &FSEventsEventPublisher::Callback, nullptr, watch_list, kFSEventStreamEventIdSinceNow, 1, flags); if (stream_ != nullptr) { // Schedule the stream on the run loop. FSEventStreamScheduleWithRunLoop( stream_, run_loop_, kCFRunLoopDefaultMode); if (FSEventStreamStart(stream_)) { stream_started_ = true; } else { LOG(ERROR) << "Cannot start FSEvent stream: FSEventStreamStart failed"; } } else { LOG(ERROR) << "Cannot create FSEvent stream: FSEventStreamCreate failed"; } // Clean up strings, watch list, and context. CFRelease(watch_list); for (auto& cf_path : cf_paths) { CFRelease(cf_path); } } } void FSEventsEventPublisher::stop() { // Stop the stream. WriteLock lock(mutex_); if (run_loop_ == nullptr) { // No need to stop if there is not run loop. return; } if (stream_ != nullptr) { FSEventStreamStop(stream_); stream_started_ = false; FSEventStreamUnscheduleFromRunLoop( stream_, run_loop_, kCFRunLoopDefaultMode); FSEventStreamInvalidate(stream_); FSEventStreamRelease(stream_); stream_ = nullptr; } // Stop the run loop. CFRunLoopStop(run_loop_); } void FSEventsEventPublisher::tearDown() { stop(); // Do not keep a reference to the run loop. run_loop_ = nullptr; } std::set<std::string> FSEventsEventPublisher::transformSubscription( FSEventsSubscriptionContextRef& sc) const { std::set<std::string> paths; sc->discovered_ = sc->path; if (sc->path.find("**") != std::string::npos) { // Double star will indicate recursive matches, restricted to endings. sc->recursive = true; sc->discovered_ = sc->path.substr(0, sc->path.find("**")); // Remove '**' from the subscription path (used to match later). sc->path = sc->discovered_; } // If the path 'still' OR 'either' contains a single wildcard. if (sc->path.find('*') != std::string::npos) { // First check if the wildcard is applied to the end. auto fullpath = fs::path(sc->path); if (fullpath.filename().string().find('*') != std::string::npos) { sc->discovered_ = fullpath.parent_path().string(); } // FSEvents needs a real path, if the wildcard is within the path then // a configure-time resolve is required. if (sc->discovered_.find('*') != std::string::npos) { std::vector<std::string> exploded_paths; resolveFilePattern(sc->discovered_, exploded_paths); for (const auto& path : exploded_paths) { paths.insert(path); } sc->recursive_match = sc->recursive; return paths; } } paths.insert(sc->discovered_); return paths; } void FSEventsEventPublisher::configure() { // Rebuild the watch paths. stop(); { WriteLock lock(mutex_); paths_.clear(); for (auto& sub : subscriptions_) { auto sc = getSubscriptionContext(sub->context); if (sc->discovered_.size() > 0) { continue; } auto paths = transformSubscription(sc); paths_.insert(paths.begin(), paths.end()); } } restart(); } Status FSEventsEventPublisher::run() { // The run entrypoint executes in a dedicated thread. if (run_loop_ == nullptr) { run_loop_ = CFRunLoopGetCurrent(); // Restart the stream creation. restart(); } // Start the run loop, it may be removed with a tearDown. CFRunLoopRun(); return Status(0, "OK"); } void FSEventsEventPublisher::Callback( ConstFSEventStreamRef stream, void* callback_info, size_t num_events, void* event_paths, const FSEventStreamEventFlags fsevent_flags[], const FSEventStreamEventId fsevent_ids[]) { for (size_t i = 0; i < num_events; ++i) { auto ec = createEventContext(); ec->fsevent_stream = stream; ec->fsevent_flags = fsevent_flags[i]; ec->transaction_id = fsevent_ids[i]; ec->path = std::string(((char**)event_paths)[i]); if (ec->fsevent_flags & kFSEventStreamEventFlagMustScanSubDirs) { // The FSEvents thread coalesced events within and will report a root. TLOG << "FSEvents collision, root: " << ec->path; } if (ec->fsevent_flags & kFSEventStreamEventFlagRootChanged) { // Must rescan for the changed root. } if (ec->fsevent_flags & kFSEventStreamEventFlagUnmount) { // Should remove the watch on this path. } // Record the string-version of the first matched mask bit. bool has_action = false; for (const auto& action : kMaskActions) { if (ec->fsevent_flags & action.first) { // Actions may be multiplexed. Fire and event for each. ec->action = action.second; EventFactory::fire<FSEventsEventPublisher>(ec); has_action = true; } } if (!has_action) { // If no action was matched for this path event, fire and unknown. ec->action = "UNKNOWN"; EventFactory::fire<FSEventsEventPublisher>(ec); } } } bool FSEventsEventPublisher::shouldFire( const FSEventsSubscriptionContextRef& sc, const FSEventsEventContextRef& ec) const { if (sc->recursive && !sc->recursive_match) { ssize_t found = ec->path.find(sc->path); if (found != 0) { return false; } } else if (fnmatch((sc->path + "*").c_str(), ec->path.c_str(), FNM_PATHNAME | FNM_CASEFOLD | ((sc->recursive_match) ? FNM_LEADING_DIR : 0)) != 0) { // Only apply a leading-dir match if this is a recursive watch with a // match requirement (an inline wildcard with ending recursive wildcard). return false; } if (sc->mask != 0 && !(ec->fsevent_flags & sc->mask)) { // Compare the event context mask to the subscription context. return false; } return true; } void FSEventsEventPublisher::flush(bool async) { if (stream_ != nullptr && stream_started_) { if (async) { FSEventStreamFlushAsync(stream_); } else { FSEventStreamFlushSync(stream_); } } } size_t FSEventsEventPublisher::numSubscriptionedPaths() const { return paths_.size(); } bool FSEventsEventPublisher::isStreamRunning() const { if (stream_ == nullptr || !stream_started_ || run_loop_ == nullptr) { return false; } return CFRunLoopIsWaiting(run_loop_); } }
29.737342
79
0.650846
justintime32
60861cacfeab2c90a6d780e5665912549d8ae382
653
cpp
C++
src/Pixel.cpp
kosiken/lion-image-to-ascii
c000d0f90f06a88935f5ffc62e40402238025f4c
[ "MIT" ]
2
2021-05-04T00:30:43.000Z
2021-10-17T15:32:26.000Z
src/Pixel.cpp
kosiken/lion-image-to-ascii
c000d0f90f06a88935f5ffc62e40402238025f4c
[ "MIT" ]
null
null
null
src/Pixel.cpp
kosiken/lion-image-to-ascii
c000d0f90f06a88935f5ffc62e40402238025f4c
[ "MIT" ]
null
null
null
#include <iostream> #include "Pixel.h" #define LION_DIV 256 LionPixel::LionPixel() { r = 0; g= 0; b = 0; } LionPixel::LionPixel(int red, int green, int blue) { r = red; g = green; b = blue; } LionPixel::LionPixel(int red, int green, int blue, double alpha) { r = red; g = green; b = blue; a= alpha; updateCss(); } double LionPixel::intensity() { intensityV = (r + g + b) * a; return intensityV; } std::ostream & operator<<(std::ostream & os, const LionPixel & t){ os << "[ r => " << t.r << ", g => " << t.g << ", b => " << t.b << ", a => " << t.a << " ]"; return os; };
14.195652
66
0.496172
kosiken
6087d9cae3034483a3e68ea7dad0b80232a6cd47
11,112
cpp
C++
f9_os/src/f9/thread.cpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
null
null
null
f9_os/src/f9/thread.cpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
null
null
null
f9_os/src/f9/thread.cpp
ghsecuritylab/arm-cortex-v7-unix
cd499fa94d6ee6cd78a31387f3512d997335df52
[ "Apache-2.0" ]
1
2020-03-08T01:08:38.000Z
2020-03-08T01:08:38.000Z
#include "thread.hpp" #include "fpage.hpp" #include "schd.hpp" #include "ktimer.hpp" #include "ipc.hpp" #include "irq.hpp" namespace f9 { __attribute__((weak)) void root_thread(); __attribute__((weak)) void root_thread() { while(1); } DECLARE_KTABLE(tcb_t, thread_table, CONFIG_MAX_THREADS); //volatile tcb_t *current = nullptr; /* Currently on CPU */ volatile tcb_t *current = nullptr; /* Currently on CPU */ void *current_utcb __USER_DATA; extern tcb_t *caller; tcb_t *thread_map[CONFIG_MAX_THREADS]; int thread_count; static tcb_t *thread_sched(sched_slot_t *); void thread_init_subsys() { // don't worry about kept #if 0 fpage_t *last = nullptr; ktable_init(&thread_table); kip.thread_info.s.system_base = THREAD_SYS; kip.thread_info.s.user_base = THREAD_USER; /* Create KIP fpages * last is ignored, because kip fpages is aligned */ fpage_t::assign_ext(-1, (memptr_t) &kip, sizeof(kip_t), &kip_fpage, &last); fpage_t::assign_ext(-1, (memptr_t) kip_extra, CONFIG_KIP_EXTRA_SIZE, &kip_extra_fpage, &last); #endif sched_slot_set_handler(SSI::NORMAL_THREAD, thread_sched); } /* * Return upper_bound using binary search */ static int thread_map_search(thread_id_t globalid, int from, int to) { int tid = GLOBALID_TO_TID(globalid); /* Upper bound if beginning of array */ if (to == from || (int)GLOBALID_TO_TID(thread_map[from]->t_globalid) >= tid) return from; while (from <= to) { if ((to - from) <= 1) return to; int mid = from + (to - from) / 2; if ((int)GLOBALID_TO_TID(thread_map[mid]->t_globalid) > tid) to = mid; else if ((int)GLOBALID_TO_TID(thread_map[mid]->t_globalid) < tid) from = mid; else return mid; } /* not reached */ return -1; } /* * Insert thread into thread map */ static void thread_map_insert(thread_id_t globalid, tcb_t *thr) { if (thread_count == 0) { thread_map[thread_count++] = thr; } else { int i = thread_map_search(globalid, 0, thread_count); int j = thread_count; /* Move forward * Don't check if count is out of range, * because we will fail on ktable_alloc */ for (; j > i; --j) thread_map[j] = thread_map[j - 1]; thread_map[i] = thr; ++thread_count; } } static void thread_map_delete(thread_id_t globalid) { if (thread_count == 1) { thread_count = 0; } else { int i = thread_map_search(globalid, 0, thread_count); --thread_count; for (; i < thread_count; i++) thread_map[i] = thread_map[i + 1]; } } tcb_t::tcb_t(thread_id_t globalid, utcb_t *utcb) : t_globalid(globalid) , t_localid(0) , state(TSTATE::INACTIVE) , stack_base(0) , stack_size(0) , ctx() #ifdef CONFIG_ENABLE_FPAGE , as(nullptr) #endif , utcb(utcb) , ipc_from(0) , t_sibling(nullptr) , t_parent(nullptr) , t_child(nullptr) , timeout_event(0) { thread_map_insert(globalid, this); if (utcb) utcb->t_globalid = globalid; dbg::print(dbg::DL_THREAD, "T: New thread: %t @[%p] \n", globalid, this); } volatile tcb_t* tcb_t::current() { return f9::current; } tcb_t* tcb_t::create(thread_id_t globalid, utcb_t *utcb){ int id = GLOBALID_TO_TID(globalid); assert(caller != nullptr); if (id < static_cast<int>(THREAD::SYS) || globalid == ANYTHREAD || globalid == ANYLOCALTHREAD) { set_caller_error(UE::TC_NOT_AVAILABLE); return nullptr; } tcb_t *thr = new tcb_t(globalid, utcb); if (!thr) { set_caller_error(UE::OUT_OF_MEM); return nullptr; } thr->t_parent = caller; /* Place under */ if (caller->t_child) { tcb_t *t = caller->t_child; while (t->t_sibling != 0) t = t->t_sibling; t->t_sibling = thr; thr->t_localid = t->t_localid + (1 << 6); } else { /* That is first thread in child chain */ caller->t_child = thr; thr->t_localid = (1 << 6); } return thr; } tcb_t::~tcb_t() { tcb_t *parent, *child, *prev_child; /* remove thr from its parent and its siblings */ parent = this->t_parent; if (parent->t_child == this) { parent->t_child = this->t_sibling; } else { child = parent->t_child; while (child != this) { prev_child = child; child = child->t_sibling; } prev_child->t_sibling = child->t_sibling; } /* move thr's children to caller */ child = this->t_child; if (child) { child->t_parent = caller; while (child->t_sibling) { child = child->t_sibling; child->t_parent = caller; } /* connect thr's children to caller's children */ child->t_sibling = caller->t_child; caller->t_child = this->t_child; } thread_map_delete(t_globalid); } void tcb_t::free_space(){ #ifdef CONFIG_ENABLE_FPAGE this->as.reset(); #endif } void tcb_t::space(thread_id_t spaceid, utcb_t *utcb){ #ifdef CONFIG_ENABLE_FPAGE /* If spaceid == dest than create new address space * else share address space between threads */ if (GLOBALID_TO_TID(this->t_globalid) == GLOBALID_TO_TID(spaceid)) { this->as = std::make_shared<as_t>(this->t_globalid); /* Grant kip_fpage & kip_ext_fpage only to new AS */ //this->as->map(kip_fpage, GRANT); //this->as->map(kip_extra_fpage, GRANT); dbg::print(dbg::DL_THREAD, "\tNew space: as: %p, utcb: %p \n", this->as, utcb); } else { tcb_t *space = thread_by_globalid(spaceid); this->as = space->as; } /* If no caller, than it is mapping from kernel to root thread * (some special case for root_utcb) */ if (caller) map_area(caller->as, this->as, (memptr_t) utcb, sizeof(utcb_t), GRANT, caller->ispriviliged()); else map_area(this->as, this->as, (memptr_t) utcb, sizeof(utcb_t), GRANT, true); #endif } void tcb_t::_init_ctx(uintptr_t spi, uintptr_t pc, uintptr_t regsi){ /* Reserve 8 words for fake context */ //sp -= RESERVED_STACK; uint32_t* sp = reinterpret_cast<uint32_t*>(reinterpret_cast<uint8_t*>(spi)-RESERVED_STACK); ctx.sp = reinterpret_cast<uint32_t>(sp); /* Set EXC_RETURN and CONTROL for thread and create initial stack for it * When thread is dispatched, on first context switch */ if (GLOBALID_TO_TID(t_globalid) >= static_cast<uint32_t>(THREAD::ROOT)) { ctx.ret = 0xFFFFFFFD; ctx.ctl = 0x3; } else { ctx.ret = 0xFFFFFFF9; ctx.ctl = 0x0; } //uint32_t* spa = reinterpret_cast<uint32_t*>(sp); if (regsi == 0) { sp[REG_R0] = 0x0; sp[REG_R1] = 0x0; sp[REG_R2] = 0x0; sp[REG_R3] = 0x0; } else { uint32_t* regs = reinterpret_cast<uint32_t*>(regsi); sp[REG_R0] = regs[0]; sp[REG_R1] = regs[1]; sp[REG_R2] = regs[2]; sp[REG_R3] = regs[3]; } sp[REG_R12] = 0x0; sp[REG_LR] = 0xFFFFFFFF; sp[REG_PC] = pc; sp[REG_xPSR] = 0x1000000; /* Thumb bit on */ } void tcb_t::_init_kernel_ctx(uintptr_t spi) { uint32_t* sp = reinterpret_cast<uint32_t*>(reinterpret_cast<uint8_t*>(spi)-RESERVED_STACK); ctx.sp = reinterpret_cast<uint32_t>(sp); ctx.ret = 0xFFFFFFF9; ctx.ctl = 0x0; } /* * Search thread by its global id */ tcb_t *thread_by_globalid(thread_id_t globalid) { int idx = thread_map_search(globalid, 0, thread_count); if (GLOBALID_TO_TID(thread_map[idx]->t_globalid) != GLOBALID_TO_TID(globalid)) return nullptr; return thread_map[idx]; } void tcb_t::switch_to() { assert(isrunnable()); f9::current = this; current_utcb =utcb; #if 0 if (current->as) current->setup_mpu(current->as, current->ctx.sp, ((uint32_t *) current->ctx.sp)[REG_PC], current->stack_base, current->stack_size); #endif } /* Select normal thread to run * * NOTE: all threads are derived from root */ static tcb_t *thread_select(tcb_t *parent) { tcb_t *thr = parent->t_child; if (thr == NULL) return NULL; while (1) { if (thr->isrunnable()) return thr; if (thr->t_child != nullptr) { thr = thr->t_child; continue; } if (thr->t_sibling != nullptr) { thr = thr->t_sibling; continue; } do { if (thr->t_parent == parent) return nullptr; thr = thr->t_parent; } while (thr->t_sibling == nullptr); thr = thr->t_sibling; } } // systhread tcb_t *idle; tcb_t *kernel; tcb_t *root; static tcb_t *thread_sched(sched_slot_t *slot) { return thread_select(root); } utcb_t root_utcb __KIP; extern void root_thread(void); static void kernel_thread(void); static void idle_thread(void) { while (1) #ifdef CONFIG_KTIMER_TICKLESS ktimer_enter_tickless(); #else ARM::wfi(); //wait_for_interrupt(); #endif /* CONFIG_KTIMER_TICKLESS */ } static void kernel_thread(void) { while (1) { /* If all softirqs processed, call SVC to * switch context immediately */ softirq_t::execute(); irq_svc(); } } void tcb_t::create_root_thread(void) { root = new tcb_t(TID_TO_GLOBALID(THREAD::ROOT), &root_utcb); #ifdef CONFIG_ENABLE_FPAGE root->space(TID_TO_GLOBALID(THREAD::ROOT), &root_utcb); root->as->map_user(); #endif uint32_t regs[4] ={ #if 0 [REG_R0] = (uint32_t) &kip, #else [REG_R0] = 0, // no kip #endif [REG_R1] = ptr_to_int(root->utcb), [REG_R2] = 0, [REG_R3] = 0 }; root->init_ctx((void *) &root_stack_end, &root_thread, regs); root->stack_base = (memptr_t) &root_stack_start; root->stack_size = (uint32_t) &root_stack_end - (uint32_t) &root_stack_start; sched_slot_dispatch(SSI::ROOT_THREAD, root); root->state = TSTATE::RUNNABLE; } void tcb_t::create_kernel_thread(void){ kernel = new tcb_t(TID_TO_GLOBALID(THREAD::KERNEL), nullptr); kernel->init_kernel_ctx(&kernel_stack_end); /* This will prevent running other threads * than kernel until it will be initialized */ sched_slot_dispatch(SSI::SOFTIRQ, kernel); kernel->state = TSTATE::RUNNABLE; } void tcb_t::create_idle_thread(void){ idle = new tcb_t(TID_TO_GLOBALID(THREAD::KERNEL), nullptr); idle->init_ctx( &idle_stack_end, idle_thread, nullptr); sched_slot_dispatch(SSI::IDLE, idle); idle->state = TSTATE::RUNNABLE; } void tcb_t::switch_to_kernel(void){ // startup? create_kernel_thread(); f9::current = kernel; init_ctx_switch(&kernel->ctx, kernel_thread); } void set_kernel_state(TSTATE state) { kernel->state = state; } void set_user_error(tcb_t *thread, UE error) { assert(thread && thread->utcb); thread->utcb->error_code = static_cast<uint32_t>(error); } void set_caller_error(UE error) { if (caller) set_user_error((tcb_t *) caller, error); else panic("User-level error %d during in-kernel call!", error); } void user_log(tcb_t *from) { char *format = (char *) from->ctx.regs[1]; va_list *va = (va_list *) from->ctx.regs[2]; dbg::print(dbg::DL_KDB, format, *va); } void tcb_t::startup(){ trace_printf("tcb_t::startup()\r\n"); create_idle_thread(); create_root_thread(); ktimer_event_init(); assert(ktimer_event_t::create(64, ipc_deliver, nullptr)); switch_to_kernel(); } }; void PendSV_Handler(void) __NAKED; void PendSV_Handler(void) { irq_enter(); schedule_in_irq(); irq_return(); }
23.4926
93
0.652988
ghsecuritylab
608b51e70ce7335628db84bb13a86b1bb3236cc9
5,187
cc
C++
daemon/timings.cc
jimwwalker/memcached
0b4aec7aff016c56edc9fb6008f21cf4ec06edcd
[ "BSD-3-Clause" ]
null
null
null
daemon/timings.cc
jimwwalker/memcached
0b4aec7aff016c56edc9fb6008f21cf4ec06edcd
[ "BSD-3-Clause" ]
null
null
null
daemon/timings.cc
jimwwalker/memcached
0b4aec7aff016c56edc9fb6008f21cf4ec06edcd
[ "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include "timings.h" #include <memcached/protocol_binary.h> #include <stdlib.h> #include <string.h> #include <sstream> #ifdef HAVE_ATOMIC #include <atomic> #else #include <cstdatomic> #endif typedef struct timings_st { /* We collect timings for <=1 us */ std::atomic<uint32_t> ns; /* We collect timings per 10usec */ std::atomic<uint32_t> usec[100]; /* we collect timings from 0-49 ms (entry 0 is never used!) */ std::atomic<uint32_t> msec[50]; std::atomic<uint32_t> halfsec[10]; std::atomic<uint32_t> wayout; std::atomic<uint64_t> total; } timings_t; timings_t timings[0x100]; void collect_timing(uint8_t cmd, hrtime_t nsec) { timings_t *t = &timings[cmd]; hrtime_t usec = nsec / 1000; hrtime_t msec = usec / 1000; hrtime_t hsec = msec / 500; if (usec == 0) { t->ns++; } else if (usec < 1000) { t->usec[usec / 10]++; } else if (msec < 50) { t->msec[msec]++; } else if (hsec < 10) { t->halfsec[hsec]++; } else { t->wayout++; } t->total++; } void initialize_timings(void) { int ii, jj; for (ii = 0; ii < 0x100; ++ii) { timings[ii].ns.store(0); for (jj = 0; jj < 100; ++jj) { timings[ii].usec[jj].store(0); } for (jj = 0; jj < 50; ++jj) { timings[ii].msec[jj].store(0); } for (jj = 0; jj < 10; ++jj) { timings[ii].halfsec[jj].store(0); } timings[ii].wayout.store(0); timings[ii].total.store(0); } } void generate_timings(uint8_t opcode, const void *cookie) { std::stringstream ss; timings_t *t = &timings[opcode]; ss << "{\"ns\":" << t->ns.load() << ",\"us\":["; for (int ii = 0; ii < 99; ++ii) { ss << t->usec[ii].load() << ","; } ss << t->usec[99].load() << "],\"ms\":["; for (int ii = 1; ii < 49; ++ii) { ss << t->msec[ii].load() << ","; } ss << t->msec[49].load() << "],\"500ms\":["; for (int ii = 0; ii < 9; ++ii) { ss << t->halfsec[ii].load() << ","; } ss << t->halfsec[9].load() << "],\"wayout\":" << t->wayout.load() << "}"; std::string str = ss.str(); binary_response_handler(NULL, 0, NULL, 0, str.data(), str.length(), PROTOCOL_BINARY_RAW_BYTES, PROTOCOL_BINARY_RESPONSE_SUCCESS, 0, cookie); } uint64_t get_aggregated_cmd_stats(cmd_stat_t type) { uint64_t ret = 0; static uint8_t mutations[] = { PROTOCOL_BINARY_CMD_ADD, PROTOCOL_BINARY_CMD_ADDQ, PROTOCOL_BINARY_CMD_APPEND, PROTOCOL_BINARY_CMD_APPENDQ, PROTOCOL_BINARY_CMD_DECREMENT, PROTOCOL_BINARY_CMD_DECREMENTQ, PROTOCOL_BINARY_CMD_DELETE, PROTOCOL_BINARY_CMD_DELETEQ, PROTOCOL_BINARY_CMD_GAT, PROTOCOL_BINARY_CMD_GATQ, PROTOCOL_BINARY_CMD_INCREMENT, PROTOCOL_BINARY_CMD_INCREMENTQ, PROTOCOL_BINARY_CMD_PREPEND, PROTOCOL_BINARY_CMD_PREPENDQ, PROTOCOL_BINARY_CMD_REPLACE, PROTOCOL_BINARY_CMD_REPLACEQ, PROTOCOL_BINARY_CMD_SET, PROTOCOL_BINARY_CMD_SETQ, PROTOCOL_BINARY_CMD_TOUCH, PROTOCOL_BINARY_CMD_INVALID}; static uint8_t retrival[] = { PROTOCOL_BINARY_CMD_GAT, PROTOCOL_BINARY_CMD_GATQ, PROTOCOL_BINARY_CMD_GET, PROTOCOL_BINARY_CMD_GETK, PROTOCOL_BINARY_CMD_GETKQ, PROTOCOL_BINARY_CMD_GETQ, PROTOCOL_BINARY_CMD_GET_LOCKED, PROTOCOL_BINARY_CMD_GET_RANDOM_KEY, PROTOCOL_BINARY_CMD_GET_REPLICA, PROTOCOL_BINARY_CMD_INVALID }; static uint8_t total[] = { PROTOCOL_BINARY_CMD_ADD, PROTOCOL_BINARY_CMD_ADDQ, PROTOCOL_BINARY_CMD_APPEND, PROTOCOL_BINARY_CMD_APPENDQ, PROTOCOL_BINARY_CMD_DECREMENT, PROTOCOL_BINARY_CMD_DECREMENTQ, PROTOCOL_BINARY_CMD_DELETE, PROTOCOL_BINARY_CMD_DELETEQ, PROTOCOL_BINARY_CMD_GAT, PROTOCOL_BINARY_CMD_GATQ, PROTOCOL_BINARY_CMD_GET, PROTOCOL_BINARY_CMD_GETK, PROTOCOL_BINARY_CMD_GETKQ, PROTOCOL_BINARY_CMD_GETQ, PROTOCOL_BINARY_CMD_GET_LOCKED, PROTOCOL_BINARY_CMD_GET_RANDOM_KEY, PROTOCOL_BINARY_CMD_GET_REPLICA, PROTOCOL_BINARY_CMD_INCREMENT, PROTOCOL_BINARY_CMD_INCREMENTQ, PROTOCOL_BINARY_CMD_PREPEND, PROTOCOL_BINARY_CMD_PREPENDQ, PROTOCOL_BINARY_CMD_REPLACE, PROTOCOL_BINARY_CMD_REPLACEQ, PROTOCOL_BINARY_CMD_SET, PROTOCOL_BINARY_CMD_SETQ, PROTOCOL_BINARY_CMD_TOUCH, PROTOCOL_BINARY_CMD_INVALID }; uint8_t *ids; switch (type) { case CMD_TOTAL_MUTATION: ids = mutations; break; case CMD_TOTAL_RETRIVAL: ids = retrival; break; case CMD_TOTAL: ids = total; break; default: abort(); } while (*ids != PROTOCOL_BINARY_CMD_INVALID) { ret += timings[*ids].total.load(); ++ids; } return ret; }
27.015625
77
0.601697
jimwwalker
608e8341b4f4009be7368848d99c77ca32307ff6
12,039
cpp
C++
source/mango/image/image_hdr.cpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
3
2021-02-27T10:29:37.000Z
2022-02-16T16:31:26.000Z
source/mango/image/image_hdr.cpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
null
null
null
source/mango/image/image_hdr.cpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
5
2021-03-22T11:06:00.000Z
2022-02-22T02:53:19.000Z
/* MANGO Multimedia Development Platform Copyright (C) 2012-2021 Twilight Finland 3D Oy Ltd. All rights reserved. */ #include <cmath> #include <mango/core/pointer.hpp> #include <mango/core/buffer.hpp> #include <mango/core/system.hpp> #include <mango/image/image.hpp> namespace { using namespace mango; using namespace mango::image; // ------------------------------------------------------------ // tokenizer // ------------------------------------------------------------ std::string readline(const u8*& data, const u8* end) { const u8* p = data; int endsize = 1; // scan for endline for ( ; data < end; ) { u8 v = *p++; // Unix ("\n") if (v == '\n') break; // MacOS ("\r") if (v == '\r') { // Windows ("\r\n") if (*p == '\n') { ++endsize; ++p; } break; } } int size = int(p - data) - endsize; std::string msg(reinterpret_cast<const char*>(data), size); data = p; return msg; } inline bool whitespace(char v) { return v == ' ' || v == '\t' || v == '='; } void insert_token(std::vector<std::string>& tokens, const char* text, int size) { if (size > 0) { std::string msg(text, size); tokens.push_back(msg); } } std::vector<std::string> tokenize(const std::string& line) { std::vector<std::string> tokens; const char* p = line.c_str(); const char* endline = p + line.length(); for ( ; p < endline;) { // skip whitespaces for ( ;; ++p) { char v = *p; if (!v) return tokens; if (!whitespace(v)) break; } const char* begin = p; // seek next whitespace for ( ;; ++p) { char v = *p; if (!v) { int size = int(p - begin); insert_token(tokens, begin, size); return tokens; } if (whitespace(v)) break; } int size = int(p - begin); insert_token(tokens, begin, size); } return tokens; } // ------------------------------------------------------------ // encoder // ------------------------------------------------------------ struct rgbe { u8 r, g, b, e; }; /* rgbe create_rgbe(float r, float g, float b) { float maxf = r > g ? r : g; maxf = maxf > b ? maxf : b; rgbe color; if (maxf <= 1e-32f) { color.r = 0; color.g = 0; color.b = 0; color.e = 0; } else { int exponent; std::frexpf(maxf, &exponent); float scale = std::ldexpf(1.0f, 8 - exponent); color.r = u8(r * scale); color.g = u8(g * scale); color.b = u8(b * scale); color.e = u8(exponent + 128); } return color; } */ // ------------------------------------------------------------ // decoder // ------------------------------------------------------------ void write_rgbe(float* buffer, rgbe color) { float scale = color.e ? std::ldexp(1.0f, color.e - 136) : 0; buffer[0] = color.r * scale; buffer[1] = color.g * scale; buffer[2] = color.b * scale; buffer[3] = 1.0f; } struct HeaderRAD { enum rad_format { rad_rle_rgbe, rad_unsupported } format = rad_unsupported; int width = 0; int height = 0; float exposure = 1.0f; bool xflip = false; bool yflip = false; ImageHeader header; const u8* parse(ConstMemory memory) { const u8* data = memory.address; const u8* end = memory.address + memory.size; std::string id = readline(data, end); if (id != "#?RADIANCE") { header.setError("[ImageDecoder.HDR] Incorrect radiance header."); return nullptr; } for ( ;; ) { std::string ln = readline(data, end); if (ln.empty()) break; std::vector<std::string> tokens = tokenize(ln); if (tokens[0] == "FORMAT") { if (tokens.size() != 2) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (format)."); return nullptr; } if (tokens[1] == "32-bit_rle_rgbe") format = rad_rle_rgbe; } else if (tokens[1] == "EXPOSURE") { if (tokens.size() != 2) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (exposure)."); return nullptr; } exposure = float(std::atof(tokens[1].c_str())); } } if (format == rad_unsupported) { header.setError("[ImageDecoder.HDR] Incorrect or unsupported format."); return nullptr; } std::string dims = readline(data, end); std::vector<std::string> tokens = tokenize(dims); if (tokens.size() != 4) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (dimensions)."); return nullptr; } for (int i = 0; i < 2; ++i) { int index = i * 2; if (tokens[index] == "+Y") { yflip = false; height = std::atoi(tokens[index + 1].c_str()); } else if (tokens[index] == "-Y") { yflip = true; height = std::atoi(tokens[index + 1].c_str()); } else if (tokens[index] == "+X") { xflip = false; width = std::atoi(tokens[index + 1].c_str()); } else if (tokens[index] == "-X") { xflip = true; width = std::atoi(tokens[index + 1].c_str()); } else { header.setError("[ImageDecoder.HDR] Incorrect radiance header (dimensions)."); return nullptr; } } if (!width || !height) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (dimensions)."); return nullptr; } header.width = width; header.height = height; header.depth = 0; header.levels = 0; header.faces = 0; header.palette = false; header.format = Format(128, Format::FLOAT32, Format::RGBA, 32, 32, 32, 32); header.compression = TextureCompression::NONE; return data; } }; void hdr_decode(ImageDecodeStatus& status, const Surface& surface, const u8* data) { Buffer buffer(surface.width * 4); for (int y = 0; y < surface.height; ++y) { if (data[0] != 2 || data[1] != 2 || data[2] & 0x80) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (wrong header)."); return; } if (((data[2] << 8) | data[3]) != surface.width) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (wrong scan)."); return; } data += 4; for (int channel = 0; channel < 4; ++channel) { u8* dest = buffer + surface.width * channel; u8* end = dest + surface.width; while (dest < end) { int count = *data++; if (count > 128) { count -= 128; if (!count || dest + count > end) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (rle count)."); return; } u8 value = *data++; std::memset(dest, value, count); dest += count; } else { if (!count || dest + count > end) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (rle count)."); return; } std::memcpy(dest, data, count); dest += count; data += count; } } } float* image = surface.address<float>(0, y); for (int x = 0; x < surface.width; ++x) { rgbe color; color.r = buffer[x + surface.width * 0]; color.g = buffer[x + surface.width * 1]; color.b = buffer[x + surface.width * 2]; color.e = buffer[x + surface.width * 3]; write_rgbe(image, color); image += 4; } } } // ------------------------------------------------------------ // ImageDecoder // ------------------------------------------------------------ struct Interface : ImageDecoderInterface { HeaderRAD m_rad_header; const u8* m_data; Interface(ConstMemory memory) { m_data = m_rad_header.parse(memory); } ~Interface() { } ImageHeader header() override { return m_rad_header.header; } ImageDecodeStatus decode(const Surface& dest, const ImageDecodeOptions& options, int level, int depth, int face) override { MANGO_UNREFERENCED(options); MANGO_UNREFERENCED(level); MANGO_UNREFERENCED(depth); MANGO_UNREFERENCED(face); ImageDecodeStatus status; const ImageHeader& header = m_rad_header.header; if (!header.success) { status.setError(header.info); return status; } status.direct = dest.format == header.format && dest.width == header.width && dest.height == header.height; if (status.direct) { hdr_decode(status, dest, m_data); } else { Bitmap temp(header.width, header.height, header.format); hdr_decode(status, temp, m_data); if (status) { dest.blit(0, 0, temp); } } return status; } }; ImageDecoderInterface* createInterface(ConstMemory memory) { ImageDecoderInterface* x = new Interface(memory); return x; } } // namespace namespace mango::image { void registerImageDecoderHDR() { registerImageDecoder(createInterface, ".hdr"); } } // namespace mango::image
27.361364
129
0.395216
ufoym
6091411015121751c0a2850261a59e0fbec426ec
711
cpp
C++
regression/esbmc-cpp/qt/QMultiMap/multimap_swap/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
regression/esbmc-cpp/qt/QMultiMap/multimap_swap/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
regression/esbmc-cpp/qt/QMultiMap/multimap_swap/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
// swap QMultiMaps #include <iostream> #include <QMultiMap> #include <cassert> using namespace std; int main () { QMultiMap<char,int> foo; QMultiMap<char,int> bar; QMultiMap<char,int>::iterator it; foo['x']=100; foo['y']=200; bar['a']=11; bar['b']=22; bar['c']=33; foo.swap(bar); cout << "foo contains:\n"; for ( it=foo.begin() ; it != foo.end(); it++ ) cout << it.key() << " => " << it.value() << endl; cout << "bar contains:\n"; for ( it=bar.begin() ; it != bar.end(); it++ ) cout << it.key() << " => " << it.value() << endl; assert(bar['x']==100); assert(bar['y']==200); assert(foo['a']==11); assert(foo['b']==22); assert(foo['c']==33); return 0; }
18.230769
53
0.528833
shmarovfedor
6091a0fd7a26cbcae458ded9ac29c32b47c6d59d
1,691
cc
C++
extensions/browser/browser_context_keyed_service_factories.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
extensions/browser/browser_context_keyed_service_factories.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
extensions/browser/browser_context_keyed_service_factories.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:13.000Z
2020-11-04T07:24:13.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/api/api_resource_manager.h" #include "extensions/browser/api/runtime/runtime_api.h" #include "extensions/browser/api/socket/socket.h" #include "extensions/browser/api/socket/tcp_socket.h" #include "extensions/browser/api/socket/udp_socket.h" #include "extensions/browser/api/sockets_tcp/tcp_socket_event_dispatcher.h" #include "extensions/browser/api/sockets_tcp_server/tcp_server_socket_event_dispatcher.h" #include "extensions/browser/api/sockets_udp/udp_socket_event_dispatcher.h" #include "extensions/browser/api/storage/storage_frontend.h" #include "extensions/browser/extension_prefs_factory.h" #include "extensions/browser/renderer_startup_helper.h" namespace extensions { void EnsureBrowserContextKeyedServiceFactoriesBuilt() { ApiResourceManager< extensions::ResumableTCPServerSocket>::GetFactoryInstance(); ApiResourceManager<extensions::ResumableTCPSocket>::GetFactoryInstance(); ApiResourceManager<extensions::ResumableUDPSocket>::GetFactoryInstance(); ApiResourceManager<extensions::Socket>::GetFactoryInstance(); core_api::TCPServerSocketEventDispatcher::GetFactoryInstance(); core_api::TCPSocketEventDispatcher::GetFactoryInstance(); core_api::UDPSocketEventDispatcher::GetFactoryInstance(); ExtensionPrefsFactory::GetInstance(); RendererStartupHelperFactory::GetInstance(); RuntimeAPI::GetFactoryInstance(); StorageFrontend::GetFactoryInstance(); } } // namespace extensions
45.702703
89
0.825547
justremotephone
60924806e9f5450a31679b7be2d3cb4ba58cdfc8
828
cpp
C++
TrackerValidation/FixationTarget.cpp
tim-murphy/eye-tracker-validation
70515aa9dc61c19fe61eb07bf2606be29e5e80e7
[ "MIT" ]
null
null
null
TrackerValidation/FixationTarget.cpp
tim-murphy/eye-tracker-validation
70515aa9dc61c19fe61eb07bf2606be29e5e80e7
[ "MIT" ]
16
2021-02-12T10:57:29.000Z
2021-11-25T00:35:29.000Z
TrackerValidation/FixationTarget.cpp
tim-murphy/eye-tracker-validation
70515aa9dc61c19fe61eb07bf2606be29e5e80e7
[ "MIT" ]
null
null
null
// Fixation target abstract class // Written by Tim Murphy <tim@murphy.org> 2021 #include "FixationTarget.h" #include "CircleTarget.h" #include "CrosshairBullseyeTarget.h" #include <stdexcept> FixationTarget::FixationTarget(unsigned int diameter) :diameter(diameter) { } unsigned int FixationTarget::getDiameter(void) const { return diameter; } FixationTarget *FixationTarget::create(const std::string &type, unsigned int diameter) { if (type == "circle") { return new CircleTarget(diameter); } else if (type == "crosshairbullseye" || type == "cbe") { return new CrosshairBullseyeTarget(diameter); } else { std::string err("Unknown fixation target type: " + type); throw std::runtime_error(err.c_str()); } }
23
65
0.642512
tim-murphy
6092e6a75c1ff242c56b736c861d3751d55f8fa7
1,007
cpp
C++
725.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
8
2018-10-31T11:00:19.000Z
2020-07-31T05:25:06.000Z
725.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
null
null
null
725.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
2
2018-05-31T11:29:22.000Z
2019-09-11T06:34:40.000Z
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector<ListNode*> splitListToParts(ListNode* root, int k) { int d=depth(root); vector<int> ls; while(k>0){ ls.push_back(d/k); d-=d/k; k--; } vector<ListNode*> ans; ListNode* prev=root; while(ls.size() && root){ while(ls.back()>1){ root=root->next; ls.back()--; } ListNode* tmp=root; root=root->next; tmp->next=NULL; ans.push_back(prev); prev=root; ls.pop_back(); } while(ls.size()){ ans.push_back(NULL); ls.pop_back(); } return ans; } int depth(ListNode* root){ if(!root) return 0; return 1+depth(root->next); } };
22.886364
63
0.443893
zfang399
6093c27fff28d9a1205aeb335ae5d728bee82eaf
2,099
cc
C++
cpp/common/statics/ordered-function-registry.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
37
2017-06-09T13:55:23.000Z
2022-01-28T12:51:17.000Z
cpp/common/statics/ordered-function-registry.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
null
null
null
cpp/common/statics/ordered-function-registry.cc
nathanawmk/SPARTA
6eeb28b2dd147088b6e851876b36eeba3e700f16
[ "BSD-2-Clause" ]
5
2017-06-09T13:55:26.000Z
2021-11-11T03:51:56.000Z
//***************************************************************** // Copyright 2015 MIT Lincoln Laboratory // Project: SPAR // Authors: OMD // Description: Implmentation of OrderedFunctionRegistry // // Modifications: // Date Name Modification // ---- ---- ------------ // 21 May 2012 omd Original Version //***************************************************************** #include "ordered-function-registry.h" #include "common/topological-iterator.h" // Can't use CHECK as logging is intializied via OrderedFunctionRegistry! #include <cassert> using std::string; using std::map; using std::list; using std::pair; void OrderedFunctionRegistry::OrderConstraint(const string& before, const string& after) { // We have no way to know if before or after have already been registered as // statics are not initialized in any deterministic order (which is exactly // the problem this class is supposed to solve) so we just store the string // and check for existence when we get to RunFunctions(). function_order_constraints_.push_back(make_pair(before, after)); } void OrderedFunctionRegistry::RunFunctions() { TopologicalIterator<NamedFunction> function_ordering; map<string, VoidFunction>::iterator i; for (i = functions_to_run_.begin(); i != functions_to_run_.end(); ++i) { function_ordering.Add(*i); } list<pair<string, string> >::iterator j; for (j = function_order_constraints_.begin(); j != function_order_constraints_.end(); ++j) { assert(functions_to_run_.find(j->first) != functions_to_run_.end()); assert(functions_to_run_.find(j->second) != functions_to_run_.end()); function_ordering.OrderConstraint(*functions_to_run_.find(j->first), *functions_to_run_.find(j->second)); } // Now the ordering is set up so iterate through the functions in topological // order and run them. while(function_ordering.HasNext()) { function_ordering.Next().function_(); } }
38.163636
79
0.626965
nathanawmk
609476a6eed961cfbe3eb1c4bc49126779a41d14
8,694
cpp
C++
dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp
wonrst/dali-toolkit
f15407e1710844219f3e418e83e689b5ff7341c2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp
wonrst/dali-toolkit
f15407e1710844219f3e418e83e689b5ff7341c2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/controls/scrollable/scrollable-impl.cpp
wonrst/dali-toolkit
f15407e1710844219f3e418e83e689b5ff7341c2
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // EXTERNAL INCLUDES #include <dali/public-api/object/type-registry-helper.h> #include <dali/public-api/object/type-registry.h> #include <cstring> // for strcmp // INTERNAL INCLUDES #include <dali-toolkit/internal/controls/control/control-data-impl.h> #include <dali-toolkit/internal/controls/scrollable/scrollable-impl.h> using namespace Dali; namespace Dali { namespace Toolkit { namespace Internal { namespace { BaseHandle Create() { // empty handle as we cannot create Scrollable (but type registered for scroll signal) return BaseHandle(); } // Setup properties, signals and actions using the type-registry. DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Scrollable, Toolkit::Control, Create); DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEffectColor", VECTOR4, OVERSHOOT_EFFECT_COLOR) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootAnimationSpeed", FLOAT, OVERSHOOT_ANIMATION_SPEED) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEnabled", BOOLEAN, OVERSHOOT_ENABLED) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootSize", VECTOR2, OVERSHOOT_SIZE) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollToAlphaFunction", INTEGER, SCROLL_TO_ALPHA_FUNCTION) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollRelativePosition", VECTOR2, SCROLL_RELATIVE_POSITION) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMin", VECTOR2, SCROLL_POSITION_MIN) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinX", SCROLL_POSITION_MIN_X, SCROLL_POSITION_MIN, 0) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinY", SCROLL_POSITION_MIN_Y, SCROLL_POSITION_MIN, 1) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMax", VECTOR2, SCROLL_POSITION_MAX) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxX", SCROLL_POSITION_MAX_X, SCROLL_POSITION_MAX, 0) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxY", SCROLL_POSITION_MAX_Y, SCROLL_POSITION_MAX, 1) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollVertical", BOOLEAN, CAN_SCROLL_VERTICAL) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollHorizontal", BOOLEAN, CAN_SCROLL_HORIZONTAL) DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollStarted", SIGNAL_SCROLL_STARTED) DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollCompleted", SIGNAL_SCROLL_COMPLETED) DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollUpdated", SIGNAL_SCROLL_UPDATED) DALI_TYPE_REGISTRATION_END() const Vector4 DEFAULT_OVERSHOOT_COLOUR(0.0f, 0.64f, 0.85f, 0.25f); const float DEFAULT_OVERSHOOT_ANIMATION_SPEED(120.0f); // 120 pixels per second const Vector2 OVERSHOOT_DEFAULT_SIZE(720.0f, 42.0f); } // namespace /////////////////////////////////////////////////////////////////////////////////////////////////// // Scrollable /////////////////////////////////////////////////////////////////////////////////////////////////// Scrollable::Scrollable(ControlBehaviour behaviourFlags) : Control(ControlBehaviour(behaviourFlags)), mOvershootEffectColor(DEFAULT_OVERSHOOT_COLOUR), mOvershootAnimationSpeed(DEFAULT_OVERSHOOT_ANIMATION_SPEED), mOvershootSize(OVERSHOOT_DEFAULT_SIZE), mScrollToAlphaFunction(AlphaFunction::EASE_OUT), mScrollStartedSignal(), mScrollUpdatedSignal(), mScrollCompletedSignal(), mOvershootEnabled(true) { } Scrollable::~Scrollable() { } bool Scrollable::AccessibleImpl::IsScrollable() { return true; } void Scrollable::OnInitialize() { DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { return std::unique_ptr<Dali::Accessibility::Accessible>( new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE)); }); } bool Scrollable::IsOvershootEnabled() const { return mOvershootEnabled; } void Scrollable::SetOvershootEnabled(bool enable) { EnableScrollOvershoot(enable); mOvershootEnabled = enable; } Vector4 Scrollable::GetOvershootEffectColor() const { return mOvershootEffectColor; }; void Scrollable::SetOvershootAnimationSpeed(float pixelsPerSecond) { mOvershootAnimationSpeed = pixelsPerSecond; } float Scrollable::GetOvershootAnimationSpeed() const { return mOvershootAnimationSpeed; }; const Vector2& Scrollable::GetOvershootSize() const { return mOvershootSize; } Toolkit::Scrollable::ScrollStartedSignalType& Scrollable::ScrollStartedSignal() { return mScrollStartedSignal; } Toolkit::Scrollable::ScrollUpdatedSignalType& Scrollable::ScrollUpdatedSignal() { return mScrollUpdatedSignal; } Toolkit::Scrollable::ScrollCompletedSignalType& Scrollable::ScrollCompletedSignal() { return mScrollCompletedSignal; } bool Scrollable::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { Dali::BaseHandle handle(object); bool connected(true); Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(handle); if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_STARTED)) { scrollable.ScrollStartedSignal().Connect(tracker, functor); } else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_UPDATED)) { scrollable.ScrollUpdatedSignal().Connect(tracker, functor); } else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_COMPLETED)) { scrollable.ScrollCompletedSignal().Connect(tracker, functor); } else { // signalName does not match any signal connected = false; } return connected; } void Scrollable::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object)); if(scrollable) { Scrollable& scrollableImpl(GetImpl(scrollable)); switch(index) { case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR: { scrollableImpl.SetOvershootEffectColor(value.Get<Vector4>()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED: { scrollableImpl.SetOvershootAnimationSpeed(value.Get<float>()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ENABLED: { scrollableImpl.SetOvershootEnabled(value.Get<bool>()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_SIZE: { scrollableImpl.SetOvershootSize(value.Get<Vector2>()); break; } case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION: { int alphaFunction = value.Get<int>(); if(alphaFunction >= AlphaFunction::DEFAULT && alphaFunction < AlphaFunction::COUNT) { scrollableImpl.mScrollToAlphaFunction = static_cast<AlphaFunction::BuiltinFunction>(alphaFunction); } break; } } } } Property::Value Scrollable::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object)); if(scrollable) { Scrollable& scrollableImpl(GetImpl(scrollable)); switch(index) { case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR: { value = scrollableImpl.GetOvershootEffectColor(); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED: { value = scrollableImpl.GetOvershootAnimationSpeed(); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ENABLED: { value = scrollableImpl.IsOvershootEnabled(); break; } case Toolkit::Scrollable::Property::OVERSHOOT_SIZE: { value = scrollableImpl.mOvershootSize; break; } case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION: { value = static_cast<int>(scrollableImpl.mScrollToAlphaFunction); break; } } } return value; } } // namespace Internal } // namespace Toolkit } // namespace Dali
31.846154
146
0.740741
wonrst
6096ff76fc04dfe49b92bc0c651093e3de6d60a7
4,838
hxx
C++
main/sd/source/ui/inc/animobjs.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/inc/animobjs.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/inc/animobjs.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SD_ANIMOBJS_HXX #define SD_ANIMOBJS_HXX #include <sfx2/dockwin.hxx> #include <vcl/fixed.hxx> #include <svtools/stdctrl.hxx> #include <vcl/group.hxx> #include <sfx2/ctrlitem.hxx> #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #include <vcl/field.hxx> #include <svx/dlgctrl.hxx> #include <sfx2/progress.hxx> #include <vcl/lstbox.hxx> #ifndef _SD_SDRESID_HXX #include "sdresid.hxx" #endif #include "misc/scopelock.hxx" class SdDrawDocument; class BitmapEx; namespace sd { class AnimationControllerItem; class View; //------------------------------------------------------------------------ enum BitmapAdjustment { BA_LEFT_UP, BA_LEFT, BA_LEFT_DOWN, BA_UP, BA_CENTER, BA_DOWN, BA_RIGHT_UP, BA_RIGHT, BA_RIGHT_DOWN }; //------------------------------------------------------------------------ class SdDisplay : public Control { private: BitmapEx aBitmapEx; Fraction aScale; public: SdDisplay( ::Window* pWin, SdResId Id ); ~SdDisplay(); virtual void Paint( const Rectangle& rRect ); void SetBitmapEx( BitmapEx* pBmpEx ); void SetScale( const Fraction& rFrac ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //------------------------------------------------------------------------ class AnimationWindow : public SfxDockingWindow { friend class AnimationChildWindow; friend class AnimationControllerItem; public: AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW, ::Window* pParent, const SdResId& rSdResId ); virtual ~AnimationWindow(); void AddObj( ::sd::View& rView ); void CreateAnimObj( ::sd::View& rView ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); protected: virtual sal_Bool Close(); virtual void Resize(); virtual void FillInfo( SfxChildWinInfo& ) const; private: SdDisplay aCtlDisplay; ImageButton aBtnFirst; ImageButton aBtnReverse; ImageButton aBtnStop; ImageButton aBtnPlay; ImageButton aBtnLast; NumericField aNumFldBitmap; TimeField aTimeField; ListBox aLbLoopCount; FixedLine aGrpBitmap; ImageButton aBtnGetOneObject; ImageButton aBtnGetAllObjects; ImageButton aBtnRemoveBitmap; ImageButton aBtnRemoveAll; FixedText aFtCount; FixedInfo aFiCount; FixedLine aGrpAnimation; RadioButton aRbtGroup; RadioButton aRbtBitmap; FixedText aFtAdjustment; ListBox aLbAdjustment; PushButton aBtnCreateGroup; ::Window* pWin; List aBmpExList; List aTimeList; SdDrawDocument* pMyDoc; BitmapEx* pBitmapEx; Size aSize; Size aFltWinSize; Size aDisplaySize; Size aBmpSize; sal_Bool bMovie; sal_Bool bAllObjects; SfxBindings* pBindings; AnimationControllerItem* pControllerItem; ScopeLock maPlayLock; //------------------------------------ DECL_LINK( ClickFirstHdl, void * ); DECL_LINK( ClickStopHdl, void * ); DECL_LINK( ClickPlayHdl, void * ); DECL_LINK( ClickLastHdl, void * ); DECL_LINK( ClickGetObjectHdl, void * ); DECL_LINK( ClickRemoveBitmapHdl, void * ); DECL_LINK( ClickRbtHdl, void * ); DECL_LINK( ClickCreateGroupHdl, void * ); DECL_LINK( ModifyBitmapHdl, void * ); DECL_LINK( ModifyTimeHdl, void * ); void UpdateControl( sal_uLong nPos, sal_Bool bDisableCtrls = sal_False ); void ResetAttrs(); void WaitInEffect( sal_uLong nMilliSeconds, sal_uLong nTime, SfxProgress* pStbMgr ) const; Fraction GetScale(); }; /************************************************************************* |* |* ControllerItem fuer Animator |* \************************************************************************/ class AnimationControllerItem : public SfxControllerItem { public: AnimationControllerItem( sal_uInt16, AnimationWindow*, SfxBindings* ); protected: virtual void StateChanged( sal_uInt16 nSId, SfxItemState eState, const SfxPoolItem* pState ); private: AnimationWindow* pAnimationWin; }; } // end of namespace sd #endif
24.434343
76
0.665771
Grosskopf
6097a5ec98ed3f1abee304f6eb6ed6a9a20ef17d
9,353
cpp
C++
gadgets/pmri/gpuCgSpiritGadget.cpp
roopchansinghv/gadgetron
fb6c56b643911152c27834a754a7b6ee2dd912da
[ "MIT" ]
1
2022-02-22T21:06:36.000Z
2022-02-22T21:06:36.000Z
gadgets/pmri/gpuCgSpiritGadget.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
gadgets/pmri/gpuCgSpiritGadget.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
#include "gpuCgSpiritGadget.h" #include "cuNDArray_operators.h" #include "cuNDArray_elemwise.h" #include "cuNDArray_blas.h" #include "cuNDArray_utils.h" #include "cuNDArray_reductions.h" #include "GadgetMRIHeaders.h" #include "b1_map.h" #include "GPUTimer.h" #include "vector_td_utilities.h" #include "hoNDArray_fileio.h" #include "ismrmrd/xml.h" #include "gpuSenseGadget.h" namespace Gadgetron{ gpuCgSpiritGadget::gpuCgSpiritGadget() : is_configured_(false) , matrix_size_reported_(0), gpuSenseGadget() { } gpuCgSpiritGadget::~gpuCgSpiritGadget() {} int gpuCgSpiritGadget::process_config( ACE_Message_Block* mb ) { gpuSenseGadget::process_config(mb); number_of_iterations_ = number_of_iterations.value(); cg_limit_ = cg_limit.value(); kappa_ = kappa.value(); // Get the Ismrmrd header // ISMRMRD::IsmrmrdHeader h; ISMRMRD::deserialize(mb->rd_ptr(),h); if (h.encoding.size() != 1) { GDEBUG("This Gadget only supports one encoding space\n"); return GADGET_FAIL; } // Get the encoding space and trajectory description ISMRMRD::EncodingSpace e_space = h.encoding[0].encodedSpace; ISMRMRD::EncodingSpace r_space = h.encoding[0].reconSpace; ISMRMRD::EncodingLimits e_limits = h.encoding[0].encodingLimits; matrix_size_seq_ = uint64d2( r_space.matrixSize.x, r_space.matrixSize.y ); if (!is_configured_) { if (h.acquisitionSystemInformation) { channels_ = h.acquisitionSystemInformation->receiverChannels ? *h.acquisitionSystemInformation->receiverChannels : 1; } else { channels_ = 1; } // Allocate Spirit operators E_ = boost::make_shared< NFFTOperator<cuNDArray,float,2> >(); S_ = boost::make_shared< cuSpirit2DOperator<float> >(); S_->set_weight( kappa_ ); // Allocate preconditioner //D_ = boost::shared_ptr< cuCgPreconditioner<float_complext> >( new cuCgPreconditioner<float_complext>() ); // Allocate regularization image operator //R_ = boost::shared_ptr< cuImageOperator<float_complext> >( new cuImageOperator<float_complext>() ); //R_->set_weight( kappa_ ); // Setup solver cg_.set_encoding_operator( E_ ); // encoding matrix if( kappa_ > 0.0f ) cg_.add_regularization_operator( S_ ); // regularization matrix //cg_.add_regularization_operator( R_ ); // regularization matrix //cg_.set_preconditioner( D_ ); // preconditioning matrix cg_.set_max_iterations( number_of_iterations_ ); cg_.set_tc_tolerance( cg_limit_ ); cg_.set_output_mode( (this->output_convergence_) ? cuCgSolver<float_complext>::OUTPUT_VERBOSE : cuCgSolver<float_complext>::OUTPUT_SILENT); is_configured_ = true; } return GADGET_OK; } int gpuCgSpiritGadget::process(GadgetContainerMessage<ISMRMRD::ImageHeader> *m1, GadgetContainerMessage<GenericReconJob> *m2) { // Is this data for this gadget's set/slice? // if( m1->getObjectPtr()->set != set_number_ || m1->getObjectPtr()->slice != slice_number_ ) { // No, pass it downstream... return this->next()->putq(m1); } //GDEBUG("gpuCgSpiritGadget::process\n"); boost::shared_ptr<GPUTimer> process_timer; if( output_timing_ ) process_timer = boost::shared_ptr<GPUTimer>( new GPUTimer("gpuCgSpiritGadget::process()") ); if (!is_configured_) { GDEBUG("Data received before configuration was completed\n"); return GADGET_FAIL; } GenericReconJob* j = m2->getObjectPtr(); // Some basic validation of the incoming Spirit job if (!j->csm_host_.get() || !j->dat_host_.get() || !j->tra_host_.get() || !j->dcw_host_.get() || !j->reg_host_.get()) { GDEBUG("Received an incomplete Spirit job\n"); return GADGET_FAIL; } unsigned int samples = j->dat_host_->get_size(0); unsigned int channels = j->dat_host_->get_size(1); unsigned int rotations = samples / j->tra_host_->get_number_of_elements(); unsigned int frames = j->tra_host_->get_size(1)*rotations; if( samples%j->tra_host_->get_number_of_elements() ) { GDEBUG("Mismatch between number of samples (%d) and number of k-space coordinates (%d).\nThe first should be a multiplum of the latter.\n", samples, j->tra_host_->get_number_of_elements()); return GADGET_FAIL; } boost::shared_ptr< cuNDArray<floatd2> > traj(new cuNDArray<floatd2> (j->tra_host_.get())); boost::shared_ptr< cuNDArray<float> > dcw(new cuNDArray<float> (j->dcw_host_.get())); sqrt_inplace(dcw.get()); //Take square root to use for weighting boost::shared_ptr< cuNDArray<float_complext> > csm(new cuNDArray<float_complext> (j->csm_host_.get())); boost::shared_ptr< cuNDArray<float_complext> > device_samples(new cuNDArray<float_complext> (j->dat_host_.get())); cudaDeviceProp deviceProp; if( cudaGetDeviceProperties( &deviceProp, device_number_ ) != cudaSuccess) { GDEBUG( "Error: unable to query device properties.\n" ); return GADGET_FAIL; } unsigned int warp_size = deviceProp.warpSize; matrix_size_ = uint64d2( j->reg_host_->get_size(0), j->reg_host_->get_size(1) ); matrix_size_os_ = uint64d2(((static_cast<unsigned int>(std::ceil(matrix_size_[0]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size, ((static_cast<unsigned int>(std::ceil(matrix_size_[1]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size); if( !matrix_size_reported_ ) { GDEBUG("Matrix size : [%d,%d] \n", matrix_size_[0], matrix_size_[1]); GDEBUG("Matrix size OS : [%d,%d] \n", matrix_size_os_[0], matrix_size_os_[1]); matrix_size_reported_ = true; } std::vector<size_t> image_dims = to_std_vector(matrix_size_); image_dims.push_back(frames); image_dims.push_back(channels); GDEBUG("Number of coils: %d %d \n",channels,image_dims.size()); E_->set_domain_dimensions(&image_dims); E_->set_codomain_dimensions(device_samples->get_dimensions().get()); E_->set_dcw(dcw); E_->setup( matrix_size_, matrix_size_os_, static_cast<float>(kernel_width_) ); E_->preprocess(traj.get()); boost::shared_ptr< cuNDArray<float_complext> > csm_device( new cuNDArray<float_complext>( csm.get() )); S_->set_calibration_kernels(csm_device); S_->set_domain_dimensions(&image_dims); S_->set_codomain_dimensions(&image_dims); /* boost::shared_ptr< cuNDArray<float_complext> > reg_image(new cuNDArray<float_complext> (j->reg_host_.get())); R_->compute(reg_image.get()); // Define preconditioning weights boost::shared_ptr< cuNDArray<float> > _precon_weights = sum(abs_square(csm.get()).get(), 2); boost::shared_ptr<cuNDArray<float> > R_diag = R_->get(); *R_diag *= float(kappa_); *_precon_weights += *R_diag; R_diag.reset(); reciprocal_sqrt_inplace(_precon_weights.get()); boost::shared_ptr< cuNDArray<float_complext> > precon_weights = real_to_complex<float_complext>( _precon_weights.get() ); _precon_weights.reset(); D_->set_weights( precon_weights ); */ /*{ static int counter = 0; char filename[256]; sprintf((char*)filename, "_traj_%d.real", counter); write_nd_array<floatd2>( traj->to_host().get(), filename ); sprintf((char*)filename, "_dcw_%d.real", counter); write_nd_array<float>( dcw->to_host().get(), filename ); sprintf((char*)filename, "_csm_%d.cplx", counter); write_nd_array<float_complext>( csm->to_host().get(), filename ); sprintf((char*)filename, "_samples_%d.cplx", counter); write_nd_array<float_complext>( device_samples->to_host().get(), filename ); sprintf((char*)filename, "_reg_%d.cplx", counter); write_nd_array<float_complext>( reg_image->to_host().get(), filename ); counter++; }*/ // Invoke solver // boost::shared_ptr< cuNDArray<float_complext> > cgresult; { boost::shared_ptr<GPUTimer> solve_timer; if( output_timing_ ) solve_timer = boost::shared_ptr<GPUTimer>( new GPUTimer("gpuCgSpiritGadget::solve()") ); cgresult = cg_.solve(device_samples.get()); if( output_timing_ ) solve_timer.reset(); } if (!cgresult.get()) { GDEBUG("Iterative_spirit_compute failed\n"); return GADGET_FAIL; } /* static int counter = 0; char filename[256]; sprintf((char*)filename, "recon_%d.real", counter); write_nd_array<float>( abs(cgresult.get())->to_host().get(), filename ); counter++; */ // If the recon matrix size exceeds the sequence matrix size then crop if( matrix_size_seq_ != matrix_size_ ) *cgresult = crop<float_complext,2>( (matrix_size_-matrix_size_seq_)>>1, matrix_size_seq_, *cgresult ); // Combine coil images // cgresult = real_to_complex<float_complext>(sqrt(sum(abs_square(cgresult.get()).get(), 3).get()).get()); // RSS //cgresult = sum(cgresult.get(), 2); // Pass on the reconstructed images // put_frames_on_que(frames,rotations,j,cgresult.get()); frame_counter_ += frames; if( output_timing_ ) process_timer.reset(); m1->release(); return GADGET_OK; } GADGET_FACTORY_DECLARE(gpuCgSpiritGadget) }
36.535156
145
0.674436
roopchansinghv
609d81f105e1a97e4bf67ec24425ba6d671c8e6b
2,441
cpp
C++
Vorlesungsmaterial/22-05-04/lambda.cpp
TEL21D/Informatik2
d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075
[ "MIT" ]
null
null
null
Vorlesungsmaterial/22-05-04/lambda.cpp
TEL21D/Informatik2
d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075
[ "MIT" ]
null
null
null
Vorlesungsmaterial/22-05-04/lambda.cpp
TEL21D/Informatik2
d0a6b6b5a0fe5dd404dadfd50d25543d5c6d5075
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <iostream> #include <iomanip> #include <string> #include <vector> #include "lambda.hpp" using namespace std; bool lessLength(const string &f, const string &s) { return f.length() < s.length(); } void lambda() { vector<string> myStrVec = {"12345", "123456", "1234", "1", "12", "123", "12345"}; cout << "\n\nSortieren mit lessLength():\n"; sort(myStrVec.begin(), myStrVec.end(), lessLength); for (auto v : myStrVec) cout << v << " "; cout << "\n\nSortieren mit einer lambda Funktion:\n"; sort(myStrVec.begin(), myStrVec.end(), [](const string &f, const string &s) { return f.length() < s.length(); }); for (auto v : myStrVec) cout << v << " "; cout << "\n\nSortieren mit einer lambda Funktion:\n"; sort(myStrVec.begin(), myStrVec.end(), [](const string &f, const string &s) { return f.length() > s.length(); }); for (auto v : myStrVec) cout << v << " "; cout << "\n"; // for_each läuft durch alle Elemte des Vektors und wendet die Funktion auf jedes Element an for_each(myStrVec.begin(), myStrVec.end(), [](const string &s) { cout << s << ", "; }); cout << "\n\nAusgeben (foreach) mit einer lambda Funktion:\n"; vector<int> myVec1{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << "i->i*i: "; for_each(myVec1.begin(), myVec1.end(), [](int &i) { i = i * i; }); for (auto v : myVec1) cout << v << " "; cout << endl; vector<double> myVec2{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for_each(myVec2.begin(), myVec2.end(), [](double &i) { i = sqrt(i); }); cout << "i->sqrt(i): "; for (auto v : myVec2) cout << fixed << setprecision(2) << v << " "; // fixed verhindert exponentialschreibweise (z.B. 1.0e-10) // Nachkommastellen auf 2 begrenzt mit setprecision cout << "\n\n"; } void lambda_captures() { cout << endl; string copy = "original"; string ref = "original"; auto lambda = [copy, &ref] { cout << copy << " " << ref << endl; }; lambda(); copy = "changed"; ref = "changed"; lambda(); copy = "changed again"; ref = "changed again"; lambda(); cout << endl; } void lambda_params() { auto addTwoNumbers = [](int a, int b){ return a + b; }; cout << endl; cout << "addTwoNumbers(2000, 17): " << addTwoNumbers(2000, 17) << endl; cout << "addTwoNumbers(2000, 21): " << addTwoNumbers(2000, 21) << endl; }
28.383721
116
0.565752
TEL21D
609dd584e2c58d9f2a457464d8ae604c3e7269dd
2,159
cpp
C++
test/unit/alphabet/mask/mask_test.cpp
BuildJet/seqan3
fc8cb3f1db119be30ec76f3d3cec3fecd7865c1c
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/alphabet/mask/mask_test.cpp
BuildJet/seqan3
fc8cb3f1db119be30ec76f3d3cec3fecd7865c1c
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/alphabet/mask/mask_test.cpp
BuildJet/seqan3
fc8cb3f1db119be30ec76f3d3cec3fecd7865c1c
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <gtest/gtest.h> #include <seqan3/alphabet/mask/mask.hpp> #include "../semi_alphabet_test_template.hpp" #include "../semi_alphabet_constexpr_test_template.hpp" INSTANTIATE_TYPED_TEST_SUITE_P(mask, semi_alphabet_test, seqan3::mask, ); INSTANTIATE_TYPED_TEST_SUITE_P(mask, semi_alphabet_constexpr, seqan3::mask, ); TEST(mask, assign_rank) { // l-value seqan3::mask lmask; EXPECT_EQ(lmask.assign_rank(1), seqan3::mask::masked); EXPECT_TRUE(lmask.to_rank()); EXPECT_EQ(lmask.assign_rank(0), seqan3::mask::unmasked); EXPECT_FALSE(lmask.to_rank()); EXPECT_EQ(lmask.assign_rank(true), seqan3::mask::masked); EXPECT_EQ(lmask.assign_rank(false), seqan3::mask::unmasked); // const l-value lmask.assign_rank(1); seqan3::mask const clmask{lmask}; EXPECT_TRUE(clmask.to_rank()); // r-value seqan3::mask rmask{lmask}; EXPECT_EQ(std::move(rmask).to_rank(), lmask.to_rank()); EXPECT_TRUE((std::is_same_v<decltype(std::move(rmask)), seqan3::mask &&>)); EXPECT_EQ(std::move(rmask).assign_rank(1), seqan3::mask::masked); EXPECT_TRUE(std::move(rmask).to_rank()); EXPECT_EQ(std::move(rmask).assign_rank(0), seqan3::mask::unmasked); EXPECT_FALSE(std::move(rmask).to_rank()); EXPECT_EQ(std::move(rmask).assign_rank(true), seqan3::mask::masked); EXPECT_EQ(std::move(rmask).assign_rank(false), seqan3::mask::unmasked); // const r-value seqan3::mask const crmask{lmask}; EXPECT_EQ(std::move(crmask).to_rank(), lmask.to_rank()); EXPECT_TRUE((std::is_same_v<decltype(std::move(crmask)), seqan3::mask const &&>)); }
43.18
104
0.645206
BuildJet
60a00c7037587a140b01a3b1c39160f93ae0d5ef
3,685
cpp
C++
Daa_code/common/Key_name_from_public_data.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
2
2020-02-28T10:40:12.000Z
2021-02-18T03:32:28.000Z
Daa_code/common/Key_name_from_public_data.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
null
null
null
Daa_code/common/Key_name_from_public_data.cpp
UoS-SCCS/ecc-daa
eebd40d01aed7a3ccb8dc33df8a4b6415f02dda9
[ "BSD-2-Clause" ]
null
null
null
/******************************************************************************* * File: Key_name_from_public_data.cpp * Description: Calculate the key's name from its public data (TPMT_PUBLIC) * * Author: Chris Newton * * Created: Tueday 29 May 2018 * * (C) Copyright 2018, University of Surrey. * *******************************************************************************/ /******************************************************************************* * * * (C) Copyright 2019 University of Surrey * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright notice, * * this list of conditions and the following disclaimer in the documentation * * and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * *******************************************************************************/ #include <iostream> #include "Marshal_public_data.h" #include "Byte_buffer.h" #include "Sha.h" Byte_buffer get_key_name( TPMT_PUBLIC* public_data ) { Byte_buffer marshalled_public_area=marshal_public_data_T(public_data); // std::cout << "Marshalled area: size: " << marshalled_public_area.size() << '\n'; // std::cout << "Marshalled area: data: " << marshalled_public_area.to_hex_string() << '\n'; Byte_buffer sha256_ma=sha256_bb(marshalled_public_area); // std::cout << "SHA256 of marshalled area: " << sha256_ma.to_hex_string() << '\n'; Byte_buffer name{0x00,0x0b}; // nameAlg (0x0b for sha256) name+=sha256_ma; // std::cout << " Key name: size: " << name.size() << '\n'; // std::cout << " Key name: data: " << name.to_hex_string() << '\n'; return name; } Byte_buffer get_key_name_bb( Byte_buffer key_pd ) { Byte_buffer name; TPM2B_PUBLIC tpm2b_pub; TPM_RC rc=unmarshal_public_data_B(key_pd, &tpm2b_pub); if (rc!=0) { return name; // Leave it to others to sort out } return get_key_name(&tpm2b_pub.publicArea); }
46.0625
95
0.52483
UoS-SCCS
60a190b7c88eb32491fe1e688731c422eca0ff47
249
cpp
C++
packages/eigen-eigen-323c052e1731/doc/snippets/MatrixBase_block_int_int.cpp
k4rth33k/dnnc-operators
a7fe3f1240c12b3438558def71fbfcd4520446c3
[ "Apache-2.0" ]
5
2019-08-16T14:35:17.000Z
2020-07-11T23:59:22.000Z
packages/eigen-eigen-323c052e1731/doc/snippets/MatrixBase_block_int_int.cpp
k4rth33k/dnnc-operators
a7fe3f1240c12b3438558def71fbfcd4520446c3
[ "Apache-2.0" ]
6
2019-08-12T04:38:14.000Z
2019-09-04T16:32:13.000Z
packages/eigen-eigen-323c052e1731/doc/snippets/MatrixBase_block_int_int.cpp
k4rth33k/dnnc-operators
a7fe3f1240c12b3438558def71fbfcd4520446c3
[ "Apache-2.0" ]
7
2019-08-15T13:29:00.000Z
2019-09-09T17:08:04.000Z
Matrix4i m = Matrix4i::Random(); cout << "Here is the matrix m:" << endl << m << endl; cout << "Here is m.block<2,2>(1,1):" << endl << m.block<2,2>(1,1) << endl; m.block<2,2>(1,1).setZero(); cout << "Now the matrix m is:" << endl << m << endl;
41.5
75
0.542169
k4rth33k
60a24eb840195547b91e04b7dae2db3b80ea5191
288
cpp
C++
test/StackTest.cpp
smikes/CppUnitLite
5714498fd5cb8d2ece2cf17e09c32cf2c1e120cf
[ "Zlib" ]
17
2015-12-05T02:32:26.000Z
2021-11-22T08:43:40.000Z
test/StackTest.cpp
brave/CppUnitLite
651565f1aed136b06469045f3b1362152de21d0f
[ "Zlib" ]
5
2015-03-25T20:36:04.000Z
2019-06-21T03:03:43.000Z
test/StackTest.cpp
smikes/CppUnitLite
5714498fd5cb8d2ece2cf17e09c32cf2c1e120cf
[ "Zlib" ]
17
2015-02-09T07:29:18.000Z
2021-04-09T07:29:42.000Z
#include "CppUnitLite/TestHarness.h" #include "Stack.h" #include <string> SimpleString StringFrom(const std::string& value) { return SimpleString(value.c_str()); } TEST( Stack, creation ) { Stack s; LONGS_EQUAL(0, s.size()); std::string b = "asa"; CHECK_EQUAL("asa", b); }
13.714286
49
0.670139
smikes
60a329f1d855e8f3374889f1ea948bd10136c032
1,091
cc
C++
korean/core/chars/distance_test.cc
jeongukjae/korean
8ce493a96558c9c2bb14b9e2ed74e3d0ddefa4ae
[ "MIT" ]
1
2022-02-11T13:47:23.000Z
2022-02-11T13:47:23.000Z
korean/core/chars/distance_test.cc
jeongukjae/korean
8ce493a96558c9c2bb14b9e2ed74e3d0ddefa4ae
[ "MIT" ]
null
null
null
korean/core/chars/distance_test.cc
jeongukjae/korean
8ce493a96558c9c2bb14b9e2ed74e3d0ddefa4ae
[ "MIT" ]
null
null
null
#include "korean/core/chars/distance.h" #include <gmock/gmock.h> #include <gtest/gtest.h> using namespace korean::chars; TEST(distance, calculateLevenshtein) { ASSERT_EQ(calculateLevenshteinDistance(L"abcdef", L"abdef"), 1); ASSERT_EQ(calculateLevenshteinDistance(L"안녕", L"안하세요"), 3); ASSERT_EQ(calculateLevenshteinDistance(L"에어팟", L"에앞ㅏㅅ"), 3); } TEST(distance, calculateDecomposedLevenshtein) { ASSERT_EQ(calculateDecomposedLevenshteinDistance(L"에어팟", L"에앞ㅏㅅ"), 1); ASSERT_EQ(calculateDecomposedLevenshteinDistance(L"에어팟", L"에어팟"), 0); ASSERT_EQ(calculateDecomposedLevenshteinDistance(L"에어팟", L"에아팟"), 1); } TEST(distance, getLongestCommonSubstring) { ASSERT_EQ(getLongestCommonSubstring(L"안녕하세요~", L"네 안녕하세요"), std::make_pair((size_t)0, (size_t)5)); ASSERT_EQ(getLongestCommonSubstring(L"커피치과의원", L"커피치과 가보세요"), std::make_pair((size_t)0, (size_t)4)); ASSERT_EQ(getLongestCommonSubstring( L"korean이라는 라이브러리를 계속 업데이트하려고 하는데, 이게 잘 될까요? 일단 열심히 해보려고요. 형태소 분석기도 곧 넣어보고요.", L"형태소분석기"), std::make_pair((size_t)57, (size_t)3)); }
38.964286
102
0.724106
jeongukjae
60a40149e2dd260cb8a0a4e503d974086c0df0ff
784
cpp
C++
ASAE/ASAE/Buffer.cpp
BenFields724/AutoSim
063350df2e27c38623a736a463aaf8b0124c9218
[ "MIT" ]
null
null
null
ASAE/ASAE/Buffer.cpp
BenFields724/AutoSim
063350df2e27c38623a736a463aaf8b0124c9218
[ "MIT" ]
null
null
null
ASAE/ASAE/Buffer.cpp
BenFields724/AutoSim
063350df2e27c38623a736a463aaf8b0124c9218
[ "MIT" ]
null
null
null
// // Buffer.cpp // ASAE // // Created by Benjamin G Fields on 4/2/18. // Copyright © 2018 Benjamin G Fields. All rights reserved. // // Description: defines the implementatin of the buffer object #include "Buffer.hpp" //Description:return the state of the buffer by saying if it is full,empty or still has space int Buffer::getState(){ if (queue.size() == capacity) { return FULL; } else if(queue.size()== 0){ return EMPTY; } else{ return SPACE_LEFT; } } int Buffer::getNumInQueue(){ return (int)queue.size(); } //Description:return the next event in the queue Event Buffer::GetNext(){ Event E = queue.front(); queue.pop(); return E; } //Description: put the event in the buffer queue void Buffer::placeInBuffer(Event E){ queue.push(E); }
19.6
93
0.672194
BenFields724
60a6ba044e3289aa9516e4a3c755391e2e6e17b9
650
cpp
C++
src/basic/tests/unit_tests_talker.cpp
sgermanserrano/gitlab_ci_test
df415655757d9674a31ca704bef6bb7c456e7c09
[ "Apache-2.0" ]
null
null
null
src/basic/tests/unit_tests_talker.cpp
sgermanserrano/gitlab_ci_test
df415655757d9674a31ca704bef6bb7c456e7c09
[ "Apache-2.0" ]
null
null
null
src/basic/tests/unit_tests_talker.cpp
sgermanserrano/gitlab_ci_test
df415655757d9674a31ca704bef6bb7c456e7c09
[ "Apache-2.0" ]
1
2019-03-05T16:33:21.000Z
2019-03-05T16:33:21.000Z
#include "basic/talker.h" #include <gtest/gtest.h> class MyTestSuite : public ::testing::Test { public: MyTestSuite(){} ~MyTestSuite(){} }; TEST_F(MyTestSuite, lowValue){ Talker rt; int initial_value = 3; int value = rt.doSomeMath(initial_value); ASSERT_EQ(value, initial_value+5) << "Value should be its initial value plus 5"; } TEST_F(MyTestSuite, highValue){ Talker rt; int initial_value = 49; int value = rt.doSomeMath(initial_value); ASSERT_EQ(value, 0) << "Value should be 0"; } //int main(int argc, char **argv) { // testing::InitGoogleTest(&argc, argv); // ros::init(argc, argv, "TestNode"); // return RUN_ALL_TESTS(); //}
19.117647
81
0.690769
sgermanserrano
60a79112e0ac1dfcca72ab62a4ad3a39509ff384
4,648
hpp
C++
Compiler/boost/boost/signals2/detail/slot_call_iterator.hpp
davidov541/MiniC
d3b16a1568b97a4d801880b110a8be04fe848adb
[ "Apache-2.0" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
LibsExternes/Includes/boost/signals2/detail/slot_call_iterator.hpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
LibsExternes/Includes/boost/signals2/detail/slot_call_iterator.hpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
// Boost.Signals2 library // Copyright Douglas Gregor 2001-2004. // Copyright Frank Mori Hess 2007-2008. // Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // For more information, see http://www.boost.org #ifndef BOOST_SIGNALS2_SLOT_CALL_ITERATOR_HPP #define BOOST_SIGNALS2_SLOT_CALL_ITERATOR_HPP #include <boost/assert.hpp> #include <boost/aligned_storage.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/optional.hpp> #include <boost/scoped_ptr.hpp> #include <boost/signals2/connection.hpp> #include <boost/signals2/slot_base.hpp> #include <boost/signals2/detail/auto_buffer.hpp> #include <boost/signals2/detail/unique_lock.hpp> #include <boost/weak_ptr.hpp> namespace boost { namespace signals2 { namespace detail { template<typename ResultType, typename Function> class slot_call_iterator_cache { public: slot_call_iterator_cache(const Function &f): f(f), connected_slot_count(0), disconnected_slot_count(0) {} optional<ResultType> result; typedef auto_buffer<boost::shared_ptr<void>, store_n_objects<10> > tracked_ptrs_type; tracked_ptrs_type tracked_ptrs; Function f; unsigned connected_slot_count; unsigned disconnected_slot_count; }; // Generates a slot call iterator. Essentially, this is an iterator that: // - skips over disconnected slots in the underlying list // - calls the connected slots when dereferenced // - caches the result of calling the slots template<typename Function, typename Iterator, typename ConnectionBody> class slot_call_iterator_t : public boost::iterator_facade<slot_call_iterator_t<Function, Iterator, ConnectionBody>, typename Function::result_type, boost::single_pass_traversal_tag, typename Function::result_type const&> { typedef boost::iterator_facade<slot_call_iterator_t<Function, Iterator, ConnectionBody>, typename Function::result_type, boost::single_pass_traversal_tag, typename Function::result_type const&> inherited; typedef typename Function::result_type result_type; friend class boost::iterator_core_access; public: slot_call_iterator_t(Iterator iter_in, Iterator end_in, slot_call_iterator_cache<result_type, Function> &c): iter(iter_in), end(end_in), cache(&c), callable_iter(end_in) { lock_next_callable(); } typename inherited::reference dereference() const { if (!cache->result) { try { cache->result.reset(cache->f(*iter)); } catch(expired_slot &) { (*iter)->disconnect(); throw; } } return cache->result.get(); } void increment() { ++iter; lock_next_callable(); cache->result.reset(); } bool equal(const slot_call_iterator_t& other) const { return iter == other.iter; } private: typedef unique_lock<connection_body_base> lock_type; void lock_next_callable() const { if(iter == callable_iter) { return; } for(;iter != end; ++iter) { lock_type lock(**iter); cache->tracked_ptrs.clear(); (*iter)->nolock_grab_tracked_objects(std::back_inserter(cache->tracked_ptrs)); if((*iter)->nolock_nograb_connected()) { ++cache->connected_slot_count; }else { ++cache->disconnected_slot_count; } if((*iter)->nolock_nograb_blocked() == false) { callable_iter = iter; break; } } if(iter == end) { callable_iter = end; } } mutable Iterator iter; Iterator end; slot_call_iterator_cache<result_type, Function> *cache; mutable Iterator callable_iter; }; } // end namespace detail } // end namespace BOOST_SIGNALS_NAMESPACE } // end namespace boost #endif // BOOST_SIGNALS2_SLOT_CALL_ITERATOR_HPP
31.405405
98
0.592083
davidov541
60aa521408a96d6d1babe621f163b73e17372c30
2,074
cpp
C++
DataCollector/process.cpp
aisecstudent/DeepPuzzling
8c3438393a5aa2a715f0058e96c07ea9ade430ac
[ "MIT" ]
61
2021-11-26T13:17:13.000Z
2022-01-24T15:42:06.000Z
DataCollector/process.cpp
aisecstudent/DeepPuzzling
8c3438393a5aa2a715f0058e96c07ea9ade430ac
[ "MIT" ]
1
2021-11-30T06:44:52.000Z
2021-12-02T11:30:09.000Z
DataCollector/process.cpp
aisecstudent/DeepPuzzling
8c3438393a5aa2a715f0058e96c07ea9ade430ac
[ "MIT" ]
4
2021-11-26T16:23:38.000Z
2021-11-27T07:38:54.000Z
#include "pch.h" #include "process.h" std::vector<ProcessInfo> GetProcessInfo() { STARTUPINFO st; PROCESS_INFORMATION pi; PROCESSENTRY32 ps; HANDLE hSnapshot; HANDLE processHandle = NULL; std::vector<ProcessInfo> PInfo; ZeroMemory(&st, sizeof(STARTUPINFO)); ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); st.cb = sizeof(STARTUPINFO); ZeroMemory(&ps, sizeof(PROCESSENTRY32)); ps.dwSize = sizeof(PROCESSENTRY32); hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot == INVALID_HANDLE_VALUE) { return PInfo; } if (!Process32First(hSnapshot, &ps)) { return PInfo; } do { processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ps.th32ProcessID); TCHAR filename[MAX_PATH]; if (processHandle != NULL) { if (GetModuleFileNameEx(processHandle, NULL, filename, MAX_PATH) == 0) { _tcscpy_s(filename, MAX_PATH, _T("NULL_Module")); } CloseHandle(processHandle); } else { _tcscpy_s(filename, MAX_PATH, _T("NULL_Process")); } PInfo.emplace_back(ps.th32ProcessID, WCHAR2String(ps.szExeFile), WCHAR2String(filename)); } while (Process32Next(hSnapshot, &ps)); CloseHandle(hSnapshot); std::sort(PInfo.begin(), PInfo.end()); return PInfo; } std::set<std::string> get_process_name() { STARTUPINFO st; PROCESS_INFORMATION pi; PROCESSENTRY32 ps; HANDLE hSnapshot; std::vector<ProcessInfo> PInfo; ZeroMemory(&st, sizeof(STARTUPINFO)); ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); st.cb = sizeof(STARTUPINFO); ZeroMemory(&ps, sizeof(PROCESSENTRY32)); ps.dwSize = sizeof(PROCESSENTRY32); hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); std::set<std::string> process_name; if (hSnapshot == INVALID_HANDLE_VALUE) { return process_name; } if (!Process32First(hSnapshot, &ps)) { return process_name; } do { process_name.insert(WCHAR2String(ps.szExeFile)); } while (Process32Next(hSnapshot, &ps)); CloseHandle(hSnapshot); return process_name; }
22.301075
101
0.69865
aisecstudent
60aaf441847206e12116cd1be45012ac344c7a02
3,386
cpp
C++
libs/qmdnsengine/src/src/prober.cpp
JinRIIS/Custom-QGC
b08876453a90ddf1d8778c4f49bcbe68021bd09d
[ "Apache-2.0" ]
51
2017-05-29T23:18:18.000Z
2021-12-04T01:59:13.000Z
libs/qmdnsengine/src/src/prober.cpp
JinRIIS/Custom-QGC
b08876453a90ddf1d8778c4f49bcbe68021bd09d
[ "Apache-2.0" ]
31
2017-05-09T02:56:29.000Z
2022-03-23T08:51:25.000Z
libs/qmdnsengine/src/src/prober.cpp
JinRIIS/Custom-QGC
b08876453a90ddf1d8778c4f49bcbe68021bd09d
[ "Apache-2.0" ]
27
2018-01-17T10:14:27.000Z
2022-03-31T01:42:20.000Z
/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * 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 <qmdnsengine/abstractserver.h> #include <qmdnsengine/dns.h> #include <qmdnsengine/message.h> #include <qmdnsengine/prober.h> #include <qmdnsengine/query.h> #include "prober_p.h" using namespace QMdnsEngine; ProberPrivate::ProberPrivate(Prober *prober, AbstractServer *server, const Record &record) : QObject(prober), server(server), confirmed(false), proposedRecord(record), suffix(1), q(prober) { // All records should contain at least one "." int index = record.name().indexOf('.'); name = record.name().left(index); type = record.name().mid(index); connect(server, &AbstractServer::messageReceived, this, &ProberPrivate::onMessageReceived); connect(&timer, &QTimer::timeout, this, &ProberPrivate::onTimeout); timer.setSingleShot(true); assertRecord(); } void ProberPrivate::assertRecord() { // Use the current suffix to set the name of the proposed record proposedRecord.setName(suffix == 1 ? name + type : name + "-" + QByteArray::number(suffix) + type); // Broadcast a query for the proposed name (using an ANY query) and // include the proposed record in the query Query query; query.setName(proposedRecord.name()); query.setType(ANY); Message message; message.addQuery(query); message.addRecord(proposedRecord); server->sendMessageToAll(message); // Wait two seconds to confirm it is unique timer.stop(); timer.start(2 * 1000); } void ProberPrivate::onMessageReceived(const Message &message) { // If the response matches the proposed record, increment the suffix and // try with the new name if (confirmed || !message.isResponse()) { return; } const auto records = message.records(); for (const Record &record : records) { if (record.name() == proposedRecord.name() && record.type() == proposedRecord.type()) { ++suffix; assertRecord(); } } } void ProberPrivate::onTimeout() { confirmed = true; emit q->nameConfirmed(proposedRecord.name()); } Prober::Prober(AbstractServer *server, const Record &record, QObject *parent) : QObject(parent), d(new ProberPrivate(this, server, record)) { }
32.247619
95
0.697874
JinRIIS
60ac292a7bd709282e30bd8dfad3bf2efe7ad776
8,323
cc
C++
chrome/common/extensions/update_manifest.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
chrome/common/extensions/update_manifest.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
chrome/common/extensions/update_manifest.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/extensions/update_manifest.h" #include <algorithm> #include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/string_util.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "base/version.h" #include "chrome/common/libxml_utils.h" #include "libxml/tree.h" static const char* kExpectedGupdateProtocol = "2.0"; static const char* kExpectedGupdateXmlns = "http://www.google.com/update2/response"; UpdateManifest::Result::Result() {} UpdateManifest::Result::~Result() {} UpdateManifest::Results::Results() : daystart_elapsed_seconds(kNoDaystart) {} UpdateManifest::Results::~Results() {} UpdateManifest::UpdateManifest() { } UpdateManifest::~UpdateManifest() {} void UpdateManifest::ParseError(const char* details, ...) { va_list args; va_start(args, details); if (errors_.length() > 0) { // TODO(asargent) make a platform abstracted newline? errors_ += "\r\n"; } base::StringAppendV(&errors_, details, args); va_end(args); } // Checks whether a given node's name matches |expected_name| and // |expected_namespace|. static bool TagNameEquals(const xmlNode* node, const char* expected_name, const xmlNs* expected_namespace) { if (node->ns != expected_namespace) { return false; } return 0 == strcmp(expected_name, reinterpret_cast<const char*>(node->name)); } // Returns child nodes of |root| with name |name| in namespace |xml_namespace|. static std::vector<xmlNode*> GetChildren(xmlNode* root, xmlNs* xml_namespace, const char* name) { std::vector<xmlNode*> result; for (xmlNode* child = root->children; child != NULL; child = child->next) { if (!TagNameEquals(child, name, xml_namespace)) { continue; } result.push_back(child); } return result; } // Returns the value of a named attribute, or the empty string. static std::string GetAttribute(xmlNode* node, const char* attribute_name) { const xmlChar* name = reinterpret_cast<const xmlChar*>(attribute_name); for (xmlAttr* attr = node->properties; attr != NULL; attr = attr->next) { if (!xmlStrcmp(attr->name, name) && attr->children && attr->children->content) { return std::string(reinterpret_cast<const char*>( attr->children->content)); } } return std::string(); } // This is used for the xml parser to report errors. This assumes the context // is a pointer to a std::string where the error message should be appended. static void XmlErrorFunc(void *context, const char *message, ...) { va_list args; va_start(args, message); std::string* error = static_cast<std::string*>(context); base::StringAppendV(error, message, args); va_end(args); } // Utility class for cleaning up the xml document when leaving a scope. class ScopedXmlDocument { public: explicit ScopedXmlDocument(xmlDocPtr document) : document_(document) {} ~ScopedXmlDocument() { if (document_) xmlFreeDoc(document_); } xmlDocPtr get() { return document_; } private: xmlDocPtr document_; }; // Returns a pointer to the xmlNs on |node| with the |expected_href|, or // NULL if there isn't one with that href. static xmlNs* GetNamespace(xmlNode* node, const char* expected_href) { const xmlChar* href = reinterpret_cast<const xmlChar*>(expected_href); for (xmlNs* ns = node->ns; ns != NULL; ns = ns->next) { if (ns->href && !xmlStrcmp(ns->href, href)) { return ns; } } return NULL; } // Helper function that reads in values for a single <app> tag. It returns a // boolean indicating success or failure. On failure, it writes a error message // into |error_detail|. static bool ParseSingleAppTag(xmlNode* app_node, xmlNs* xml_namespace, UpdateManifest::Result* result, std::string *error_detail) { // Read the extension id. result->extension_id = GetAttribute(app_node, "appid"); if (result->extension_id.length() == 0) { *error_detail = "Missing appid on app node"; return false; } // Get the updatecheck node. std::vector<xmlNode*> updates = GetChildren(app_node, xml_namespace, "updatecheck"); if (updates.size() > 1) { *error_detail = "Too many updatecheck tags on app (expecting only 1)."; return false; } if (updates.empty()) { *error_detail = "Missing updatecheck on app."; return false; } xmlNode *updatecheck = updates[0]; if (GetAttribute(updatecheck, "status") == "noupdate") { return true; } // Find the url to the crx file. result->crx_url = GURL(GetAttribute(updatecheck, "codebase")); if (!result->crx_url.is_valid()) { *error_detail = "Invalid codebase url: '"; *error_detail += GetAttribute(updatecheck, "codebase"); *error_detail += "'."; return false; } // Get the version. result->version = GetAttribute(updatecheck, "version"); if (result->version.length() == 0) { *error_detail = "Missing version for updatecheck."; return false; } scoped_ptr<Version> version(Version::GetVersionFromString(result->version)); if (!version.get()) { *error_detail = "Invalid version: '"; *error_detail += result->version; *error_detail += "'."; return false; } // Get the minimum browser version (not required). result->browser_min_version = GetAttribute(updatecheck, "prodversionmin"); if (result->browser_min_version.length()) { scoped_ptr<Version> browser_min_version( Version::GetVersionFromString(result->browser_min_version)); if (!browser_min_version.get()) { *error_detail = "Invalid prodversionmin: '"; *error_detail += result->browser_min_version; *error_detail += "'."; return false; } } // package_hash is optional. It is only required for blacklist. It is a // sha256 hash of the package in hex format. result->package_hash = GetAttribute(updatecheck, "hash"); return true; } bool UpdateManifest::Parse(const std::string& manifest_xml) { results_.list.resize(0); results_.daystart_elapsed_seconds = kNoDaystart; errors_ = ""; if (manifest_xml.length() < 1) { ParseError("Empty xml"); return false; } std::string xml_errors; ScopedXmlErrorFunc error_func(&xml_errors, &XmlErrorFunc); // Start up the xml parser with the manifest_xml contents. ScopedXmlDocument document(xmlParseDoc( reinterpret_cast<const xmlChar*>(manifest_xml.c_str()))); if (!document.get()) { ParseError("%s", xml_errors.c_str()); return false; } xmlNode *root = xmlDocGetRootElement(document.get()); if (!root) { ParseError("Missing root node"); return false; } // Look for the required namespace declaration. xmlNs* gupdate_ns = GetNamespace(root, kExpectedGupdateXmlns); if (!gupdate_ns) { ParseError("Missing or incorrect xmlns on gupdate tag"); return false; } if (!TagNameEquals(root, "gupdate", gupdate_ns)) { ParseError("Missing gupdate tag"); return false; } // Check for the gupdate "protocol" attribute. if (GetAttribute(root, "protocol") != kExpectedGupdateProtocol) { ParseError("Missing/incorrect protocol on gupdate tag " "(expected '%s')", kExpectedGupdateProtocol); return false; } // Parse the first <daystart> if it's present. std::vector<xmlNode*> daystarts = GetChildren(root, gupdate_ns, "daystart"); if (!daystarts.empty()) { xmlNode* first = daystarts[0]; std::string elapsed_seconds = GetAttribute(first, "elapsed_seconds"); int parsed_elapsed = kNoDaystart; if (base::StringToInt(elapsed_seconds, &parsed_elapsed)) { results_.daystart_elapsed_seconds = parsed_elapsed; } } // Parse each of the <app> tags. std::vector<xmlNode*> apps = GetChildren(root, gupdate_ns, "app"); for (unsigned int i = 0; i < apps.size(); i++) { Result current; std::string error; if (!ParseSingleAppTag(apps[i], gupdate_ns, &current, &error)) { ParseError("%s", error.c_str()); } else { results_.list.push_back(current); } } return true; }
31.05597
79
0.675237
Scopetta197
60acc4f14e001deaee20496a931c0689e58789e7
36,168
cpp
C++
external/vulkancts/modules/vulkan/pipeline/vktPipelineMultisampleBaseResolveAndPerSampleFetch.cpp
jljusten/VK-GL-CTS
711e764f295a627eebe677a54ebc85d58d6e8920
[ "Apache-2.0" ]
1
2021-02-25T09:06:00.000Z
2021-02-25T09:06:00.000Z
external/vulkancts/modules/vulkan/pipeline/vktPipelineMultisampleBaseResolveAndPerSampleFetch.cpp
jljusten/VK-GL-CTS
711e764f295a627eebe677a54ebc85d58d6e8920
[ "Apache-2.0" ]
null
null
null
external/vulkancts/modules/vulkan/pipeline/vktPipelineMultisampleBaseResolveAndPerSampleFetch.cpp
jljusten/VK-GL-CTS
711e764f295a627eebe677a54ebc85d58d6e8920
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------ * 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 vktPipelineMultisampleBaseResolveAndPerSampleFetch.cpp * \brief Base class for tests that check results of multisample resolve * and/or values of individual samples *//*--------------------------------------------------------------------*/ #include "vktPipelineMultisampleBaseResolveAndPerSampleFetch.hpp" #include "vktPipelineMakeUtil.hpp" #include "vkBarrierUtil.hpp" #include "vkBuilderUtil.hpp" #include "vkQueryUtil.hpp" #include "vkTypeUtil.hpp" #include "vkCmdUtil.hpp" #include "vkTypeUtil.hpp" #include "vkObjUtil.hpp" #include "tcuTestLog.hpp" #include <vector> namespace vkt { namespace pipeline { namespace multisample { using namespace vk; void MSCaseBaseResolveAndPerSampleFetch::initPrograms (vk::SourceCollections& programCollection) const { // Create vertex shader std::ostringstream vs; vs << "#version 440\n" << "layout(location = 0) in vec4 vs_in_position_ndc;\n" << "\n" << "out gl_PerVertex {\n" << " vec4 gl_Position;\n" << "};\n" << "void main (void)\n" << "{\n" << " gl_Position = vs_in_position_ndc;\n" << "}\n"; programCollection.glslSources.add("per_sample_fetch_vs") << glu::VertexSource(vs.str()); // Create fragment shader std::ostringstream fs; fs << "#version 440\n" << "\n" << "layout(location = 0) out vec4 fs_out_color;\n" << "\n" << "layout(set = 0, binding = 0, input_attachment_index = 0) uniform subpassInputMS imageMS;\n" << "\n" << "layout(set = 0, binding = 1, std140) uniform SampleBlock {\n" << " int sampleNdx;\n" << "};\n" << "void main (void)\n" << "{\n" << " fs_out_color = subpassLoad(imageMS, sampleNdx);\n" << "}\n"; programCollection.glslSources.add("per_sample_fetch_fs") << glu::FragmentSource(fs.str()); } VkPipelineMultisampleStateCreateInfo MSInstanceBaseResolveAndPerSampleFetch::getMSStateCreateInfo (const ImageMSParams& imageMSParams) const { const VkPipelineMultisampleStateCreateInfo multisampleStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkPipelineMultisampleStateCreateFlags)0u, // VkPipelineMultisampleStateCreateFlags flags; imageMSParams.numSamples, // VkSampleCountFlagBits rasterizationSamples; VK_TRUE, // VkBool32 sampleShadingEnable; 1.0f, // float minSampleShading; DE_NULL, // const VkSampleMask* pSampleMask; VK_FALSE, // VkBool32 alphaToCoverageEnable; VK_FALSE, // VkBool32 alphaToOneEnable; }; return multisampleStateInfo; } const VkDescriptorSetLayout* MSInstanceBaseResolveAndPerSampleFetch::createMSPassDescSetLayout(const ImageMSParams& imageMSParams) { DE_UNREF(imageMSParams); return DE_NULL; } const VkDescriptorSet* MSInstanceBaseResolveAndPerSampleFetch::createMSPassDescSet(const ImageMSParams& imageMSParams, const VkDescriptorSetLayout* descSetLayout) { DE_UNREF(imageMSParams); DE_UNREF(descSetLayout); return DE_NULL; } tcu::TestStatus MSInstanceBaseResolveAndPerSampleFetch::iterate (void) { const InstanceInterface& instance = m_context.getInstanceInterface(); const DeviceInterface& deviceInterface = m_context.getDeviceInterface(); const VkDevice device = m_context.getDevice(); const VkPhysicalDevice physicalDevice = m_context.getPhysicalDevice(); Allocator& allocator = m_context.getDefaultAllocator(); const VkQueue queue = m_context.getUniversalQueue(); const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex(); VkImageCreateInfo imageMSInfo; VkImageCreateInfo imageRSInfo; const deUint32 firstSubpassAttachmentsCount = 2u; // Check if image size does not exceed device limits validateImageSize(instance, physicalDevice, m_imageType, m_imageMSParams.imageSize); // Check if device supports image format as color attachment validateImageFeatureFlags(instance, physicalDevice, mapTextureFormat(m_imageFormat), VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT); imageMSInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageMSInfo.pNext = DE_NULL; imageMSInfo.flags = 0u; imageMSInfo.imageType = mapImageType(m_imageType); imageMSInfo.format = mapTextureFormat(m_imageFormat); imageMSInfo.extent = makeExtent3D(getLayerSize(m_imageType, m_imageMSParams.imageSize)); imageMSInfo.arrayLayers = getNumLayers(m_imageType, m_imageMSParams.imageSize); imageMSInfo.mipLevels = 1u; imageMSInfo.samples = m_imageMSParams.numSamples; imageMSInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageMSInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageMSInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; imageMSInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageMSInfo.queueFamilyIndexCount = 0u; imageMSInfo.pQueueFamilyIndices = DE_NULL; if (m_imageType == IMAGE_TYPE_CUBE || m_imageType == IMAGE_TYPE_CUBE_ARRAY) { imageMSInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; } validateImageInfo(instance, physicalDevice, imageMSInfo); const de::UniquePtr<Image> imageMS(new Image(deviceInterface, device, allocator, imageMSInfo, MemoryRequirement::Any)); imageRSInfo = imageMSInfo; imageRSInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageRSInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; validateImageInfo(instance, physicalDevice, imageRSInfo); const de::UniquePtr<Image> imageRS(new Image(deviceInterface, device, allocator, imageRSInfo, MemoryRequirement::Any)); const deUint32 numSamples = static_cast<deUint32>(imageMSInfo.samples); std::vector<de::SharedPtr<Image> > imagesPerSampleVec(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imagesPerSampleVec[sampleNdx] = de::SharedPtr<Image>(new Image(deviceInterface, device, allocator, imageRSInfo, MemoryRequirement::Any)); } // Create render pass std::vector<VkAttachmentDescription> attachments(firstSubpassAttachmentsCount + numSamples); { const VkAttachmentDescription attachmentMSDesc = { (VkAttachmentDescriptionFlags)0u, // VkAttachmentDescriptionFlags flags; imageMSInfo.format, // VkFormat format; imageMSInfo.samples, // VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout initialLayout; VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL // VkImageLayout finalLayout; }; attachments[0] = attachmentMSDesc; const VkAttachmentDescription attachmentRSDesc = { (VkAttachmentDescriptionFlags)0u, // VkAttachmentDescriptionFlags flags; imageRSInfo.format, // VkFormat format; imageRSInfo.samples, // VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout initialLayout; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout finalLayout; }; attachments[1] = attachmentRSDesc; for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { attachments[firstSubpassAttachmentsCount + sampleNdx] = attachmentRSDesc; } } const VkAttachmentReference attachmentMSColorRef = { 0u, // deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }; const VkAttachmentReference attachmentMSInputRef = { 0u, // deUint32 attachment; VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL // VkImageLayout layout; }; const VkAttachmentReference attachmentRSColorRef = { 1u, // deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }; std::vector<VkAttachmentReference> perSampleAttachmentRef(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { const VkAttachmentReference attachmentRef = { firstSubpassAttachmentsCount + sampleNdx, // deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }; perSampleAttachmentRef[sampleNdx] = attachmentRef; } std::vector<deUint32> preserveAttachments(1u + numSamples); for (deUint32 attachNdx = 0u; attachNdx < 1u + numSamples; ++attachNdx) { preserveAttachments[attachNdx] = 1u + attachNdx; } std::vector<VkSubpassDescription> subpasses(1u + numSamples); std::vector<VkSubpassDependency> subpassDependencies(numSamples); const VkSubpassDescription firstSubpassDesc = { (VkSubpassDescriptionFlags)0u, // VkSubpassDescriptionFlags flags; VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint; 0u, // deUint32 inputAttachmentCount; DE_NULL, // const VkAttachmentReference* pInputAttachments; 1u, // deUint32 colorAttachmentCount; &attachmentMSColorRef, // const VkAttachmentReference* pColorAttachments; &attachmentRSColorRef, // const VkAttachmentReference* pResolveAttachments; DE_NULL, // const VkAttachmentReference* pDepthStencilAttachment; 0u, // deUint32 preserveAttachmentCount; DE_NULL // const deUint32* pPreserveAttachments; }; subpasses[0] = firstSubpassDesc; for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { const VkSubpassDescription subpassDesc = { (VkSubpassDescriptionFlags)0u, // VkSubpassDescriptionFlags flags; VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint; 1u, // deUint32 inputAttachmentCount; &attachmentMSInputRef, // const VkAttachmentReference* pInputAttachments; 1u, // deUint32 colorAttachmentCount; &perSampleAttachmentRef[sampleNdx], // const VkAttachmentReference* pColorAttachments; DE_NULL, // const VkAttachmentReference* pResolveAttachments; DE_NULL, // const VkAttachmentReference* pDepthStencilAttachment; 1u + sampleNdx, // deUint32 preserveAttachmentCount; dataPointer(preserveAttachments) // const deUint32* pPreserveAttachments; }; subpasses[1u + sampleNdx] = subpassDesc; const VkSubpassDependency subpassDependency = { 0u, // uint32_t srcSubpass; 1u + sampleNdx, // uint32_t dstSubpass; VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VkPipelineStageFlags srcStageMask; VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, // VkPipelineStageFlags dstStageMask; VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags srcAccessMask; VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, // VkAccessFlags dstAccessMask; 0u, // VkDependencyFlags dependencyFlags; }; subpassDependencies[sampleNdx] = subpassDependency; } const VkRenderPassCreateInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkRenderPassCreateFlags)0u, // VkRenderPassCreateFlags flags; static_cast<deUint32>(attachments.size()), // deUint32 attachmentCount; dataPointer(attachments), // const VkAttachmentDescription* pAttachments; static_cast<deUint32>(subpasses.size()), // deUint32 subpassCount; dataPointer(subpasses), // const VkSubpassDescription* pSubpasses; static_cast<deUint32>(subpassDependencies.size()), // deUint32 dependencyCount; dataPointer(subpassDependencies) // const VkSubpassDependency* pDependencies; }; const Unique<VkRenderPass> renderPass(createRenderPass(deviceInterface, device, &renderPassInfo)); const VkImageSubresourceRange fullImageRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, imageMSInfo.mipLevels, 0u, imageMSInfo.arrayLayers); // Create color attachments image views typedef de::SharedPtr<Unique<VkImageView> > VkImageViewSp; std::vector<VkImageViewSp> imageViewsShPtrs(firstSubpassAttachmentsCount + numSamples); std::vector<VkImageView> imageViews(firstSubpassAttachmentsCount + numSamples); imageViewsShPtrs[0] = makeVkSharedPtr(makeImageView(deviceInterface, device, **imageMS, mapImageViewType(m_imageType), imageMSInfo.format, fullImageRange)); imageViewsShPtrs[1] = makeVkSharedPtr(makeImageView(deviceInterface, device, **imageRS, mapImageViewType(m_imageType), imageRSInfo.format, fullImageRange)); imageViews[0] = **imageViewsShPtrs[0]; imageViews[1] = **imageViewsShPtrs[1]; for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imageViewsShPtrs[firstSubpassAttachmentsCount + sampleNdx] = makeVkSharedPtr(makeImageView(deviceInterface, device, **imagesPerSampleVec[sampleNdx], mapImageViewType(m_imageType), imageRSInfo.format, fullImageRange)); imageViews[firstSubpassAttachmentsCount + sampleNdx] = **imageViewsShPtrs[firstSubpassAttachmentsCount + sampleNdx]; } // Create framebuffer const VkFramebufferCreateInfo framebufferInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkFramebufferCreateFlags)0u, // VkFramebufferCreateFlags flags; *renderPass, // VkRenderPass renderPass; static_cast<deUint32>(imageViews.size()), // uint32_t attachmentCount; dataPointer(imageViews), // const VkImageView* pAttachments; imageMSInfo.extent.width, // uint32_t width; imageMSInfo.extent.height, // uint32_t height; imageMSInfo.arrayLayers, // uint32_t layers; }; const Unique<VkFramebuffer> framebuffer(createFramebuffer(deviceInterface, device, &framebufferInfo)); const VkDescriptorSetLayout* descriptorSetLayoutMSPass = createMSPassDescSetLayout(m_imageMSParams); // Create pipeline layout const VkPipelineLayoutCreateInfo pipelineLayoutMSPassParams = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkPipelineLayoutCreateFlags)0u, // VkPipelineLayoutCreateFlags flags; descriptorSetLayoutMSPass ? 1u : 0u, // deUint32 setLayoutCount; descriptorSetLayoutMSPass, // const VkDescriptorSetLayout* pSetLayouts; 0u, // deUint32 pushConstantRangeCount; DE_NULL, // const VkPushConstantRange* pPushConstantRanges; }; const Unique<VkPipelineLayout> pipelineLayoutMSPass(createPipelineLayout(deviceInterface, device, &pipelineLayoutMSPassParams)); // Create vertex attributes data const VertexDataDesc vertexDataDesc = getVertexDataDescripton(); de::SharedPtr<Buffer> vertexBuffer = de::SharedPtr<Buffer>(new Buffer(deviceInterface, device, allocator, makeBufferCreateInfo(vertexDataDesc.dataSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), MemoryRequirement::HostVisible)); const Allocation& vertexBufferAllocation = vertexBuffer->getAllocation(); uploadVertexData(vertexBufferAllocation, vertexDataDesc); flushAlloc(deviceInterface, device, vertexBufferAllocation); const VkVertexInputBindingDescription vertexBinding = { 0u, // deUint32 binding; vertexDataDesc.dataStride, // deUint32 stride; VK_VERTEX_INPUT_RATE_VERTEX // VkVertexInputRate inputRate; }; const VkPipelineVertexInputStateCreateInfo vertexInputStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkPipelineVertexInputStateCreateFlags)0u, // VkPipelineVertexInputStateCreateFlags flags; 1u, // uint32_t vertexBindingDescriptionCount; &vertexBinding, // const VkVertexInputBindingDescription* pVertexBindingDescriptions; static_cast<deUint32>(vertexDataDesc.vertexAttribDescVec.size()), // uint32_t vertexAttributeDescriptionCount; dataPointer(vertexDataDesc.vertexAttribDescVec), // const VkVertexInputAttributeDescription* pVertexAttributeDescriptions; }; const std::vector<VkViewport> viewports (1, makeViewport(imageMSInfo.extent)); const std::vector<VkRect2D> scissors (1, makeRect2D(imageMSInfo.extent)); const VkPipelineMultisampleStateCreateInfo multisampleStateInfo = getMSStateCreateInfo(m_imageMSParams); // Create graphics pipeline for multisample pass const Unique<VkShaderModule> vsMSPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("vertex_shader"), (VkShaderModuleCreateFlags)0u)); const Unique<VkShaderModule> fsMSPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("fragment_shader"), (VkShaderModuleCreateFlags)0u)); const Unique<VkPipeline> graphicsPipelineMSPass(makeGraphicsPipeline(deviceInterface, // const DeviceInterface& vk device, // const VkDevice device *pipelineLayoutMSPass, // const VkPipelineLayout pipelineLayout *vsMSPassModule, // const VkShaderModule vertexShaderModule DE_NULL, // const VkShaderModule tessellationControlModule DE_NULL, // const VkShaderModule tessellationEvalModule DE_NULL, // const VkShaderModule geometryShaderModule *fsMSPassModule, // const VkShaderModule fragmentShaderModule *renderPass, // const VkRenderPass renderPass viewports, // const std::vector<VkViewport>& viewports scissors, // const std::vector<VkRect2D>& scissors vertexDataDesc.primitiveTopology, // const VkPrimitiveTopology topology 0u, // const deUint32 subpass 0u, // const deUint32 patchControlPoints &vertexInputStateInfo, // const VkPipelineVertexInputStateCreateInfo* vertexInputStateCreateInfo DE_NULL, // const VkPipelineRasterizationStateCreateInfo* rasterizationStateCreateInfo &multisampleStateInfo)); // const VkPipelineMultisampleStateCreateInfo* multisampleStateCreateInfo typedef de::SharedPtr<Unique<VkPipeline> > VkPipelineSp; std::vector<VkPipelineSp> graphicsPipelinesPerSampleFetch(numSamples); // Create descriptor set layout const Unique<VkDescriptorSetLayout> descriptorSetLayout( DescriptorSetLayoutBuilder() .addSingleBinding(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, VK_SHADER_STAGE_FRAGMENT_BIT) .addSingleBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_SHADER_STAGE_FRAGMENT_BIT) .build(deviceInterface, device)); const Unique<VkPipelineLayout> pipelineLayoutPerSampleFetchPass(makePipelineLayout(deviceInterface, device, *descriptorSetLayout)); const deUint32 bufferPerSampleFetchPassSize = 4u * (deUint32)sizeof(tcu::Vec4); de::SharedPtr<Buffer> vertexBufferPerSampleFetchPass = de::SharedPtr<Buffer>(new Buffer(deviceInterface, device, allocator, makeBufferCreateInfo(bufferPerSampleFetchPassSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), MemoryRequirement::HostVisible)); // Create graphics pipelines for per sample texel fetch passes { const Unique<VkShaderModule> vsPerSampleFetchPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("per_sample_fetch_vs"), (VkShaderModuleCreateFlags)0u)); const Unique<VkShaderModule> fsPerSampleFetchPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("per_sample_fetch_fs"), (VkShaderModuleCreateFlags)0u)); std::vector<tcu::Vec4> vertices; vertices.push_back(tcu::Vec4(-1.0f, -1.0f, 0.0f, 1.0f)); vertices.push_back(tcu::Vec4( 1.0f, -1.0f, 0.0f, 1.0f)); vertices.push_back(tcu::Vec4(-1.0f, 1.0f, 0.0f, 1.0f)); vertices.push_back(tcu::Vec4( 1.0f, 1.0f, 0.0f, 1.0f)); const Allocation& vertexAllocPerSampleFetchPass = vertexBufferPerSampleFetchPass->getAllocation(); deMemcpy(vertexAllocPerSampleFetchPass.getHostPtr(), dataPointer(vertices), static_cast<std::size_t>(bufferPerSampleFetchPassSize)); flushAlloc(deviceInterface, device, vertexAllocPerSampleFetchPass); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { graphicsPipelinesPerSampleFetch[sampleNdx] = makeVkSharedPtr((makeGraphicsPipeline(deviceInterface, // const DeviceInterface& vk device, // const VkDevice device *pipelineLayoutPerSampleFetchPass, // const VkPipelineLayout pipelineLayout *vsPerSampleFetchPassModule, // const VkShaderModule vertexShaderModule DE_NULL, // const VkShaderModule tessellationControlModule DE_NULL, // const VkShaderModule tessellationEvalModule DE_NULL, // const VkShaderModule geometryShaderModule *fsPerSampleFetchPassModule, // const VkShaderModule fragmentShaderModule *renderPass, // const VkRenderPass renderPass viewports, // const std::vector<VkViewport>& viewports scissors, // const std::vector<VkRect2D>& scissors VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, // const VkPrimitiveTopology topology 1u + sampleNdx))); // const deUint32 subpass } } // Create descriptor pool const Unique<VkDescriptorPool> descriptorPool( DescriptorPoolBuilder() .addType(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1u) .addType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1u) .build(deviceInterface, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u)); // Create descriptor set const Unique<VkDescriptorSet> descriptorSet(makeDescriptorSet(deviceInterface, device, *descriptorPool, *descriptorSetLayout)); const VkPhysicalDeviceLimits deviceLimits = getPhysicalDeviceProperties(instance, physicalDevice).limits; VkDeviceSize uboOffsetAlignment = sizeof(deInt32) < deviceLimits.minUniformBufferOffsetAlignment ? deviceLimits.minUniformBufferOffsetAlignment : sizeof(deInt32); uboOffsetAlignment += (deviceLimits.minUniformBufferOffsetAlignment - uboOffsetAlignment % deviceLimits.minUniformBufferOffsetAlignment) % deviceLimits.minUniformBufferOffsetAlignment; const VkBufferCreateInfo bufferSampleIDInfo = makeBufferCreateInfo(uboOffsetAlignment * numSamples, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); const de::UniquePtr<Buffer> bufferSampleID(new Buffer(deviceInterface, device, allocator, bufferSampleIDInfo, MemoryRequirement::HostVisible)); std::vector<deUint32> sampleIDsOffsets(numSamples); { deInt8* sampleIDs = new deInt8[static_cast<deUint32>(uboOffsetAlignment) * numSamples]; for (deInt32 sampleNdx = 0u; sampleNdx < static_cast<deInt32>(numSamples); ++sampleNdx) { sampleIDsOffsets[sampleNdx] = static_cast<deUint32>(sampleNdx * uboOffsetAlignment); deInt8* samplePtr = sampleIDs + sampleIDsOffsets[sampleNdx]; deMemcpy(samplePtr, &sampleNdx, sizeof(deInt32)); } deMemcpy(bufferSampleID->getAllocation().getHostPtr(), sampleIDs, static_cast<deUint32>(uboOffsetAlignment * numSamples)); flushAlloc(deviceInterface, device, bufferSampleID->getAllocation()); delete[] sampleIDs; } { const VkDescriptorImageInfo descImageInfo = makeDescriptorImageInfo(DE_NULL, imageViews[0], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); const VkDescriptorBufferInfo descBufferInfo = makeDescriptorBufferInfo(**bufferSampleID, 0u, sizeof(deInt32)); DescriptorSetUpdateBuilder() .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, &descImageInfo) .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, &descBufferInfo) .update(deviceInterface, device); } // Create command buffer for compute and transfer oparations const Unique<VkCommandPool> commandPool(createCommandPool(deviceInterface, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex)); const Unique<VkCommandBuffer> commandBuffer(makeCommandBuffer(deviceInterface, device, *commandPool)); // Start recording commands beginCommandBuffer(deviceInterface, *commandBuffer); { std::vector<VkImageMemoryBarrier> imageOutputAttachmentBarriers(firstSubpassAttachmentsCount + numSamples); imageOutputAttachmentBarriers[0] = makeImageMemoryBarrier ( 0u, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, **imageMS, fullImageRange ); imageOutputAttachmentBarriers[1] = makeImageMemoryBarrier ( 0u, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, **imageRS, fullImageRange ); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imageOutputAttachmentBarriers[firstSubpassAttachmentsCount + sampleNdx] = makeImageMemoryBarrier ( 0u, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, **imagesPerSampleVec[sampleNdx], fullImageRange ); } deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, static_cast<deUint32>(imageOutputAttachmentBarriers.size()), dataPointer(imageOutputAttachmentBarriers)); } { const VkDeviceSize vertexStartOffset = 0u; std::vector<VkClearValue> clearValues(firstSubpassAttachmentsCount + numSamples); for (deUint32 attachmentNdx = 0u; attachmentNdx < firstSubpassAttachmentsCount + numSamples; ++attachmentNdx) { clearValues[attachmentNdx] = makeClearValueColor(tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f)); } beginRenderPass(deviceInterface, *commandBuffer, *renderPass, *framebuffer, makeRect2D(0, 0, imageMSInfo.extent.width, imageMSInfo.extent.height), (deUint32)clearValues.size(), dataPointer(clearValues)); // Bind graphics pipeline deviceInterface.cmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *graphicsPipelineMSPass); const VkDescriptorSet* descriptorSetMSPass = createMSPassDescSet(m_imageMSParams, descriptorSetLayoutMSPass); if (descriptorSetMSPass) { // Bind descriptor set deviceInterface.cmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipelineLayoutMSPass, 0u, 1u, descriptorSetMSPass, 0u, DE_NULL); } // Bind vertex buffer deviceInterface.cmdBindVertexBuffers(*commandBuffer, 0u, 1u, &vertexBuffer->get(), &vertexStartOffset); // Perform a draw deviceInterface.cmdDraw(*commandBuffer, vertexDataDesc.verticesCount, 1u, 0u, 0u); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { deviceInterface.cmdNextSubpass(*commandBuffer, VK_SUBPASS_CONTENTS_INLINE); // Bind graphics pipeline deviceInterface.cmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, **graphicsPipelinesPerSampleFetch[sampleNdx]); // Bind descriptor set deviceInterface.cmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipelineLayoutPerSampleFetchPass, 0u, 1u, &descriptorSet.get(), 1u, &sampleIDsOffsets[sampleNdx]); // Bind vertex buffer deviceInterface.cmdBindVertexBuffers(*commandBuffer, 0u, 1u, &vertexBufferPerSampleFetchPass->get(), &vertexStartOffset); // Perform a draw deviceInterface.cmdDraw(*commandBuffer, 4u, 1u, 0u, 0u); } // End render pass endRenderPass(deviceInterface, *commandBuffer); } { const VkImageMemoryBarrier imageRSTransferBarrier = makeImageMemoryBarrier ( VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **imageRS, fullImageRange ); deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &imageRSTransferBarrier); } // Copy data from imageRS to buffer const deUint32 imageRSSizeInBytes = getImageSizeInBytes(imageRSInfo.extent, imageRSInfo.arrayLayers, m_imageFormat, imageRSInfo.mipLevels, 1u); const VkBufferCreateInfo bufferRSInfo = makeBufferCreateInfo(imageRSSizeInBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT); const de::UniquePtr<Buffer> bufferRS(new Buffer(deviceInterface, device, allocator, bufferRSInfo, MemoryRequirement::HostVisible)); { const VkBufferImageCopy bufferImageCopy = { 0u, // VkDeviceSize bufferOffset; 0u, // deUint32 bufferRowLength; 0u, // deUint32 bufferImageHeight; makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, imageRSInfo.arrayLayers), // VkImageSubresourceLayers imageSubresource; makeOffset3D(0, 0, 0), // VkOffset3D imageOffset; imageRSInfo.extent, // VkExtent3D imageExtent; }; deviceInterface.cmdCopyImageToBuffer(*commandBuffer, **imageRS, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, bufferRS->get(), 1u, &bufferImageCopy); } { const VkBufferMemoryBarrier bufferRSHostReadBarrier = makeBufferMemoryBarrier ( VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, bufferRS->get(), 0u, imageRSSizeInBytes ); deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, 1u, &bufferRSHostReadBarrier, 0u, DE_NULL); } // Copy data from per sample images to buffers std::vector<VkImageMemoryBarrier> imagesPerSampleTransferBarriers(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imagesPerSampleTransferBarriers[sampleNdx] = makeImageMemoryBarrier ( VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **imagesPerSampleVec[sampleNdx], fullImageRange ); } deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, static_cast<deUint32>(imagesPerSampleTransferBarriers.size()), dataPointer(imagesPerSampleTransferBarriers)); std::vector<de::SharedPtr<Buffer> > buffersPerSample(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { buffersPerSample[sampleNdx] = de::SharedPtr<Buffer>(new Buffer(deviceInterface, device, allocator, bufferRSInfo, MemoryRequirement::HostVisible)); const VkBufferImageCopy bufferImageCopy = { 0u, // VkDeviceSize bufferOffset; 0u, // deUint32 bufferRowLength; 0u, // deUint32 bufferImageHeight; makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, imageRSInfo.arrayLayers), // VkImageSubresourceLayers imageSubresource; makeOffset3D(0, 0, 0), // VkOffset3D imageOffset; imageRSInfo.extent, // VkExtent3D imageExtent; }; deviceInterface.cmdCopyImageToBuffer(*commandBuffer, **imagesPerSampleVec[sampleNdx], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **buffersPerSample[sampleNdx], 1u, &bufferImageCopy); } std::vector<VkBufferMemoryBarrier> buffersPerSampleHostReadBarriers(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { buffersPerSampleHostReadBarriers[sampleNdx] = makeBufferMemoryBarrier ( VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, **buffersPerSample[sampleNdx], 0u, imageRSSizeInBytes ); } deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, static_cast<deUint32>(buffersPerSampleHostReadBarriers.size()), dataPointer(buffersPerSampleHostReadBarriers), 0u, DE_NULL); // End recording commands endCommandBuffer(deviceInterface, *commandBuffer); // Submit commands for execution and wait for completion submitCommandsAndWait(deviceInterface, device, queue, *commandBuffer); // Retrieve data from bufferRS to host memory const Allocation& bufferRSAlloc = bufferRS->getAllocation(); invalidateAlloc(deviceInterface, device, bufferRSAlloc); const tcu::ConstPixelBufferAccess bufferRSData (m_imageFormat, imageRSInfo.extent.width, imageRSInfo.extent.height, imageRSInfo.extent.depth * imageRSInfo.arrayLayers, bufferRSAlloc.getHostPtr()); std::stringstream resolveName; resolveName << "Resolve image " << getImageTypeName(m_imageType) << "_" << bufferRSData.getWidth() << "_" << bufferRSData.getHeight() << "_" << bufferRSData.getDepth() << std::endl; m_context.getTestContext().getLog() << tcu::TestLog::Section(resolveName.str(), resolveName.str()) << tcu::LogImage("resolve", "", bufferRSData) << tcu::TestLog::EndSection; std::vector<tcu::ConstPixelBufferAccess> buffersPerSampleData(numSamples); // Retrieve data from per sample buffers to host memory for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { const Allocation& bufferAlloc = buffersPerSample[sampleNdx]->getAllocation(); invalidateAlloc(deviceInterface, device, bufferAlloc); buffersPerSampleData[sampleNdx] = tcu::ConstPixelBufferAccess ( m_imageFormat, imageRSInfo.extent.width, imageRSInfo.extent.height, imageRSInfo.extent.depth * imageRSInfo.arrayLayers, bufferAlloc.getHostPtr() ); std::stringstream sampleName; sampleName << "Sample " << sampleNdx << " image" << std::endl; m_context.getTestContext().getLog() << tcu::TestLog::Section(sampleName.str(), sampleName.str()) << tcu::LogImage("sample", "", buffersPerSampleData[sampleNdx]) << tcu::TestLog::EndSection; } return verifyImageData(imageMSInfo, imageRSInfo, buffersPerSampleData, bufferRSData); } } // multisample } // pipeline } // vkt
45.956798
245
0.729982
jljusten
60ad8e75b8cc5955a9a862f5195d25d658fe4cd0
1,527
hpp
C++
LeetCode/C++/0041._First_Missing_Positive/solution.hpp
icgw/LeetCode
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
4
2018-09-12T09:32:17.000Z
2018-12-06T03:17:38.000Z
LeetCode/C++/0041._First_Missing_Positive/solution.hpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
LeetCode/C++/0041._First_Missing_Positive/solution.hpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
#include <vector> using std::vector; using std::swap; class Solution { public: int firstMissingPositive(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) swap(nums[i], nums[nums[i] - 1]); } for (int i = 0; i < n; ++i) { if (nums[i] != i + 1) return i + 1; } return n + 1; } /************************************************************* int partition(vector<int> &nums) { int p = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] > 0) { swap(nums[i], nums[p]); p++; } } return p; } int firstMissingPositive(vector<int>& nums) { int k = partition(nums); int first_missing_index = k; for (int i = 0; i < k; ++i) { int tmp = nums[i] < 0 ? -nums[i] : nums[i]; tmp = tmp - 1; if (tmp < k && nums[tmp] > 0) nums[tmp] = -nums[tmp]; } for (int i = 0; i < k; ++i) { if (nums[i] > 0) { first_missing_index = i; break; } } return first_missing_index + 1; } ************************************************************/ };
30.54
83
0.32482
icgw
60ae90add18acce55ac34c30fcffcc2909635dd5
4,367
cc
C++
drds/src/model/DescribeDrdsDBClusterResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
drds/src/model/DescribeDrdsDBClusterResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
drds/src/model/DescribeDrdsDBClusterResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/drds/model/DescribeDrdsDBClusterResult.h> #include <json/json.h> using namespace AlibabaCloud::Drds; using namespace AlibabaCloud::Drds::Model; DescribeDrdsDBClusterResult::DescribeDrdsDBClusterResult() : ServiceResult() {} DescribeDrdsDBClusterResult::DescribeDrdsDBClusterResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeDrdsDBClusterResult::~DescribeDrdsDBClusterResult() {} void DescribeDrdsDBClusterResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dbInstanceNode = value["DbInstance"]; if(!dbInstanceNode["DBInstanceId"].isNull()) dbInstance_.dBInstanceId = dbInstanceNode["DBInstanceId"].asString(); if(!dbInstanceNode["Port"].isNull()) dbInstance_.port = std::stoi(dbInstanceNode["Port"].asString()); if(!dbInstanceNode["DBInstanceStatus"].isNull()) dbInstance_.dBInstanceStatus = dbInstanceNode["DBInstanceStatus"].asString(); if(!dbInstanceNode["DbInstType"].isNull()) dbInstance_.dbInstType = dbInstanceNode["DbInstType"].asString(); if(!dbInstanceNode["Engine"].isNull()) dbInstance_.engine = dbInstanceNode["Engine"].asString(); if(!dbInstanceNode["EngineVersion"].isNull()) dbInstance_.engineVersion = dbInstanceNode["EngineVersion"].asString(); if(!dbInstanceNode["RdsInstType"].isNull()) dbInstance_.rdsInstType = dbInstanceNode["RdsInstType"].asString(); if(!dbInstanceNode["PayType"].isNull()) dbInstance_.payType = dbInstanceNode["PayType"].asString(); if(!dbInstanceNode["ExpireTime"].isNull()) dbInstance_.expireTime = dbInstanceNode["ExpireTime"].asString(); if(!dbInstanceNode["RemainDays"].isNull()) dbInstance_.remainDays = dbInstanceNode["RemainDays"].asString(); if(!dbInstanceNode["NetworkType"].isNull()) dbInstance_.networkType = dbInstanceNode["NetworkType"].asString(); if(!dbInstanceNode["ReadMode"].isNull()) dbInstance_.readMode = dbInstanceNode["ReadMode"].asString(); auto allEndpointsNode = dbInstanceNode["Endpoints"]["Endpoint"]; for (auto dbInstanceNodeEndpointsEndpoint : allEndpointsNode) { DbInstance::Endpoint endpointObject; if(!dbInstanceNodeEndpointsEndpoint["NodeIds"].isNull()) endpointObject.nodeIds = dbInstanceNodeEndpointsEndpoint["NodeIds"].asString(); if(!dbInstanceNodeEndpointsEndpoint["EndpointId"].isNull()) endpointObject.endpointId = dbInstanceNodeEndpointsEndpoint["EndpointId"].asString(); if(!dbInstanceNodeEndpointsEndpoint["ReadWeight"].isNull()) endpointObject.readWeight = std::stoi(dbInstanceNodeEndpointsEndpoint["ReadWeight"].asString()); dbInstance_.endpoints.push_back(endpointObject); } auto allDBNodesNode = dbInstanceNode["DBNodes"]["DBNode"]; for (auto dbInstanceNodeDBNodesDBNode : allDBNodesNode) { DbInstance::DBNode dBNodeObject; if(!dbInstanceNodeDBNodesDBNode["DBNodeId"].isNull()) dBNodeObject.dBNodeId = dbInstanceNodeDBNodesDBNode["DBNodeId"].asString(); if(!dbInstanceNodeDBNodesDBNode["ZoneId"].isNull()) dBNodeObject.zoneId = dbInstanceNodeDBNodesDBNode["ZoneId"].asString(); if(!dbInstanceNodeDBNodesDBNode["DBNodeStatus"].isNull()) dBNodeObject.dBNodeStatus = dbInstanceNodeDBNodesDBNode["DBNodeStatus"].asString(); if(!dbInstanceNodeDBNodesDBNode["DBNodeRole"].isNull()) dBNodeObject.dBNodeRole = dbInstanceNodeDBNodesDBNode["DBNodeRole"].asString(); dbInstance_.dBNodes.push_back(dBNodeObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } DescribeDrdsDBClusterResult::DbInstance DescribeDrdsDBClusterResult::getDbInstance()const { return dbInstance_; } bool DescribeDrdsDBClusterResult::getSuccess()const { return success_; }
40.435185
99
0.771468
iamzken
60af0dfb31366455544682d2c976e9e7ac494484
3,306
cc
C++
chrome/common/extensions/api/system_indicator/system_indicator_handler_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/common/extensions/api/system_indicator/system_indicator_handler_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/common/extensions/api/system_indicator/system_indicator_handler_unittest.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/extensions/api/system_indicator/system_indicator_handler.h" #include "base/test/values_test_util.h" #include "components/version_info/channel.h" #include "extensions/common/constants.h" #include "extensions/common/extension_icon_set.h" #include "extensions/common/features/feature_channel.h" #include "extensions/common/manifest_test.h" #include "testing/gmock/include/gmock/gmock.h" namespace extensions { using SystemIndicatorHandlerTest = ManifestTest; TEST_F(SystemIndicatorHandlerTest, BasicTests) { ScopedCurrentChannel current_channel(version_info::Channel::DEV); // Simple icon path. { constexpr char kManifest[] = R"({ "name": "System Indicator", "manifest_version": 2, "version": "0.1", "system_indicator": { "default_icon": "icon.png" } })"; scoped_refptr<const Extension> extension = LoadAndExpectSuccess( ManifestData(base::test::ParseJson(kManifest), "icon")); ASSERT_TRUE(extension); const ExtensionIconSet* icon = SystemIndicatorHandler::GetSystemIndicatorIcon(*extension); ASSERT_TRUE(icon); // Make a copy of the map since [] is more readable than find() for // comparing values. ExtensionIconSet::IconMap icon_map = icon->map(); EXPECT_THAT(icon_map, testing::ElementsAre(std::make_pair( extension_misc::EXTENSION_ICON_GIGANTOR, "icon.png"))); } // Icon dictionary. { constexpr char kManifest[] = R"({ "name": "System Indicator", "manifest_version": 2, "version": "0.1", "system_indicator": { "default_icon": { "24": "icon24.png", "48": "icon48.png", "79": "icon79.png" } } })"; scoped_refptr<const Extension> extension = LoadAndExpectSuccess( ManifestData(base::test::ParseJson(kManifest), "icon")); ASSERT_TRUE(extension); const ExtensionIconSet* icon = SystemIndicatorHandler::GetSystemIndicatorIcon(*extension); ASSERT_TRUE(icon); // Make a copy of the map since [] is more readable than find() for // comparing values. ExtensionIconSet::IconMap icon_map = icon->map(); EXPECT_THAT(icon_map, testing::ElementsAre(std::make_pair(24, "icon24.png"), std::make_pair(48, "icon48.png"), std::make_pair(79, "icon79.png"))); } // Empty dictionary. { constexpr char kManifest[] = R"({ "name": "System Indicator", "manifest_version": 2, "version": "0.1", "system_indicator": {} })"; scoped_refptr<const Extension> extension = LoadAndExpectSuccess( ManifestData(base::test::ParseJson(kManifest), "icon")); ASSERT_TRUE(extension); const ExtensionIconSet* icon = SystemIndicatorHandler::GetSystemIndicatorIcon(*extension); ASSERT_TRUE(icon); EXPECT_TRUE(icon->empty()); } } } // namespace extensions
34.8
83
0.621295
sarang-apps
60afebb2dc180c6fed882952e29a3a46b908a1d5
16,636
cpp
C++
NOLF/ObjectDLL/Intelligence.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
38
2019-09-16T14:46:42.000Z
2022-03-10T20:28:10.000Z
NOLF/ObjectDLL/Intelligence.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
39
2019-08-12T01:35:33.000Z
2022-02-28T16:48:16.000Z
NOLF/ObjectDLL/Intelligence.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
6
2019-09-17T12:49:18.000Z
2022-03-10T20:28:12.000Z
// ----------------------------------------------------------------------- // // // MODULE : Intelligence.cpp // // PURPOSE : Implementation of the Intelligence object // // CREATED : 9/14/99 // // (c) 1999-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "Intelligence.h" #include "ObjectMsgs.h" #include "PlayerObj.h" #include "CommandMgr.h" // Statics static char *s_szActivate = "ACTIVATE"; static char *s_szGadget = "GADGET"; static char *s_szRespawn = "RESPAWN"; extern CVarTrack g_vtNetIntelScore; CVarTrack g_IntelRespawnScale; #define INTEL_RESPAWN_SOUND "Powerups\\Snd\\spawn_intel.wav" #define INTEL_PICKUP_SOUND "Powerups\\Snd\\pu_intel.wav" // ----------------------------------------------------------------------- // // // CLASS: Intelligence // // PURPOSE: An Intelligence object // // ----------------------------------------------------------------------- // BEGIN_CLASS(Intelligence) // Hide parent properties we don't care about... ADD_STRINGPROP_FLAG(Filename, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(Skin, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(Type, "", PF_STATICLIST | PF_DIMS | PF_LOCALDIMS) ADD_LONGINTPROP(InfoId, 0) ADD_BOOLPROP_FLAG(ShowPopup, LTTRUE, 0) ADD_BOOLPROP_FLAG(PhotoOnly, LTFALSE, 0) ADD_STRINGPROP_FLAG(PickedUpCommand, "", 0) ADD_LONGINTPROP(PlayerTeamFilter, 0) ADD_BOOLPROP_FLAG(StartHidden, LTFALSE, 0) ADD_REALPROP(RespawnTime, 30.0f) END_CLASS_DEFAULT_FLAGS_PLUGIN(Intelligence, Prop, NULL, NULL, 0, CIntelPlugin) LTRESULT CIntelPlugin::PreHook_EditStringList( const char* szRezPath, const char* szPropName, char** aszStrings, uint32* pcStrings, const uint32 cMaxStrings, const uint32 cMaxStringLength) { if ( LT_OK == CPropPlugin::PreHook_EditStringList(szRezPath, szPropName, aszStrings, pcStrings, cMaxStrings, cMaxStringLength) ) { return LT_OK; } else if (_strcmpi("Type", szPropName) == 0) { if (m_IntelMgrPlugin.PreHook_EditStringList(szRezPath, szPropName, aszStrings, pcStrings, cMaxStrings, cMaxStringLength) == LT_OK) { return LT_OK; } } return LT_UNSUPPORTED; } LTRESULT CIntelPlugin::PreHook_Dims( const char* szRezPath, const char* szPropValue, char* szModelFilenameBuf, int nModelFilenameBufLen, LTVector & vDims) { if (m_IntelMgrPlugin.PreHook_Dims(szRezPath, szPropValue, szModelFilenameBuf, nModelFilenameBufLen, vDims) == LT_OK) { return LT_OK; } return LT_UNSUPPORTED; } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Intelligence() // // PURPOSE: Initialize object // // ----------------------------------------------------------------------- // Intelligence::Intelligence() : Prop () { m_bShowPopup = LTTRUE; m_bPhotoOnly = LTFALSE; m_hstrPickedUpCmd = LTNULL; m_nPlayerTeamFilter = 0; m_nInfoId = 0; m_nIntelId = INTELMGR_INVALID_ID; m_fRespawnDelay = 30.0f; m_bStartHidden = LTFALSE; m_bFirstUpdate = LTTRUE; m_bSkipUpdate = LTFALSE; } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::~Intelligence() // // PURPOSE: Deallocate object // // ----------------------------------------------------------------------- // Intelligence::~Intelligence() { if (m_hstrPickedUpCmd) { g_pLTServer->FreeString(m_hstrPickedUpCmd); m_hstrPickedUpCmd = LTNULL; } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::EngineMessageFn // // PURPOSE: Handle engine messages // // ----------------------------------------------------------------------- // uint32 Intelligence::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData) { switch(messageID) { case MID_UPDATE: { Update(); } break; case MID_PRECREATE: { uint32 dwRet = Prop::EngineMessageFn(messageID, pData, fData); if (fData == PRECREATE_WORLDFILE || fData == PRECREATE_STRINGPROP) { ReadProp((ObjectCreateStruct*)pData); PostPropRead((ObjectCreateStruct*)pData); } return dwRet; } break; case MID_SAVEOBJECT: { Save((HMESSAGEWRITE)pData); } break; case MID_LOADOBJECT: { Load((HMESSAGEREAD)pData); } break; case MID_INITIALUPDATE: { if (fData != INITIALUPDATE_SAVEGAME) { InitialUpdate(); } CacheFiles(); } break; default : break; } return Prop::EngineMessageFn(messageID, pData, fData); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::ReadProp // // PURPOSE: Set property value // // ----------------------------------------------------------------------- // void Intelligence::ReadProp(ObjectCreateStruct *pInfo) { if (!pInfo) return; GenericProp genProp; if (g_pLTServer->GetPropGeneric("PhotoOnly", &genProp) == LT_OK) { m_bPhotoOnly = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("StartHidden", &genProp) == LT_OK) { m_bStartHidden = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("ShowPopup", &genProp) == LT_OK) { m_bShowPopup = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("PickedUpCommand", &genProp) == LT_OK) { if (genProp.m_String[0]) { m_hstrPickedUpCmd = g_pLTServer->CreateString(genProp.m_String); } } if (g_pLTServer->GetPropGeneric("PlayerTeamFilter", &genProp) == LT_OK) { m_nPlayerTeamFilter = (uint8) genProp.m_Long; } if (g_pLTServer->GetPropGeneric("InfoId", &genProp) == LT_OK) { m_nInfoId = genProp.m_Long; } if (g_pLTServer->GetPropGeneric("RespawnTime", &genProp) == LT_OK) { m_fRespawnDelay = genProp.m_Float; } INTEL* pIntel = LTNULL; if (g_pLTServer->GetPropGeneric("Type", &genProp) == LT_OK) { if (genProp.m_String[0]) { pIntel = g_pIntelMgr->GetIntel(genProp.m_String); } } if (pIntel) { if (!pIntel || !pIntel->szFilename[0]) return; SAFE_STRCPY(pInfo->m_Filename, pIntel->szFilename); uint32 iSkin = 0; ConParse conParse; conParse.Init(pIntel->szSkin); while (g_pLTServer->Common()->Parse(&conParse) == LT_OK) { if (conParse.m_nArgs > 0) { SAFE_STRCPY(pInfo->m_SkinNames[iSkin], conParse.m_Args[0]); iSkin++; } if (iSkin >= MAX_MODEL_TEXTURES) break; } pInfo->m_SkinName[MAX_CS_FILENAME_LEN] = '\0'; m_nIntelId = pIntel->nId; if (pIntel->bChromakey) { m_dwFlags2 |= FLAG2_CHROMAKEY; } m_dwFlags = (pIntel->bChrome ? (m_dwFlags | FLAG_ENVIRONMENTMAP) : (m_dwFlags & ~FLAG_ENVIRONMENTMAP)); } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::PostPropRead() // // PURPOSE: Update Properties // // ----------------------------------------------------------------------- // void Intelligence::PostPropRead(ObjectCreateStruct *pStruct) { if (!pStruct) return; // Make us activateable... pStruct->m_Flags |= FLAG_RAYHIT; // Make sure we don't have gravity set... pStruct->m_Flags &= ~FLAG_GRAVITY; pStruct->m_fDeactivationTime = 0.5f; m_dwUsrFlgs |= (USRFLG_GLOW | USRFLG_IGNORE_PROJECTILES); if (m_bPhotoOnly) { m_dwUsrFlgs |= USRFLG_GADGET_INTELLIGENCE; } else { m_dwUsrFlgs |= USRFLG_CAN_ACTIVATE; } m_damage.SetCanHeal(LTFALSE); m_damage.SetCanRepair(LTFALSE); m_damage.SetApplyDamagePhysics(LTFALSE); m_damage.SetMaxHitPoints(1.0f); m_damage.SetHitPoints(1.0f); m_damage.SetCanDamage(LTFALSE); // Use the default info id if necessary... if (!m_nInfoId) { INTEL* pIntel = g_pIntelMgr->GetIntel(m_nIntelId); if (pIntel && m_bShowPopup) { m_nInfoId = pIntel->nDefaultTextId; } } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::ObjectMessageFn // // PURPOSE: Handle object-to-object messages // // ----------------------------------------------------------------------- // uint32 Intelligence::ObjectMessageFn(HOBJECT hSender, uint32 messageID, HMESSAGEREAD hRead) { if (!g_pLTServer) return 0; switch(messageID) { case MID_TRIGGER: { const char* szMsg = (const char*)g_pLTServer->ReadFromMessageDWord(hRead); // ConParse does not destroy szMsg, so this is safe ConParse parse; parse.Init((char*)szMsg); while (g_pLTServer->Common()->Parse(&parse) == LT_OK) { if (parse.m_nArgs > 0 && parse.m_Args[0]) { if (_stricmp(parse.m_Args[0], s_szActivate) == 0) { if (!m_bPhotoOnly) { DoActivate(hSender); } } else if (_stricmp(parse.m_Args[0], s_szGadget) == 0) { if (m_bPhotoOnly) { HandleGadgetMsg(hSender, parse); } } else if (_stricmp(parse.m_Args[0], s_szRespawn) == 0) { SetNextUpdate( m_fRespawnDelay / g_IntelRespawnScale.GetFloat(1.0f)); } } } } break; default : break; } return Prop::ObjectMessageFn(hSender, messageID, hRead); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::HandleGadgetMsg // // PURPOSE: Handle the camera gadget // // ----------------------------------------------------------------------- // void Intelligence::HandleGadgetMsg(HOBJECT hSender, ConParse & parse) { DoActivate(hSender); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::DoActivate() // // PURPOSE: Handle Activate... // // ----------------------------------------------------------------------- // void Intelligence::DoActivate(HOBJECT hSender) { // BL 10/30/00 - fix multiple photographs of items in multiplayer { if ( g_pGameServerShell->GetGameType() != SINGLE ) { uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); if ( !(dwFlags & FLAG_VISIBLE) ) { return; } } } HOBJECT hPlayer = hSender; if (!hSender || !IsPlayer(hSender)) { // Find the player if the sender isn't one... ObjArray <HOBJECT, 1> objArray; g_pLTServer->FindNamedObjects(DEFAULT_PLAYERNAME, objArray); if (!objArray.NumObjects()) return; hPlayer = objArray.GetObject(0); } // Increment the player's intelligence count... CPlayerObj* pPlayer = (CPlayerObj*)g_pLTServer->HandleToObject(hPlayer); if (pPlayer) { if (g_pGameServerShell->GetGameType() == COOPERATIVE_ASSAULT && m_nPlayerTeamFilter) { if (pPlayer->GetTeamID() != m_nPlayerTeamFilter) return; uint8 nScore = (uint8)g_vtNetIntelScore.GetFloat(); pPlayer->AddToScore(nScore); HCLIENT hClient = pPlayer->GetClient(); uint32 nPlayerID = g_pLTServer->GetClientID(hClient); HMESSAGEWRITE hWrite = g_pLTServer->StartMessage (LTNULL, MID_TEAM_SCORED); g_pLTServer->WriteToMessageDWord (hWrite, nPlayerID); g_pLTServer->WriteToMessageByte (hWrite, (uint8)pPlayer->GetTeamID()); g_pLTServer->WriteToMessageByte (hWrite, nScore); g_pLTServer->EndMessage (hWrite); } CPlayerSummaryMgr* pPSMgr = pPlayer->GetPlayerSummaryMgr(); if (pPSMgr) { pPSMgr->IncIntelligenceCount(); } HCLIENT hClient = pPlayer->GetClient(); if (hClient) { HMESSAGEWRITE hMessage = g_pLTServer->StartMessage(hClient, MID_PLAYER_INFOCHANGE); g_pLTServer->WriteToMessageByte(hMessage, IC_INTEL_PICKUP_ID); g_pLTServer->WriteToMessageByte(hMessage, 0); g_pLTServer->WriteToMessageByte(hMessage, 0); g_pLTServer->WriteToMessageFloat(hMessage, 0.0f); g_pLTServer->EndMessage(hMessage); } // Show the pop-up associated with the intelligence item, if // applicable... INTEL* pIntel = g_pIntelMgr->GetIntel(m_nIntelId); if (pIntel && m_bShowPopup) { char buf[255]; sprintf(buf, "msg %s (popup %d", DEFAULT_PLAYERNAME, m_nInfoId); // Add the scale fx... for (int i=0; i < pIntel->nNumScaleFXNames; i++) { if (pIntel->szScaleFXNames[i]) { strcat(buf, " "); strcat(buf, pIntel->szScaleFXNames[i]); } } strcat(buf, ")"); if (g_pCmdMgr->IsValidCmd(buf)) { g_pCmdMgr->Process(buf); } } // If we have a command, process it... if (m_hstrPickedUpCmd) { char* pCmd = g_pLTServer->GetStringData(m_hstrPickedUpCmd); if (pCmd && g_pCmdMgr->IsValidCmd(pCmd)) { g_pCmdMgr->Process(pCmd); } } if (g_pGameServerShell->GetGameType() == SINGLE) { g_pLTServer->RemoveObject(m_hObject); } else { uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); dwFlags &= (~FLAG_VISIBLE & ~FLAG_RAYHIT); g_pLTServer->SetObjectFlags(m_hObject, dwFlags); // Play pickup sound... LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); g_pServerSoundMgr->PlaySoundFromPos(vPos, INTEL_PICKUP_SOUND, 600.0f, SOUNDPRIORITY_MISC_HIGH); } } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Save // // PURPOSE: Save the object // // ----------------------------------------------------------------------- // void Intelligence::Save(HMESSAGEWRITE hWrite) { if (!hWrite) return; g_pLTServer->WriteToMessageByte(hWrite, m_bPhotoOnly); g_pLTServer->WriteToMessageByte(hWrite, m_bShowPopup); g_pLTServer->WriteToMessageHString(hWrite, m_hstrPickedUpCmd); g_pLTServer->WriteToMessageDWord(hWrite, m_nInfoId); g_pLTServer->WriteToMessageDWord(hWrite, m_nIntelId); g_pLTServer->WriteToMessageByte(hWrite, m_bStartHidden); g_pLTServer->WriteToMessageByte(hWrite, m_bFirstUpdate); g_pLTServer->WriteToMessageByte(hWrite, m_bSkipUpdate); g_pLTServer->WriteToMessageFloat(hWrite, m_fRespawnDelay); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Load // // PURPOSE: Load the object // // ----------------------------------------------------------------------- // void Intelligence::Load(HMESSAGEREAD hRead) { if (!hRead) return; m_bPhotoOnly = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_bShowPopup = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_hstrPickedUpCmd = g_pLTServer->ReadFromMessageHString(hRead); m_nInfoId = g_pLTServer->ReadFromMessageDWord(hRead); m_nIntelId = g_pLTServer->ReadFromMessageDWord(hRead); m_bStartHidden = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_bFirstUpdate = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_bSkipUpdate = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_fRespawnDelay = g_pLTServer->ReadFromMessageFloat(hRead); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Update() // // PURPOSE: Update // // ----------------------------------------------------------------------- // LTBOOL Intelligence::Update() { if (m_bFirstUpdate) { m_bFirstUpdate = LTFALSE; if (m_bStartHidden) { SendTriggerMsgToObject(this, m_hObject, LTFALSE, "Hidden 1"); return LTTRUE; } } // If we aren't visible it must be time to respawn... uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); if (!m_bSkipUpdate && !(dwFlags & FLAG_VISIBLE)) { uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); dwFlags |= (FLAG_VISIBLE | FLAG_RAYHIT); g_pLTServer->SetObjectFlags(m_hObject, dwFlags); // Let the world know what happened... LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); g_pServerSoundMgr->PlaySoundFromPos(vPos, INTEL_RESPAWN_SOUND, 600.0f, SOUNDPRIORITY_MISC_HIGH); } m_bSkipUpdate = LTFALSE; return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::InitialUpdate() // // PURPOSE: First update // // ----------------------------------------------------------------------- // void Intelligence::InitialUpdate() { if (!g_IntelRespawnScale.IsInitted()) { g_IntelRespawnScale.Init(GetServerDE(), "IntelRespawnScale", LTNULL, 1.0f); } if (m_bStartHidden) { SetNextUpdate(0.001f); } m_bSkipUpdate = m_bMoveToFloor; CacheFiles(); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::CacheFiles // // PURPOSE: Cache whatever resources this object uses // // ----------------------------------------------------------------------- // void Intelligence::CacheFiles() { g_pLTServer->CacheFile(FT_SOUND, INTEL_RESPAWN_SOUND); g_pLTServer->CacheFile(FT_SOUND, INTEL_PICKUP_SOUND); }
24.215429
105
0.592871
haekb
60b2316d6236b4b14589dff7691e1415e36d80ec
141
cpp
C++
test2.cpp
abc123me/mandelbrot_c
8bd3f61ce1941310f48fe9f0f2ca68e15f8b2a83
[ "MIT" ]
null
null
null
test2.cpp
abc123me/mandelbrot_c
8bd3f61ce1941310f48fe9f0f2ca68e15f8b2a83
[ "MIT" ]
null
null
null
test2.cpp
abc123me/mandelbrot_c
8bd3f61ce1941310f48fe9f0f2ca68e15f8b2a83
[ "MIT" ]
null
null
null
#include "stdio.h" #include "util.h" int main(int argc, char** argv) { cmplx_f c = atocmplx_f(argv[1]); c.print(); puts(""); return 0; }
15.666667
33
0.617021
abc123me
60b565b0e2126fc08988fc395e67a41e12ba07bc
1,142
hpp
C++
include/Filas.hpp
PedroAcA/so
938ceb7bd6ee4160ec0799d6415ca133eb53e02a
[ "MIT" ]
null
null
null
include/Filas.hpp
PedroAcA/so
938ceb7bd6ee4160ec0799d6415ca133eb53e02a
[ "MIT" ]
null
null
null
include/Filas.hpp
PedroAcA/so
938ceb7bd6ee4160ec0799d6415ca133eb53e02a
[ "MIT" ]
null
null
null
#ifndef MODULO_FILAS_H//include de guarda #define MODULO_FILAS_H #include <deque> #include <vector> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Processos/Processo.hpp" #include "../include/LeitorEntradas.hpp" class Filas{ public: /* Esta classe implementa as filas de prioridade simples. São, na pratica quatro filas de inteiros. Ou seja, nestas filas, apenas os PID's dos processos serão guardados. */ std::deque<int> Fila0; //fila prioridade 0 std::deque<int> Fila1; //fila prioridade 1 std::deque<int> Fila2; //fila prioridade 2 std::deque<int> Fila3; //fila prioridade 3 Filas(); void insereProcesso(Processo );//Metodo que verifica a prioridade do processo e o coloca na fila adequada bool existe_processo_para_executar(); bool existe_processo_para_executar_fila0(); bool existe_processo_para_executar_fila1(); bool existe_processo_para_executar_fila2(); bool existe_processo_para_executar_fila3(); int retira_processo_fila0(); int retira_processo_fila1(); int retira_processo_fila2(); int retira_processo_fila3(); void destroiFilas(); void imprimeEstado(); }; #endif
21.961538
106
0.759194
PedroAcA
60b751ac3f280f755897d8c9f1585e27ca241b83
2,912
cpp
C++
src/tests/functional/inference_engine/transformations/resolve_gen_names_collisions.cpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
null
null
null
src/tests/functional/inference_engine/transformations/resolve_gen_names_collisions.cpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
17
2021-11-25T10:22:17.000Z
2022-03-28T13:19:31.000Z
src/tests/functional/inference_engine/transformations/resolve_gen_names_collisions.cpp
pfinashx/openvino
1d417e888b508415510fb0a92e4a9264cf8bdef7
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "transformations/resolve_gen_names_collisions.hpp" #include "gtest/gtest.h" #include "openvino/opsets/opset8.hpp" #include "openvino/pass/manager.hpp" TEST(ResolveGeneratedNameCollisionsTest, FixGeneratedNames) { auto arg0 = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape{1, 3, 3, 3}); const auto gen_friendly_name = arg0->get_friendly_name(); std::string name = "Parameter_"; EXPECT_NE(std::string::npos, gen_friendly_name.find("Parameter_")); unsigned long long index = std::stoull(gen_friendly_name.substr(name.length())); name += std::to_string(++index); arg0->set_friendly_name(name); auto arg1 = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape{1, 2, 3, 3}); auto concat = std::make_shared<ov::opset8::Concat>(ov::NodeVector{arg0, arg1}, 1); auto result1 = std::make_shared<ov::opset8::Result>(concat); auto model = std::make_shared<ov::Model>(ov::ResultVector{result1}, ov::ParameterVector{arg0, arg1}); EXPECT_EQ(name, arg0->get_friendly_name()); EXPECT_EQ(arg1->get_friendly_name(), arg0->get_friendly_name()); EXPECT_NE(arg1->get_friendly_name(), arg0->get_friendly_name() + "_2"); ov::pass::Manager pass_manager; pass_manager.register_pass<ov::pass::ResolveGeneratedNameCollisions>(); pass_manager.run_passes(model); EXPECT_EQ(name, arg0->get_friendly_name()); EXPECT_NE(arg1->get_friendly_name(), arg0->get_friendly_name()); EXPECT_EQ(arg1->get_friendly_name(), arg0->get_friendly_name() + "_2"); } TEST(ResolveGeneratedNameCollisionsTest, DoNotFixFriendlyNames) { auto arg0 = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape{1, 3, 3, 3}); const auto gen_friendly_name = arg0->get_friendly_name(); arg0->set_friendly_name(gen_friendly_name); auto arg1 = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape{1, 2, 3, 3}); arg1->set_friendly_name(gen_friendly_name); auto concat = std::make_shared<ov::opset8::Concat>(ov::NodeVector{arg0, arg1}, 1); auto result1 = std::make_shared<ov::opset8::Result>(concat); auto model = std::make_shared<ov::Model>(ov::ResultVector{result1}, ov::ParameterVector{arg0, arg1}); EXPECT_EQ(gen_friendly_name, arg0->get_friendly_name()); EXPECT_EQ(arg1->get_friendly_name(), arg0->get_friendly_name()); EXPECT_NE(arg1->get_friendly_name(), arg0->get_friendly_name() + "_2"); ov::pass::Manager pass_manager; pass_manager.register_pass<ov::pass::ResolveGeneratedNameCollisions>(); pass_manager.run_passes(model); EXPECT_EQ(gen_friendly_name, arg0->get_friendly_name()); EXPECT_EQ(arg1->get_friendly_name(), arg0->get_friendly_name()); EXPECT_NE(arg1->get_friendly_name(), arg0->get_friendly_name() + "_2"); }
44.121212
105
0.721841
pfinashx
60b7d809be74bbc4f5480a2294bf44b71745a167
6,201
cc
C++
cryptohome/cert/cert_provision_client.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
null
null
null
cryptohome/cert/cert_provision_client.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
null
null
null
cryptohome/cert/cert_provision_client.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Client for cert_provision library. #include <base/bind.h> #include <base/command_line.h> #include <base/files/file_util.h> #include <base/strings/string_number_conversions.h> #include <brillo/syslog_logging.h> #include "cryptohome/cert_provision.h" void ProgressCallback(cert_provision::Status status, int progress, const std::string& message) { LOG(INFO) << "ProgressCallback: " << static_cast<int>(status) << ", " << progress << "%: " << message; } void PrintHelp() { printf("Usage: cert_provision_client <command> [--v=<log_verbosity>]\n"); printf("Commands:\n"); printf(" Provision a certificate:\n"); printf(" --provision --label=<label> --pca=<type> --profile=<profile>\n"); printf(" where type: default, test\n"); printf(" profile: cast, jetstream\n"); printf(" Force enroll:\n"); printf(" --enroll --pca=<type>\n"); printf(" Print the provisioned certificate:\n"); printf(" --get --label=<label> --include_chain\n"); printf(" [--out=<file_out>]\n"); printf(" Sign using the provisioned certificate:\n"); printf(" --sign --label=<label> --in=<file_in> [--out=<file_out>]\n"); printf(" --mechanism=<mechanism>\n"); printf(" where mechanism: sha1_rsa, sha256_rsa, sha256_rsa_pss\n"); } int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); brillo::InitLog(brillo::kLogToSyslog | brillo::kLogToStderr); if (cl->HasSwitch("h") || cl->HasSwitch("help")) { PrintHelp(); return 2; } cert_provision::Status sts; if (cl->HasSwitch("provision")) { std::string cert_label = cl->GetSwitchValueASCII("label"); if (cert_label.empty()) { PrintHelp(); return 2; } cert_provision::PCAType pca_type; std::string pca = cl->GetSwitchValueASCII("pca"); if (pca == "default") { pca_type = cert_provision::PCAType::kDefaultPCA; } else if (pca == "test") { pca_type = cert_provision::PCAType::kTestPCA; } else { PrintHelp(); return 2; } cert_provision::CertificateProfile cert_profile; std::string profile = cl->GetSwitchValueASCII("profile"); if (profile == "cast") { cert_profile = cert_provision::CertificateProfile::CAST_CERTIFICATE; } else if (profile == "jetstream") { cert_profile = cert_provision::CertificateProfile::JETSTREAM_CERTIFICATE; } else { PrintHelp(); return 2; } sts = cert_provision::ProvisionCertificate(pca_type, std::string(), cert_label, cert_profile, base::Bind(&ProgressCallback)); if (sts != cert_provision::Status::Success) { LOG(ERROR) << "ProvisionCertificate returned " << static_cast<int>(sts); return 3; } VLOG(1) << "ProvisionCertificate returned " << static_cast<int>(sts); } else if (cl->HasSwitch("enroll")) { cert_provision::PCAType pca_type; std::string pca = cl->GetSwitchValueASCII("pca"); if (pca == "default") { pca_type = cert_provision::PCAType::kDefaultPCA; } else if (pca == "test") { pca_type = cert_provision::PCAType::kTestPCA; } else { PrintHelp(); return 2; } sts = cert_provision::ForceEnroll(pca_type, std::string(), base::Bind(&ProgressCallback)); if (sts != cert_provision::Status::Success) { LOG(ERROR) << "ForceEnroll returned " << static_cast<int>(sts); return 3; } VLOG(1) << "ForceEnroll returned " << static_cast<int>(sts); } else if (cl->HasSwitch("get")) { std::string cert_label = cl->GetSwitchValueASCII("label"); if (cert_label.empty()) { PrintHelp(); return 2; } std::string certificate; sts = cert_provision::GetCertificate( cert_label, cl->HasSwitch("include_chain"), &certificate); if (sts != cert_provision::Status::Success) { LOG(ERROR) << "GetCertificate returned " << static_cast<int>(sts); return 3; } VLOG(1) << "GetCertificate returned " << static_cast<int>(sts); base::FilePath out(cl->GetSwitchValueASCII("out")); if (!out.empty()) { if (base::WriteFile(out, certificate.data(), certificate.size()) < 0) { LOG(ERROR) << "Failed to write output file: " << out.value(); return 1; } } else { puts(certificate.c_str()); } } else if (cl->HasSwitch("sign")) { std::string cert_label = cl->GetSwitchValueASCII("label"); if (cert_label.empty()) { PrintHelp(); return 2; } base::FilePath in(cl->GetSwitchValueASCII("in")); if (in.empty()) { PrintHelp(); return 2; } cert_provision::SignMechanism sign_mechanism; std::string mechanism = cl->GetSwitchValueASCII("mechanism"); if (mechanism == "sha1_rsa") { sign_mechanism = cert_provision::SHA1_RSA_PKCS; } else if (mechanism == "sha256_rsa") { sign_mechanism = cert_provision::SHA256_RSA_PKCS; } else if (mechanism == "sha256_rsa_pss") { sign_mechanism = cert_provision::SHA256_RSA_PSS; } else { PrintHelp(); return 2; } std::string data; if (!base::ReadFileToString(in, &data)) { LOG(ERROR) << "Failed to read input file: " << in.value(); return 1; } std::string sig; sts = cert_provision::Sign(cert_label, sign_mechanism, data, &sig); if (sts != cert_provision::Status::Success) { LOG(ERROR) << "Sign returned " << static_cast<int>(sts); return 3; } VLOG(1) << "Sign returned " << static_cast<int>(sts); base::FilePath out(cl->GetSwitchValueASCII("out")); if (!out.empty()) { if (base::WriteFile(out, sig.data(), sig.size()) < 0) { LOG(ERROR) << "Failed to write output file: " << out.value(); return 1; } } else { puts(base::HexEncode(sig.data(), sig.size()).c_str()); } } return 0; }
34.071429
79
0.607805
strassek
60b9ec2465e416545a7422c557240225431a473f
4,245
cpp
C++
examples/win32/Win32.cpp
yoyonel/sflm2-custom
1ebeabe7cfe6605590b341f7b415b24bed1f50d1
[ "Zlib" ]
null
null
null
examples/win32/Win32.cpp
yoyonel/sflm2-custom
1ebeabe7cfe6605590b341f7b415b24bed1f50d1
[ "Zlib" ]
null
null
null
examples/win32/Win32.cpp
yoyonel/sflm2-custom
1ebeabe7cfe6605590b341f7b415b24bed1f50d1
[ "Zlib" ]
null
null
null
//////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Graphics.hpp> #include <windows.h> #include <cmath> HWND button; //////////////////////////////////////////////////////////// /// Function called whenever one of our windows receives a message /// //////////////////////////////////////////////////////////// LRESULT CALLBACK OnEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { // Quit when we close the main window case WM_CLOSE : { PostQuitMessage(0); return 0; } // Quit when we click the "quit" button case WM_COMMAND : { if (reinterpret_cast<HWND>(lParam) == button) { PostQuitMessage(0); return 0; } } } return DefWindowProc(handle, message, wParam, lParam); } //////////////////////////////////////////////////////////// /// Entry point of application /// /// \param Instance : Instance of the application /// /// \return Error code /// //////////////////////////////////////////////////////////// INT WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, INT) { // Define a class for our main window WNDCLASS windowClass; windowClass.style = 0; windowClass.lpfnWndProc = &OnEvent; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = instance; windowClass.hIcon = NULL; windowClass.hCursor = 0; windowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND); windowClass.lpszMenuName = NULL; windowClass.lpszClassName = TEXT("SFML App"); RegisterClass(&windowClass); // Let's create the main window HWND window = CreateWindow(TEXT("SFML App"), TEXT("SFML Win32"), WS_SYSMENU | WS_VISIBLE, 200, 200, 660, 520, NULL, NULL, instance, NULL); // Add a button for exiting button = CreateWindow(TEXT("BUTTON"), TEXT("Quit"), WS_CHILD | WS_VISIBLE, 560, 440, 80, 40, window, NULL, instance, NULL); // Let's create two SFML views HWND view1 = CreateWindow(TEXT("STATIC"), NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 20, 20, 300, 400, window, NULL, instance, NULL); HWND view2 = CreateWindow(TEXT("STATIC"), NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 340, 20, 300, 400, window, NULL, instance, NULL); sf::RenderWindow SFMLView1(view1); sf::RenderWindow SFMLView2(view2); // Load some images to display sf::Image image1, image2; if (!image1.LoadFromFile("resources/image1.jpg") || !image2.LoadFromFile("resources/image2.jpg")) return EXIT_FAILURE; sf::Sprite sprite1(image1); sf::Sprite sprite2(image2); sprite1.SetOrigin(sprite1.GetSize() / 2.f); sprite1.SetPosition(sprite1.GetSize() / 2.f); // Create a clock for measuring elapsed time sf::Clock clock; // Loop until a WM_QUIT message is received MSG message; message.message = static_cast<UINT>(~WM_QUIT); while (message.message != WM_QUIT) { if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) { // If a message was waiting in the message queue, process it TranslateMessage(&message); DispatchMessage(&message); } else { // Clear views SFMLView1.Clear(); SFMLView2.Clear(); // Draw sprite 1 on view 1 sprite1.SetRotation(clock.GetElapsedTime() * 100); SFMLView1.Draw(sprite1); // Draw sprite 2 on view 2 sprite2.SetX(cos(clock.GetElapsedTime()) * 100); SFMLView2.Draw(sprite2); // Display each view on screen SFMLView1.Display(); SFMLView2.Display(); } } // Destroy the main window (all its child controls will be destroyed) DestroyWindow(window); // Don't forget to unregister the window class UnregisterClass(TEXT("SFML App"), instance); return EXIT_SUCCESS; }
32.906977
143
0.54629
yoyonel
60bb1ee20f89d138407a84ba5d07d197b2ca436b
166,332
hpp
C++
external/boost_1_60_0/qsboost/phoenix/core/detail/preprocessed/call_50.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/phoenix/core/detail/preprocessed/call_50.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/phoenix/core/detail/preprocessed/call_50.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
/*============================================================================== Copyright (c) 2005-2010 Joel de Guzman Copyright (c) 2010 Thomas Heller Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ namespace detail { template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 1> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename qsboost::result_of< Fun(A0, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 2> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename qsboost::result_of< Fun(A0 , A1, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 3> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename qsboost::result_of< Fun(A0 , A1 , A2, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 4> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 5> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 6> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 7> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 8> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 9> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 10> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 11> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 12> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 13> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 14> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 15> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 16> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 17> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 18> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 19> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 20> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 21> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 22> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 23> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 24> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 25> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 26> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 27> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 28> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 29> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 30> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 31> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 32> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 33> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 34> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 35> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 36> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 37> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 38> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 39> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 40> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 41> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 42> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 43> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 44> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 45> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 46> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 47> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 48> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename proto::result_of::child_c<Expr, 47>::type A47; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46 , A47, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , proto::child_c< 47>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 49> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename proto::result_of::child_c<Expr, 47>::type A47; typedef typename proto::result_of::child_c<Expr, 48>::type A48; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46 , A47 , A48, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , proto::child_c< 47>(e) , proto::child_c< 48>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 50> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename proto::result_of::child_c<Expr, 47>::type A47; typedef typename proto::result_of::child_c<Expr, 48>::type A48; typedef typename proto::result_of::child_c<Expr, 49>::type A49; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46 , A47 , A48 , A49, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , proto::child_c< 47>(e) , proto::child_c< 48>(e) , proto::child_c< 49>(e) , qsboost::phoenix::context(s, d) ); } }; }
97.156542
3,191
0.621859
wouterboomsma
60bb6951d7ba7390222e945f807c0b5551e529c6
1,039
cpp
C++
Ass7/Q8.cpp
nitishgarg2002/DSA-assignments
34ec3e77e6bb00bc2ab86d2960a18d9e53300c06
[ "MIT" ]
null
null
null
Ass7/Q8.cpp
nitishgarg2002/DSA-assignments
34ec3e77e6bb00bc2ab86d2960a18d9e53300c06
[ "MIT" ]
null
null
null
Ass7/Q8.cpp
nitishgarg2002/DSA-assignments
34ec3e77e6bb00bc2ab86d2960a18d9e53300c06
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *left, *right; }; bool iterativeSearch(struct Node* root, int key) { while (root != NULL) { if (key > root->data) root = root->right; else if (key < root->data) root = root->left; else return true; } return false; } struct Node* newNode(int item) { struct Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } struct Node* insert(struct Node* Node, int data) { if (Node == NULL) return newNode(data); if (data < Node->data) Node->left = insert(Node->left, data); else if (data > Node->data) Node->right = insert(Node->right, data); return Node; } int main() { struct Node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout<<"Searching for 15: in 30 20 40 70 60 80 "<<endl; if (iterativeSearch(root, 15)) cout << "Found"; else cout << "Not Found"; return 0; }
17.610169
58
0.628489
nitishgarg2002
60bd34d4741ea33784463ca8c037f839c8bef2c3
1,574
cpp
C++
Train/El_Sageer/El_Sageer_Pupil/08 - 14 - [SP]/08 - 10 - [SP] Brute Force/10 - [SP] Brute Force/extra/4.CF [467B].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
1
2019-12-19T06:51:20.000Z
2019-12-19T06:51:20.000Z
Train/El_Sageer/El_Sageer_Pupil/08 - 14 - [SP]/08 - 10 - [SP] Brute Force/10 - [SP] Brute Force/extra/4.CF [467B].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
Train/El_Sageer/El_Sageer_Pupil/08 - 14 - [SP]/08 - 10 - [SP] Brute Force/10 - [SP] Brute Force/extra/4.CF [467B].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // input handle #define iln() scanf("\n") #define in(n) scanf("%d",&n) #define ins(n) scanf("%s",n) #define inc(n) scanf("%c",&n) #define inf(n) scanf("%lf",&n) #define inl(n) scanf("%lld",&n) #define ot(x) printf("%d", x) #define sp() printf(" ") #define ots(x) printf("%s", x) #define otc(x) printf("%c", x) #define ln() printf("\n") #define otl(x) printf("%lld", x) #define otf(x) printf("%.2lf", x) // helpers defines #define all(v) v.begin(), v.end() #define sz(v) ((int)((v).size())) #define ssz(s) ((int)strlen(s)) #define pb push_back #define mem(a,b) memset(a,b,sizeof(a)) //helpers void file() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); // freopen("ot.txt", "w", stdout); #else // freopen("jumping.in", "r", stdin); // HERE #endif } // constants #define EPS 1e-9 #define PI acos(-1.0) // important constant; alternative #define PI (2.0 * acos(0.0)) const int MN = 1e9 + 1e2; const int MW = 1e3 + 5; typedef long long int lli; const int OO = 1e9 + 5; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ii> vii; typedef pair<lli, string> lls; #define isOn(S, j) (S & (1 << j)) #define setBit(S, j) (S |= (1 << j)) #define clearBit(S, j) (S &= ~(1 << j)) int main() { file(); //TODO int n, m, k, p[1002] { 0 }, ans = 0; in(n), in(m), in(k); for (int i = 0; i <= m and in(p[i]); ++i) ; for (int i = 0, df = 0; i < m; ans += (df <= k), df = 0, ++i) for (int j = 0; j < 21 and df <= k; ++j) if (isOn(p[m],j) != isOn(p[i], j)) df++; ot(ans); return 0; }
25.387097
85
0.576239
mohamedGamalAbuGalala
60bd97fce1793240c01a2c27f987df91e406831a
776
hpp
C++
Libraries/Gameplay/DefaultGame.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Libraries/Gameplay/DefaultGame.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Gameplay/DefaultGame.hpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #pragma once namespace Zero { /// Create the starting space and load the starting level into that space class DefaultGameSetup : public Component { public: ZilchDeclareType(DefaultGameSetup, TypeCopyMode::ReferenceType); DefaultGameSetup(); // Component Interface void Initialize(CogInitializer& initializer) override; void Serialize(Serializer& stream) override; void SetDefaults() override; // Space to create for the game. ResourceProperty(Archetype, StartingSpace); // Level to load into the game. ResourceProperty(Level, StartingLevel); void OnSetup(GameEvent* event); // If set to true StartingLevel will be overridden by the currently edited // level bool mLoadEditingLevel; }; } // namespace Zero
22.823529
76
0.753866
RyanTylerRae
60bdb76c845c09b3386e2c3d06b65c916577ae7b
8,110
cpp
C++
Core/GDCore/Serialization/SerializerElement.cpp
sutao80216/GDevelop
79461bf01cc0c626e2f094d3fca940d643f93d76
[ "MIT" ]
1
2019-08-24T03:18:42.000Z
2019-08-24T03:18:42.000Z
Core/GDCore/Serialization/SerializerElement.cpp
sutao80216/GDevelop
79461bf01cc0c626e2f094d3fca940d643f93d76
[ "MIT" ]
9
2020-04-04T19:26:47.000Z
2022-03-25T18:41:20.000Z
Core/GDCore/Serialization/SerializerElement.cpp
sutao80216/GDevelop
79461bf01cc0c626e2f094d3fca940d643f93d76
[ "MIT" ]
2
2020-03-02T05:20:41.000Z
2021-05-10T03:59:05.000Z
#include "GDCore/Serialization/SerializerElement.h" #include <iostream> namespace gd { SerializerElement SerializerElement::nullElement; SerializerElement::SerializerElement() : valueUndefined(true), isArray(false) {} SerializerElement::SerializerElement(const SerializerValue& value) : valueUndefined(false), elementValue(value), isArray(false) {} SerializerElement::~SerializerElement() {} const SerializerValue& SerializerElement::GetValue() const { if (valueUndefined && attributes.find("value") != attributes.end()) return attributes.find("value")->second; return elementValue; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, bool value) { attributes[name].SetBool(value); return *this; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, const gd::String& value) { attributes[name].SetString(value); return *this; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, int value) { attributes[name].SetInt(value); return *this; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, double value) { attributes[name].SetDouble(value); return *this; } bool SerializerElement::GetBoolAttribute(const gd::String& name, bool defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) { return attributes.find(name)->second.GetBool(); } else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) { return attributes.find(deprecatedName)->second.GetBool(); } else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) { return child.GetValue().GetBool(); } } } std::cout << "Bool attribute \"" << name << "\" not found, returning " << defaultValue; return defaultValue; } gd::String SerializerElement::GetStringAttribute( const gd::String& name, gd::String defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) return attributes.find(name)->second.GetString(); else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) return attributes.find(deprecatedName)->second.GetString(); else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) return child.GetValue().GetString(); } } return defaultValue; } int SerializerElement::GetIntAttribute(const gd::String& name, int defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) return attributes.find(name)->second.GetInt(); else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) return attributes.find(deprecatedName)->second.GetInt(); else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) return child.GetValue().GetInt(); } } return defaultValue; } double SerializerElement::GetDoubleAttribute(const gd::String& name, double defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) return attributes.find(name)->second.GetDouble(); else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) return attributes.find(deprecatedName)->second.GetDouble(); else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) return child.GetValue().GetDouble(); } } return defaultValue; } bool SerializerElement::HasAttribute(const gd::String& name) const { return attributes.find(name) != attributes.end(); } SerializerElement& SerializerElement::AddChild(gd::String name) { if (!arrayOf.empty()) { if (name != arrayOf) { std::cout << "WARNING: Adding a child, to a SerializerElement which is " "considered as an array, with a name (" << name << ") which is not the same as the array elements (" << arrayOf << "). Child was renamed." << std::endl; name = arrayOf; } } std::shared_ptr<SerializerElement> newElement(new SerializerElement); children.push_back(std::make_pair(name, newElement)); return *newElement; } SerializerElement& SerializerElement::GetChild(std::size_t index) const { if (arrayOf.empty()) { std::cout << "ERROR: Getting a child from its index whereas the parent is " "not considered as an array." << std::endl; return nullElement; } std::size_t currentIndex = 0; for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == arrayOf || children[i].first.empty() || (!deprecatedArrayOf.empty() && children[i].first == deprecatedArrayOf)) { if (index == currentIndex) return *children[i].second; else currentIndex++; } } std::cout << "ERROR: Request out of bound child at index " << index << std::endl; return nullElement; } SerializerElement& SerializerElement::GetChild( gd::String name, std::size_t index, gd::String deprecatedName) const { if (!arrayOf.empty()) { if (name != arrayOf) { std::cout << "WARNING: Getting a child, from a SerializerElement which " "is considered as an array, with a name (" << name << ") which is not the same as the array elements (" << arrayOf << ")." << std::endl; name = arrayOf; } } std::size_t currentIndex = 0; for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == name || (!arrayOf.empty() && children[i].first.empty()) || (!deprecatedName.empty() && children[i].first == deprecatedName)) { if (index == currentIndex) return *children[i].second; else currentIndex++; } } std::cout << "Child " << name << " not found in SerializerElement::GetChild" << std::endl; return nullElement; } std::size_t SerializerElement::GetChildrenCount( gd::String name, gd::String deprecatedName) const { if (name.empty()) { if (arrayOf.empty()) { std::cout << "ERROR: Getting children count without specifying name, from a " "SerializerElement which is NOT considered as an array." << std::endl; return 0; } name = arrayOf; deprecatedName = deprecatedArrayOf; } std::size_t currentIndex = 0; for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == name || (!arrayOf.empty() && children[i].first.empty()) || (!deprecatedName.empty() && children[i].first == deprecatedName)) currentIndex++; } return currentIndex; } bool SerializerElement::HasChild(const gd::String& name, gd::String deprecatedName) const { for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == name || (!deprecatedName.empty() && children[i].first == deprecatedName)) return true; } return false; } } // namespace gd
33.102041
80
0.6164
sutao80216
60bff93a2d1c86ee195cce173b5eb541bb0eff88
7,087
cpp
C++
test/thread/source/TestThreadRWSemaLock.cpp
tlzyh/EAThread
b5e246fa86d8de5ddbcdb098df0a75f5e8839f5a
[ "BSD-3-Clause" ]
255
2019-06-11T07:05:51.000Z
2022-03-08T20:35:12.000Z
test/thread/source/TestThreadRWSemaLock.cpp
tlzyh/EAThread
b5e246fa86d8de5ddbcdb098df0a75f5e8839f5a
[ "BSD-3-Clause" ]
4
2019-08-10T21:35:17.000Z
2021-11-24T10:42:24.000Z
test/thread/source/TestThreadRWSemaLock.cpp
tlzyh/EAThread
b5e246fa86d8de5ddbcdb098df0a75f5e8839f5a
[ "BSD-3-Clause" ]
75
2019-07-08T00:16:33.000Z
2022-02-25T03:41:13.000Z
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Electronic Arts Inc. All rights reserved. /////////////////////////////////////////////////////////////////////////////// #include "TestThread.h" #include <EATest/EATest.h> #include <eathread/eathread_thread.h> #include <eathread/eathread_rwsemalock.h> #include <stdlib.h> const int kThreadCount = EATHREAD_MAX_CONCURRENT_THREAD_COUNT; /////////////////////////////////////////////////////////////////////////////// // RWSTestType // enum RWSTestType { kRWSTestTypeStandard, kRWSTestTypeAllWriters, kRWSTestTypeAllReaders, kRWSTestTypeMostlyWriters, kRWSTestTypeMostlyReaders, kRWSTestTypeCount }; /////////////////////////////////////////////////////////////////////////////// // RWSemaWorkData // struct RWSemaWorkData { volatile bool mbShouldQuit; EA::Thread::RWSemaLock mRWSemaLock; volatile int mnWriterCount; EA::Thread::AtomicInt32 mnErrorCount; EA::Thread::AtomicInt32 mnCurrentTestType; RWSemaWorkData() : mbShouldQuit(false) , mRWSemaLock() , mnWriterCount(0) , mnErrorCount(0) , mnCurrentTestType(kRWSTestTypeStandard) {} private: RWSemaWorkData(const RWSemaWorkData& rhs); RWSemaWorkData& operator=(const RWSemaWorkData& rhs); }; /////////////////////////////////////////////////////////////////////////////// // RWSThreadFunction // static intptr_t RWSThreadFunction(void* pvWorkData) { using namespace EA::Thread; RWSemaWorkData* const pWorkData = (RWSemaWorkData*)pvWorkData; ThreadId threadId = GetThreadId(); EA::UnitTest::ReportVerbosity(1, "RWSemaLock test function created: %s\n", EAThreadThreadIdToString(threadId)); int nErrorCount = 0; while(!pWorkData->mbShouldQuit) { int nWriteLockChance = 0; const RWSTestType testType = (RWSTestType)pWorkData->mnCurrentTestType.GetValue(); switch (testType) { default: case kRWSTestTypeStandard: nWriteLockChance = 20; break; case kRWSTestTypeAllWriters: nWriteLockChance = 1000; break; case kRWSTestTypeAllReaders: nWriteLockChance = 0; break; case kRWSTestTypeMostlyWriters: nWriteLockChance = 700; break; case kRWSTestTypeMostlyReaders: nWriteLockChance = 5; break; } const bool bShouldWrite = ((rand() % 1000) < nWriteLockChance); if(bShouldWrite) { AutoSemaWriteLock _(pWorkData->mRWSemaLock); pWorkData->mnWriterCount++; EA::UnitTest::ThreadSleepRandom(2, 10); pWorkData->mnWriterCount--; } else { AutoSemaReadLock _(pWorkData->mRWSemaLock); EATEST_VERIFY_MSG(pWorkData->mnWriterCount == 0, "ReadLock is held, there should be no active WriteLocks."); } } pWorkData->mnErrorCount.SetValue(nErrorCount); return nErrorCount; } // NOTE(rparolin): // This exists to introduce test-only functionality for the RWSemaLock. We can add these functions here because we // guarantee they will not be called in a concurrent context and they simplify validation of assumption of the lock. struct TestRWSemaLock : public EA::Thread::RWSemaLock { TestRWSemaLock() = default; TestRWSemaLock(const TestRWSemaLock&) = delete; TestRWSemaLock(TestRWSemaLock&&) = delete; TestRWSemaLock& operator=(const TestRWSemaLock&) = delete; TestRWSemaLock& operator=(TestRWSemaLock&&) = delete; bool IsReadLocked() { Status status; status.data = mStatus.GetValue(); return status.readers > 0; } bool IsWriteLocked() { Status status; status.data = mStatus.GetValue(); return status.writers > 0; } }; int TestThreadRWSemaLock() { using namespace EA::Thread; int nErrorCount = 0; { // RWSemaLock -- Basic single-threaded test. TestRWSemaLock rwSemaLock; // There are no construction parameters. EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); rwSemaLock.ReadTryLock(); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.WriteTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); rwSemaLock.ReadLock(); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); rwSemaLock.ReadUnlock(); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); rwSemaLock.ReadUnlock(); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); rwSemaLock.WriteTryLock(); EATEST_VERIFY_MSG(rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.ReadTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.WriteTryLock(), "RWSemaLock failure"); } { // AutoRWSemaLock -- Basic single-threaded test. TestRWSemaLock rwSemaLock; // There are no construction parameters. { //Special scope just for the AutoRWSemaLock AutoSemaReadLock autoRWSemaLock1(rwSemaLock); AutoSemaReadLock autoRWSemaLock2(rwSemaLock); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.WriteTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); } EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); { //Special scope just for the AutoRWSemaLock AutoSemaWriteLock autoRWSemaLock(rwSemaLock); EATEST_VERIFY_MSG(rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.ReadTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); } EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); } #if EA_THREADS_AVAILABLE { // Multithreaded test RWSemaWorkData workData; Thread thread[kThreadCount]; ThreadId threadId[kThreadCount]; Thread::Status status; for(int i(0); i < kThreadCount; i++) threadId[i] = thread[i].Begin(RWSThreadFunction, &workData); for(int e = 0; e < kRWSTestTypeCount; e++) { workData.mnCurrentTestType.SetValue(e); EA::UnitTest::ThreadSleepRandom(gTestLengthSeconds * 500, gTestLengthSeconds * 500); } workData.mbShouldQuit = true; for(int t(0); t < kThreadCount; t++) { if(threadId[t] != kThreadIdInvalid) { status = thread[t].WaitForEnd(GetThreadTime() + 30000); EATEST_VERIFY_MSG(status != Thread::kStatusRunning, "RWSemalock/Thread failure: status == kStatusRunning.\n"); } } nErrorCount += (int)workData.mnErrorCount; } #endif return nErrorCount; }
27.257692
116
0.693241
tlzyh
60c2a63fc40b22d424c579291dbc7add26e10f4f
8,693
cpp
C++
applications/_libs/cmp_mesh/jrt/jrtppmimage.cpp
galek/Compressonator
cb281b97eb05e35ec739a462c71524c4b1eefae3
[ "MIT" ]
622
2016-05-12T17:39:27.000Z
2020-03-09T08:51:41.000Z
applications/_libs/cmp_mesh/jrt/jrtppmimage.cpp
galek/Compressonator
cb281b97eb05e35ec739a462c71524c4b1eefae3
[ "MIT" ]
110
2020-03-14T15:30:42.000Z
2022-03-31T07:59:29.000Z
applications/_libs/cmp_mesh/jrt/jrtppmimage.cpp
galek/Compressonator
cb281b97eb05e35ec739a462c71524c4b1eefae3
[ "MIT" ]
105
2016-05-12T18:55:39.000Z
2020-03-04T15:02:01.000Z
/************************************************************************************//** // Copyright (c) 2006-2015 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file ****************************************************************************************/ #include "tootlepch.h" #include "jrtcommon.h" #include "jrtppmimage.h" /********************************************************/ /****** Implementation of Class JRTPPMJRTPPMImage *******************/ /********************************************************/ /*************************** * JRTPPMImage Constructor: * Sets the width and height of the image, in pixels * allocates memory for pixels. Each pixel is initialized to * 0,0,0 (black) ***************************/ JRTPPMImage::JRTPPMImage(int width, int height) { p_mlpPixels = NULL; p_miWidth = 0; p_miHeight = 0; AllocPixels(width, height); } JRTPPMImage::JRTPPMImage(const JRTPPMImage& img) { *this = img; } const JRTPPMImage& JRTPPMImage::operator =(const JRTPPMImage& img) { FreePixels(); this->p_miHeight = img.p_miHeight; this->p_miWidth = img.p_miWidth; this->p_mlpPixels = new PIXEL[ GetWidth() * GetHeight() ]; memcpy(this->p_mlpPixels, img.p_mlpPixels, sizeof(PIXEL)*GetWidth()*GetHeight()); return *this; } /*************************** * JRTPPMImage Destructor: * Frees all dynamic memory. ***************************/ JRTPPMImage::~JRTPPMImage() { FreePixels(); } double Round(double x) { double frac = x - floor(x); if (frac > 0.5) { return ceil(x); } else { return floor(x); } } void JRTPPMImage::SetPixel(int x, int y, float r, float g, float b) { if (x >= 0 && x < p_miWidth && y >= 0 && y < p_miHeight) { p_mlpPixels[y * p_miWidth + x].r = (unsigned char)Round(r * 255.0); p_mlpPixels[y * p_miWidth + x].g = (unsigned char)Round(g * 255.0); p_mlpPixels[y * p_miWidth + x].b = (unsigned char)Round(b * 255.0); } } /****************************** * SaveFile * Outputs the image to a PPM (P6) file * with the specified filename. Returns true if the * output was a success, false if not. *********************************/ bool JRTPPMImage::SaveFile(const char* sFile) { // binary write must be specified or this code blows up // on windows FILE* fp = fopen(sFile, "wb"); // sanity check if (fp == NULL) { return false; } // print PPM header stuff fprintf(fp, "P6\n%d %d\n%d\n", this->p_miWidth, this->p_miHeight, 255); // iterate across pixels and dump them to the file for (int row = 0; row < p_miHeight; row++) { for (int col = 0; col < p_miWidth; col++) { const PIXEL& pix = p_mlpPixels[(row * p_miWidth) + col]; fwrite(&pix, 3, 1, fp); } // repeat for next pixel } fclose(fp); return true; } /* Helper function for parsing the headers of PPM files */ void ISkipToToken(FILE* fp) { bool hit_token = false; while (!feof(fp) && !hit_token) { // skip to beginning of next token (width, height, or maxval) int c = fgetc(fp); if (c == '#') { // comment, skip ahead till next newline while (!feof(fp) && c != '\n' && c != '\f' && c != '\r') { c = fgetc(fp); } } else if (c == '\n' || c == '\f' || c == '\r' || c == '\t' || c == ' ') { // whitespace, skip it } else { hit_token = true; // we need that character we just read, so backtrack so we're pointed at it ungetc(c, fp); } } } bool JRTPPMImage::LoadFile(const char* filename) { // try and open the image file FILE* fp = fopen(filename, "rb"); if (fp == NULL) { return false; } /* For reference, here is the PPM image format description, direct from the ppm man page. A "magic number" for identifying the file type. A ppm file's magic number is the two characters "P3". Whitespace (blanks, TABs, CRs, LFs). A width, formatted as ASCII characters in decimal. Whitespace. A height, again in ASCII decimal. Whitespace. The maximum color-component value, again in ASCII decimal. Whitespace. Width * height pixels, each three ASCII decimal values between 0 and the specified maximum value, starting at the top-left corner of the pixmap, proceeding in normal English reading order. The three values for each pixel represent red, green, and blue, respectively; a value of 0 means that color is off, and the maximum value means that color is maxxed out. Characters from a "#" to the next end-of-line are ignored (comments). No line should be longer than 70 characters. The "magic number" is "P6" instead of "P3". The pixel values are stored as plain bytes, instead of ASCII decimal. Whitespace is not allowed in the pixels area, and only a single character of whitespace (typically a newline) is allowed after the maxval. */ // first two bytes had better be "P6" if (fgetc(fp) != 'P') { fclose(fp); return false; } if (fgetc(fp) != '6') { fclose(fp); return false; } UINT width = 0, height = 0, maxval = 0; // parse out the width, height, and maxval, ignoring whitespace and comments. bool at_bits = false, got_width = false, got_height = false, got_maxval = false; while (!at_bits && !feof(fp)) { ISkipToToken(fp); if (!got_width) { // read width if (fscanf(fp, "%d", &width) != 1) { fclose(fp); return false; } got_width = true; } else if (!got_height) { // read height if (fscanf(fp, "%d", &height) != 1) { fclose(fp); return false; } got_height = true; } else if (!got_maxval) { // read maxval if (fscanf(fp, "%d", &maxval) != 1) { fclose(fp); return false; } got_maxval = true; at_bits = true; } } // verify that we got all the header information we needed // if we're EOF, it means we did not if (feof(fp) && (!got_width || !got_height || !got_maxval)) { fclose(fp); return false; } // there are now 3*width*height bytes left in the file. // excluding the extraneous whitespace that may or may not be there // allocate enough space for the rest of the data unsigned char* bytes = (unsigned char*)malloc(3 * width * height); // store current file position long offs = ftell(fp); // read the data size_t bytes_read = fread(bytes, 1, 3 * width * height, fp); if (bytes_read < 3 * width * height) { // not enough bytes fclose(fp); free(bytes); return false; } else if (!feof(fp)) { // still more data in file, means that there was // extraneous whitespace before that needs to be skipped int extra_bytes = 0; while (!feof(fp)) { extra_bytes++; fgetc(fp); } extra_bytes--; // disregard EOF character fseek(fp, offs, SEEK_SET); for (int i = 0; i < extra_bytes; i++) { fgetc(fp); } bytes_read = fread(bytes, 1, 3 * width * height, fp); if (bytes_read != 3 * width * height) { // something is wrong fclose(fp); free(bytes); return false; } } // convert data to double and copy it AllocPixels(width, height); int i = 0; for (int y = 0; y < GetHeight(); y++) { for (int x = 0; x < GetWidth(); x++) { float r = bytes[i] / (float)maxval; float g = bytes[i + 1] / (float)maxval; float b = bytes[i + 2] / (float)maxval; i += 3; SetPixel(x, y, r, g, b); } } free(bytes); return true; } void JRTPPMImage::AllocPixels(int iWidth, int iHeight) { // prevent accidental memory leaks if (p_mlpPixels != NULL) { FreePixels(); } p_miWidth = iWidth; p_miHeight = iHeight; // and make new pixel memory p_mlpPixels = new PIXEL[p_miHeight * p_miWidth]; } void JRTPPMImage::FreePixels() { delete[] p_mlpPixels; p_mlpPixels = NULL; } PIXEL* JRTPPMImage::AccessPixel(int x, int y) { return &p_mlpPixels[ y * p_miWidth + x ]; }
26.26284
130
0.531002
galek
60c347cbfc16aacf9b224bbdadebd88d336cf128
3,371
cpp
C++
3rdparty/unittest-cpp-master/tests/TestDeferredTestReporter.cpp
SiddGururani/MUSI8903_Assignment_2
c4a4dba1206e5772cd1c515ecc59fe7eac803de5
[ "MIT" ]
493
2015-04-16T13:43:20.000Z
2022-03-31T03:54:17.000Z
3rdparty/unittest-cpp-master/tests/TestDeferredTestReporter.cpp
SiddGururani/MUSI8903_Assignment_2
c4a4dba1206e5772cd1c515ecc59fe7eac803de5
[ "MIT" ]
30
2015-01-13T12:17:13.000Z
2021-06-03T14:12:10.000Z
3rdparty/unittest-cpp-master/tests/TestDeferredTestReporter.cpp
SiddGururani/MUSI8903_Assignment_2
c4a4dba1206e5772cd1c515ecc59fe7eac803de5
[ "MIT" ]
112
2015-01-14T12:01:00.000Z
2022-03-29T06:42:00.000Z
#include "UnitTest++/Config.h" #ifndef UNITTEST_NO_DEFERRED_REPORTER #include "UnitTest++/UnitTestPP.h" #include "UnitTest++/DeferredTestReporter.h" #include <cstring> namespace UnitTest { namespace { #ifndef UNITTEST_MEMORYOUTSTREAM_IS_STD_OSTRINGSTREAM MemoryOutStream& operator <<(MemoryOutStream& lhs, const std::string& rhs) { lhs << rhs.c_str(); return lhs; } #endif struct MockDeferredTestReporter : public DeferredTestReporter { virtual void ReportSummary(int, int, int, float) { } }; struct DeferredTestReporterFixture { DeferredTestReporterFixture() : testName("UniqueTestName") , testSuite("UniqueTestSuite") , fileName("filename.h") , lineNumber(12) , details(testName.c_str(), testSuite.c_str(), fileName.c_str(), lineNumber) { } MockDeferredTestReporter reporter; std::string const testName; std::string const testSuite; std::string const fileName; int const lineNumber; TestDetails const details; }; TEST_FIXTURE(DeferredTestReporterFixture, ReportTestStartCreatesANewDeferredTest) { reporter.ReportTestStart(details); CHECK_EQUAL(1, (int)reporter.GetResults().size()); } TEST_FIXTURE(DeferredTestReporterFixture, ReportTestStartCapturesTestNameAndSuite) { reporter.ReportTestStart(details); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK_EQUAL(testName.c_str(), result.testName.c_str()); CHECK_EQUAL(testSuite.c_str(), result.suiteName.c_str()); } TEST_FIXTURE(DeferredTestReporterFixture, ReportTestEndCapturesTestTime) { float const elapsed = 123.45f; reporter.ReportTestStart(details); reporter.ReportTestFinish(details, elapsed); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK_CLOSE(elapsed, result.timeElapsed, 0.0001f); } TEST_FIXTURE(DeferredTestReporterFixture, ReportFailureSavesFailureDetails) { char const* failure = "failure"; reporter.ReportTestStart(details); reporter.ReportFailure(details, failure); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK(result.failed == true); CHECK_EQUAL(fileName.c_str(), result.failureFile.c_str()); } TEST_FIXTURE(DeferredTestReporterFixture, ReportFailureSavesFailureDetailsForMultipleFailures) { char const* failure1 = "failure 1"; char const* failure2 = "failure 2"; reporter.ReportTestStart(details); reporter.ReportFailure(details, failure1); reporter.ReportFailure(details, failure2); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK_EQUAL(2, (int)result.failures.size()); CHECK_EQUAL(failure1, result.failures[0].failureStr); CHECK_EQUAL(failure2, result.failures[1].failureStr); } TEST_FIXTURE(DeferredTestReporterFixture, DeferredTestReporterTakesCopyOfFailureMessage) { reporter.ReportTestStart(details); char failureMessage[128]; char const* goodStr = "Real failure message"; char const* badStr = "Bogus failure message"; using namespace std; strcpy(failureMessage, goodStr); reporter.ReportFailure(details, failureMessage); strcpy(failureMessage, badStr); DeferredTestResult const& result = reporter.GetResults().at(0); DeferredTestFailure const& failure = result.failures.at(0); CHECK_EQUAL(goodStr, failure.failureStr); } }} #endif
27.406504
94
0.741916
SiddGururani
60c3624ae54625c59d506dfb35ab0fe7368b4bd6
16,722
cc
C++
llcc/front-end/src/inter_code_generator.cc
toy-compiler/toy_js_compiler
4267c96cd65b2359b6ba70dad7ee1f17114e88fc
[ "MIT" ]
2
2019-03-12T07:42:33.000Z
2019-03-12T07:42:41.000Z
llcc/front-end/src/inter_code_generator.cc
toy-compiler/awesomeCC
4267c96cd65b2359b6ba70dad7ee1f17114e88fc
[ "MIT" ]
null
null
null
llcc/front-end/src/inter_code_generator.cc
toy-compiler/awesomeCC
4267c96cd65b2359b6ba70dad7ee1f17114e88fc
[ "MIT" ]
1
2019-11-29T11:13:22.000Z
2019-11-29T11:13:22.000Z
/** * @file inter_code_generator.h * @brief 中间代码生成器类具体实现 */ #include "../include/inter_code_generator.h" #define POS(cur) cur->line_number, cur->pos map<string, VARIABLE_INFO_ENUM> Info::VAR_INFO_MAP = { {"double", VARIABLE_INFO_ENUM::DOUBLE}, {"float", VARIABLE_INFO_ENUM::DOUBLE}, {"int", VARIABLE_INFO_ENUM::INT}, {"void", VARIABLE_INFO_ENUM::VOID}, }; /** * @brief VarInfo构造函数 */ VarInfo::VarInfo() = default; /** * @brief VarInfo构造函数 * @param _name 变量名字 * @param _type 种类 */ VarInfo::VarInfo(VARIABLE_INFO_ENUM _type, int _place) { name = "v" + int2string(_place); place = _place; type = _type; } FuncInfo::FuncInfo() = default; FuncInfo::FuncInfo(string _name, VARIABLE_INFO_ENUM _ret_type, int _start_place, int _end_place) { name = move(_name); ret_type = _ret_type; start_place = _start_place; end_place = _end_place; } /** * @brief 中间代码生成器构造函数 */ InterCodeGenerator::InterCodeGenerator() = default; /** * @brief 中间代码生成 * @param _tree SyntaxTree * */ void InterCodeGenerator::analyze(SyntaxTree * _tree, bool verbose) { inter_code.clear(); var_index = 0; temp_var_index = 0; context_index = 0; func_backpatch.clear(); tree = _tree; try { _analyze(tree -> root -> first_son); } catch (Error & e) { cout << "Semantic analyze errors :" << endl; cout << e; exit(0); } if (verbose) { int l = inter_code.size(); cout << "Generated " << l << " inter codes" << endl; for (int i = 0; i < l; i ++) { cout << "#" << setw(3) << setfill(' ') << std::left << i; cout << inter_code[i]; } } } void InterCodeGenerator::_analyze(SyntaxTreeNode * cur) { SyntaxTreeNode * name_tree, * main_block; vector<SyntaxTreeNode *> funcs; string name, type; while (cur) { temp_var_index = 0; if (cur -> value == "FunctionStatement") { name_tree = cur -> first_son -> right; name = name_tree -> first_son -> value; if (name == "main") main_block = name_tree -> right -> right; else { type = cur -> first_son -> value; func_table[name] = FuncInfo(name, Info::VAR_INFO_MAP[type], 0, 0); funcs.emplace_back(cur); } } else if (cur -> value == "Statement") { _statement(cur); } else throw Error("`" + cur -> value + "` is not allowed in a root of a class", POS(cur)); cur = cur -> right; } // main 函数直接执行 _block(main_block, false); int main_end = inter_code.size(); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); // 翻译别的函数 for (auto func: funcs) _functionStatement(func); // main 结束就直接结束 inter_code[main_end].res = int2string(inter_code.size()); for (auto it: func_backpatch) if (! it.second.empty()) { string dest = int2string(func_table[it.first].start_place); for (auto i: it.second) inter_code[i].res = dest; } } void InterCodeGenerator::_functionStatement(SyntaxTreeNode * cur) { SyntaxTreeNode * name_tree, * param_tree, * block_tree, * type_tree; type_tree = cur -> first_son; name_tree = type_tree -> right; param_tree = name_tree -> right; block_tree = param_tree -> right; string func_name = name_tree -> first_son -> value; int func_start = int(inter_code.size()); // start SyntaxTreeNode * ps = param_tree -> first_son; while (ps) { _statement(ps); _emit(INTER_CODE_OP_ENUM::POP, "", "", table[ps -> first_son -> value].name); ps = ps -> right; } _block(block_tree); string temp_place = "t" + int2string(temp_var_index ++); // 自动return _emit(INTER_CODE_OP_ENUM::POP, "", "", temp_place); _emit(INTER_CODE_OP_ENUM::J, "", "", temp_place); // end int func_end = inter_code.size() - 1; func_table[func_name] = FuncInfo(name_tree -> first_son -> value, Info::VAR_INFO_MAP[type_tree -> first_son -> value], func_start, func_end); } /** * @brief 翻译block */ void InterCodeGenerator::_block(SyntaxTreeNode * cur, bool restore) { int _pre_var_index = var_index; map<string, VarInfo> pre_table = table; context_index ++; SyntaxTreeNode * cs = cur -> first_son; cur -> next_list = cs -> next_list; while (cs) { if (cs -> value == "Statement") _statement(cs); else if (cs -> value == "Assignment") _assignment(cs); else if (cs -> value == "Print") _print(cs); else if (cs -> value == "Control-If") _if(cs); else if (cs -> value == "Control-While") _while(cs); else if (cs -> value == "Block") { _block(cs); cur -> next_list = cs -> next_list; } else if (cs -> value == "FunctionCall") _functionCall(cs); else if (cs -> value == "VoidReturn") _voidReturn(cs); // TODO 其他 else cout << "Debug <<<" << cs -> value << endl; // 回填 _backpatch(cs -> next_list, inter_code.size()); cs = cs -> right; // 回填 if (cs) cur -> next_list = cs -> next_list; } if (restore) { var_index = _pre_var_index; table = pre_table; } } /** * @brief 翻译Print */ void InterCodeGenerator::_if(SyntaxTreeNode * cur) { SyntaxTreeNode * cs = cur -> first_son, * pre = nullptr; int m1_inst, m2_inst; while (cs) { if (cs -> value == "Control-Condition") { // 读取条件语句 _expression(cs -> first_son); pre = cs -> first_son; // 回填一下 m1_inst = inter_code.size(); // 读取紧随其后的执行语句 cs = cs -> right; _block(cs); // 只有if if (! cs -> right) { _backpatch(pre -> true_list, m1_inst); cur -> next_list.insert(cur -> next_list.end(), V(cs -> left -> first_son -> false_list)); cur -> next_list.insert(cur -> next_list.end(), V(cs -> next_list)); } else { cur -> next_list.emplace_back(inter_code.size()); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); cur -> next_list.insert(cur -> next_list.end(), V(cs -> next_list)); } } else { // 回填一下 m2_inst = inter_code.size(); _block(cs); _backpatch(pre -> true_list, m1_inst); _backpatch(pre -> false_list, m2_inst); cur -> next_list.insert(cur -> next_list.end(), V(cs -> next_list)); } cs = cs -> right; } } /** * @brief 翻译Print */ void InterCodeGenerator::_print(SyntaxTreeNode * cur) { SyntaxTreeNode * ps = cur -> first_son; string print_place; while (ps) { print_place = _expression(ps); _emit(INTER_CODE_OP_ENUM::PRINT, print_place, "", ""); ps = ps -> right; } _emit(INTER_CODE_OP_ENUM::PRINT, "", "", ""); } /** * @brief 翻译赋值语句 */ void InterCodeGenerator::_assignment(SyntaxTreeNode * cur) { SyntaxTreeNode * cs = cur -> first_son; string r_value_place = _expression(cs -> right); string store_place; if (cs -> value == "Expression-ArrayItem") store_place = _lookUpVar(cs); else store_place = _lookUpVar(cur -> first_son -> value, cur); _emit(INTER_CODE_OP_ENUM::MOV, r_value_place, "", store_place); } /** * @brief 翻译表达式 * @param cur 一个Expression-*节点执政 * @return place, string */ string InterCodeGenerator::_expression(SyntaxTreeNode * cur) { // 双目运算符 if (cur -> value == "Expression-DoubleOp" || cur -> value == "Expression-Bool-DoubleOp") { SyntaxTreeNode * a = cur -> first_son; SyntaxTreeNode * op = a -> right; SyntaxTreeNode * b = op -> right; string a_place, b_place; // 如果是数字运算的话 if (cur -> value == "Expression-DoubleOp") { a_place = _expression(a); b_place = _expression(b); string temp_var_place = "t" + int2string(temp_var_index ++); _emit(Quadruple::INTER_CODE_MAP[op -> first_son -> value], a_place, b_place, temp_var_place); return temp_var_place; } // bool运算要考虑回填 else { string a_place, b_place; if (op -> first_son -> value == "||") { a_place = _expression(a); int m_inst = inter_code.size(); b_place = _expression(b); _backpatch(a -> false_list, m_inst); // update true_list cur -> true_list.insert(cur -> true_list.end(), V(a -> true_list)); cur -> true_list.insert(cur -> true_list.end(), V(b -> true_list)); // update false_list cur -> false_list = b -> false_list; } else if (op -> first_son -> value == "&&") { a_place = _expression(a); int m_inst = inter_code.size(); b_place = _expression(b); _backpatch(a -> true_list, m_inst); // update true_list cur -> true_list = b -> true_list; // update false_list cur -> false_list.insert(cur -> false_list.end(), a -> false_list.begin(), a -> false_list.end()); cur -> false_list.insert(cur -> false_list.end(), b -> false_list.begin(), b -> false_list.end()); } else { a_place = _expression(a); b_place = _expression(b); cur -> true_list.emplace_back(inter_code.size()); _emit(Quadruple::INTER_CODE_MAP[op -> first_son -> value], a_place, b_place, ""); cur -> false_list.emplace_back(inter_code.size()); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); } return ""; } } // 单目运算符 else if (cur -> value == "Expression-UniOp") { // TODO } else if (cur -> value == "Expression-Bool-UniOp") { // TODO } // 常量 else if (cur -> value == "Expression-Constant"){ return cur -> first_son -> value; } // 字符串常量 else if (cur -> value == "Expression-String") { string temp = cur -> first_son -> value; // 转义 temp = regex_replace(temp, regex(","), string("\\,")); temp = regex_replace(temp, regex("\\\\"), string("\\\\")); return temp; } // 变量 else if (cur -> value == "Expression-Variable") { return _lookUpVar(cur -> first_son -> value, cur); } // 数组项 else if (cur -> value == "Expression-ArrayItem") { return _lookUpVar(cur); } cout << "debug >> " << cur -> value << endl; throw Error("How can you step into this place???", POS(cur)); } /** * @brief 翻译while语句 */ void InterCodeGenerator::_while(SyntaxTreeNode * cur) { int m_inst1 = inter_code.size(); SyntaxTreeNode * condition_tree = cur -> first_son -> first_son; _expression(condition_tree); int m_inst2 = inter_code.size(); SyntaxTreeNode * block_tree = cur -> first_son -> right; _block(block_tree); _backpatch(block_tree -> next_list, m_inst1); _backpatch(condition_tree -> true_list, m_inst2); cur -> next_list = condition_tree -> false_list; _emit(INTER_CODE_OP_ENUM::J, "", "", int2string(m_inst1)); } /** * @brief 翻译变量声明语句 */ void InterCodeGenerator::_statement(SyntaxTreeNode * cur) { SyntaxTreeNode * cs = cur -> first_son; while (cs) { string type = cs -> type; if (type == "double" || type == "float") { VarInfo info(VARIABLE_INFO_ENUM::DOUBLE, var_index ++); table[cs -> value] = info; } else if (type == "int") { VarInfo info(VARIABLE_INFO_ENUM::INT, var_index ++); table[cs -> value] = info; } else if (type.size() > 6 && type.substr(0, 6) == "array-") { VarInfo info(VARIABLE_INFO_ENUM::ARRAY, var_index ++); table[cs -> value] = info; string extra_info = cs -> extra_info; int extra_info_len = extra_info.size(); int cur_i = 0; if (cur_i < extra_info_len && extra_info.substr(cur_i, 5) == "size=") { cur_i += 5; int len = 0; while (cur_i + len < extra_info_len && extra_info[cur_i + len] != '&') len ++; var_index += string2int(extra_info.substr(cur_i, len)); cur_i += len; } if (cur_i < extra_info_len && extra_info.substr(cur_i, 3) == "&v=") { cur_i += 3; int len, arr_i = 0; while (cur_i < extra_info_len) { len = 0; while (cur_i + len < extra_info_len && extra_info[cur_i + len] != ',') len ++; _emit(INTER_CODE_OP_ENUM::MOV, extra_info.substr(cur_i, len), "", info.name + "[" + int2string(arr_i) + "]"); cur_i += len + 1; arr_i ++; } } } else { throw Error("type `" + type + "` are not supported yet", POS(cur)); } cs = cs -> right; } } /** * @brief 处理函数调用 */ void InterCodeGenerator::_functionCall(SyntaxTreeNode * cur) { // backup int _pre_var_index = var_index; map<string, VarInfo> pre_table = table; string func_name = cur -> first_son -> first_son -> value; if (func_table.find(func_name) == func_table.end()) throw Error("function `" + func_name + "` is not defined before use", POS(cur)); // TODO 返回地址 int temp_place = inter_code.size(); _emit(INTER_CODE_OP_ENUM::PUSH, "", "", ""); SyntaxTreeNode * param = cur -> first_son -> right; SyntaxTreeNode * ps = param -> first_son; while (ps -> right) ps = ps -> right; string param_place; while (ps) { param_place = _expression(ps -> first_son); _emit(INTER_CODE_OP_ENUM::PUSH, "", "", param_place); ps = ps -> left; } inter_code[temp_place].res = "pc+" + int2string(inter_code.size() - temp_place + 1); if (func_backpatch.find(func_name) == func_backpatch.end()) { vector<int> t; func_backpatch[func_name] = t; } func_backpatch[func_name].emplace_back(inter_code.size()); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); // restore var_index = _pre_var_index; table = pre_table; } /** * @brief 寻找标识符 * @param name 标识符 * @return code var */ string InterCodeGenerator::_lookUpVar(string name, SyntaxTreeNode * cur) { if (table.find(name) == table.end()) throw Error("variable `" + name + "` is not defined before use", POS(cur)); return table[name].name; } /** * @brief 寻找标识符 * @param name 标识符 * @return code var */ string InterCodeGenerator::_lookUpVar(SyntaxTreeNode * arr_pointer) { string base = arr_pointer -> first_son -> value; string index_place = _expression(arr_pointer -> first_son -> right -> first_son); return _lookUpVar(base, arr_pointer) + "[" + index_place + "]"; } /** * @brief 生成一个四元式 * @param op 操作符 * @param arg1 参数1 * @param arg2 参数2 * @param res 结果 */ void InterCodeGenerator::_emit(INTER_CODE_OP_ENUM op, string arg1, string arg2, string res) { inter_code.emplace_back(Quadruple(op, move(arg1), move(arg2), move(res))); } /** * @brief 保存到文件 * @param 路径 */ void InterCodeGenerator::saveToFile(string path) { ofstream out_file; out_file.open(path, ofstream::out | ofstream::trunc); for (auto ic: inter_code) out_file << Quadruple::INTER_CODE_OP[int(ic.op)] << "," << ic.arg1 << "," << ic.arg2 << "," << ic.res << endl; out_file.close(); } void InterCodeGenerator::_backpatch(vector<int> v, int dest_index) { for (auto i: v) inter_code[i].res = int2string(dest_index); } void InterCodeGenerator::_voidReturn(SyntaxTreeNode * cur) { SyntaxTreeNode * cf = cur; while (cf && cf -> value != "FunctionStatement") cf = cf -> father; string temp_place = "t" + int2string(temp_var_index ++); // 自动return _emit(INTER_CODE_OP_ENUM::POP, "", "", temp_place); _emit(INTER_CODE_OP_ENUM::J, "", "", temp_place); }
27.916528
118
0.54204
toy-compiler
60c3729869adc42ebc876a7485af606fca846d14
10,759
hxx
C++
inc/TimerThread.hxx
Clovel/TimerThread
95083010066deeedb3d9e19e332f10827d7b0852
[ "MIT" ]
1
2020-03-04T08:59:59.000Z
2020-03-04T08:59:59.000Z
inc/TimerThread.hxx
Clovel/TimerThread
95083010066deeedb3d9e19e332f10827d7b0852
[ "MIT" ]
2
2020-03-05T08:33:02.000Z
2020-03-05T08:49:17.000Z
inc/TimerThread.hxx
Clovel/TimerThread
95083010066deeedb3d9e19e332f10827d7b0852
[ "MIT" ]
null
null
null
/** * TimerThread class definition * * @file TimerThread.hxx */ #ifndef TIMERTHREAD_HXX #define TIMERTHREAD_HXX /* Includes -------------------------------------------- */ #include <functional> #include <chrono> #include <unordered_map> #include <set> #include <thread> #include <mutex> #include <condition_variable> #include <cstdint> /* TimerThread class definition ------------------------ */ class TimerThread { public: /* Defining the timer ID type */ using timer_id_t = std::uint64_t; /* Each Timer is assigned a unique ID of type timer_id_t */ static timer_id_t constexpr no_timer = timer_id_t(0); /* Valid IDs are guaranteed not to be this value */ /* Defining the handler function type */ using handler_type = std::function<void()>; // Function object we actually use // Function object that we boil down to handler_type with std::bind template<typename ... Args> using bound_handler_type = std::function<void(Args ...)>; /* Defining the microsecond type */ using time_us_t = std::int64_t; /* Values that are a large-range microsecond count */ /** @brief Constructor does not start worker until there is a Timer */ explicit TimerThread(); /** @brief Destructor is thread safe, even if a timer * callback is running. All callbacks are guaranteed * to have returned before this destructor returns */ ~TimerThread(); /** @brief Create timer using microseconds * The delay will be called msDelay microseconds from now * If msPeriod is nonzero, call the callback again every * msPeriod microseconds * All timer creation functions eventually call this one */ timer_id_t addTimer(time_us_t msDelay, time_us_t msPeriod, handler_type handler); /** @brief Create timer using std::chrono delay and period * Optionally binds additional arguments to the callback */ template<typename SRep, typename SPer, typename PRep, typename PPer, typename ... Args> timer_id_t addTimer(typename std::chrono::duration<SRep, SPer> const &delay, typename std::chrono::duration<PRep, PPer> const &period, bound_handler_type<Args ...> handler, Args && ... args); /** @brief Create timer using millisecond units delay and period * Optionally binds additional arguments to the callback */ template<typename ... Args> timer_id_t addTimer(time_us_t msDelay, time_us_t msPeriod, bound_handler_type<Args ...> handler, Args && ... args); /** @brief setInterval API like browser javascript * Call handler every `period` milliseconds, * starting `period` milliseconds from now * Optionally binds additional arguments to the callback */ timer_id_t setInterval(handler_type handler, time_us_t period); /** @brief setTimeout API like browser javascript * Call handler once `timeout` ms from now */ timer_id_t setTimeout(handler_type handler, time_us_t timeout); /** @brief setInterval API like browser javascript * Call handler every `period` microseconds, * starting `period` microseconds from now */ template<typename ... Args> timer_id_t setInterval(bound_handler_type<Args ...> handler, time_us_t period, Args && ... args); /** @brief setTimeout API like browser javascript * Call handler once `timeout` ms from now * binds extra arguments and passes them to the * timer callback */ template<typename ... Args> timer_id_t setTimeout(bound_handler_type<Args ...> handler, time_us_t timeout, Args && ... args); /** @brief Destroy the specified timer * * Synchronizes with the worker thread if the * callback for this timer is running, which * guarantees that the handler for that callback * is not running before clearTimer returns * * You are not required to clear any timers. You can * forget their timer_id_t if you do not need to cancel * them. * * The only time you need this is when you want to * stop a timer that has a repetition period, or * you want to cancel a timeout that has not fired * yet * * See clear() to wipe out all timers in one go */ bool clearTimer(timer_id_t id); /* @brief Destroy all timers, but preserve id uniqueness * This carefully makes sure every timer is not * executing its callback before destructing it */ void clear(); /* @brief Set the TimerThread's priority */ int setScheduling(const int &pPolicy, const int &pPriority); /* @brief Get the TimerThread's priority */ int scheduling(int * const pPolicy, int * const pPriority) noexcept; /* Peek at current state */ std::size_t size() const noexcept; bool empty() const noexcept; /** @brief Returns initialized singleton */ static TimerThread &global(); private: /* Type definitions */ using Lock = std::mutex; using ScopedLock = std::unique_lock<Lock>; using ConditionVar = std::condition_variable; using Clock = std::chrono::high_resolution_clock; using Timestamp = std::chrono::time_point<Clock>; using Duration = std::chrono::microseconds; /* changed milliseconds to microseconds */ /** @brief Timer structure definition */ struct Timer { explicit Timer(timer_id_t id = 0U); Timer(Timer &&r) noexcept; Timer &operator=(Timer &&r) noexcept; Timer(timer_id_t id, Timestamp next, Duration period, handler_type handler) noexcept; // Never called Timer(Timer const &r) = delete; Timer &operator=(Timer const &r) = delete; timer_id_t id; Timestamp next; Duration period; handler_type handler; // You must be holding the 'sync' lock to assign waitCond std::unique_ptr<ConditionVar> waitCond; bool running; }; // Comparison functor to sort the timer "queue" by Timer::next struct NextActiveComparator { bool operator()(Timer const &a, Timer const &b) const noexcept { return a.next < b.next; } }; // Queue is a set of references to Timer objects, sorted by next using QueueValue = std::reference_wrapper<Timer>; using Queue = std::multiset<QueueValue, NextActiveComparator>; using TimerMap = std::unordered_map<timer_id_t, Timer>; void timerThreadWorker(); bool destroy_impl(ScopedLock &lock, TimerMap::iterator i, bool notify); // Inexhaustible source of unique IDs timer_id_t nextId; // The Timer objects are physically stored in this map TimerMap active; // The ordering queue holds references to items in `active` Queue queue; // One worker thread for an unlimited number of timers is acceptable // Lazily started when first timer is started // TODO: Implement auto-stopping the timer thread when it is idle for // a configurable period. mutable Lock sync; ConditionVar wakeUp; std::thread worker; bool done; }; /* Template implementation fo class methods */ template<typename SRep, typename SPer, typename PRep, typename PPer, typename ... Args> TimerThread::timer_id_t TimerThread::addTimer(typename std::chrono::duration<SRep, SPer> const &delay, typename std::chrono::duration<PRep, PPer> const &period, bound_handler_type<Args ...> handler, Args && ... args) { time_us_t msDelay = std::chrono::duration_cast<std::chrono::microseconds>(delay).count(); time_us_t msPeriod = std::chrono::duration_cast<std::chrono::microseconds>(period).count(); return addTimer(msDelay, msPeriod, std::move(handler), std::forward<Args>(args) ...); } template<typename ... Args> TimerThread::timer_id_t TimerThread::addTimer(time_us_t msDelay, time_us_t msPeriod, bound_handler_type<Args ...> handler, Args && ... args) { return addTimer(msDelay, msPeriod, std::bind(std::move(handler), std::forward<Args>(args) ...)); } // Javascript-like setInterval template<typename ... Args> TimerThread::timer_id_t TimerThread::setInterval(bound_handler_type<Args ...> handler, time_us_t period, Args && ... args) { return setInterval(std::bind(std::move(handler), std::forward<Args>(args) ...), period); } // Javascript-like setTimeout template<typename ... Args> TimerThread::timer_id_t TimerThread::setTimeout(bound_handler_type<Args ...> handler, time_us_t timeout, Args && ... args) { return setTimeout(std::bind(std::move(handler), std::forward<Args>(args) ...), timeout); } #endif /* TIMERTHREAD_HXX */
38.701439
121
0.53992
Clovel
60c6a5e9afdf2df843fcafedeeeb78e3ecf4f186
1,910
cc
C++
src/parser/uparser.cc
aldebaran/urbi
12fe46efbee81a662bfa792fce7b75353d166dbb
[ "BSD-3-Clause" ]
12
2015-01-10T10:49:05.000Z
2018-08-20T14:53:31.000Z
src/parser/uparser.cc
akimd/urbi
12fe46efbee81a662bfa792fce7b75353d166dbb
[ "BSD-3-Clause" ]
4
2016-08-14T16:44:41.000Z
2018-09-21T11:56:12.000Z
src/parser/uparser.cc
akimd/urbi
12fe46efbee81a662bfa792fce7b75353d166dbb
[ "BSD-3-Clause" ]
15
2015-01-28T20:27:02.000Z
2021-09-28T19:26:08.000Z
/* * Copyright (C) 2006-2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file parser/uparser.cc #include <fstream> #include <parser/uparser.hh> #include <parser/parser-impl.hh> namespace parser { /*----------. | UParser. | `----------*/ UParser::UParser(std::istream& input, const yy::location* loc) : pimpl_(0) , stream_(&input) , stream_delete_(false) , oneshot_(false) , loc_(loc) { pimpl_ = new ParserImpl(*stream_); } UParser::UParser(const std::string& code, const yy::location* loc) : pimpl_(0) , stream_(new std::stringstream(code)) , stream_delete_(true) , oneshot_(true) , loc_(loc) { pimpl_ = new ParserImpl(*stream_); } UParser::UParser(const libport::path& file) : pimpl_(0) , stream_(0) , stream_delete_(true) , oneshot_(true) , loc_file_(new libport::Symbol(file.to_string())) // FIXME: leaks. , loc_(&loc_file_) { std::ifstream* input = new std::ifstream(file.to_string().c_str()); if (!input->good()) throw 42; // FIXME stream_ = input; pimpl_ = new ParserImpl(*stream_); } UParser::UParser(const UParser& rhs) : pimpl_(new ParserImpl(*rhs.pimpl_)) { } UParser::~UParser() { if (stream_delete_) delete stream_; delete pimpl_; } void UParser::meta(bool b) { pimpl_->meta(b); } parse_result_type UParser::parse() { pimpl_->initial_token_set(oneshot_ ? ::yy::parser::token::TOK_MODE_EXPS : ::yy::parser::token::TOK_MODE_EXP); return pimpl_->parse(loc_); } void UParser::oneshot_set(bool v) { oneshot_ = v; } }
20.537634
71
0.603141
aldebaran
60c85ecb66d625c57d203206d68bcaf76636cbcf
215
hpp
C++
src/modules/osg/generated_code/BufferObject.pypp.hpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osg/generated_code/BufferObject.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osg/generated_code/BufferObject.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #ifndef BufferObject_hpp__pyplusplus_wrapper #define BufferObject_hpp__pyplusplus_wrapper void register_BufferObject_class(); #endif//BufferObject_hpp__pyplusplus_wrapper
23.888889
44
0.855814
JaneliaSciComp
60c8fb1d62c0c830f6f1f6d628612b2f38e982bc
82,756
cpp
C++
test/cpp/tensorexpr/test_loopnest.cpp
jsun94/nimble
e5c899a69677818b1becc58100577441e15ede13
[ "BSD-3-Clause" ]
206
2020-11-28T22:56:38.000Z
2022-03-27T02:33:04.000Z
test/cpp/tensorexpr/test_loopnest.cpp
jsun94/nimble
e5c899a69677818b1becc58100577441e15ede13
[ "BSD-3-Clause" ]
19
2020-12-09T23:13:14.000Z
2022-01-24T23:24:08.000Z
test/cpp/tensorexpr/test_loopnest.cpp
jsun94/nimble
e5c899a69677818b1becc58100577441e15ede13
[ "BSD-3-Clause" ]
28
2020-11-29T15:25:12.000Z
2022-01-20T02:16:27.000Z
#include <test/cpp/tensorexpr/test_base.h> #include <memory> #include <sstream> #include <stdexcept> #include <unordered_map> #include <test/cpp/tensorexpr/padded_buffer.h> #include <torch/csrc/jit/tensorexpr/analysis.h> #include <torch/csrc/jit/tensorexpr/bounds_inference.h> #include <torch/csrc/jit/tensorexpr/eval.h> #include <torch/csrc/jit/tensorexpr/ir.h> #include <torch/csrc/jit/tensorexpr/ir_printer.h> #include <torch/csrc/jit/tensorexpr/ir_simplifier.h> #include <torch/csrc/jit/tensorexpr/loopnest.h> #include <torch/csrc/jit/tensorexpr/tensor.h> #include <torch/csrc/jit/testing/file_check.h> namespace torch { namespace jit { using namespace torch::jit::tensorexpr; void testExprSimple01() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{16, "X"}, {5, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); For* x_outer; For* x_inner; For* x_tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithTail(loops[0], 2, &x_outer, &x_inner, &x_tail); For* x_2; For* x_1; For* x_tail_2; l.splitWithTail(x_outer, 2, &x_2, &x_1, &x_tail_2); } void testExprLower01() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{16, "x"}, {5, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; ASSERT_GT(oss.str().size(), 20); ASSERT_LT(oss.str().size(), 200); } void testExprSimple02() { KernelScope kernel_scope; auto func = [](const ExprHandle& x, const ExprHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }; Tensor* tensor = Compute("f", {{26, "x"}, {5, "y"}}, func); LoopNest l({tensor}); For* x_outer; For* x_inner; For* x_tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithTail(loops[0], 4, &x_outer, &x_inner, &x_tail); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; ASSERT_GT(oss.str().size(), 200); ASSERT_LT(oss.str().size(), 600); { // Compare to a reference loop structure structure. VarHandle x_outer("x_outer", kInt); VarHandle x_inner("x_inner", kInt); VarHandle y("y", kInt); VarHandle x_tail("x_tail", kInt); BufHandle f("f", {26, 5}, kFloat); ExprHandle x_1 = x_outer * 4 + x_inner; ExprHandle x_outer_end = (ExprHandle(26) - 0) / 4; For* stmt1 = For::make( x_outer, 0, x_outer_end, For::make( x_inner, 0, 4, For::make(y, 0, 5, Store::make(f, {x_1, y}, func(x_1, y), 1)))); ExprHandle x_2 = x_tail + x_outer_end * 4; For* stmt2 = For::make( x_tail, 0, (ExprHandle(26) - 0) % 4, For::make(y, 0, 5, Store::make(f, {x_2, y}, func(x_2, y), 1))); Stmt* stmt = Block::make({stmt1, stmt2}); std::ostringstream oss_ref; oss_ref << *stmt; ASSERT_EQ(oss.str(), oss_ref.str()); } { PaddedBuffer<float> f_v(26, 5, "f_v"); PaddedBuffer<float> f_ref(26, 5, "f_res"); stmt = FlattenIndexes(stmt); SimpleIREvaluator ir_eval(stmt, tensor); ir_eval(f_v); for (int x = 0; x < 26; x++) { for (int y = 0; y < 5; y++) { f_ref(x, y) = 1 + x * x + y * y; } } ExpectAllNear(f_v, f_ref, 1e-5); } } Block* getSimplifiedBody(const LoopNest& l) { Stmt* stmt = l.root_stmt(); Stmt* simplified = IRSimplifier::simplify(stmt); return dynamic_cast<Block*>(simplified); } void assertForRange(For* f, int expected_start, int expected_stop) { ASSERT_NE(f, nullptr); const IntImm* start = dynamic_cast<const IntImm*>(f->start()); ASSERT_NE(start, nullptr); ASSERT_EQ(start->value(), expected_start); const IntImm* stop = dynamic_cast<const IntImm*>(f->stop()); ASSERT_NE(stop, nullptr); ASSERT_EQ(stop->value(), expected_stop); } void assertForRanges( Block* body, const std::vector<std::pair<int, int>>& start_stops) { ASSERT_EQ(body->nstmts(), start_stops.size()); auto it = body->begin(); for (size_t i = 0; i < start_stops.size(); i++, it++) { For* loop = dynamic_cast<For*>(*it); assertForRange(loop, start_stops[i].first, start_stops[i].second); } } void testExprSliceHeadWithLoopOptions() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.setGPUBlockIndex(loops[0], LoopOptions::IDX_Y); l.sliceHead(loops[0], 2, &head, &tail); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 2}, {0, 8}}); ASSERT_TRUE(tail->loop_options().is_gpu_block_index()); ASSERT_EQ(tail->loop_options().gpu_block_index(), LoopOptions::IDX_Y); ASSERT_TRUE(head->loop_options().isDefault()); } void testExprSliceTailWithLoopOptions() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceTail(loops[0], 4, &head, &tail); For* tail_head; For* tail_tail; l.setGPUBlockIndex(tail, LoopOptions::IDX_Y); l.sliceTail(tail, 2, &tail_head, &tail_tail); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 6}, {0, 2}, {8, 10}}); ASSERT_TRUE(tail_head->loop_options().is_gpu_block_index()); ASSERT_EQ(tail_head->loop_options().gpu_block_index(), LoopOptions::IDX_Y); ASSERT_TRUE(head->loop_options().isDefault()); ASSERT_TRUE(tail_tail->loop_options().isDefault()); } void testExprSliceHeadWhenFactorEqualsSize() { // When factor equals the For loop's original size, keep using the original // For loop. KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceHead(loops[0], 10, &head, &tail); ASSERT_EQ(head, loops[0]); ASSERT_EQ(tail, nullptr); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 10}}); } void testExprSliceHeadWhenFactorLargerThanSize() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceHead(loops[0], 100, &head, &tail); ASSERT_EQ(head, loops[0]); ASSERT_EQ(tail, nullptr); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 10}}); } void testExprSliceHead() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceHead(loops[0], 4, &head, &tail); ASSERT_NE(head, nullptr); ASSERT_NE(head, loops[0]); ASSERT_NE(tail, nullptr); ASSERT_NE(tail, loops[0]); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 4}, {4, 10}}); } void testExprSliceHeadWithNonZeroStart() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); For* head; For* tail; l.sliceTail(loops[0], 4, &head, &tail); // head: [0, 6) // tail: [6, 10) For* tail_head; For* tail_tail; l.sliceHead(tail, 2, &tail_head, &tail_tail); // tail_head: [6, 8) // tail_tail: [8, 10) Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 6}, {6, 8}, {8, 10}}); } void testExprSliceTailWhenFactorEqualsSize() { // When factor equals the For loop's original size, keep using the original // For loop. KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceTail(loops[0], 10, &head, &tail); ASSERT_EQ(head, nullptr); ASSERT_EQ(tail, loops[0]); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 10}}); } void testExprSliceTailWhenFactorLargerThanSize() { // When factor equals the For loop's original size, keep using the original // For loop. KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceTail(loops[0], 100, &head, &tail); ASSERT_EQ(head, nullptr); ASSERT_EQ(tail, loops[0]); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 10}}); } void testExprSliceTail() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceTail(loops[0], 4, &head, &tail); ASSERT_NE(head, nullptr); ASSERT_NE(head, loops[0]); ASSERT_NE(tail, nullptr); ASSERT_NE(tail, loops[0]); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 6}, {6, 10}}); } void testExprSplitAndSlice() { // 0: splitWithTail // 1: sliceTail on inner loop // 2: sliceHead on outer loop KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{100, "x"}}, func); LoopNest l({tensor}); For* outer; For* inner; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); // outer: [0, 4) // inner: [0, 21) // tail: [84, 100) l.splitWithTail(loops[0], 21, &outer, &inner, &tail); For* inner_head; For* inner_tail; l.sliceTail(inner, 2, &inner_head, &inner_tail); For* outer_head; For* outer_tail; l.sliceHead(outer, 2, &outer_head, &outer_tail); // for (int x_outer = 0; x_outer < 2; x_outer++) { // for (int x_inner = 0; x_inner < 19; x_inner++) { // f[21 * x_outer + x_inner] = 1.f + float(21 * x_outer + x_inner); // } // for (int x_inner = 19; x_inner < 21; x_inner++) { // f[21 * x_outer + x_inner] = 1.f + float(21 * x_outer + x_inner); // } // } // for (int x_outer = 2; x_outer < 4; x_outer++) { // for (int x_inner = 0; x_inner < 19; x_inner++) { // f[21 * x_outer + x_inner] = 1.f + float(21 * x_outer + x_inner); // } // for (int x_inner = 19; x_inner < 21; x_inner++) { // f[21 * x_outer + x_inner] = 1.f + float(21 * x_outer + x_inner); // } // } // for (int x_tail = 0; x_tail < 16; x_tail++) { // f[x_tail + 84] = 1.f + float(x_tail + 84); // } Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 2}, {2, 4}, {0, 16}}); auto biter = body->begin(); For* loop = dynamic_cast<For*>(*biter++); assertForRanges(loop->body(), {{0, 19}, {19, 21}}); loop = dynamic_cast<For*>(*biter); assertForRanges(loop->body(), {{0, 19}, {19, 21}}); } void testExprSliceAndNormalize() { // 0: sliceHead // 1: normalize tail KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); For* head; For* tail; l.sliceHead(loops[0], 2, &head, &tail); // head: [0, 2) // tail: [2, 10) For* normalized_tail; LoopNest::normalize(tail, &normalized_tail); // normalized_tail: [0, 8) Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 2}, {0, 8}}); } template <typename T> T evalExpr(const ExprHandle& expr, const VarHandle& var, T value) { ExprEval<SimpleIREvaluator> eval(expr, {var}); return eval.value<T>(value); } void testExprSliceWithVariableDimension() { auto testWithDimension = [](int dimension, const std::vector<std::pair<int, int>>& expected_for_ranges) { KernelScope kernel_scope; VarHandle dim("dim", kInt); Tensor* tensor = Compute("f", {{dim, "x"}}, [](const ExprHandle& x) { return x; }); LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); For* head; For* tail; l.sliceHead(loops[0], 2, &head, &tail); For* tail_head; For* tail_tail; l.sliceTail(tail, 2, &tail_head, &tail_tail); Block* body = getSimplifiedBody(l); ASSERT_EQ(expected_for_ranges.size(), 3); auto it = body->begin(); for (auto& start_stop : expected_for_ranges) { For* loop = dynamic_cast<For*>(*it++); int start = evalExpr<int>(ExprHandle(loop->start()), dim, dimension); int stop = evalExpr<int>(ExprHandle(loop->stop()), dim, dimension); ASSERT_EQ(start, start_stop.first); ASSERT_EQ(stop, start_stop.second); } }; testWithDimension(1, {{0, 1}, {1, 1}, {1, 1}}); testWithDimension(2, {{0, 2}, {2, 2}, {2, 2}}); testWithDimension(3, {{0, 2}, {2, 2}, {2, 3}}); testWithDimension(4, {{0, 2}, {2, 2}, {2, 4}}); testWithDimension(5, {{0, 2}, {2, 3}, {3, 5}}); testWithDimension(10, {{0, 2}, {2, 8}, {8, 10}}); } void testExprSplitWithTail() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{199, "x"}}, func); LoopNest l({tensor}); For* x_outer; For* x_inner; For* x_tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithTail(loops[0], 17, &x_outer, &x_inner, &x_tail); For* a; For* b; For* c; l.splitWithTail(x_outer, 7, &a, &b, &c); Stmt* stmt = l.root_stmt(); Stmt* simplified = IRSimplifier::simplify(stmt); Block* body = dynamic_cast<Block*>(simplified); ASSERT_EQ(body->nstmts(), 3); auto biter = body->begin(); // Verify that the split loops are ordered correctly. For* loop = dynamic_cast<For*>(*biter++); assertForRange(loop, 0, 7); loop = dynamic_cast<For*>(*biter++); assertForRange(loop, 0, 4); loop = dynamic_cast<For*>(*biter); assertForRange(loop, 0, 12); } void testExprSplitWithTailNone() { KernelScope kernel_scope; auto func = [](const ExprHandle& x, const ExprHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }; Tensor* tensor = Compute("f", {{24, "x"}, {5, "y"}}, func); LoopNest l({tensor}); For* x_outer; For* x_inner; For* x_tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithTail(loops[0], 4, &x_outer, &x_inner, &x_tail); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; ASSERT_GT(oss.str().size(), 200); ASSERT_LT(oss.str().size(), 600); { // Compare to a reference loop structure structure. VarHandle x_outer("x_outer", kInt); VarHandle x_inner("x_inner", kInt); VarHandle y("y", kInt); VarHandle x_tail("x_tail", kInt); BufHandle f("f", {24, 5}, kFloat); ExprHandle x_1 = x_outer * 4 + x_inner; ExprHandle x_outer_end = (ExprHandle(24) - 0) / 4; Stmt* stmt = new Block({For::make( x_outer, 0, x_outer_end, For::make( x_inner, 0, 4, For::make(y, 0, 5, Store::make(f, {x_1, y}, func(x_1, y), 1))))}); std::ostringstream oss_ref; oss_ref << *stmt; ASSERT_EQ(oss.str(), oss_ref.str()); } { PaddedBuffer<float> f_v(24, 5, "f_v"); PaddedBuffer<float> f_ref(24, 5, "f_res"); SimpleIREvaluator ir_eval(stmt, tensor); ir_eval(f_v); for (int x = 0; x < 24; x++) { for (int y = 0; y < 5; y++) { f_ref(x, y) = 1 + x * x + y * y; } } ExpectAllNear(f_v, f_ref, 1e-5); } } void testExprSplitWithMask01() { KernelScope kernel_scope; const int M = 26; const int N = 5; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {M, N}); Tensor* tensor = Compute( "f", {{M, "m"}, {N, "n"}}, [&](const ExprHandle& m, const ExprHandle& n) { return a_buf.load(m, n) + b_buf.load(m, n) + 1.0f; }); For* n_outer; For* n_inner; LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithMask(loops[1], 4, &n_outer, &n_inner); Stmt* stmt = l.root_stmt(); PaddedBuffer<float> a_v(M, N, "a"); PaddedBuffer<float> b_v(M, N, "b"); PaddedBuffer<float> c_v(M, N, "c"); PaddedBuffer<float> c_ref(M, N, "c_ref"); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { a_v(m, n) = 2 * m; b_v(m, n) = 3 * n; c_ref(m, n) = a_v(m, n) + b_v(m, n) + 1.0f; } } SimpleIREvaluator(stmt, a_buf, b_buf, tensor)(a_v, b_v, c_v); ExpectAllNear(c_v, c_ref, 1e-5); } // Tests the case where we split a loop cleanly multiple times, we should not // insert any masks. void testExprSplitWithMaskRepeatedNoMask() { KernelScope kernel_scope; const int M = 64; Placeholder a_buf("a", kFloat, {M}); Placeholder b_buf("b", kFloat, {M}); Tensor* tensor = Compute("f", {{M, "m"}}, [&](const ExprHandle& m) { return a_buf.load(m) + b_buf.load(m) + 1.0f; }); LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); For *outer, *mid, *inner; l.splitWithMask(loops[0], 4, &outer, &inner); l.splitWithMask(outer, 4, &outer, &mid); Stmt* stmt1 = IRSimplifier::simplify(l.root_stmt()); std::ostringstream oss; oss << *stmt1; // Two splits mean 3 loops, but should need no masks in this case. const std::string& verification_pattern = R"IR( # CHECK: for ( # CHECK-NOT: if ( # CHECK: for ( # CHECK-NOT: if ( # CHECK: for ( # CHECK-NOT: if ( # CHECK: f[)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } void testSplitWithTailWithLoopOptions() { KernelScope kernel_scope; const int M = 21; Placeholder a_buf("a", kFloat, {M}); Placeholder b_buf("b", kFloat, {M}); Tensor* tensor = Compute("f", {{M, "m"}}, [&](const ExprHandle& m) { return a_buf.load(m) + b_buf.load(m) + 1.0f; }); For *outer, *inner, *tail; LoopNest l({tensor}); auto loops = NodeFinder<For>::find(l.root_stmt()); ASSERT_GT(loops.size(), 0); l.setGPUBlockIndex(loops[0], LoopOptions::IDX_Y); l.splitWithTail(loops[0], 4, &outer, &inner, &tail); ASSERT_NE(outer, nullptr); ASSERT_NE(inner, nullptr); ASSERT_NE(tail, nullptr); // Outer loop carries loop axis bindings. ASSERT_TRUE(outer->loop_options().is_gpu_block_index()); ASSERT_EQ(outer->loop_options().gpu_block_index(), LoopOptions::IDX_Y); // Inner loop has none. ASSERT_TRUE(inner->loop_options().isDefault()); // Tail loop has none. ASSERT_TRUE(tail->loop_options().isDefault()); } void testSplitWithMaskWithLoopOptions() { KernelScope kernel_scope; const int M = 21; Placeholder a_buf("a", kFloat, {M}); Placeholder b_buf("b", kFloat, {M}); Tensor* tensor = Compute("f", {{M, "m"}}, [&](const ExprHandle& m) { return a_buf.load(m) + b_buf.load(m) + 1.0f; }); For *outer, *inner; LoopNest l({tensor}); auto loops = NodeFinder<For>::find(l.root_stmt()); l.setGPUBlockIndex(loops[0], LoopOptions::IDX_Y); l.splitWithMask(loops[0], 4, &outer, &inner); // Outer loop carries loop axis bindings. ASSERT_TRUE(outer->loop_options().is_gpu_block_index()); ASSERT_EQ(outer->loop_options().gpu_block_index(), LoopOptions::IDX_Y); // Inner loop has none. ASSERT_TRUE(inner->loop_options().isDefault()); } void testScheduleBroadcastAddBuffer() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Tensor* c = Compute( "broadcast_add", {{M, "m"}, {N, "n"}, {K, "k"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) + b_buf.load(n, k); }); LoopNest l({c}); Stmt* stmt = l.root_stmt(); PaddedBuffer<float> a_v(M, N, "a_v"); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { a_v(m, n) = 7 * m * n; } } a_v.Backup(); PaddedBuffer<float> b_v(N, K, "b_v"); for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { b_v(n, k) = 11 * n * k; } } b_v.Backup(); PaddedBuffer<float> c_v(M, N, K, "c_buf"); SimpleIREvaluator ir_eval(stmt, a_buf, b_buf, c); ir_eval(a_v, b_v, c_v); a_v.CheckBackup(); b_v.CheckBackup(); PaddedBuffer<float> c_ref(M, N, K, "c_ref"); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { c_ref(m, n, k) = 7 * m * n + 11 * n * k; } } } ExpectAllNear(c_v, c_ref, 1e-5); } void testScheduleFunctionCall01() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Tensor* c = Compute( "broadcast_add", {{M, "m"}, {N, "n"}, {K, "k"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) + b_buf.load(n, k); }); Tensor* d = Compute( "d", {{M, "m"}, {N, "n"}, {K, "k"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return c->call(m, n, k) + 1; }); LoopNest l({d}); l.prepareForCodegen(); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; ASSERT_GT(oss.str().size(), 100); PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); PaddedBuffer<float> c_v(M, N, K); PaddedBuffer<float> d_v(M, N, K); PaddedBuffer<float> d_ref(M, N, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < K; k++) { d_ref(i, j, k) = a_v(i, j) + b_v(j, k) + 1; } } } SimpleIREvaluator eval(stmt, a_buf, b_buf, d); eval(a_v, b_v, d_v); ExpectAllNear(d_v, d_ref, 1e-5); } void testScheduleInlineSimple() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Placeholder c_buf("c", kFloat, {M, N}); Placeholder d_buf("d", kFloat, {M, K}); Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return c_buf.load(m, n) * d_buf.load(m, k) + x->call(m, n, k); }); LoopNest l1({y}); LoopNest l2({y}); l2.computeInline(x->buf()); l1.prepareForCodegen(); l2.prepareForCodegen(); Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); Stmt* stmt2 = IRSimplifier::simplify(l2.root_stmt()); SimpleIREvaluator eval1(stmt1, a_buf, b_buf, c_buf, d_buf, y); SimpleIREvaluator eval2(stmt2, a_buf, b_buf, c_buf, d_buf, y); PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); PaddedBuffer<float> c_v(M, N); PaddedBuffer<float> d_v(M, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c_v(i, j) = i + j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < K; j++) { d_v(i, j) = i * j; } } PaddedBuffer<float> y_1(M, N, K); PaddedBuffer<float> y_2(M, N, K); eval1(a_v, b_v, c_v, d_v, y_1); eval2(a_v, b_v, c_v, d_v, y_2); ExpectAllNear(y_1, y_2, 1e-5); std::ostringstream oss1, oss2; oss1 << *stmt1; oss2 << *stmt2; ASSERT_GT(oss1.str().size(), oss2.str().size()); } static std::string remove_space(const std::string& str) { std::string str_new = str; str_new.erase( remove_if(str_new.begin(), str_new.end(), isspace), str_new.end()); return str_new; } void InlineFunc01Helper(const std::vector<std::string>& inline_order) { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Placeholder c_buf("c", kFloat, {M, N}); Placeholder d_buf("d", kFloat, {M, K}); Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return c_buf.load(m, n) * d_buf.load(m, k) + x->call(m, n, k); }); Tensor* z = Compute( "z", {{M, "m3"}, {N, "n3"}, {K, "k3"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m, n, k) + y->call(m, n, k); }); LoopNest l({z}); for (const std::string& order : inline_order) { if (order == "x") { l.computeInline(x->buf()); } else if (order == "y") { l.computeInline(y->buf()); } else { throw std::runtime_error("Invalid order: " + order); } } l.prepareForCodegen(); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; std::string str1 = remove_space(oss.str()); { PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); PaddedBuffer<float> c_v(M, N); PaddedBuffer<float> d_v(M, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c_v(i, j) = i + j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < K; j++) { d_v(i, j) = i * j; } } PaddedBuffer<float> z_v(M, N, K); PaddedBuffer<float> z_ref(M, N, K); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { z_ref(m, n, k) = a_v(m, n) * b_v(n, k) * 2 + c_v(m, n) * d_v(m, k); } } } SimpleIREvaluator eval(stmt, a_buf, b_buf, c_buf, d_buf, z); eval(a_v, b_v, c_v, d_v, z_v); ExpectAllNear(z_v, z_ref, 1e-5); } if (inline_order.size() == 2) { Tensor* z2 = Compute( "z", {{M, "m3"}, {N, "n3"}, {K, "k3"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k) + (c_buf.load(m, n) * d_buf.load(m, k) + a_buf.load(m, n) * b_buf.load(n, k)); }); LoopNest l2({z2}); l2.prepareForCodegen(); Stmt* stmt2 = l2.root_stmt(); std::ostringstream oss2; oss2 << *stmt2; std::string str2 = remove_space(oss2.str()); ASSERT_EQ(str1, str2); ASSERT_GT(str1.size(), 100); } } void testScheduleInlineFunc01() { InlineFunc01Helper({"x", "y"}); InlineFunc01Helper({"y", "x"}); InlineFunc01Helper({"x"}); InlineFunc01Helper({"y"}); InlineFunc01Helper({}); } // Make sure we cache random vars if we should. void testScheduleInlineRandom() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return Mod::make(Intrinsics::make(kRand, kInt), 5); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m, n, k) + x->call(m, n, k); }); LoopNest l1({y}); l1.computeInline(x->buf()); // would normally compare results but Rand isn't implemented in the // SimpleIREvaluator, even if we could seed it. Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); std::ostringstream oss; oss << *stmt1; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int m2 = 0; m2 < 4; m2++) # CHECK: for (int n2 = 0; n2 < 5; n2++) # CHECK: for (int k2 = 0; k2 < 6; k2++) # CHECK: int x = rand(); # CHECK: y[m2, n2, k2] = 2 * (x % 5);)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } // Make sure we don't cache random vars that are not being inlined. void testScheduleInlineRandomUnrelated() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return m * n * k; }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m, n, k) + Intrinsics::make(kRand, kInt) + Intrinsics::make(kRand, kInt); }); LoopNest l1({y}); l1.computeInline(x->buf()); // would normally compare results but Rand isn't implemented in the // SimpleIREvaluator, even if we could seed it. Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); std::ostringstream oss; oss << *stmt1; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int m2 = 0; m2 < 4; m2++) # CHECK: for (int n2 = 0; n2 < 5; n2++) # CHECK: for (int k2 = 0; k2 < 6; k2++) # CHECK: y[m2, n2, k2] = ((n2 * m2) * k2 + (rand())) + (rand());)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } // Make sure we generate the right number of random values == the dimensionality // of the production tensor. void testScheduleInlineRandomLowerDimensions() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Tensor* x = Compute("x", {{M, "m1"}}, [&](const VarHandle& m) { return Mod::make(Intrinsics::make(kRand, kInt), 5); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m) + x->call(m); }); LoopNest l1({y}); l1.computeInline(x->buf()); // would normally compare results but Rand isn't implemented in the // SimpleIREvaluator, even if we could seed it. Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); std::ostringstream oss; oss << *stmt1; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int m2 = 0; m2 < 4; m2++) # CHECK: int x = rand(); # CHECK: for (int n2 = 0; n2 < 5; n2++) # CHECK: for (int k2 = 0; k2 < 6; k2++) # CHECK: y[m2, n2, k2] = 2 * (x % 5);)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } // Make sure we don't screw up intrinsics thinking they're rand. void testScheduleInlineIntrinsics() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return Intrinsics::make(kSqrt, x->call(m, n, k)); }); PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } LoopNest l1({y}); LoopNest l2({y}); l2.computeInline(x->buf()); l1.prepareForCodegen(); l2.prepareForCodegen(); Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); Stmt* stmt2 = IRSimplifier::simplify(l2.root_stmt()); SimpleIREvaluator eval1(stmt1, a_buf, b_buf, y); SimpleIREvaluator eval2(stmt2, a_buf, b_buf, y); PaddedBuffer<float> y_1(M, N, K); PaddedBuffer<float> y_2(M, N, K); eval1(a_v, b_v, y_1); eval2(a_v, b_v, y_2); ExpectAllNear(y_1, y_2, 1e-5); std::ostringstream oss1, oss2; oss1 << *stmt1; oss2 << *stmt2; ASSERT_GT(oss1.str().size(), oss2.str().size()); } // Make sure we can handle rand and non-rand intrinsics. void testScheduleInlineRandWithIntrinsics() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return Intrinsics::make(kRand, kFloat); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return Intrinsics::make(kSqrt, x->call(m, n, k)); }); LoopNest l1({y}); l1.computeInline(x->buf()); Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); std::ostringstream oss; oss << *stmt1; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int m2 = 0; m2 < 4; m2++) # CHECK: for (int n2 = 0; n2 < 5; n2++) # CHECK: for (int k2 = 0; k2 < 6; k2++) # CHECK: float x = rand(); # CHECK: y[m2, n2, k2] = sqrt(x);)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } // Split a Compute then inline it into another compute. void testScheduleSplitAThenInline() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{2, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.splitWithMask(loops[0], 4, &i_outer, &i_inner); ASSERT_THROWS_WITH(l.computeInline(a->buf()), "compound indices"); } // Split a Compute then inline another Compute into it. void testScheduleSplitBThenInline() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); std::vector<For*> loops = l.getLoopStmtsFor(b); l.splitWithMask(loops[0], 3, &i_outer, &i_inner); l.computeInline(a->buf()); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(6, 0); SimpleIREvaluator eval(s, b); eval(output); for (int i = 0; i < 6; ++i) { ASSERT_EQ(output[i], (i + 8) * (i + 8)); } } // Split a Compute twice then inline it. void testScheduleSplitTwiceThenInline() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{2, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.splitWithMask(loops[0], 4, &i_outer, &i_inner); l.splitWithMask(i_inner, 2, &i_outer, &i_inner); ASSERT_THROWS_WITH(l.computeInline(a->buf()), "compound indices"); } // Inline a Compute, then split. void testScheduleInlineThenSplit() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); l.computeInline(a->buf()); std::vector<For*> loops = NodeFinder<For>::find(l.root_stmt()); l.splitWithMask(loops.back(), 3, &i_outer, &i_inner); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(6, 0); SimpleIREvaluator eval(s, b); eval(output); for (int i = 0; i < 6; ++i) { ASSERT_EQ(output[i], (i + 8) * (i + 8)); } } // Split a Compute, inline it, then split the result. void testScheduleSplitInlineThenSplit() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{16, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); auto loops = NodeFinder<For>::find(l.root_stmt()); l.splitWithMask(loops.back(), 2, &i_outer, &i_inner); l.computeInline(a->buf()); loops = NodeFinder<For>::find(l.root_stmt()); l.splitWithMask(loops.front(), 2, &i_outer, &i_inner); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(16, 0); SimpleIREvaluator eval(s, b); eval(output); for (int i = 0; i < 16; ++i) { ASSERT_EQ(output[i], (i + 8) * (i + 8)); } } // Oversplit a loop that is simplified out after inlining. void testScheduleSplitInlineSimplify() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return ExprHandle(4) * i - ExprHandle(2) * i; }); Tensor* b = Compute("b", {{2, "j"}}, [&](const VarHandle& j) { return a->call(j) - ExprHandle(1); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.splitWithMask(loops[0], 4, &i_outer, &i_inner); ASSERT_THROWS_WITH(l.computeInline(a->buf()), "compound indices"); } // Inline a Compute with two consumers. void testScheduleInlineThreeMixedOnce() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); Tensor* c = Compute( "c", {{4, "k"}, {3, "l"}}, [&](const VarHandle& k, const VarHandle& l) { return a->call(k) * b->call(l); }); LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.computeInline(a->buf()); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(4 * 3, 0); SimpleIREvaluator eval(s, c); eval(output); for (int k = 0; k < 4; ++k) { for (int l = 0; l < 3; ++l) { ASSERT_EQ(output[k * 3 + l], (k) * (k) * (l + 8) * (l + 8)); } } } // Inline Compute A into B, then inline B into C. void testScheduleInlineThreeMixedTwice() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); Tensor* c = Compute( "c", {{4, "k"}, {3, "l"}}, [&](const VarHandle& k, const VarHandle& l) { return a->call(k) * b->call(l); }); LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.computeInline(a->buf()); l.computeInline(b->buf()); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(4 * 3, 0); SimpleIREvaluator eval(s, c); eval(output); for (int k = 0; k < 4; ++k) { for (int l = 0; l < 3; ++l) { ASSERT_EQ(output[k * 3 + l], (k) * (k) * (l + 8) * (l + 8)); } } } // Inline a Compute that is both a producer and consumer. void testScheduleInlineThreeMixedInner() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); Tensor* c = Compute( "c", {{4, "k"}, {3, "l"}}, [&](const VarHandle& k, const VarHandle& l) { return a->call(k) * b->call(l); }); LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.computeInline(b->buf()); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(4 * 3, 0); SimpleIREvaluator eval(s, c); eval(output); for (int k = 0; k < 4; ++k) { for (int l = 0; l < 3; ++l) { ASSERT_EQ(output[k * 3 + l], (k) * (k) * (l + 8) * (l + 8)); } } } // Split 3 Computes, then inline the first two into the last. void testScheduleInlineThreeMixedSplit() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); Tensor* c = Compute( "c", {{4, "k"}, {3, "l"}}, [&](const VarHandle& k, const VarHandle& l) { return a->call(k) * b->call(l); }); For* i_outer; For* i_inner; LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.splitWithMask(loops[0], 4, &i_outer, &i_inner); loops = l.getLoopStmtsFor(b); l.splitWithMask(loops[0], 3, &i_outer, &i_inner); loops = l.getLoopStmtsFor(c); l.splitWithMask(loops[0], 2, &i_outer, &i_inner); ASSERT_THROWS_WITH(l.computeInline(a->buf()), "compound indices"); } void testScheduleFuserStyle() { KernelScope kernel_scope; const int kVectorSize = 8; const int kVectorCount = 128; const int kTotalSize = kVectorSize * kVectorCount; Placeholder a_buf(BufHandle("A", {ExprHandle(kTotalSize)}, kFloat)); Tensor* b = Compute( "f", {{kTotalSize, "i"}}, [&](const std::vector<VarHandle>& axes) { return a_buf.load(axes[0]) + 11.0f; }); Tensor* c = Compute( "g", {{kTotalSize, "i"}}, [&](const std::vector<VarHandle>& axes) { return b->call(axes[0]) + 1.0f; }); LoopNest l({b, c}); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::vector<float> a_data(kTotalSize, 7.0f); std::vector<float> b_data(kTotalSize, 0.0f); std::vector<float> c_data(kTotalSize, 0.0f); SimpleIREvaluator(s, a_buf, b, c)(a_data, b_data, c_data); for (int i = 0; i < kTotalSize; i++) { ASSERT_EQ(b_data[i], 18.0f); ASSERT_EQ(c_data[i], 19.0f); } } void testScheduleFuserThreeArg() { KernelScope kernel_scope; const int kVectorSize = 8; const int kVectorCount = 128; const int kTotalSize = kVectorSize * kVectorCount; Placeholder a(BufHandle("A", {ExprHandle(kTotalSize)}, kFloat)); Placeholder b(BufHandle("B", {ExprHandle(kTotalSize)}, kFloat)); Placeholder c(BufHandle("C", {ExprHandle(kTotalSize)}, kFloat)); Placeholder d(BufHandle("D", {ExprHandle(kTotalSize)}, kFloat)); Tensor* e = Compute("e", {{kTotalSize, "i"}}, [&](const VarHandle& i) { return a.load(i) + b.load(i); }); Tensor* f = Compute("f", {{kTotalSize, "i"}}, [&](const VarHandle& i) { return e->call(i) + c.load(i); }); Tensor* g = Compute("g", {{kTotalSize, "i"}}, [&](const VarHandle& i) { return f->call(i) + d.load(i); }); LoopNest l({g}); l.computeInline(l.getLoopBodyFor(e)); l.computeInline(l.getLoopBodyFor(f)); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::vector<float> a_data(kTotalSize, 1.0f); std::vector<float> b_data(kTotalSize, 2.0f); std::vector<float> c_data(kTotalSize, 3.0f); std::vector<float> d_data(kTotalSize, 4.0f); std::vector<float> g_data(kTotalSize, 0.0f); SimpleIREvaluator(s, a, b, c, d, g)(a_data, b_data, c_data, d_data, g_data); for (int i = 0; i < kTotalSize; i++) { ASSERT_EQ(g_data[i], 10.0f); } } void testScheduleDynamicShape2D() { KernelScope kernel_scope; auto testWithSize = [](int32_t M, int32_t N) { VarHandle m("m", kInt); VarHandle n("n", kInt); Placeholder a(BufHandle("a", {m, n}, kFloat)); Placeholder b(BufHandle("b", {m, n}, kFloat)); Tensor* c = Compute( "c", {{m, "m"}, {n, "n"}}, [&](const VarHandle& i, const VarHandle& j) { return a.load(i, j) + b.load(i, j); }); LoopNest l({c}); Stmt* s = l.root_stmt(); SimpleIREvaluator cg(s, {a, b, c, m, n}); std::vector<float> aData(M * N, 1.0f); std::vector<float> bData(M * N, 2.0f); std::vector<float> cData(M * N, 0.0f); cg.call({aData, bData, cData, M, N}); ExpectAllNear(cData, std::vector<float>(M * N, 3.0f), 1e-7); }; testWithSize(1, 8); testWithSize(16, 32); testWithSize(37, 11); } void testLoopNestComputeAt_1() { // Verify that compute_at works on the following example: // // for (int i_a = 0; i_a < N; i_a++) { // A[i_a] = i_a * i_a // } // for (int i_b = 0; i_b < N; i_b++) { // B[i_b] = A[i_b] // } // // After the transformation the i_b loop should have an allocation for a temp // buffer and that buffer should be used in computation of B. No use of A // should be in that loop after the transformation. Also, computation of A // should not be inlined into B. Instead, it should be computed into the temp, // and the temp should be used in B. KernelScope kernel_scope; VarHandle N("N", kInt); Tensor* A = Compute( "A", {{N, "i_a"}}, [&](const VarHandle& i_a) { return i_a * i_a; }); Tensor* B = Compute( "B", {{N, "i_b"}}, [&](const VarHandle& i_b) { return A->call(i_b); }); LoopNest l({B}); std::vector<For*> loops = l.getLoopStmtsFor(B); l.computeAt(l.getLoopBodyFor(A), loops[0]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; const std::string& verification_pattern = R"IR( # CHECK: for (int i_b = 0; i_b < N; i_b++) # CHECK: Allocate(temp, int, {1}) # CHECK: temp[ # CHECK-NOT: A[ # CHECK: B[i_b] = temp[0] # CHECK: Free(temp))IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> b_data(100, 0); SimpleIREvaluator cg(s, {B, N}); cg.call({b_data, 100}); std::vector<int> b_ref(100, 0); for (int i = 0; i < 100; i++) { b_ref[i] = i * i; } assertAllEqual(b_data, b_ref); } void testLoopNestComputeAt_2() { // Verify that compute_at works on the following example: // // for (int py = 0; py < H+1; py++) { // for (int px = 0; px < W+1; px++) { // p[py, px] = py*px // } // } // for (int cy = 0; cy < H; cy++) { // for (int cx = 0; cx < W; cx++) { // c[py, px] = p[cy,cx] + p[cy+1,cx] + // p[cy,cx+1] + p[cy+1,cx+1] // } // } KernelScope kernel_scope; const int kW = 16, kH = 16; VarHandle W("W", kInt); VarHandle H("H", kInt); Tensor* p = Compute( "prod", {{H + 1, "py"}, {W + 1, "px"}}, [&](const VarHandle& py, const VarHandle& px) { return px * py; }); Tensor* c = Compute( "cons", {{H, "cy"}, {W, "cx"}}, [&](const VarHandle& y, const VarHandle& x) { return p->call(y, x) + p->call(y + 1, x) + p->call(y, x + 1) + p->call(y + 1, x + 1); }); std::vector<int> c_ref(kW * kH, 0); for (int y = 0; y < kH; y++) { for (int x = 0; x < kW; x++) { c_ref[y * kW + x] = y * x + (y + 1) * x + y * (x + 1) + (y + 1) * (x + 1); } } { // First let's try to compute P at axis cy (the outer loop) LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(c); l.computeAt(l.getLoopBodyFor(p), loops[0]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int cy = 0; cy < H; cy++) # CHECK: Allocate(temp, int, {2, W + 1}) # CHECK: for # CHECK: for # CHECK: for (int cx = 0; cx < W; cx++) # CHECK-NOT: prod[ # CHECK: cons[ # CHECK: Free(temp))IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> c_data(kW * kH, 0); SimpleIREvaluator cg(s, {c, W, H}); cg.call({c_data, kW, kH}); assertAllEqual(c_data, c_ref); } { // Now let's try to compute P at axis cx (the inner loop) LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(c); l.computeAt(l.getLoopBodyFor(p), loops[1]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int cy = 0; cy < H; cy++) # CHECK: for (int cx = 0; cx < W; cx++) # CHECK: Allocate(temp, int, {2, 2}) # CHECK: for # CHECK: for # CHECK-NOT: prod[ # CHECK: cons[ # CHECK: Free(temp))IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> c_data(kW * kH, 0); SimpleIREvaluator cg(s, {c, W, H}); cg.call({c_data, kW, kH}); assertAllEqual(c_data, c_ref); } } void testLoopNestComputeAt_3() { // Verify that compute_at works on the following example: // // A(x,y) = x*y // B(x,y) = A(x, y) // C(x,y) = B(x+1, y) // D(x,y) = A(x, y+1) + C(x, y) // // i.e. when 'A' comes to 'D' directly and indirectly through 'C'. KernelScope kernel_scope; const int kW = 16, kH = 16; VarHandle W("W", kInt); VarHandle H("H", kInt); Tensor* A = Compute( "A", {{H + 1, "ay"}, {W + 1, "ax"}}, [&](const VarHandle& ay, const VarHandle& ax) { return ax * ay; }); Tensor* B = Compute( "B", {{H + 1, "by"}, {W + 1, "bx"}}, [&](const VarHandle& by, const VarHandle& bx) { return A->call(by, bx); }); Tensor* C = Compute( "C", {{H, "cy"}, {W, "cx"}}, [&](const VarHandle& cy, const VarHandle& cx) { return B->call(cy, cx + 1); }); Tensor* D = Compute( "D", {{H, "dy"}, {W, "dx"}}, [&](const VarHandle& dy, const VarHandle& dx) { return A->call(dy + 1, dx) + C->call(dy, dx); }); std::vector<int> c_ref(kW * kH, 0); for (int y = 0; y < kH; y++) { for (int x = 0; x < kW; x++) { c_ref[y * kW + x] = (y + 1) * x + y * (x + 1); } } { // First let's try to compute A at axis dy (the outer loop) LoopNest l({D}); std::vector<For*> loops = l.getLoopStmtsFor(D); l.computeAt(l.getLoopBodyFor(A), loops[0]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int ay = 0; ay < H + 1; ay++) # CHECK: for (int ax = 0; ax < W + 1; ax++) # CHECK: A[ # CHECK: for (int by = 0; by < H + 1; by++) # CHECK: for (int bx = 0; bx < W + 1; bx++) # CHECK: B[ # CHECK: for (int cy = 0; cy < H; cy++) # CHECK: for (int cx = 0; cx < W; cx++) # CHECK: C[ # CHECK: for (int dy = 0; dy < H; dy++) # CHECK: Allocate(temp, int, {1, W}) # CHECK: for (int dx = 0; dx < W; dx++) # CHECK-NOT: A[)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> c_data(kW * kH, 0); SimpleIREvaluator cg(s, {D, W, H}); cg.call({c_data, kW, kH}); assertAllEqual(c_data, c_ref); } { // Now let's try to compute A at axis dx (the inner loop) LoopNest l({D}); std::vector<For*> loops = l.getLoopStmtsFor(D); l.computeAt(l.getLoopBodyFor(A), loops[1]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int ay = 0; ay < H + 1; ay++) # CHECK: for (int ax = 0; ax < W + 1; ax++) # CHECK: A[ # CHECK: for (int by = 0; by < H + 1; by++) # CHECK: for (int bx = 0; bx < W + 1; bx++) # CHECK: B[ # CHECK: for (int cy = 0; cy < H; cy++) # CHECK: for (int cx = 0; cx < W; cx++) # CHECK: C[ # CHECK: for (int dy = 0; dy < H; dy++) # CHECK: for (int dx = 0; dx < W; dx++) # CHECK: Allocate(temp, int, {1, 1}) # CHECK-NOT: A[)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> c_data(kW * kH, 0); SimpleIREvaluator cg(s, {D, W, H}); cg.call({c_data, kW, kH}); assertAllEqual(c_data, c_ref); } } void testLoopNestComputeAt_4() { // TODO: Verify that computeAt works with reduction axis } class LoopOrderHelper : public IRVisitor { std::stringstream ordering; public: std::string getOrder(Stmt* s) { ordering.str(""); s->accept(this); return ordering.str(); } void visit(const For* v) { ordering << v->var()->name_hint() << ","; IRVisitor::visit(v); } }; void testLoopNestReorderAxis1() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{2, "x"}, {3, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); Stmt* stmt1 = Stmt::clone(l.root_stmt()); std::vector<int> stmt1_output(6, 0); SimpleIREvaluator cg(stmt1, {tensor}); cg.call({stmt1_output}); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[1]); Stmt* stmt2 = Stmt::clone(l.root_stmt()); ASSERT_NE(stmt1, stmt2); LoopOrderHelper loopOrderHelper; std::string order1 = loopOrderHelper.getOrder(stmt1); std::string order2 = loopOrderHelper.getOrder(stmt2); ASSERT_EQ(order1, "x,y,"); ASSERT_EQ(order2, "y,x,"); std::vector<int> stmt2_output(6, 0); SimpleIREvaluator cg2(stmt2, {tensor}); cg.call({stmt2_output}); for (int i = 0; i < 6; ++i) { ASSERT_EQ(stmt1_output[i], stmt2_output[i]); } // Reorder them back. loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[1]); Stmt* stmt3 = l.root_stmt(); std::string order3 = loopOrderHelper.getOrder(stmt3); ASSERT_EQ(order3, order1); std::ostringstream oss1, oss2; oss1 << *stmt1; oss2 << *stmt3; // Should be identical to the unreordered statement. ASSERT_EQ(oss1.str(), oss2.str()); } void testLoopNestReorderPartialAxes() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{2, "x"}, {3, "y"}, {4, "z"}}, [](const VarHandle& x, const VarHandle& y, const VarHandle& z) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y + cast<float>(z) * z; }); LoopNest l({tensor}); LoopOrderHelper loopOrderHelper; Stmt* stmt1 = Stmt::clone(l.root_stmt()); ASSERT_EQ(loopOrderHelper.getOrder(stmt1), "x,y,z,"); std::vector<int> stmt1_output(24, 0); SimpleIREvaluator cg(stmt1, {tensor}); cg.call({stmt1_output}); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[1]); ASSERT_EQ(loopOrderHelper.getOrder(l.root_stmt()), "y,x,z,"); Stmt* stmt2 = Stmt::clone(l.root_stmt()); std::vector<int> stmt2_output(24, 0); SimpleIREvaluator cg2(stmt2, {tensor}); cg2.call({stmt2_output}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(stmt1_output[i], stmt2_output[i]); } loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[1], loops[2]); ASSERT_EQ(loopOrderHelper.getOrder(l.root_stmt()), "y,z,x,"); Stmt* stmt3 = Stmt::clone(l.root_stmt()); std::vector<int> stmt3_output(24, 0); SimpleIREvaluator cg3(stmt3, {tensor}); cg3.call({stmt3_output}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(stmt1_output[i], stmt3_output[i]); } } void testLoopNestReorderInternalAxis() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{1, "w"}, {2, "x"}, {3, "y"}, {4, "z"}}, [](const VarHandle& w, const VarHandle& x, const VarHandle& y, const VarHandle& z) { return ExprHandle(1.0f) + w + cast<float>(x) * x + cast<float>(y) * y + cast<float>(z) * z; }); LoopNest l({tensor}); LoopOrderHelper loopOrderHelper; Stmt* stmt1 = Stmt::clone(l.root_stmt()); ASSERT_EQ(loopOrderHelper.getOrder(stmt1), "w,x,y,z,"); std::vector<int> stmt1_output(24, 0); SimpleIREvaluator cg(stmt1, {tensor}); cg.call({stmt1_output}); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[2], loops[1]); ASSERT_EQ(loopOrderHelper.getOrder(l.root_stmt()), "w,y,x,z,"); Stmt* stmt2 = l.root_stmt(); std::vector<int> stmt2_output(24, 0); SimpleIREvaluator cg2(stmt2, {tensor}); cg2.call({stmt2_output}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(stmt1_output[i], stmt2_output[i]); } } void testLoopNestReorderEnclosingAxis() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{1, "w"}, {2, "x"}, {3, "y"}, {4, "z"}}, [](const VarHandle& w, const VarHandle& x, const VarHandle& y, const VarHandle& z) { return ExprHandle(1.0f) + w + cast<float>(x) * x + cast<float>(y) * y + cast<float>(z) * z; }); LoopNest l({tensor}); LoopOrderHelper loopOrderHelper; Stmt* stmt1 = Stmt::clone(l.root_stmt()); std::vector<int> stmt1_output(24, 0); SimpleIREvaluator cg(stmt1, {tensor}); cg.call({stmt1_output}); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[3]); ASSERT_EQ(loopOrderHelper.getOrder(l.root_stmt()), "z,x,y,w,"); Stmt* stmt2 = l.root_stmt(); std::vector<int> stmt2_output(24, 0); SimpleIREvaluator cg2(stmt2, {tensor}); cg2.call({stmt2_output}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(stmt1_output[i], stmt2_output[i]); } } void testLoopNestReorderSameAxis() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{2, "x"}, {3, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); Stmt* stmt1 = Stmt::clone(l.root_stmt()); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[1], loops[1]); Stmt* stmt2 = Stmt::clone(l.root_stmt()); std::ostringstream oss, oss2; oss << *stmt1; oss2 << *stmt2; ASSERT_EQ(oss.str(), oss2.str()); } void testLoopNestReorderExtraStatements() { /* We're going for a structure like this: * for x in ... * Stmt 1 * for y in ... * Stmt 2 * for z in ... * Stmt 3 * Stmt 4 */ KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{2, "x"}, {3, "y"}, {4, "z"}}, [](const VarHandle& x, const VarHandle& y, const VarHandle& z) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y + cast<float>(z) * z; }); LoopNest l({tensor}); Placeholder extra(BufHandle("res", {6, 3}, kFloat)); auto loops = l.getLoopStmtsFor(tensor); VarHandle i = VarHandle(loops[0]->var()); Stmt* store_1 = Store::make(BufHandle(extra.data()), {i, 0}, ExprHandle(1.f), 1); Stmt* store_2 = Store::make(BufHandle(extra.data()), {i, 1}, ExprHandle(2.f), 1); // stmt 3 is the Function body. Stmt* store_3 = Store::make(BufHandle(extra.data()), {i, 2}, ExprHandle(4.f), 1); loops[0]->body()->prepend_stmt(store_1); loops[1]->body()->prepend_stmt(store_2); loops[1]->body()->append_stmt(store_3); Stmt* stmt1 = Stmt::clone(l.root_stmt()); std::vector<int> extra1(6, 0); std::vector<int> res1(24, 0); SimpleIREvaluator cg(stmt1, {tensor, extra}); cg.call({res1, extra1}); /* Then we reorder loop y and z, we want it to look like: * * for x in ... * Stmt 1 * for y in ... * Stmt 2 * for z in ... * for y in ... * Stmt 3 * for y in ... * Stmt 4 * * We need extra loops because we don't have dependency info about stmt 3 * and 4. * */ l.reorderAxis(loops[1], loops[2]); Stmt* stmt2 = Stmt::clone(l.root_stmt()); std::ostringstream oss; oss << *l.root_stmt(); // Check the IR we produced const std::string& verification_pattern1 = R"IR( # CHECK: for (int x # CHECK: res[x, 0] = 1 # CHECK: for (int y # CHECK: res[x, 1] = 2 # CHECK: for (int z # CHECK: for (int y # CHECK: f[ # CHECK: for (int y # CHECK: res[x, 2] = 4 )IR"; torch::jit::testing::FileCheck().run(verification_pattern1, oss.str()); std::vector<int> extra2(6, 0); std::vector<int> res2(24, 0); SimpleIREvaluator cg2(stmt2, {tensor, extra}); cg2.call({res2, extra2}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(res1[i], res2[i]); } for (int i = 0; i < 6; ++i) { ASSERT_EQ(extra1[i], extra2[i]); } /* Now reorder x and the y above stmt 3: * * * for x in ... * Stmt 1 * for y in ... * Stmt 2 * * for y in ... * for z in ... * for x in ... * Stmt 3 * * for x in ... * for y in ... * Stmt 4 * * */ loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[2]); Stmt* stmt3 = Stmt::clone(l.root_stmt()); std::ostringstream oss2; oss2 << *stmt3; // Check the IR we produced const std::string& verification_pattern2 = R"IR( # CHECK: for (int x # CHECK: res[x, 0] = 1 # CHECK: for (int y # CHECK: res[x, 1] = 2 # CHECK: for (int y # CHECK: for (int z # CHECK: for (int x # CHECK: f[ # CHECK: for (int x # CHECK: for (int y # CHECK: res[x, 2] = 4 )IR"; torch::jit::testing::FileCheck().run(verification_pattern2, oss2.str()); std::vector<int> extra3(6, 0); std::vector<int> res3(24, 0); SimpleIREvaluator cg3(stmt3, {tensor, extra}); cg3.call({res3, extra3}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(res1[i], res3[i]); } for (int i = 0; i < 6; ++i) { ASSERT_EQ(extra1[i], extra3[i]); } } void LoopNestReorderTestHelper( bool prepend, bool append, int index1, int index2) { KernelScope kernel_scope; Tensor* c = Compute( "5d", {{2, "a"}, {3, "b"}, {2, "c"}, {3, "d"}, {2, "e"}}, [](const std::vector<VarHandle>&) { return -1; }); LoopNest l({c}); Placeholder extra(BufHandle("extra", {5}, kInt)); auto loops = l.getLoopStmtsFor(c); int j = 0; for (auto* l : loops) { // Add an increment at each layer of the loop which counts the number of // times the loop executes. Load* load = new Load(extra.data(), {new IntImm(j)}, new IntImm(1)); Add* add = new Add(load, new IntImm(1)); Stmt* store = new Store(extra.data(), {new IntImm(j)}, add, new IntImm(1)); if (prepend) { l->body()->prepend_stmt(store); } if (append) { l->body()->append_stmt(Stmt::clone(store)); } j++; } Stmt* stmt1 = Stmt::clone(l.root_stmt()); std::vector<int> extra1(5, 0); std::vector<int> res1(2 * 3 * 2 * 3 * 2, 0); SimpleIREvaluator cg(stmt1, {c, extra}); cg.call({res1, extra1}); std::vector<int> loopExtents = {2, 3, 2, 3, 2}; int expected_loops = 0; if (prepend) { expected_loops++; } if (append) { expected_loops++; } for (int i = 0; i < 5; ++i) { expected_loops *= loopExtents[i]; ASSERT_EQ(extra1[i], expected_loops); } loops = l.getLoopStmtsFor(c); l.reorderAxis(loops[index1], loops[index2]); Stmt* stmt2 = Stmt::clone(l.root_stmt()); std::ostringstream oss, oss2; oss << *stmt1; oss2 << *stmt2; ASSERT_NE(oss.str(), oss2.str()); std::vector<int> extra2(5, 0); std::vector<int> res2(2 * 3 * 2 * 3 * 2, 0); SimpleIREvaluator cg2(stmt2, {c, extra}); cg2.call({res2, extra2}); expected_loops = 0; if (prepend) { expected_loops++; } if (append) { expected_loops++; } for (int i = 0; i < 5; ++i) { expected_loops *= loopExtents[i]; ASSERT_EQ(extra2[i], expected_loops); } for (int i = 0; i < 2 * 3 * 2 * 3 * 2; ++i) { ASSERT_EQ(res2[i], res1[i]); } } void testLoopNestReorderLongStringOfPreOrphans() { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { // skip noops, since we check the loop isn't the same after reordering. if (i != j) { LoopNestReorderTestHelper(true, false, i, j); } } } } void testLoopNestReorderLongStringOfPostOrphans() { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { // skip noops, since we check the loop isn't the same after reordering. if (i != j) { LoopNestReorderTestHelper(false, true, i, j); } } } } void testLoopNestReorderLongStringFull() { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { // skip noops, since we check the loop isn't the same after reordering. if (i != j) { LoopNestReorderTestHelper(true, true, i, j); } } } } void testLoopNestReorderInternalLoopNest() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Placeholder c_buf("c", kFloat, {M, N}); Placeholder d_buf("d", kFloat, {M, K}); Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return c_buf.load(m, n) * d_buf.load(m, k) + x->call(m, n, k); }); Tensor* z = Compute( "z", {{M, "m3"}, {N, "n3"}, {K, "k3"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m, n, k) + y->call(m, n, k); }); LoopNest l({z}); For* a = nullptr; For* b = nullptr; auto fors = NodeFinder<For>::find(l.root_stmt()); for (auto* f : fors) { if (f->var()->name_hint() == "m2") { a = f; } else if (f->var()->name_hint() == "k2") { b = f; } } l.reorderAxis(a, b); l.prepareForCodegen(); Stmt* stmt = IRSimplifier::simplify(l.root_stmt()); std::ostringstream oss; oss << *stmt; // Check the IR we produced has the 3 nests in the right order, but k and m // swapped in the middle. const std::string& verification_pattern = R"IR( # CHECK: for (int m1 # CHECK: for (int n1 # CHECK: for (int k1 # CHECK: for (int k2 # CHECK: for (int n2 # CHECK: for (int m2 # CHECK: for (int m3 # CHECK: for (int n3 # CHECK: for (int k3)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); { PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); PaddedBuffer<float> c_v(M, N); PaddedBuffer<float> d_v(M, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c_v(i, j) = i + j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < K; j++) { d_v(i, j) = i * j; } } PaddedBuffer<float> z_v(M, N, K); PaddedBuffer<float> z_ref(M, N, K); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { z_ref(m, n, k) = a_v(m, n) * b_v(n, k) * 2 + c_v(m, n) * d_v(m, k); } } } SimpleIREvaluator eval(stmt, a_buf, b_buf, c_buf, d_buf, z); eval(a_v, b_v, c_v, d_v, z_v); ExpectAllNear(z_v, z_ref, 1e-5); } } void testOuterLoopVectorization() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{8, "X"}, {8, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); l.vectorize(l.getLoopStmtsFor(tensor)[0]); Stmt* root_stmt = l.root_stmt(); Block* outer_block = dynamic_cast<Block*>(root_stmt); ASSERT_NE(outer_block, nullptr); while (Block* inner_block = dynamic_cast<Block*>(outer_block->front())) { outer_block = inner_block; } // Verify that we have only a single loop level remaining after // vectorization. ASSERT_EQ(outer_block->nstmts(), 1); For* for_loop = dynamic_cast<For*>(outer_block->front()); ASSERT_NE(for_loop, nullptr); Block* for_body = for_loop->body(); ASSERT_EQ(for_body->nstmts(), 1); ASSERT_EQ(dynamic_cast<For*>(for_body->front()), nullptr); } namespace { std::string constantUpperBoundLoopIR(int upper_bound_val) { KernelScope kernel_scope; ExprHandle upper_bound(upper_bound_val); Tensor* A = Compute( "A", {{upper_bound, "x"}}, [&](const VarHandle& x) { return x * 2; }); LoopNest l({A}); std::vector<For*> loops = l.getLoopStmtsFor(A); Stmt* unrolled = nullptr; LoopNest::unroll(loops[0], &unrolled); std::ostringstream oss; oss << *unrolled; return oss.str(); } } // namespace void testUnroll() { const std::string actual = constantUpperBoundLoopIR(3); const std::string& verification_pattern = R"IR( # CHECK: A[0] = 0; # CHECK: A[1] = 2; # CHECK: A[2] = 4)IR"; torch::jit::testing::FileCheck().run(verification_pattern, actual); } void testUnrollOuter() { KernelScope kernel_scope; ExprHandle outer_bound(3); ExprHandle inner_bound(4); Tensor* A = Compute( "A", {{outer_bound, "x"}, {inner_bound, "y"}}, [&](const VarHandle& x, const VarHandle& y) { return x + y; }); LoopNest l({A}); std::vector<For*> loops = l.getLoopStmtsFor(A); Stmt* unrolled = nullptr; LoopNest::unroll(loops[0], &unrolled); const std::string& verification_pattern = R"IR( # CHECK: for (int y = 0; y < 4; y++) { # CHECK: A[0, y] = y; # CHECK: } # CHECK: for (int y = 0; y < 4; y++) { # CHECK: A[1, y] = y + 1; # CHECK: } # CHECK: for (int y = 0; y < 4; y++) { # CHECK: A[2, y] = y + 2; # CHECK: })IR"; std::ostringstream oss; oss << *unrolled; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } void testUnrollInner() { KernelScope kernel_scope; ExprHandle outer_bound(3); ExprHandle inner_bound(4); Tensor* A = Compute( "A", {{outer_bound, "x"}, {inner_bound, "y"}}, [&](const VarHandle& x, const VarHandle& y) { return x + y; }); LoopNest l({A}); std::vector<For*> loops = l.getLoopStmtsFor(A); Stmt* unrolled = nullptr; LoopNest::unroll( static_cast<For*>(loops[0]->body()->stmts().front()), &unrolled); const std::string& verification_pattern = R"IR( # CHECK: for (int x = 0; x < 3; x++) { # CHECK: A[x, 0] = x; # CHECK: A[x, 1] = x + 1; # CHECK: A[x, 2] = x + 2; # CHECK: A[x, 3] = x + 3; # CHECK: })IR"; std::ostringstream oss; oss << *loops[0]; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } void testUnrollMultipleStatements() { KernelScope kernel_scope; const int kTotalSize = 3; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto f = For::make( x, 0, kTotalSize, Block::make({Store::make(a_buf, {x}, x * 2), Store::make(b_buf, {x}, Load::make(a_buf, {x}, 1))})); Block::make({f}); Stmt* unrolled = nullptr; LoopNest::unroll(f, &unrolled); std::ostringstream oss; oss << *unrolled; const std::string& verification_pattern = R"IR( # CHECK: A[0] = 0; # CHECK: B[0] = A[0]; # CHECK: A[1] = 2; # CHECK: B[1] = A[1]; # CHECK: A[2] = 4 # CHECK: B[2] = A[2];)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } void testUnrollEmpty() { const std::string actual = constantUpperBoundLoopIR(0); const std::string& verification_pattern = R"IR( # CHECK-NOT: A[ )IR"; torch::jit::testing::FileCheck().run(verification_pattern, actual); } void testNoUnroll() { KernelScope kernel_scope; VarHandle upper_bound("N", kInt); Tensor* A = Compute( "A", {{upper_bound, "x"}}, [&](const VarHandle& x) { return x * 2; }); LoopNest l({A}); std::vector<For*> loops = l.getLoopStmtsFor(A); Stmt* unrolled = nullptr; ASSERT_THROWS_WITH( LoopNest::unroll(loops[0], &unrolled), "non-constant loop"); } void testUnrollWithLet() { KernelScope kernel_scope; const int kTotalSize = 3; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle e("e", kInt); VarHandle x("x", kInt); auto f = For::make( x, 0, kTotalSize, Block::make({Let::make(e, 7), Store::make(a_buf, {x}, e), Store::make(b_buf, {x}, e + 1)})); Block::make({f}); Stmt* unrolled = nullptr; LoopNest::unroll(f, &unrolled); std::ostringstream oss; oss << *unrolled; const std::string& verification_pattern = R"IR( # CHECK: int e = 7; # CHECK: A[0] = e; # CHECK: B[0] = e + 1; # CHECK: A[1] = e; # CHECK: B[1] = e + 1; # CHECK: A[2] = e; # CHECK: B[2] = e + 1;)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); std::vector<int> a_v(kTotalSize, 0); std::vector<int> b_v(kTotalSize, 0); SimpleIREvaluator eval(unrolled, a_buf, b_buf); eval(a_v, b_v); for (int i = 0; i < kTotalSize; ++i) { ASSERT_EQ(a_v[i], 7); ASSERT_EQ(b_v[i], 8); } } void testNormalizeStartPositive() { KernelScope kernel_scope; // Input IR: // for (int x = 50; x < 100; x++) { // A[x] = B[x]; // B[x] = x * 2; // } const int kTotalSize = 50; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto for_body = Block::make({Store::make(a_buf, {x}, Load::make(kInt, b_buf, {x}, 1), 1), Store::make(b_buf, {x}, x * 2)}); auto for_stmt = For::make(x, 50, 100, for_body); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 50; x++) { # CHECK: A[x + 50] = B[x + 50]; # CHECK: B[x + 50] = 2 * (x + 50); )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeStartNegative() { KernelScope kernel_scope; // Input IR: // for (int x = -50; x < 100; x++) { // A[x + 50] = B[x + 50]; // B[x + 50] = x * 2; // } const int kTotalSize = 150; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto for_body = Block::make( {Store::make(a_buf, {x + 50}, Load::make(kInt, b_buf, {x + 50}, 1), 1), Store::make(b_buf, {x + 50}, x * 2)}); auto for_stmt = For::make(x, -50, 100, for_body); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 150; x++) { # CHECK: A[x] = B[x]; # CHECK: B[x] = 2 * (x - 50); )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeStartZero() { KernelScope kernel_scope; // Input IR: // for (int x = 0; x < 100; x++) { // A[x] = B[x]; // B[x] = x * 2; // } // Should not be modified. const int kTotalSize = 100; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto for_body = Block::make({Store::make(a_buf, {x}, Load::make(kInt, b_buf, {x}, 1), 1), Store::make(b_buf, {x}, x * 2)}); auto for_stmt = For::make(x, 0, 100, for_body); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 100; x++) { # CHECK: A[x] = B[x]; # CHECK: B[x] = 2 * x; )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeStartVariable() { KernelScope kernel_scope; // Input IR: // for (int x = y; x < 100; x++) { // A[x] = B[x]; // B[x] = x * 2; // } const int kTotalSize = 100; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); auto for_body = Block::make({Store::make(a_buf, {x}, Load::make(kInt, b_buf, {x}, 1), 1), Store::make(b_buf, {x}, x * 2)}); auto for_stmt = For::make(x, y, 100, for_body); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 100 - y; x++) { # CHECK: A[y + x] = B[y + x]; # CHECK: B[y + x] = 2 * (y + x); )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeOnNestedOuterLoop() { KernelScope kernel_scope; // Input IR: // for (int x = 50; x < 100; x++) { // for (int y = 10; y < 100; y++) { // A[x] = A[x] + B[y] + y * 2; // } // } BufHandle a_buf("A", {ExprHandle(50)}, kInt); BufHandle b_buf("B", {ExprHandle(100)}, kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); auto inner_for_body = Store::make( a_buf, {x}, Load::make(a_buf, {x}, 1) + Load::make(b_buf, {y}, 1) + y * 2, 1); auto inner_for = For::make(y, 10, 100, inner_for_body); auto for_stmt = For::make(x, 50, 100, inner_for); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 50; x++) { # CHECK: for (int y = 10; y < 100; y++) { # CHECK: A[x + 50] = ((B[y]) + (A[x + 50])) + 2 * y; )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeOnNestedInnerLoop() { KernelScope kernel_scope; // Input IR: // for (int x = 50; x < 100; x++) { // for (int y = 10; y < 100; y++) { // A[x] = A[x] + B[y] + y * 2; // } // } BufHandle a_buf("A", {ExprHandle(50)}, kInt); BufHandle b_buf("B", {ExprHandle(100)}, kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); auto inner_for_body = Store::make( a_buf, {x}, Load::make(a_buf, {x}, 1) + Load::make(b_buf, {y}, 1) + y * 2, 1); auto inner_for = For::make(y, 10, 100, inner_for_body); auto for_stmt = For::make(x, 50, 100, inner_for); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(inner_for, &normalized); auto result = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 50; x < 100; x++) { # CHECK: for (int y = 0; y < 90; y++) { # CHECK: A[x] = (((B[y + 10]) + (A[x])) + 2 * y) + 20; )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeAndSplitWithTail() { KernelScope kernel_scope; // Create a dummy tensor to construct LoopNest. ExprHandle n(100); Placeholder a(BufHandle("a", {n}, kFloat)); Tensor* b = Compute("b", {{n, "i"}}, [&](const VarHandle& i) { return a.load(i); }); LoopNest l({b}); // Input IR: // for (int x = 5; x < 10; x++) { // A[x] = x * 2; // } const int kTotalSize = 5; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto for_stmt = For::make(x, 5, 10, Store::make(a_buf, {x}, x * 2)); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); For* x_outer; For* x_inner; For* x_tail; l.splitWithTail(normalized, 10, &x_outer, &x_inner, &x_tail); auto x_outer_result = IRSimplifier::simplify(x_outer); std::ostringstream oss_outer; oss_outer << *x_outer_result; const std::string& expected_outer_ir = R"IR( # CHECK: { # CHECK: } )IR"; torch::jit::testing::FileCheck().run(expected_outer_ir, oss_outer.str()); auto x_tail_result = IRSimplifier::simplify(x_tail); std::ostringstream oss_tail; oss_tail << *x_tail_result; const std::string& expected_tail_ir = R"IR( # CHECK: for (int x_tail = 0; x_tail < 5; x_tail++) { # CHECK: A[x_tail + 5] = 2 * (x_tail + 5); )IR"; torch::jit::testing::FileCheck().run(expected_tail_ir, oss_tail.str()); } void testDetectInlineRankMismatch() { KernelScope kernel_scope; const int kTotalSize = 8; Placeholder a_buf(BufHandle("A", {ExprHandle(kTotalSize)}, kFloat)); Tensor* a = Compute("a", {{kTotalSize, "i"}}, [&](const VarHandle& i) { return a_buf.load(i); }); Tensor* reshape = Compute( "reshape", {{kTotalSize / 2, "i"}, {2, "j"}}, [&](const VarHandle& i, const VarHandle& j) { return a->call(i, j); }); LoopNest l({reshape}); ASSERT_THROWS_WITH( l.computeInline(l.getLoopBodyFor(a)), "Placeholder indexed access is inconsistent with its rank"); } } // namespace jit } // namespace torch
28.273317
80
0.579221
jsun94
60c93459c11005fc58de0e9708297bb4ac81b707
7,948
hpp
C++
src/lib/analysis/Args.hpp
testdlc/repo-new-18
1f95a44997c46081cce17cd2379216b9c039bd95
[ "BSD-3-Clause" ]
null
null
null
src/lib/analysis/Args.hpp
testdlc/repo-new-18
1f95a44997c46081cce17cd2379216b9c039bd95
[ "BSD-3-Clause" ]
null
null
null
src/lib/analysis/Args.hpp
testdlc/repo-new-18
1f95a44997c46081cce17cd2379216b9c039bd95
[ "BSD-3-Clause" ]
null
null
null
// -*-Mode: C++;-*- // * BeginRiceCopyright ***************************************************** // // $HeadURL$ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2018, Rice University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // $HeadURL$ // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** #ifndef Analysis_Args_hpp #define Analysis_Args_hpp //************************* System Include Files **************************** #include <iostream> #include <string> #include <vector> //*************************** User Include Files **************************** #include <include/uint.h> //*************************** Forward Declarations ************************** //*************************************************************************** namespace Analysis { // PathTuple: a {path, viewname} pair. // PathTuple.first = path; PathTuple.second = path target or viewname // PathTupleVec: the vector of all 'PathTuple' typedef std::pair<std::string, std::string> PathTuple; typedef std::vector<PathTuple> PathTupleVec; const std::string DefaultPathTupleTarget = "src"; } // namespace Analysis //*************************************************************************** namespace Analysis { //--------------------------------------------------------------------------- // Arguments for source code correlation //--------------------------------------------------------------------------- class Args { public: Args(); virtual ~Args(); // Dump virtual std::string toString() const; virtual void dump(std::ostream& os = std::cerr) const; void ddump() const; public: // ------------------------------------------------------- // Agent options // ------------------------------------------------------- std::string agent; // ------------------------------------------------------- // Attribution/Correlation arguments: general // ------------------------------------------------------- // Title std::string title; // Search paths //std::vector<std::string> searchPaths; PathTupleVec searchPathTpls; // Structure files std::vector<std::string> structureFiles; // Group files std::vector<std::string> groupFiles; // Replace paths std::vector<std::string> replaceInPath; std::vector<std::string> replaceOutPath; // Profile files std::vector<std::string> profileFiles; bool doNormalizeTy; // ------------------------------------------------------- // Attribution/Correlation arguments: special // ------------------------------------------------------- enum MetricFlg { MetricFlg_NULL = 0, MetricFlg_Thread = (1 << 1), MetricFlg_StatsSum = (1 << 2), MetricFlg_StatsAll = (1 << 3) }; static inline bool MetricFlg_isSet(uint flags, MetricFlg x) { return (flags & x); } static inline void MetricFlg_set(uint& flags, MetricFlg x) { flags |= x; } static inline void MetricFlg_clear(uint& flags, MetricFlg x) { flags &= ~x; } static inline bool MetricFlg_isThread(uint flags) { return MetricFlg_isSet(flags, MetricFlg_Thread); } static inline bool MetricFlg_isSum(uint flags) { return (MetricFlg_isSet(flags, MetricFlg_StatsSum) || MetricFlg_isSet(flags, MetricFlg_StatsAll)); } uint prof_metrics; // TODO: Currently this is always true even though we only need to // compute final metric values for (1) hpcproftt (flat) and (2) // hpcprof-flat when it computes derived metrics. However, at the // moment this is a sinking ship and not worth the time investment. bool profflat_computeFinalMetricValues; // ------------------------------------------------------- // Output arguments: experiment database output // ------------------------------------------------------- #define Analysis_OUT_DB_EXPERIMENT "experiment.xml" #define Analysis_OUT_DB_CSV "experiment.csv" #define Analysis_DB_DIR_pfx "hpctoolkit" #define Analysis_DB_DIR_nm "database" #define Analysis_DB_DIR "hpctoolkit-<app>-database" std::string out_db_experiment; // disable: "", stdout: "-" std::string out_db_csv; // disable: "", stdout: "-" std::string db_dir; // disable: "" bool db_copySrcFiles; std::string out_db_config; // disable: "", stdout: "-" bool db_makeMetricDB; bool db_addStructId; // ------------------------------------------------------- // Output arguments: textual output // ------------------------------------------------------- #define Analysis_OUT_TXT "" std::string out_txt; // disable: "", stdout: "-" enum TxtSum { TxtSum_NULL = 0, // individual flags TxtSum_fPgm = 0x00000001, TxtSum_fLM = 0x00000010, TxtSum_fFile = 0x00000100, TxtSum_fProc = 0x00001000, TxtSum_fLoop = 0x00010000, TxtSum_fStmt = 0x00100000, // composite flags TxtSum_ALL = (TxtSum_fPgm | TxtSum_fLM | TxtSum_fFile | TxtSum_fProc | TxtSum_fLoop | TxtSum_fStmt) }; int/*TxtSum*/ txt_summary; bool txt_srcAnnotation; std::vector<std::string> txt_srcFileGlobs; // flag to remove procedure name redundancy // this feature is not fully reliable to remove procedure // name redundancy, especially if compiled with g++ -O2 // since the compiler doesn't generate function parameters // and cannot distinguish between foo(int) and foo(int, int) bool remove_redundancy; public: // ------------------------------------------------------- // // ------------------------------------------------------- void normalizeSearchPaths(); // makes a unique database dir void makeDatabaseDir(); std::string searchPathStr() const; private: void Ctor(); }; } // namespace Analysis //*************************************************************************** #endif // Analysis_Args_hpp
29.656716
77
0.55385
testdlc
60cab731452bbb76cb0839c1bfa98e55f65e1325
1,823
cpp
C++
Experimental/Grace-Experimental/src/Commands/TurnByAngle.cpp
quasics/quasics-frc-sw-2015
e5a4f1b4e209ba941f12c2cc41759854f3c5420b
[ "BSD-3-Clause" ]
5
2016-12-16T19:05:05.000Z
2021-03-05T01:23:27.000Z
Experimental/Grace-Experimental/src/Commands/TurnByAngle.cpp
quasics/quasics-frc-sw-2015
e5a4f1b4e209ba941f12c2cc41759854f3c5420b
[ "BSD-3-Clause" ]
null
null
null
Experimental/Grace-Experimental/src/Commands/TurnByAngle.cpp
quasics/quasics-frc-sw-2015
e5a4f1b4e209ba941f12c2cc41759854f3c5420b
[ "BSD-3-Clause" ]
2
2020-01-03T01:52:43.000Z
2022-02-02T01:23:45.000Z
/* * TurnByAngle.cpp * * Created on: Apr 14, 2018 * Author: healym */ #include "TurnByAngle.h" #include "../Robot.h" constexpr double LEFT_POWER = .25; constexpr double RIGHT_POWER = -.25; namespace { // Converts an angle (in degrees) to a value in the range [0..360). double normalizeAngle(double angleDegrees) { double result = 0; if (angleDegrees >= 0 && angleDegrees < 360) { result = angleDegrees; } else if (angleDegrees < 0) { // Angle is negative (and for now, we'll only turn to the left), so // convert it to a positive value. result = angleDegrees - (((int(angleDegrees) / 360) - 1) * 360); } else { // Angle is too big: reduce it result = angleDegrees - ((int(angleDegrees) / 360) * 360); } return result; } } TurnByAngle::TurnByAngle(double angleDegrees) : angleDegrees(normalizeAngle(angleDegrees)) { Requires (Robot::driveBase.get()); Requires (Robot::navAlt.get()); } // Called just before this Command runs the first time void TurnByAngle::Initialize() { Robot::navAlt->resetGyro(); // Note: This is going to produce pretty jerky motion, especially at // anything near full power. A better approach might be to start out at // low power, ramping up to speed (in an overload of the execute() // function), and ramping down as we get close to the end of the allotted // time. Robot::driveBase->SetPower(LEFT_POWER, RIGHT_POWER); } // Make this return true when this Command no longer needs to run execute() bool TurnByAngle::IsFinished() { return Robot::navAlt->getGyroValue() >= angleDegrees; } // Called once after isFinished returns true void TurnByAngle::End() { Robot::driveBase->Stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run void TurnByAngle::Interrupted() { End(); }
27.621212
75
0.696105
quasics
60cc3df86cf31033db5c0ff70ed6e6f94509b3c5
2,717
cpp
C++
core/inst_c4c.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
10
2017-07-04T03:05:42.000Z
2022-01-20T17:37:06.000Z
core/inst_c4c.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
2
2020-06-29T13:32:15.000Z
2021-12-22T23:04:43.000Z
core/inst_c4c.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
5
2021-08-28T02:21:56.000Z
2022-01-16T21:39:16.000Z
#include "inst.h" /**************************************************************************** * CLASS 4C ****************************************************************************/ #undef INST #define INST INST_CLASS_4C C33_OP(scan0_rd_rs) { c33word ua, ub; ua = Rs.w; for(ub = 0; ub < 8; ub++) { if(!(ua & (1 << 31))) break; ua <<= 1; } Rd.w = ub; PSR.z = ub == 0; PSR.c = ub == 8; PC.w += 2; CLK += 1; } C33_OP(scan1_rd_rs) { c33word ua, ub; ua = Rs.w; for(ub = 0; ub < 8; ub++) { if(ua & (1 << 31)) break; ua <<= 1; } Rd.w = ub; PSR.z = ub == 0; PSR.c = ub == 8; PC.w += 2; CLK += 1; } C33_OP(swap_rd_rs) { c33word ua; ua = Rs.w; Rd.w = ((ua & 0x000000ff) << 24) | ((ua & 0x0000ff00) << 8) | ((ua & 0x00ff0000) >> 8) | ((ua & 0xff000000) >> 24); PC.w += 2; CLK += 1; } C33_OP(mirror_rd_rs) { c33word ua; ua = Rs.w; Rd.w = ((ua & 0x01010101) << 7) | ((ua & 0x02020202) << 5) | ((ua & 0x04040404) << 3) | ((ua & 0x08080808) << 1) | ((ua & 0x10101010) >> 1) | ((ua & 0x20202020) >> 3) | ((ua & 0x40404040) >> 5) | ((ua & 0x80808080) >> 7); PC.w += 2; CLK += 1; } C33_OP(div0s_rs) { if(!Rs.i) core_trap(TRAP_ZERODIV, 0); AHR.w = (c33int)ALR.w >> 31; PSR.ds = ALR.w >> 31; PSR.n = Rs.w >> 31; PC.w += 2; CLK += 1; } C33_OP(div0u_rs) { if(!Rs.i) core_trap(TRAP_ZERODIV, 0); AHR.w = 0; PSR.ds = 0; PSR.n = 0; PC.w += 2; CLK += 1; } C33_OP(div1_rs) { c33int tmp; /* div0x以外では、ゼロ除算例外は発生しません。 */ AR <<= 1; if(!PSR.ds) { if(!PSR.n) { /* 正÷正 */ tmp = AHR.i - Rs.i; if(tmp <= AHR.i) { /* !C */ AHR.i = tmp; ALR.i |= 1; } } else { /* 正÷負 */ tmp = AHR.i + Rs.i; if(tmp < AHR.i) { /* C */ AHR.i = tmp; ALR.i |= 1; } } } else { if(!PSR.n) { /* 負÷正 */ tmp = AHR.i + Rs.i; if(tmp >= AHR.i) { /* !C */ AHR.i = tmp; ALR.i |= 1; } } else { /* 負÷負 */ tmp = AHR.i - Rs.i; if(tmp > AHR.i) { /* !C */ AHR.i = tmp; ALR.i |= 1; } } } PC.w += 2; CLK += 1; } C33_OP(div2s_rs) { c33word tmp; /* div0x以外では、ゼロ除算例外は発生しません。 */ if(PSR.ds) { if(!PSR.n) { tmp = AHR.i + Rs.i; } else { tmp = AHR.i - Rs.i; } if(!tmp) { AHR.i = tmp; ALR.i += 1; } } PC.w += 2; CLK += 1; } C33_OP(div3s) { /* div0x以外では、ゼロ除算例外は発生しません。 */ if(PSR.ds != PSR.n) { ALR.i = 0 - ALR.i; /* ALR = -ALR では警告になるので… */ } PC.w += 2; CLK += 1; }
14.686486
78
0.375782
autch
60cd2c65df7bc743837a1fbc20efeca4e6d56e69
41
hpp
C++
src/boost_fusion_include_at_c.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_include_at_c.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_include_at_c.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/include/at_c.hpp>
20.5
40
0.780488
miathedev