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
80ed2ad5b3adb1be832fa47ad9ed66fd518e0574
4,219
hpp
C++
src/base/interpolator/Interpolator.hpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
1
2018-09-18T07:09:36.000Z
2018-09-18T07:09:36.000Z
src/base/interpolator/Interpolator.hpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
null
null
null
src/base/interpolator/Interpolator.hpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
2
2020-06-18T04:45:30.000Z
2021-07-20T02:11:54.000Z
//$Id$ //------------------------------------------------------------------------------ // Interpolator //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: Darrel J. Conway // Created: 2003/09/23 // /** * Definition for the Interpolator base class */ //------------------------------------------------------------------------------ #ifndef Interpolator_hpp #define Interpolator_hpp #include "GmatBase.hpp" /** * Base class for the GMAT Interpolators */ class GMAT_API Interpolator : public GmatBase { public: Interpolator(const std::string &name, const std::string &typestr, Integer dim = 1); virtual ~Interpolator(); Interpolator(const Interpolator &i); Interpolator& operator=(const Interpolator &i); virtual Integer IsInterpolationFeasible(Real ind); virtual void SetForceInterpolation(bool flag); virtual bool GetForceInterpolation(); virtual bool AddPoint(const Real ind, const Real *data); virtual void Clear(); virtual Integer GetBufferSize(); virtual Integer GetPointCount(); //--------------------------------------------------------------------------- // bool Interpolate(const Real ind, Real *results) //--------------------------------------------------------------------------- /** * Interpolate the data. * * Derived classes implement this method to provide the mathematics that * perform the data interpolation, resulint in an array of interpolated data * valid at the desired value of the independent variable. * * @param <ind> Value of the independent variable at which the data is * interpolated. * @param <results> Array of interpolated data. * * @return true on success, false (or throw) on failure. */ //--------------------------------------------------------------------------- virtual bool Interpolate(const Real ind, Real *results) = 0; DEFAULT_TO_NO_CLONES DEFAULT_TO_NO_REFOBJECTS protected: /// Data array used for the independent variable Real *independent; /// The data that gets interpolated Real **dependent; /// Previous independent value, used to determine direction data is going Real previousX; // Parameters /// Number of dependent points to be interpolated Integer dimension; /// Number of points required to interpolate Integer requiredPoints; /// Number of points managed by the interpolator Integer bufferSize; /// Number of points fed to the interpolator Integer pointCount; /// Pointer to most recent point, for the ring buffer implementation Integer latestPoint; /// Valid range for the data points Real range[2]; /// Flag used to detect if range has already been calculated bool rangeCalculated; /// Flag used to determine if independent variable increases or decreases bool dataIncreases; /// Flag used for additional feasiblity checking bool forceInterpolation; virtual void AllocateArrays(); virtual void CleanupArrays(); virtual void CopyArrays(const Interpolator &i); void SetRange(); }; #endif // Interpolator_hpp
35.158333
81
0.604172
rockstorm101
80ee8e5fcad8c9774fabe3dc0d0081079af6ae80
4,849
cc
C++
lite/backends/nnadapter/nnadapter/driver/huawei_ascend_npu/converter/pool2d.cc
ChinaCYong/Paddle-Lite
8d161bd76c86445c42f00421983e389c11323797
[ "Apache-2.0" ]
1
2021-07-12T10:46:19.000Z
2021-07-12T10:46:19.000Z
lite/backends/nnadapter/nnadapter/driver/huawei_ascend_npu/converter/pool2d.cc
fuaq/Paddle-Lite
56e1239410d976842fc6f7792de13c9d007d253f
[ "Apache-2.0" ]
null
null
null
lite/backends/nnadapter/nnadapter/driver/huawei_ascend_npu/converter/pool2d.cc
fuaq/Paddle-Lite
56e1239410d976842fc6f7792de13c9d007d253f
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "driver/huawei_ascend_npu/converter.h" #include "utility/debug.h" #include "utility/logging.h" namespace nnadapter { namespace huawei_ascend_npu { int Program::ConvertPool2D(hal::Operation* operation) { auto& input_operands = operation->input_operands; auto& output_operands = operation->output_operands; auto input_count = input_operands.size(); auto output_count = output_operands.size(); NNADAPTER_CHECK_EQ(input_count, 12); NNADAPTER_CHECK_EQ(output_count, 1); // Input auto input_operand = input_operands[0]; NNADAPTER_VLOG(5) << "input: " << OperandToString(input_operand); // Paddings auto padding_width_left = *reinterpret_cast<int32_t*>(input_operands[1]->buffer); auto padding_width_right = *reinterpret_cast<int32_t*>(input_operands[2]->buffer); auto padding_height_top = *reinterpret_cast<int32_t*>(input_operands[3]->buffer); auto padding_height_bottom = *reinterpret_cast<int32_t*>(input_operands[4]->buffer); NNADAPTER_VLOG(5) << "paddings=[" << padding_width_left << "," << padding_width_right << "," << padding_height_top << "," << padding_height_bottom << "]"; // Strides auto stride_width = *reinterpret_cast<int32_t*>(input_operands[5]->buffer); auto stride_height = *reinterpret_cast<int32_t*>(input_operands[6]->buffer); NNADAPTER_VLOG(5) << "strides=[" << stride_width << "," << stride_height << "]"; // Filter auto filter_width = *reinterpret_cast<int32_t*>(input_operands[7]->buffer); auto filter_height = *reinterpret_cast<int32_t*>(input_operands[8]->buffer); NNADAPTER_VLOG(5) << "filter=[" << filter_width << "," << filter_height << "]"; bool global_pooling = filter_width == input_operand->type.dimensions[3] && filter_height == input_operand->type.dimensions[2]; NNADAPTER_VLOG(5) << "global_pooling=" << global_pooling; // Fuse code auto fuse_code = *reinterpret_cast<int32_t*>(input_operands[9]->buffer); NNADAPTER_VLOG(5) << "fuse_code=" << fuse_code; // Ceil mode bool ceil_mode = *reinterpret_cast<int8_t*>(input_operands[10]->buffer); NNADAPTER_VLOG(5) << "ceil_mode=" << ceil_mode; // Count include pad bool count_include_pad = *reinterpret_cast<int8_t*>(input_operands[11]->buffer); NNADAPTER_VLOG(5) << "count_include_pad=" << count_include_pad; // Output auto output_operand = output_operands[0]; NNADAPTER_VLOG(5) << "output: " << OperandToString(output_operand); // Convert to GE operators auto input_operator = GetMappedOperator(input_operand); if (!input_operator) { input_operator = ConvertOperand(input_operand); } auto pool2d_name = GetOperatorName(output_operand); auto pool2d_op = std::make_shared<ge::op::Pooling>(pool2d_name); if (operation->type == NNADAPTER_AVERAGE_POOL_2D) { pool2d_op->set_attr_mode(1); NNADAPTER_CHECK(!count_include_pad) << "Only count_include_pad=false is " "supported for the pooling type " "'avg' in GE"; } else if (operation->type == NNADAPTER_MAX_POOL_2D) { pool2d_op->set_attr_mode(0); } else { NNADAPTER_LOG(FATAL) << "Unsupported pooling operation type " << OperationTypeToString(operation->type) << " is found."; } pool2d_op->set_attr_global_pooling(global_pooling); pool2d_op->set_attr_window( ge::Operator::OpListInt({filter_height, filter_width})); pool2d_op->set_attr_pad(ge::Operator::OpListInt({padding_height_bottom, padding_height_top, padding_width_right, padding_width_left})); pool2d_op->set_attr_stride( ge::Operator::OpListInt({stride_height, stride_width})); // "0" (ceil mode) or "1" (floor mode). Defaults to "0" if (!ceil_mode) { pool2d_op->set_attr_ceil_mode(1); } SET_INPUT(pool2d_op, x, input_operator); MAP_OUTPUT(pool2d_op, y, output_operand); return NNADAPTER_NO_ERROR; } } // namespace huawei_ascend_npu } // namespace nnadapter
44.081818
78
0.670241
ChinaCYong
80ef0d8a50449bb2b90ce59f752fc9c46bbcd66d
4,254
cpp
C++
Userland/Libraries/LibWeb/Layout/Label.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
19,438
2019-05-20T15:11:11.000Z
2022-03-31T23:31:32.000Z
Userland/Libraries/LibWeb/Layout/Label.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
7,882
2019-05-20T01:03:52.000Z
2022-03-31T23:26:31.000Z
Userland/Libraries/LibWeb/Layout/Label.cpp
r00ster91/serenity
f8387dea2689d564aff612bfd4ec5086393fac35
[ "BSD-2-Clause" ]
2,721
2019-05-23T00:44:57.000Z
2022-03-31T22:49:34.000Z
/* * Copyright (c) 2021, Tim Flynn <trflynn89@pm.me> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibGUI/Event.h> #include <LibGfx/Painter.h> #include <LibGfx/StylePainter.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/DOM/Element.h> #include <LibWeb/HTML/BrowsingContext.h> #include <LibWeb/Layout/InitialContainingBlock.h> #include <LibWeb/Layout/Label.h> #include <LibWeb/Layout/LabelableNode.h> #include <LibWeb/Layout/TextNode.h> namespace Web::Layout { Label::Label(DOM::Document& document, HTML::HTMLLabelElement* element, NonnullRefPtr<CSS::StyleProperties> style) : BlockContainer(document, element, move(style)) { } Label::~Label() { } void Label::handle_mousedown_on_label(Badge<TextNode>, const Gfx::IntPoint&, unsigned button) { if (button != GUI::MouseButton::Primary) return; if (auto* control = control_node(); control) control->handle_associated_label_mousedown({}); m_tracking_mouse = true; } void Label::handle_mouseup_on_label(Badge<TextNode>, const Gfx::IntPoint& position, unsigned button) { if (!m_tracking_mouse || button != GUI::MouseButton::Primary) return; // NOTE: Changing the checked state of the DOM node may run arbitrary JS, which could disappear this node. NonnullRefPtr protect = *this; if (auto* control = control_node(); control) { bool is_inside_control = enclosing_int_rect(control->absolute_rect()).contains(position); bool is_inside_label = enclosing_int_rect(absolute_rect()).contains(position); if (is_inside_control || is_inside_label) control->handle_associated_label_mouseup({}); } m_tracking_mouse = false; } void Label::handle_mousemove_on_label(Badge<TextNode>, const Gfx::IntPoint& position, unsigned) { if (!m_tracking_mouse) return; if (auto* control = control_node(); control) { bool is_inside_control = enclosing_int_rect(control->absolute_rect()).contains(position); bool is_inside_label = enclosing_int_rect(absolute_rect()).contains(position); control->handle_associated_label_mousemove({}, is_inside_control || is_inside_label); } } bool Label::is_inside_associated_label(LabelableNode& control, const Gfx::IntPoint& position) { if (auto* label = label_for_control_node(control); label) return enclosing_int_rect(label->absolute_rect()).contains(position); return false; } bool Label::is_associated_label_hovered(LabelableNode& control) { if (auto* label = label_for_control_node(control); label) { if (label->document().hovered_node() == &label->dom_node()) return true; if (auto* child = label->first_child_of_type<TextNode>(); child) return label->document().hovered_node() == &child->dom_node(); } return false; } Label* Label::label_for_control_node(LabelableNode& control) { Label* label = nullptr; if (!control.document().layout_node()) return label; String id = control.dom_node().attribute(HTML::AttributeNames::id); if (id.is_empty()) return label; control.document().layout_node()->for_each_in_inclusive_subtree_of_type<Label>([&](auto& node) { if (node.dom_node().for_() == id) { label = &node; return IterationDecision::Break; } return IterationDecision::Continue; }); // FIXME: The spec also allows for associating a label with a labelable node by putting the // labelable node inside the label. return label; } LabelableNode* Label::control_node() { LabelableNode* control = nullptr; if (!document().layout_node()) return control; String for_ = dom_node().for_(); if (for_.is_empty()) return control; document().layout_node()->for_each_in_inclusive_subtree_of_type<LabelableNode>([&](auto& node) { if (node.dom_node().attribute(HTML::AttributeNames::id) == for_) { control = &node; return IterationDecision::Break; } return IterationDecision::Continue; }); // FIXME: The spec also allows for associating a label with a labelable node by putting the // labelable node inside the label. return control; } }
30.170213
113
0.683827
r00ster91
80f1149c50a621b596022f27e1eb8c5ddc1b3b2f
4,540
hpp
C++
src/mat/opr/num.hpp
Thhethssmuz/mmm
ee91a990fba3849db1fc2b6df0e89004e2df466f
[ "MIT" ]
1
2017-03-14T20:45:54.000Z
2017-03-14T20:45:54.000Z
src/mat/opr/num.hpp
Thhethssmuz/mmm
ee91a990fba3849db1fc2b6df0e89004e2df466f
[ "MIT" ]
1
2017-03-08T17:14:03.000Z
2017-03-08T23:40:35.000Z
src/mat/opr/num.hpp
Thhethssmuz/mmm
ee91a990fba3849db1fc2b6df0e89004e2df466f
[ "MIT" ]
null
null
null
#pragma once template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator+(T s, const tmat<T, N, M>& m); template <typename T, typename U, size_t N, size_t M, typename = typefu::for_arithmetic<T, U>> constexpr tmat<T, N, M> operator+(U s, const tmat<T, N, M>& m); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator+(const tmat<T, N, M>& m, T s); template <typename T, typename U, size_t N, size_t M, typename = typefu::for_arithmetic<T, U>> constexpr tmat<T, N, M> operator+(const tmat<T, N, M>& m, U s); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator+(const tmat<T, N, M>& m, const tmat<T, N, M>& n); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator-(T s, const tmat<T, N, M>& m); template <typename T, typename U, size_t N, size_t M, typename = typefu::for_arithmetic<T, U>> constexpr tmat<T, N, M> operator-(U s, const tmat<T, N, M>& m); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator-(const tmat<T, N, M>& m, T s); template <typename T, typename U, size_t N, size_t M, typename = typefu::for_arithmetic<T, U>> constexpr tmat<T, N, M> operator-(const tmat<T, N, M>& m, U s); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator-(const tmat<T, N, M>& m); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator-(const tmat<T, N, M>& m, const tmat<T, N, M>& n); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator*(T s, const tmat<T, N, M>& m); template <typename T, typename U, size_t N, size_t M, typename = typefu::for_arithmetic<T, U>> constexpr tmat<T, N, M> operator*(U s, const tmat<T, N, M>& m); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator*(const tmat<T, N, M>& m, T s); template <typename T, typename U, size_t N, size_t M, typename = typefu::for_arithmetic<T, U>> constexpr tmat<T, N, M> operator*(const tmat<T, N, M>& m, U s); template <typename T, size_t M, typename = typefu::for_arithmetic<T>> constexpr tvec<T, 2> operator*(const tvec<T, M>& v, const tmat<T, 2, M>& m); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tvec<T, N> operator*(const tvec<T, M>& v, const tmat<T, N, M>& m); template <typename T, size_t N, size_t M, typename A, typename = typefu::for_arithmetic<T>> constexpr tvec<T, N> operator*(const vecType<T, M, A>& v, const tmat<T, N, M>& m); template <typename T, size_t N, typename = typefu::for_arithmetic<T>> constexpr tvec<T, 2> operator*(const tmat<T, N, 2>& m, const tvec<T, N>& v); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tvec<T, M> operator*(const tmat<T, N, M>& m, const tvec<T, N>& v); template <typename T, size_t N, size_t M, typename A, typename = typefu::for_arithmetic<T>> constexpr tvec<T, M> operator*(const tmat<T, N, M>& m, const vecType<T, N, A>& v); template <typename T, size_t N, size_t M, size_t O, typename = typefu::for_arithmetic<T>> constexpr tmat<T, O, M> operator*(const tmat<T, N, M>& m, const tmat<T, O, N>& n); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator/(T s, const tmat<T, N, M>& m); template <typename T, typename U, size_t N, size_t M, typename = typefu::for_arithmetic<T, U>> constexpr tmat<T, N, M> operator/(U s, const tmat<T, N, M>& m); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator/(const tmat<T, N, M>& m, T s); template <typename T, typename U, size_t N, size_t M, typename = typefu::for_arithmetic<T, U>> constexpr tmat<T, N, M> operator/(const tmat<T, N, M>& m, U s); template <typename T, size_t N, size_t M, typename = typefu::for_arithmetic<T>> constexpr tmat<T, N, M> operator/(const tmat<T, N, M>& m, const tmat<T, N, M>& n);
41.651376
79
0.633921
Thhethssmuz
80f13c80ed70d799f2b000a71c7483cab558589d
534
cpp
C++
src/10.cpp
wandering007/ProjectEuler
332e1053aa8d65e764952f4133ff0f06d028136a
[ "Apache-2.0" ]
4
2015-05-02T09:15:54.000Z
2018-06-28T16:18:20.000Z
src/10.cpp
wandering007/ProjectEuler
332e1053aa8d65e764952f4133ff0f06d028136a
[ "Apache-2.0" ]
null
null
null
src/10.cpp
wandering007/ProjectEuler
332e1053aa8d65e764952f4133ff0f06d028136a
[ "Apache-2.0" ]
1
2017-10-29T06:35:59.000Z
2017-10-29T06:35:59.000Z
#include <iostream> #include <vector> int main() { const int N = 2000000; std::vector<int> is_prime(N, 1); for (int k = 2; k + k < N; ++k) { for (int j = k + k; j < N; j += k) { is_prime[j] = 0; } } long long sum_of_primes = 0; // 不能用int for (int i = 2; i < N; ++i) { if (1 == is_prime[i]) { sum_of_primes += i; } } std::cout << "The sum of all the primes below two million is " << sum_of_primes << std::endl; return 0; }
26.7
98
0.456929
wandering007
80f150649a995bbec45e690f159257810537b405
25,084
hpp
C++
include/RAJA/policy/hip/sort.hpp
keichi/RAJA
8e8cc96cbccda2bfc33b14b57a8591b2cf9ca342
[ "BSD-3-Clause" ]
null
null
null
include/RAJA/policy/hip/sort.hpp
keichi/RAJA
8e8cc96cbccda2bfc33b14b57a8591b2cf9ca342
[ "BSD-3-Clause" ]
null
null
null
include/RAJA/policy/hip/sort.hpp
keichi/RAJA
8e8cc96cbccda2bfc33b14b57a8591b2cf9ca342
[ "BSD-3-Clause" ]
null
null
null
/*! ****************************************************************************** * * \file * * \brief Header file providing RAJA sort declarations. * ****************************************************************************** */ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2016-22, Lawrence Livermore National Security, LLC // and RAJA project contributors. See the RAJA/LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// #ifndef RAJA_sort_hip_HPP #define RAJA_sort_hip_HPP #include "RAJA/config.hpp" #if defined(RAJA_ENABLE_HIP) #include <climits> #include <iterator> #include <type_traits> #if defined(__HIPCC__) #define ROCPRIM_HIP_API 1 #include "rocprim/device/device_transform.hpp" #include "rocprim/device/device_radix_sort.hpp" #elif defined(__CUDACC__) #include "cub/device/device_radix_sort.cuh" #endif #include "RAJA/util/concepts.hpp" #include "RAJA/util/Operators.hpp" #include "RAJA/pattern/detail/algorithm.hpp" #include "RAJA/policy/hip/MemUtils_HIP.hpp" #include "RAJA/policy/hip/policy.hpp" namespace RAJA { namespace impl { namespace sort { namespace detail { #if defined(__HIPCC__) template < typename R > using double_buffer = ::rocprim::double_buffer<R>; #elif defined(__CUDACC__) template < typename R > using double_buffer = ::cub::DoubleBuffer<R>; #endif template < typename R > R* get_current(double_buffer<R>& d_bufs) { #if defined(__HIPCC__) return d_bufs.current(); #elif defined(__CUDACC__) return d_bufs.Current(); #endif } } /*! \brief static assert unimplemented stable sort */ template <size_t BLOCK_SIZE, bool Async, typename Iter, typename Compare> concepts::enable_if_t<resources::EventProxy<resources::Hip>, concepts::negate<concepts::all_of< type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>, std::is_pointer<Iter>, concepts::any_of< camp::is_same<Compare, operators::less<RAJA::detail::IterVal<Iter>>>, camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<Iter>>>>>>> stable( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async>, Iter, Iter, Compare) { static_assert(concepts::all_of< type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>, std::is_pointer<Iter>, concepts::any_of< camp::is_same<Compare, operators::less<RAJA::detail::IterVal<Iter>>>, camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<Iter>>>>>::value, "RAJA stable_sort<hip_exec> is only implemented for pointers to arithmetic types and RAJA::operators::less and RAJA::operators::greater."); return resources::EventProxy<resources::Hip>(hip_res); } /*! \brief stable sort given range in ascending order */ template <size_t BLOCK_SIZE, bool Async, typename Iter> concepts::enable_if_t<resources::EventProxy<resources::Hip>, type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>, std::is_pointer<Iter>> stable( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async>, Iter begin, Iter end, operators::less<RAJA::detail::IterVal<Iter>>) { hipStream_t stream = hip_res.get_stream(); using R = RAJA::detail::IterVal<Iter>; int len = std::distance(begin, end); int begin_bit=0; int end_bit=sizeof(R)*CHAR_BIT; // Allocate temporary storage for the output array R* d_out = hip::device_mempool_type::getInstance().malloc<R>(len); // use cub double buffer to reduce temporary memory requirements // by allowing cub to write to the begin buffer detail::double_buffer<R> d_keys(begin, d_out); // Determine temporary device storage requirements void* d_temp_storage = nullptr; size_t temp_storage_bytes = 0; #if defined(__HIPCC__) hipErrchk(::rocprim::radix_sort_keys(d_temp_storage, temp_storage_bytes, d_keys, len, begin_bit, end_bit, stream)); #elif defined(__CUDACC__) cudaErrchk(::cub::DeviceRadixSort::SortKeys(d_temp_storage, temp_storage_bytes, d_keys, len, begin_bit, end_bit, stream)); #endif // Allocate temporary storage d_temp_storage = hip::device_mempool_type::getInstance().malloc<unsigned char>( temp_storage_bytes); // Run #if defined(__HIPCC__) hipErrchk(::rocprim::radix_sort_keys(d_temp_storage, temp_storage_bytes, d_keys, len, begin_bit, end_bit, stream)); #elif defined(__CUDACC__) cudaErrchk(::cub::DeviceRadixSort::SortKeys(d_temp_storage, temp_storage_bytes, d_keys, len, begin_bit, end_bit, stream)); #endif // Free temporary storage hip::device_mempool_type::getInstance().free(d_temp_storage); if (detail::get_current(d_keys) == d_out) { // copy hipErrchk(hipMemcpyAsync(begin, d_out, len*sizeof(R), hipMemcpyDefault, stream)); } hip::device_mempool_type::getInstance().free(d_out); hip::launch(hip_res, Async); return resources::EventProxy<resources::Hip>(hip_res); } /*! \brief stable sort given range in descending order */ template <size_t BLOCK_SIZE, bool Async, typename Iter> concepts::enable_if_t<resources::EventProxy<resources::Hip>, type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>, std::is_pointer<Iter>> stable( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async>, Iter begin, Iter end, operators::greater<RAJA::detail::IterVal<Iter>>) { hipStream_t stream = hip_res.get_stream(); using R = RAJA::detail::IterVal<Iter>; int len = std::distance(begin, end); int begin_bit=0; int end_bit=sizeof(R)*CHAR_BIT; // Allocate temporary storage for the output array R* d_out = hip::device_mempool_type::getInstance().malloc<R>(len); // use cub double buffer to reduce temporary memory requirements // by allowing cub to write to the begin buffer detail::double_buffer<R> d_keys(begin, d_out); // Determine temporary device storage requirements void* d_temp_storage = nullptr; size_t temp_storage_bytes = 0; #if defined(__HIPCC__) hipErrchk(::rocprim::radix_sort_keys_desc(d_temp_storage, temp_storage_bytes, d_keys, len, begin_bit, end_bit, stream)); #elif defined(__CUDACC__) cudaErrchk(::cub::DeviceRadixSort::SortKeysDescending(d_temp_storage, temp_storage_bytes, d_keys, len, begin_bit, end_bit, stream)); #endif // Allocate temporary storage d_temp_storage = hip::device_mempool_type::getInstance().malloc<unsigned char>( temp_storage_bytes); // Run #if defined(__HIPCC__) hipErrchk(::rocprim::radix_sort_keys_desc(d_temp_storage, temp_storage_bytes, d_keys, len, begin_bit, end_bit, stream)); #elif defined(__CUDACC__) cudaErrchk(::cub::DeviceRadixSort::SortKeysDescending(d_temp_storage, temp_storage_bytes, d_keys, len, begin_bit, end_bit, stream)); #endif // Free temporary storage hip::device_mempool_type::getInstance().free(d_temp_storage); if (detail::get_current(d_keys) == d_out) { // copy hipErrchk(hipMemcpyAsync(begin, d_out, len*sizeof(R), hipMemcpyDefault, stream)); } hip::device_mempool_type::getInstance().free(d_out); hip::launch(hip_res, Async); return resources::EventProxy<resources::Hip>(hip_res); } /*! \brief static assert unimplemented sort */ template <size_t BLOCK_SIZE, bool Async, typename Iter, typename Compare> concepts::enable_if_t<resources::EventProxy<resources::Hip>, concepts::negate<concepts::all_of< type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>, std::is_pointer<Iter>, concepts::any_of< camp::is_same<Compare, operators::less<RAJA::detail::IterVal<Iter>>>, camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<Iter>>>>>>> unstable( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async>, Iter, Iter, Compare) { static_assert(concepts::all_of< type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>, std::is_pointer<Iter>, concepts::any_of< camp::is_same<Compare, operators::less<RAJA::detail::IterVal<Iter>>>, camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<Iter>>>>>::value, "RAJA sort<hip_exec> is only implemented for pointers to arithmetic types and RAJA::operators::less and RAJA::operators::greater."); return resources::EventProxy<resources::Hip>(hip_res); } /*! \brief sort given range in ascending order */ template <size_t BLOCK_SIZE, bool Async, typename Iter> concepts::enable_if_t<resources::EventProxy<resources::Hip>, type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>, std::is_pointer<Iter>> unstable( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async> p, Iter begin, Iter end, operators::less<RAJA::detail::IterVal<Iter>> comp) { return stable(hip_res, p, begin, end, comp); } /*! \brief sort given range in descending order */ template <size_t BLOCK_SIZE, bool Async, typename Iter> concepts::enable_if_t<resources::EventProxy<resources::Hip>, type_traits::is_arithmetic<RAJA::detail::IterVal<Iter>>, std::is_pointer<Iter>> unstable( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async> p, Iter begin, Iter end, operators::greater<RAJA::detail::IterVal<Iter>> comp) { return stable(hip_res, p, begin, end, comp); } /*! \brief static assert unimplemented stable sort pairs */ template <size_t BLOCK_SIZE, bool Async, typename KeyIter, typename ValIter, typename Compare> concepts::enable_if_t<resources::EventProxy<resources::Hip>, concepts::negate<concepts::all_of< type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>, std::is_pointer<KeyIter>, std::is_pointer<ValIter>, concepts::any_of< camp::is_same<Compare, operators::less<RAJA::detail::IterVal<KeyIter>>>, camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<KeyIter>>>>>>> stable_pairs( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async>, KeyIter, KeyIter, ValIter, Compare) { static_assert (std::is_pointer<KeyIter>::value, "stable_sort_pairs<hip_exec> is only implemented for pointers"); static_assert (std::is_pointer<ValIter>::value, "stable_sort_pairs<hip_exec> is only implemented for pointers"); using K = RAJA::detail::IterVal<KeyIter>; static_assert (type_traits::is_arithmetic<K>::value, "stable_sort_pairs<hip_exec> is only implemented for arithmetic types"); static_assert (concepts::any_of< camp::is_same<Compare, operators::less<K>>, camp::is_same<Compare, operators::greater<K>>>::value, "stable_sort_pairs<hip_exec> is only implemented for RAJA::operators::less or RAJA::operators::greater"); return resources::EventProxy<resources::Hip>(hip_res); } /*! \brief stable sort given range of pairs in ascending order of keys */ template <size_t BLOCK_SIZE, bool Async, typename KeyIter, typename ValIter> concepts::enable_if_t<resources::EventProxy<resources::Hip>, type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>, std::is_pointer<KeyIter>, std::is_pointer<ValIter>> stable_pairs( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async>, KeyIter keys_begin, KeyIter keys_end, ValIter vals_begin, operators::less<RAJA::detail::IterVal<KeyIter>>) { hipStream_t stream = hip_res.get_stream(); using K = RAJA::detail::IterVal<KeyIter>; using V = RAJA::detail::IterVal<ValIter>; int len = std::distance(keys_begin, keys_end); int begin_bit=0; int end_bit=sizeof(K)*CHAR_BIT; // Allocate temporary storage for the output arrays K* d_keys_out = hip::device_mempool_type::getInstance().malloc<K>(len); V* d_vals_out = hip::device_mempool_type::getInstance().malloc<V>(len); // use cub double buffer to reduce temporary memory requirements // by allowing cub to write to the keys_begin and vals_begin buffers detail::double_buffer<K> d_keys(keys_begin, d_keys_out); detail::double_buffer<V> d_vals(vals_begin, d_vals_out); // Determine temporary device storage requirements void* d_temp_storage = nullptr; size_t temp_storage_bytes = 0; #if defined(__HIPCC__) hipErrchk(::rocprim::radix_sort_pairs(d_temp_storage, temp_storage_bytes, d_keys, d_vals, len, begin_bit, end_bit, stream)); #elif defined(__CUDACC__) cudaErrchk(::cub::DeviceRadixSort::SortPairs(d_temp_storage, temp_storage_bytes, d_keys, d_vals, len, begin_bit, end_bit, stream)); #endif // Allocate temporary storage d_temp_storage = hip::device_mempool_type::getInstance().malloc<unsigned char>( temp_storage_bytes); // Run #if defined(__HIPCC__) hipErrchk(::rocprim::radix_sort_pairs(d_temp_storage, temp_storage_bytes, d_keys, d_vals, len, begin_bit, end_bit, stream)); #elif defined(__CUDACC__) cudaErrchk(::cub::DeviceRadixSort::SortPairs(d_temp_storage, temp_storage_bytes, d_keys, d_vals, len, begin_bit, end_bit, stream)); #endif // Free temporary storage hip::device_mempool_type::getInstance().free(d_temp_storage); if (detail::get_current(d_keys) == d_keys_out) { // copy keys hipErrchk(hipMemcpyAsync(keys_begin, d_keys_out, len*sizeof(K), hipMemcpyDefault, stream)); } if (detail::get_current(d_vals) == d_vals_out) { // copy vals hipErrchk(hipMemcpyAsync(vals_begin, d_vals_out, len*sizeof(V), hipMemcpyDefault, stream)); } hip::device_mempool_type::getInstance().free(d_keys_out); hip::device_mempool_type::getInstance().free(d_vals_out); hip::launch(hip_res, Async); return resources::EventProxy<resources::Hip>(hip_res); } /*! \brief stable sort given range of pairs in descending order of keys */ template <size_t BLOCK_SIZE, bool Async, typename KeyIter, typename ValIter> concepts::enable_if_t<resources::EventProxy<resources::Hip>, type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>, std::is_pointer<KeyIter>, std::is_pointer<ValIter>> stable_pairs( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async>, KeyIter keys_begin, KeyIter keys_end, ValIter vals_begin, operators::greater<RAJA::detail::IterVal<KeyIter>>) { hipStream_t stream = hip_res.get_stream(); using K = RAJA::detail::IterVal<KeyIter>; using V = RAJA::detail::IterVal<ValIter>; int len = std::distance(keys_begin, keys_end); int begin_bit=0; int end_bit=sizeof(K)*CHAR_BIT; // Allocate temporary storage for the output arrays K* d_keys_out = hip::device_mempool_type::getInstance().malloc<K>(len); V* d_vals_out = hip::device_mempool_type::getInstance().malloc<V>(len); // use cub double buffer to reduce temporary memory requirements // by allowing cub to write to the keys_begin and vals_begin buffers detail::double_buffer<K> d_keys(keys_begin, d_keys_out); detail::double_buffer<V> d_vals(vals_begin, d_vals_out); // Determine temporary device storage requirements void* d_temp_storage = nullptr; size_t temp_storage_bytes = 0; #if defined(__HIPCC__) hipErrchk(::rocprim::radix_sort_pairs_desc(d_temp_storage, temp_storage_bytes, d_keys, d_vals, len, begin_bit, end_bit, stream)); #elif defined(__CUDACC__) cudaErrchk(::cub::DeviceRadixSort::SortPairsDescending(d_temp_storage, temp_storage_bytes, d_keys, d_vals, len, begin_bit, end_bit, stream)); #endif // Allocate temporary storage d_temp_storage = hip::device_mempool_type::getInstance().malloc<unsigned char>( temp_storage_bytes); // Run #if defined(__HIPCC__) hipErrchk(::rocprim::radix_sort_pairs_desc(d_temp_storage, temp_storage_bytes, d_keys, d_vals, len, begin_bit, end_bit, stream)); #elif defined(__CUDACC__) cudaErrchk(::cub::DeviceRadixSort::SortPairsDescending(d_temp_storage, temp_storage_bytes, d_keys, d_vals, len, begin_bit, end_bit, stream)); #endif // Free temporary storage hip::device_mempool_type::getInstance().free(d_temp_storage); if (detail::get_current(d_keys) == d_keys_out) { // copy keys hipErrchk(hipMemcpyAsync(keys_begin, d_keys_out, len*sizeof(K), hipMemcpyDefault, stream)); } if (detail::get_current(d_vals) == d_vals_out) { // copy vals hipErrchk(hipMemcpyAsync(vals_begin, d_vals_out, len*sizeof(V), hipMemcpyDefault, stream)); } hip::device_mempool_type::getInstance().free(d_keys_out); hip::device_mempool_type::getInstance().free(d_vals_out); hip::launch(hip_res, Async); return resources::EventProxy<resources::Hip>(hip_res); } /*! \brief static assert unimplemented sort pairs */ template <size_t BLOCK_SIZE, bool Async, typename KeyIter, typename ValIter, typename Compare> concepts::enable_if_t<resources::EventProxy<resources::Hip>, concepts::negate<concepts::all_of< type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>, std::is_pointer<KeyIter>, std::is_pointer<ValIter>, concepts::any_of< camp::is_same<Compare, operators::less<RAJA::detail::IterVal<KeyIter>>>, camp::is_same<Compare, operators::greater<RAJA::detail::IterVal<KeyIter>>>>>>> unstable_pairs( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async>, KeyIter, KeyIter, ValIter, Compare) { static_assert (std::is_pointer<KeyIter>::value, "sort_pairs<hip_exec> is only implemented for pointers"); static_assert (std::is_pointer<ValIter>::value, "sort_pairs<hip_exec> is only implemented for pointers"); using K = RAJA::detail::IterVal<KeyIter>; static_assert (type_traits::is_arithmetic<K>::value, "sort_pairs<hip_exec> is only implemented for arithmetic types"); static_assert (concepts::any_of< camp::is_same<Compare, operators::less<K>>, camp::is_same<Compare, operators::greater<K>>>::value, "sort_pairs<hip_exec> is only implemented for RAJA::operators::less or RAJA::operators::greater"); return resources::EventProxy<resources::Hip>(hip_res); } /*! \brief stable sort given range of pairs in ascending order of keys */ template <size_t BLOCK_SIZE, bool Async, typename KeyIter, typename ValIter> concepts::enable_if_t<resources::EventProxy<resources::Hip>, type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>, std::is_pointer<KeyIter>, std::is_pointer<ValIter>> unstable_pairs( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async> p, KeyIter keys_begin, KeyIter keys_end, ValIter vals_begin, operators::less<RAJA::detail::IterVal<KeyIter>> comp) { return stable_pairs(hip_res, p, keys_begin, keys_end, vals_begin, comp); } /*! \brief stable sort given range of pairs in descending order of keys */ template <size_t BLOCK_SIZE, bool Async, typename KeyIter, typename ValIter> concepts::enable_if_t<resources::EventProxy<resources::Hip>, type_traits::is_arithmetic<RAJA::detail::IterVal<KeyIter>>, std::is_pointer<KeyIter>, std::is_pointer<ValIter>> unstable_pairs( resources::Hip hip_res, hip_exec<BLOCK_SIZE, Async> p, KeyIter keys_begin, KeyIter keys_end, ValIter vals_begin, operators::greater<RAJA::detail::IterVal<KeyIter>> comp) { return stable_pairs(hip_res, p, keys_begin, keys_end, vals_begin, comp); } } // namespace sort } // namespace impl } // namespace RAJA #endif // closing endif for RAJA_ENABLE_HIP guard #endif // closing endif for header file include guard
37.271917
155
0.54772
keichi
80f1a3fe3290d70601a0530de0edda17489931b1
42
cpp
C++
2018/day15/day15/graph.cpp
zagura/aoc-2017
bfd38fb6fbe4211017a306d218b32ecff741e006
[ "MIT" ]
2
2018-12-09T16:00:09.000Z
2018-12-09T17:56:15.000Z
2018/day15/day15/graph.cpp
zagura/aoc-2017
bfd38fb6fbe4211017a306d218b32ecff741e006
[ "MIT" ]
null
null
null
2018/day15/day15/graph.cpp
zagura/aoc-2017
bfd38fb6fbe4211017a306d218b32ecff741e006
[ "MIT" ]
null
null
null
#include "graph.hpp" Graph::Graph() { }
6
20
0.595238
zagura
80f3d98b065279779da3a4fa531dcb89099b8e50
14,935
cc
C++
modules/perception/obstacle/camera/converter/geometry_camera_converter.cc
DinnerHowe/apollo
f45b63ea2f2409dbd1b007476d816d6ec44ba06c
[ "Apache-2.0" ]
19
2018-07-26T03:17:32.000Z
2021-01-04T02:17:09.000Z
modules/perception/obstacle/camera/converter/geometry_camera_converter.cc
DinnerHowe/apollo
f45b63ea2f2409dbd1b007476d816d6ec44ba06c
[ "Apache-2.0" ]
null
null
null
modules/perception/obstacle/camera/converter/geometry_camera_converter.cc
DinnerHowe/apollo
f45b63ea2f2409dbd1b007476d816d6ec44ba06c
[ "Apache-2.0" ]
10
2018-10-17T03:18:16.000Z
2020-07-02T06:18:14.000Z
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ // Convert 2D detections into 3D objects #include "modules/perception/obstacle/camera/converter/geometry_camera_converter.h" namespace apollo { namespace perception { bool GeometryCameraConverter::Init() { ConfigManager *config_manager = ConfigManager::instance(); const ModelConfig *model_config = config_manager->GetModelConfig(Name()); if (model_config == nullptr) { AERROR << "Model config: " << Name() << " not found"; return false; } std::string intrinsic_file_path = ""; if (!model_config->GetValue("camera_intrinsic_file", &intrinsic_file_path)) { AERROR << "Failed to get camera intrinsics file path: " << Name(); return false; } if (!LoadCameraIntrinsics(intrinsic_file_path)) { AERROR << "Failed to get camera intrinsics: " << intrinsic_file_path; return false; } return true; } bool GeometryCameraConverter::Convert(std::vector<VisualObjectPtr> *objects) { if (!objects) return false; for (auto &obj : *objects) { Eigen::Vector2f trunc_center_pixel = Eigen::Vector2f::Zero(); CheckTruncation(obj, &trunc_center_pixel); CheckSizeSanity(obj); float deg_alpha = obj->alpha * 180.0f / M_PI; Eigen::Vector2f upper_left(obj->upper_left.x(), obj->upper_left.y()); Eigen::Vector2f lower_right(obj->lower_right.x(), obj->lower_right.y()); float distance_w = 0.0; float distance_h = 0.0; Eigen::Vector2f mass_center_pixel = Eigen::Vector2f::Zero(); ConvertSingle(obj->height, obj->width, obj->length, deg_alpha, upper_left, lower_right, &distance_w, &distance_h, &mass_center_pixel); if (obj->trunc_width > 0.25f && obj->trunc_height > 0.25f) { // Give fix values for detected box with both side and bottom truncation distance_w = distance_h = 10.0f; obj->distance = DecideDistance(distance_h, distance_w, obj); // Estimation of center pixel due to unknown truncation ratio if (obj->trunc_width > 0.25f) mass_center_pixel = trunc_center_pixel; } else if (distance_w > 40.0f || distance_h > 40.0f || obj->trunc_width > 0.25f) { // Reset alpha angle and redo again (Model dependent issue) obj->distance = DecideDistance(distance_h, distance_w, obj); DecideAngle(camera_model_.unproject(mass_center_pixel), obj); deg_alpha = obj->alpha * 180.0f / M_PI; ConvertSingle(obj->height, obj->width, obj->length, deg_alpha, upper_left, lower_right, &distance_w, &distance_h, &mass_center_pixel); } obj->distance = DecideDistance(distance_h, distance_w, obj); Eigen::Vector3f camera_ray = camera_model_.unproject(mass_center_pixel); DecideAngle(camera_ray, obj); // Center (3D Mass Center of 3D BBox) float scale = obj->distance / sqrt(camera_ray.x() * camera_ray.x() + camera_ray.y() * camera_ray.y() + camera_ray.z() * camera_ray.z()); obj->center = camera_ray * scale; // Set 8 corner pixels obj->pts8.resize(16); if (obj->trunc_width < 0.25f && obj->trunc_height < 0.25f) { for (int i = 0; i < 8; i++) { obj->pts8[i * 2] = pixel_corners_[i].x(); obj->pts8[i * 2 + 1] = pixel_corners_[i].y(); } } } return true; } void GeometryCameraConverter::SetDebug(bool flag) { debug_ = flag; } std::string GeometryCameraConverter::Name() const { return "GeometryCameraConverter"; } bool GeometryCameraConverter::LoadCameraIntrinsics( const std::string &file_path) { YAML::Node node = YAML::LoadFile(file_path); Eigen::Matrix3f intrinsic_k; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { int index = i * 3 + j; intrinsic_k(i, j) = node["K"][index].as<float>(); } } Eigen::Matrix<float, 5, 1> intrinsic_d; for (int i = 0; i < 5; i++) { intrinsic_d(i, 0) = node["D"][i].as<float>(); } float height = node["height"].as<float>(); float width = node["width"].as<float>(); camera_model_.set(intrinsic_k, width, height); camera_model_.set_distort_params(intrinsic_d); return true; } bool GeometryCameraConverter::ConvertSingle( const float &h, const float &w, const float &l, const float &alpha_deg, const Eigen::Vector2f &upper_left, const Eigen::Vector2f &lower_right, float *distance_w, float *distance_h, Eigen::Vector2f *mass_center_pixel) { // Target Goals: Projection target int pixel_width = static_cast<int>(lower_right.x() - upper_left.x()); int pixel_height = static_cast<int>(lower_right.y() - upper_left.y()); // Target Goals: Box center pixel Eigen::Matrix<float, 2, 1> box_center_pixel; box_center_pixel.x() = (lower_right.x() + upper_left.x()) / 2.0f; box_center_pixel.y() = (lower_right.y() + upper_left.y()) / 2.0f; // Generate alpha rotated 3D template here. Corners in Camera space: // Bottom: FL, FR, RR, RL => Top: FL, FR, RR, RL float deg_alpha = alpha_deg; float h_half = h / 2.0f; float w_half = w / 2.0f; float l_half = l / 2.0f; std::vector<Eigen::Vector3f> corners; corners.resize(8); corners[0] = Eigen::Vector3f(l_half, h_half, w_half); corners[1] = Eigen::Vector3f(l_half, h_half, -w_half); corners[2] = Eigen::Vector3f(-l_half, h_half, -w_half); corners[3] = Eigen::Vector3f(-l_half, h_half, w_half); corners[4] = Eigen::Vector3f(l_half, -h_half, w_half); corners[5] = Eigen::Vector3f(l_half, -h_half, -w_half); corners[6] = Eigen::Vector3f(-l_half, -h_half, -w_half); corners[7] = Eigen::Vector3f(-l_half, -h_half, w_half); Rotate(deg_alpha, &corners); corners_ = corners; pixel_corners_.clear(); pixel_corners_.resize(8); // Try to get an initial Mass center pixel and vector Eigen::Matrix<float, 3, 1> middle_v(0.0f, 0.0f, 20.0f); Eigen::Matrix<float, 2, 1> center_pixel = camera_model_.project(middle_v); float max_pixel_x = std::numeric_limits<float>::min(); float min_pixel_x = std::numeric_limits<float>::max(); float max_pixel_y = std::numeric_limits<float>::min(); float min_pixel_y = std::numeric_limits<float>::max(); for (size_t i = 0; i < corners.size(); ++i) { Eigen::Vector2f point_2d = camera_model_.project(corners[i] + middle_v); min_pixel_x = std::min(min_pixel_x, point_2d.x()); max_pixel_x = std::max(max_pixel_x, point_2d.x()); min_pixel_y = std::min(min_pixel_y, point_2d.y()); max_pixel_y = std::max(max_pixel_y, point_2d.y()); } float relative_x = (center_pixel.x() - min_pixel_x) / (max_pixel_x - min_pixel_x); float relative_y = (center_pixel.y() - min_pixel_y) / (max_pixel_y - min_pixel_y); mass_center_pixel->x() = (lower_right.x() - upper_left.x()) * relative_x + upper_left.x(); mass_center_pixel->y() = (lower_right.y() - upper_left.y()) * relative_y + upper_left.y(); Eigen::Matrix<float, 3, 1> mass_center_v = camera_model_.unproject(*mass_center_pixel); mass_center_v = MakeUnit(mass_center_v); // Binary search *distance_w = SearchDistance(pixel_width, true, mass_center_v); *distance_h = SearchDistance(pixel_height, false, mass_center_v); for (size_t i = 0; i < 2; ++i) { // Mass center search SearchCenterDirection(box_center_pixel, *distance_h, &mass_center_v, mass_center_pixel); // Binary search *distance_w = SearchDistance(pixel_width, true, mass_center_v); *distance_h = SearchDistance(pixel_height, false, mass_center_v); } return true; } void GeometryCameraConverter::Rotate( const float &alpha_deg, std::vector<Eigen::Vector3f> *corners) const { Eigen::AngleAxisf yaw(alpha_deg / 180.0f * M_PI, Eigen::Vector3f::UnitY()); Eigen::AngleAxisf pitch(0.0, Eigen::Vector3f::UnitX()); Eigen::AngleAxisf roll(0.0, Eigen::Vector3f::UnitZ()); Eigen::Matrix3f rotation = yaw.toRotationMatrix() * pitch.toRotationMatrix() * roll.toRotationMatrix(); Eigen::Matrix4f transform; transform.setIdentity(); transform.block(0, 0, 3, 3) = rotation; for (auto &corner : *corners) { Eigen::Vector4f temp(corner.x(), corner.y(), corner.z(), 1.0f); temp = transform * temp; corner = Eigen::Vector3f(temp.x(), temp.y(), temp.z()); } } float GeometryCameraConverter::SearchDistance( const int &pixel_length, const bool &use_width, const Eigen::Matrix<float, 3, 1> &mass_center_v) { float close_d = 0.1f; float far_d = 200.0f; float curr_d = 0.0f; int depth = 0; while (close_d <= far_d && depth < kMaxDistanceSearchDepth_) { curr_d = (far_d + close_d) / 2.0f; Eigen::Vector3f curr_p = mass_center_v * curr_d; float min_p = std::numeric_limits<float>::max(); float max_p = 0.0f; for (size_t i = 0; i < corners_.size(); ++i) { Eigen::Vector2f point_2d = camera_model_.project(corners_[i] + curr_p); pixel_corners_[i] = point_2d; float curr_pixel = 0.0f; if (use_width) { curr_pixel = point_2d.x(); } else { curr_pixel = point_2d.y(); } min_p = std::min(min_p, curr_pixel); max_p = std::max(max_p, curr_pixel); } int curr_pixel_length = static_cast<int>(max_p - min_p); if (curr_pixel_length == pixel_length) { break; } else if (pixel_length < curr_pixel_length) { close_d = curr_d + 0.01f; } else { // pixel_length > curr_pixel_length far_d = curr_d - 0.01f; } // Early break for 0.01m accuracy float next_d = (far_d + close_d) / 2.0f; if (std::abs(next_d - curr_d) < 0.01f) { break; } ++depth; } return curr_d; } void GeometryCameraConverter::SearchCenterDirection( const Eigen::Matrix<float, 2, 1> &box_center_pixel, const float &curr_d, Eigen::Matrix<float, 3, 1> *mass_center_v, Eigen::Matrix<float, 2, 1> *mass_center_pixel) const { int depth = 0; while (depth < kMaxCenterDirectionSearchDepth_) { Eigen::Matrix<float, 3, 1> new_center_v = *mass_center_v * curr_d; float max_pixel_x = std::numeric_limits<float>::min(); float min_pixel_x = std::numeric_limits<float>::max(); float max_pixel_y = std::numeric_limits<float>::min(); float min_pixel_y = std::numeric_limits<float>::max(); for (size_t i = 0; i < corners_.size(); ++i) { Eigen::Vector2f point_2d = camera_model_.project(corners_[i] + new_center_v); min_pixel_x = std::min(min_pixel_x, point_2d.x()); max_pixel_x = std::max(max_pixel_x, point_2d.x()); min_pixel_y = std::min(min_pixel_y, point_2d.y()); max_pixel_y = std::max(max_pixel_y, point_2d.y()); } Eigen::Matrix<float, 2, 1> current_box_center_pixel; current_box_center_pixel.x() = (max_pixel_x + min_pixel_x) / 2.0; current_box_center_pixel.y() = (max_pixel_y + min_pixel_y) / 2.0; // Update mass center *mass_center_pixel += box_center_pixel - current_box_center_pixel; *mass_center_v = camera_model_.unproject(*mass_center_pixel); *mass_center_v = MakeUnit(*mass_center_v); if (std::abs(mass_center_pixel->x() - box_center_pixel.x()) < 1.0 && std::abs(mass_center_pixel->y() - box_center_pixel.y()) < 1.0) { break; } ++depth; } return; } Eigen::Matrix<float, 3, 1> GeometryCameraConverter::MakeUnit( const Eigen::Matrix<float, 3, 1> &v) const { Eigen::Matrix<float, 3, 1> unit_v = v; float to_unit_scale = std::sqrt(unit_v.x() * unit_v.x() + unit_v.y() * unit_v.y() + unit_v.z() * unit_v.z()); unit_v /= to_unit_scale; return unit_v; } void GeometryCameraConverter::CheckSizeSanity(VisualObjectPtr obj) const { if (obj->type == ObjectType::VEHICLE) { obj->length = std::max(obj->length, 3.6f); obj->width = std::max(obj->width, 1.6f); obj->height = std::max(obj->height, 1.5f); } else if (obj->type == ObjectType::PEDESTRIAN) { obj->length = std::max(obj->length, 0.5f); obj->width = std::max(obj->width, 0.5f); obj->height = std::max(obj->height, 1.7f); } else if (obj->type == ObjectType::BICYCLE) { obj->length = std::max(obj->length, 1.8f); obj->width = std::max(obj->width, 1.2f); obj->height = std::max(obj->height, 1.5f); } else { obj->length = std::max(obj->length, 0.5f); obj->width = std::max(obj->width, 0.5f); obj->height = std::max(obj->height, 1.5f); } } void GeometryCameraConverter::CheckTruncation(VisualObjectPtr obj, Eigen::Matrix<float, 2, 1> *trunc_center_pixel) const { auto width = camera_model_.get_width(); auto height = camera_model_.get_height(); // Ad-hoc 2D box truncation binary determination if (obj->upper_left.x() < 30.0f || width - 30.0f < obj->lower_right.x()) { obj->trunc_width = 0.5f; trunc_center_pixel->y() = (obj->upper_left.y() + obj->lower_right.y()) / 2.0f; if (obj->upper_left.x() < 30.0f) { trunc_center_pixel->x() = obj->upper_left.x(); } else { trunc_center_pixel->x() = obj->lower_right.x(); } } if (obj->upper_left.y() < 30.0f || height - 30.0f < obj->lower_right.y()) { obj->trunc_height = 0.5f; } } float GeometryCameraConverter::DecideDistance(const float &distance_h, const float &distance_w, VisualObjectPtr obj) const { float distance = distance_h; // TODO(later): Deal with truncation return distance; } void GeometryCameraConverter::DecideAngle(const Eigen::Vector3f &camera_ray, VisualObjectPtr obj) const { float beta = std::atan2(camera_ray.x(), camera_ray.z()); // Orientation is not reliable in these cases (DL model specific issue) if (obj->distance > 50.0f || obj->trunc_width > 0.25f) { obj->theta = -1.0f * M_PI_2; obj->alpha = obj->theta - beta; if (obj->alpha > M_PI) { obj->alpha -= 2 * M_PI; } else if (obj->alpha < -M_PI) { obj->alpha += 2 * M_PI; } } else { // Normal cases float theta = obj->alpha + beta; if (theta > M_PI) { theta -= 2 * M_PI; } else if (theta < -M_PI) { theta += 2 * M_PI; } obj->theta = theta; } } } // namespace perception } // namespace apollo
36.3382
83
0.640509
DinnerHowe
80f457acb73146c1efd6b335b61609bd3182ebbc
2,890
cpp
C++
StepEditor/RawResponseDlg.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
1
2021-12-31T17:20:01.000Z
2021-12-31T17:20:01.000Z
StepEditor/RawResponseDlg.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
10
2022-01-14T13:28:32.000Z
2022-02-13T12:46:34.000Z
StepEditor/RawResponseDlg.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////////// // // // ██╗░░██╗░██╗░░░░░░░██╗░█████╗░████████╗████████╗░█████╗░ // ██║░██╔╝░██║░░██╗░░██║██╔══██╗╚══██╔══╝╚══██╔══╝██╔══██╗ // █████═╝░░╚██╗████╗██╔╝███████║░░░██║░░░░░░██║░░░███████║ // ██╔═██╗░░░████╔═████║░██╔══██║░░░██║░░░░░░██║░░░██╔══██║ // ██║░╚██╗░░╚██╔╝░╚██╔╝░██║░░██║░░░██║░░░░░░██║░░░██║░░██║ // ╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝░░░╚═╝░░░░░░╚═╝░░░╚═╝░░╚═╝ // // // This product: KWATTA (KWAliTy Test API) Test suite for Command-line SOAP/JSON/HTTP internet API's // This program: StepEditor // This File : RawResponseDlg.cpp // What it does: Resulting raw response of a HTTP internet test call // Author : ir. W.E. Huisman // License : See license.md file in the root directory // /////////////////////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "StepEditor.h" #include "TestStepNET.h" #include "StepResultNET.h" #include "RawResponseDlg.h" #include "StepInternetDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif // RawResponseDlg dialog IMPLEMENT_DYNAMIC(RawResponseDlg,StyleDialog) RawResponseDlg::RawResponseDlg(CWnd* pParent /*=nullptr*/) :StyleDialog(IDD_RAW_RESPONSE,pParent) { } RawResponseDlg::~RawResponseDlg() { } void RawResponseDlg::DoDataExchange(CDataExchange* pDX) { StyleDialog::DoDataExchange(pDX); DDX_Control(pDX,IDC_RAW,m_editPayload,m_payload); } BEGIN_MESSAGE_MAP(RawResponseDlg,StyleDialog) ON_EN_KILLFOCUS(IDC_RAW,&RawResponseDlg::OnEnKillfocusPayload) END_MESSAGE_MAP() BOOL RawResponseDlg::OnInitDialog() { StyleDialog::OnInitDialog(); InitPayload(); SetCanResize(); return TRUE; } void RawResponseDlg::SetupDynamicLayout() { StyleDialog::SetupDynamicLayout(); CMFCDynamicLayout& manager = *GetDynamicLayout(); #ifdef _DEBUG manager.AssertValid(); #endif manager.AddItem(IDC_RAW,CMFCDynamicLayout::MoveNone(),CMFCDynamicLayout::SizeHorizontalAndVertical(100,100)); } void RawResponseDlg::InitPayload() { m_editPayload.SetFontName("Courier new",100); m_editPayload.SetMutable(false); } void RawResponseDlg::InitTab() { m_payload.Empty(); UpdateData(FALSE); } void RawResponseDlg::SetResult(StepResultNET* p_result) { m_payload = p_result->GetRawResponse(); m_payload.Replace("\n","\r\n"); UpdateData(FALSE); } void RawResponseDlg::StoreVariables() { // Nothing to do } // RawResponseDlg message handlers void RawResponseDlg::OnEnKillfocusPayload() { // Getting the payload as body for the message UpdateData(); if(m_testStep) { m_testStep->SetBody(m_payload); // Check parameters StepInternetDlg* step = reinterpret_cast<StepInternetDlg*>(GetParent()->GetParent()); step->EffectiveParameters(); } }
22.403101
111
0.597924
edwig
80f6bc462b24e46667b580c21423f59b1e35b003
226
cpp
C++
Engine/Source/Runtime/Engine/Private/AI/Navigation/NavAreas/NavArea_Default.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/Engine/Private/AI/Navigation/NavAreas/NavArea_Default.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/Engine/Private/AI/Navigation/NavAreas/NavArea_Default.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "AI/Navigation/NavAreas/NavArea_Default.h" UNavArea_Default::UNavArea_Default(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { }
28.25
106
0.809735
windystrife
80f9094b2e531ee4919911441a2d788de2d55135
2,871
hpp
C++
hpx/performance_counters/parcels/count_time_stats.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/performance_counters/parcels/count_time_stats.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/performance_counters/parcels/count_time_stats.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2011 Katelyn Kufahl // // 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) //////////////////////////////////////////////////////////////////////////////// #if !defined(HPX_05A1C29B_DB73_463A_8C9D_B8EDC3B69F5E) #define HPX_05A1C29B_DB73_463A_8C9D_B8EDC3B69F5E #include <boost/config.hpp> #include <boost/assert.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/variance.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/moment.hpp> #include <boost/cstdint.hpp> #include <boost/atomic.hpp> #include <hpx/performance_counters/parcels/count_and_time_data_point.hpp> #include <hpx/util/high_resolution_timer.hpp> #include <hpx/util/spinlock.hpp> namespace hpx { namespace performance_counters { namespace parcels { class count_time_stats { typedef hpx::util::spinlock mutex_type; typedef mutex_type::scoped_lock lock; typedef boost::accumulators::accumulator_set acc_set; public: count_time_stats(): count_time_stats_size(0) {} boost::int64_t size() const; void push_back(data_point const& x); double mean_time() const; double moment_time() const; double variance_time() const; double total_time() const; private: util::high_resolution_timer timer; boost::atomic<boost::int64_t> count_time_stats_size; // Create mutexes for accumulator functions. mutable mutex_type acc_mtx; // Create accumulator sets. acc_set < double, boost::accumulators::features< boost::accumulators::tag::mean > > mean_time_acc; acc_set < double, boost::accumulators::features< boost::accumulators::tag::moment<2> > > moment_time_acc; acc_set < double, boost::accumulators::features< boost::accumulators::tag::variance> > variance_time_acc; }; inline void count_time_stats::push_back(count_and_time_data_point const& x) { lock mtx(acc_mtx) ++count_time_stats_size; mean_time_acc(x.time); moment_time_acc(x.time); variance_time_acc(x.time); } inline boost::int64_t count_time_stats::size() const { return count_time_stats_size.load(); } inline double count_time_stats::mean_time() const { lock mtx(acc_mtx); return boost::accumulators::extract::mean(mean_time_acc); } inline double count_time_stats::moment_time() const { lock mtx(acc_mtx); return boost::accumulators::extract::moment<2>(moment_time_acc); } inline double count_time_stats::variance_time() const { lock mtx(acc_mtx); return boost::accumulators::extract::variance(variance_time_acc); } }}} #endif // HPX_05A1C29B_DB73_463A_8C9D_B8EDC3B69F5E
26.831776
80
0.695925
andreasbuhr
80fc1f458a79c0de61a543dd5740af2af132a74f
12,484
hpp
C++
libs/core/algorithms/include/hpx/parallel/algorithms/detail/dispatch.hpp
Andrea-MariaDB-2/hpx
e230dddce4a8783817f38e07f5a77e624f64f826
[ "BSL-1.0" ]
1,822
2015-01-03T11:22:37.000Z
2022-03-31T14:49:59.000Z
libs/core/algorithms/include/hpx/parallel/algorithms/detail/dispatch.hpp
Andrea-MariaDB-2/hpx
e230dddce4a8783817f38e07f5a77e624f64f826
[ "BSL-1.0" ]
3,288
2015-01-05T17:00:23.000Z
2022-03-31T18:49:41.000Z
libs/core/algorithms/include/hpx/parallel/algorithms/detail/dispatch.hpp
Andrea-MariaDB-2/hpx
e230dddce4a8783817f38e07f5a77e624f64f826
[ "BSL-1.0" ]
431
2015-01-07T06:22:14.000Z
2022-03-31T14:50:04.000Z
// Copyright (c) 2007-2017 Hartmut Kaiser // Copyright (c) 2021 Giannis Gonidelis // // SPDX-License-Identifier: BSL-1.0 // 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) #pragma once #include <hpx/config.hpp> #include <hpx/algorithms/traits/segmented_iterator_traits.hpp> #include <hpx/concepts/concepts.hpp> #include <hpx/datastructures/tuple.hpp> #include <hpx/execution/executors/execution.hpp> #include <hpx/executors/exception_list.hpp> #include <hpx/executors/execution_policy.hpp> #include <hpx/futures/future.hpp> #include <hpx/modules/errors.hpp> #include <hpx/parallel/util/detail/algorithm_result.hpp> #include <hpx/parallel/util/detail/scoped_executor_parameters.hpp> #include <hpx/parallel/util/result_types.hpp> #include <hpx/serialization/serialization_fwd.hpp> #if defined(HPX_HAVE_CXX17_STD_EXECUTION_POLICES) #include <execution> #endif #include <string> #include <type_traits> #include <utility> namespace hpx { namespace parallel { inline namespace v1 { namespace detail { /////////////////////////////////////////////////////////////////////////// template <typename Result> struct local_algorithm_result { using type = typename hpx::traits::segmented_local_iterator_traits< Result>::local_raw_iterator; }; template <typename Result1, typename Result2> struct local_algorithm_result<std::pair<Result1, Result2>> { using type1 = typename hpx::traits::segmented_local_iterator_traits< Result1>::local_raw_iterator; using type2 = typename hpx::traits::segmented_local_iterator_traits< Result2>::local_raw_iterator; using type = std::pair<type1, type2>; }; template <typename Result1, typename Result2> struct local_algorithm_result<util::in_out_result<Result1, Result2>> { using type1 = typename hpx::traits::segmented_local_iterator_traits< Result1>::local_raw_iterator; using type2 = typename hpx::traits::segmented_local_iterator_traits< Result2>::local_raw_iterator; using type = util::in_out_result<type1, type2>; }; template <typename Result1, typename Result2, typename Result3> struct local_algorithm_result<hpx::tuple<Result1, Result2, Result3>> { using type1 = typename hpx::traits::segmented_local_iterator_traits< Result1>::local_raw_iterator; using type2 = typename hpx::traits::segmented_local_iterator_traits< Result2>::local_raw_iterator; using type3 = typename hpx::traits::segmented_local_iterator_traits< Result3>::local_raw_iterator; using type = hpx::tuple<type1, type2, type3>; }; template <typename Result1, typename Result2, typename Result3> struct local_algorithm_result< util::in_in_out_result<Result1, Result2, Result3>> { using type1 = typename hpx::traits::segmented_local_iterator_traits< Result1>::local_raw_iterator; using type2 = typename hpx::traits::segmented_local_iterator_traits< Result2>::local_raw_iterator; using type3 = typename hpx::traits::segmented_local_iterator_traits< Result3>::local_raw_iterator; using type = util::in_in_out_result<type1, type2, type3>; }; template <> struct local_algorithm_result<void> { using type = void; }; /////////////////////////////////////////////////////////////////////////// template <typename Derived, typename Result = void> struct algorithm { private: Derived const& derived() const { return static_cast<Derived const&>(*this); } public: using result_type = Result; using local_result_type = typename local_algorithm_result<result_type>::type; explicit algorithm(char const* const name) : name_(name) { } /////////////////////////////////////////////////////////////////////// // this equivalent to sequential execution template <typename ExPolicy, typename... Args> HPX_HOST_DEVICE typename parallel::util::detail::algorithm_result<ExPolicy, local_result_type>::type operator()(ExPolicy&& policy, Args&&... args) const { #if !defined(__CUDA_ARCH__) try { #endif using parameters_type = typename std::decay< ExPolicy>::type::executor_parameters_type; using executor_type = typename std::decay<ExPolicy>::type::executor_type; parallel::util::detail::scoped_executor_parameters_ref< parameters_type, executor_type> scoped_param(policy.parameters(), policy.executor()); return parallel::util::detail:: algorithm_result<ExPolicy, local_result_type>::get( Derived::sequential(std::forward<ExPolicy>(policy), std::forward<Args>(args)...)); #if !defined(__CUDA_ARCH__) } catch (...) { // this does not return return detail::handle_exception<ExPolicy, local_result_type>::call(); } #endif } protected: /////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename... Args> constexpr typename parallel::util::detail::algorithm_result<ExPolicy, local_result_type>::type call_execute(ExPolicy&& policy, std::false_type, Args&&... args) const { using result = parallel::util::detail::algorithm_result<ExPolicy, local_result_type>; return result::get(execution::sync_execute(policy.executor(), derived(), std::forward<ExPolicy>(policy), std::forward<Args>(args)...)); } template <typename ExPolicy, typename... Args> constexpr typename parallel::util::detail::algorithm_result<ExPolicy>::type call_execute( ExPolicy&& policy, std::true_type, Args&&... args) const { execution::sync_execute(policy.executor(), derived(), std::forward<ExPolicy>(policy), std::forward<Args>(args)...); return parallel::util::detail::algorithm_result<ExPolicy>::get(); } /////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename... Args> typename parallel::util::detail::algorithm_result<ExPolicy, local_result_type>::type call_sequential(ExPolicy&& policy, Args&&... args) const { try { // run the launched task on the requested executor hpx::future<local_result_type> result = execution::async_execute(policy.executor(), derived(), std::forward<ExPolicy>(policy), std::forward<Args>(args)...); return parallel::util::detail::algorithm_result<ExPolicy, local_result_type>::get(std::move(result)); } catch (std::bad_alloc const& ba) { throw ba; } catch (...) { return detail::handle_exception<ExPolicy, local_result_type>::call(); } } public: /////////////////////////////////////////////////////////////////////// // main sequential dispatch entry points // specialization for all task-based (asynchronous) execution policies // clang-format off template <typename ExPolicy, typename... Args, HPX_CONCEPT_REQUIRES_( hpx::is_async_execution_policy_v<std::decay_t<ExPolicy>> )> // clang-format on constexpr typename parallel::util::detail::algorithm_result<ExPolicy, local_result_type>::type call2(ExPolicy&& policy, std::true_type, Args&&... args) const { return call_sequential( std::forward<ExPolicy>(policy), std::forward<Args>(args)...); } // clang-format off template <typename ExPolicy, typename... Args, HPX_CONCEPT_REQUIRES_( !hpx::is_async_execution_policy_v<std::decay_t<ExPolicy>> )> // clang-format on typename parallel::util::detail::algorithm_result<ExPolicy, local_result_type>::type call2(ExPolicy&& policy, std::true_type, Args&&... args) const { try { using is_void = std::is_void<local_result_type>; return call_execute(std::forward<ExPolicy>(policy), is_void(), std::forward<Args>(args)...); } catch (std::bad_alloc const& ba) { throw ba; } catch (...) { return detail::handle_exception<ExPolicy, local_result_type>::call(); } } // main parallel dispatch entry point template <typename ExPolicy, typename... Args> static constexpr typename parallel::util::detail::algorithm_result<ExPolicy, local_result_type>::type call2(ExPolicy&& policy, std::false_type, Args&&... args) { return Derived::parallel( std::forward<ExPolicy>(policy), std::forward<Args>(args)...); } template <typename ExPolicy, typename... Args> HPX_FORCEINLINE constexpr typename parallel::util::detail::algorithm_result<ExPolicy, local_result_type>::type call(ExPolicy&& policy, Args&&... args) { using is_seq = hpx::is_sequenced_execution_policy<ExPolicy>; return call2(std::forward<ExPolicy>(policy), is_seq(), std::forward<Args>(args)...); } #if defined(HPX_HAVE_CXX17_STD_EXECUTION_POLICES) // main dispatch entry points for std execution policies template <typename... Args> HPX_FORCEINLINE constexpr typename parallel::util::detail::algorithm_result< hpx::execution::sequenced_policy, local_result_type>::type call(std::execution::sequenced_policy, Args&&... args) { return call2(hpx::execution::seq, std::true_type(), std::forward<Args>(args)...); } template <typename... Args> HPX_FORCEINLINE constexpr typename parallel::util::detail::algorithm_result< hpx::execution::parallel_policy, local_result_type>::type call(std::execution::parallel_policy, Args&&... args) { return call2(hpx::execution::par, std::false_type(), std::forward<Args>(args)...); } template <typename... Args> HPX_FORCEINLINE constexpr typename parallel::util::detail::algorithm_result< hpx::execution::parallel_unsequenced_policy, local_result_type>::type call(std::execution::parallel_unsequenced_policy, Args&&... args) { return call2(hpx::execution::par_unseq, std::false_type(), std::forward<Args>(args)...); } #if defined(HPX_HAVE_CXX20_STD_EXECUTION_POLICES) template <typename... Args> HPX_FORCEINLINE constexpr typename parallel::util::detail::algorithm_result< hpx::execution::unsequenced_policy, local_result_type>::type call(std::execution::unsequenced_policy, Args&&... args) { return call2(hpx::execution::unseq, std::false_type(), std::forward<Args>(args)...); } #endif #endif private: char const* const name_; friend class hpx::serialization::access; template <typename Archive> void serialize(Archive&, unsigned int) { // no need to serialize 'name_' as it is always initialized by the // constructor } }; }}}} // namespace hpx::parallel::v1::detail
37.377246
80
0.577539
Andrea-MariaDB-2
80fd9445db389266bd3811e34ba54dcf7ca678d3
532
cpp
C++
lab0/Q5.cpp
jasonsie88/Algorithm
4d373df037aa68f4810e271d7f8488f3ded81864
[ "MIT" ]
1
2021-09-14T12:10:50.000Z
2021-09-14T12:10:50.000Z
lab0/Q5.cpp
jasonsie88/Algorithm
4d373df037aa68f4810e271d7f8488f3ded81864
[ "MIT" ]
null
null
null
lab0/Q5.cpp
jasonsie88/Algorithm
4d373df037aa68f4810e271d7f8488f3ded81864
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int ncase; while(cin>>ncase){ if(ncase==0){ break; } int a1[ncase+5],a2[ncase+5]; for(int i=0;i<ncase;i++){ cin>>a1[i]>>a2[i]; } bool flag=true; if(ncase%2){ cout<<"NO\n"; }else{ sort(a1,a1+ncase); sort(a2,a2+ncase); for(int i=0;i<ncase;i++){ if(a1[i]!=a2[i]){ flag=false; break; } } if(flag){ cout<<"YES\n"; }else{ cout<<"NO\n"; } } } return 0; }
14
33
0.456767
jasonsie88
80febcc662731b8104dbabdf1bfd52b7ff8bab4d
25,134
cpp
C++
wznmcmbd/IexWznm/JobWznmIexIex.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
wznmcmbd/IexWznm/JobWznmIexIex.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
wznmcmbd/IexWznm/JobWznmIexIex.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file JobWznmIexIex.cpp * job handler for job JobWznmIexIex (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 28 Nov 2020 */ // IP header --- ABOVE #ifdef WZNMCMBD #include <Wznmcmbd.h> #else #include <Wznmd.h> #endif #include "JobWznmIexIex.h" #include "JobWznmIexIex_blks.cpp" using namespace std; using namespace Sbecore; using namespace Xmlio; // IP ns.cust --- INSERT using namespace IexWznmIex; /****************************************************************************** class JobWznmIexIex ******************************************************************************/ JobWznmIexIex::JobWznmIexIex( XchgWznm* xchg , DbsWznm* dbswznm , const ubigint jrefSup , const uint ixWznmVLocale ) : JobWznm(xchg, VecWznmVJob::JOBWZNMIEXIEX, jrefSup, ixWznmVLocale) { jref = xchg->addJob(dbswznm, this, jrefSup); // IP constructor.cust1 --- INSERT // IP constructor.cust2 --- INSERT changeStage(dbswznm, VecVSge::IDLE); // IP constructor.cust3 --- INSERT }; JobWznmIexIex::~JobWznmIexIex() { // IP destructor.spec --- INSERT // IP destructor.cust --- INSERT xchg->removeJobByJref(jref); }; // IP cust --- INSERT void JobWznmIexIex::reset( DbsWznm* dbswznm ) { if (ixVSge != VecVSge::IDLE) changeStage(dbswznm, VecVSge::IDLE); }; void JobWznmIexIex::parseFromFile( DbsWznm* dbswznm , const string& _fullpath , const bool _xmlNotTxt , const string& _rectpath ) { if (ixVSge == VecVSge::IDLE) { fullpath = _fullpath; xmlNotTxt = _xmlNotTxt; rectpath = _rectpath; changeStage(dbswznm, VecVSge::PARSE); }; }; void JobWznmIexIex::import( DbsWznm* dbswznm ) { if (ixVSge == VecVSge::PRSDONE) changeStage(dbswznm, VecVSge::IMPORT); }; void JobWznmIexIex::reverse( DbsWznm* dbswznm ) { if (ixVSge == VecVSge::IMPERR) changeStage(dbswznm, VecVSge::REVERSE); }; void JobWznmIexIex::collect( DbsWznm* dbswznm , const map<uint,uint>& _icsWznmVIop ) { if (ixVSge == VecVSge::IDLE) { icsWznmVIop = _icsWznmVIop; changeStage(dbswznm, VecVSge::COLLECT); }; }; void JobWznmIexIex::exportToFile( DbsWznm* dbswznm , const string& _fullpath , const bool _xmlNotTxt , const bool _shorttags ) { if ((ixVSge == VecVSge::IDLE) || (ixVSge == VecVSge::CLTDONE)) { fullpath = _fullpath; xmlNotTxt = _xmlNotTxt; shorttags = _shorttags; changeStage(dbswznm, VecVSge::EXPORT); }; }; void JobWznmIexIex::handleRequest( DbsWznm* dbswznm , ReqWznm* req ) { if (req->ixVBasetype == ReqWznm::VecVBasetype::CMD) { reqCmd = req; if (req->cmd == "cmdset") { } else { cout << "\tinvalid command!" << endl; }; if (!req->retain) reqCmd = NULL; }; }; void JobWznmIexIex::changeStage( DbsWznm* dbswznm , uint _ixVSge ) { bool reenter = true; do { if (ixVSge != _ixVSge) { switch (ixVSge) { case VecVSge::IDLE: leaveSgeIdle(dbswznm); break; case VecVSge::PARSE: leaveSgeParse(dbswznm); break; case VecVSge::PRSERR: leaveSgePrserr(dbswznm); break; case VecVSge::PRSDONE: leaveSgePrsdone(dbswznm); break; case VecVSge::IMPORT: leaveSgeImport(dbswznm); break; case VecVSge::IMPERR: leaveSgeImperr(dbswznm); break; case VecVSge::REVERSE: leaveSgeReverse(dbswznm); break; case VecVSge::COLLECT: leaveSgeCollect(dbswznm); break; case VecVSge::CLTDONE: leaveSgeCltdone(dbswznm); break; case VecVSge::EXPORT: leaveSgeExport(dbswznm); break; case VecVSge::DONE: leaveSgeDone(dbswznm); break; }; setStage(dbswznm, _ixVSge); reenter = false; // IP changeStage.refresh1 --- INSERT }; switch (_ixVSge) { case VecVSge::IDLE: _ixVSge = enterSgeIdle(dbswznm, reenter); break; case VecVSge::PARSE: _ixVSge = enterSgeParse(dbswznm, reenter); break; case VecVSge::PRSERR: _ixVSge = enterSgePrserr(dbswznm, reenter); break; case VecVSge::PRSDONE: _ixVSge = enterSgePrsdone(dbswznm, reenter); break; case VecVSge::IMPORT: _ixVSge = enterSgeImport(dbswznm, reenter); break; case VecVSge::IMPERR: _ixVSge = enterSgeImperr(dbswznm, reenter); break; case VecVSge::REVERSE: _ixVSge = enterSgeReverse(dbswznm, reenter); break; case VecVSge::COLLECT: _ixVSge = enterSgeCollect(dbswznm, reenter); break; case VecVSge::CLTDONE: _ixVSge = enterSgeCltdone(dbswznm, reenter); break; case VecVSge::EXPORT: _ixVSge = enterSgeExport(dbswznm, reenter); break; case VecVSge::DONE: _ixVSge = enterSgeDone(dbswznm, reenter); break; }; // IP changeStage.refresh2 --- INSERT } while (ixVSge != _ixVSge); }; string JobWznmIexIex::getSquawk( DbsWznm* dbswznm ) { string retval; // IP getSquawk --- RBEGIN if ( (ixVSge == VecVSge::PARSE) || (ixVSge == VecVSge::PRSDONE) || (ixVSge == VecVSge::IMPORT) || (ixVSge == VecVSge::REVERSE) || (ixVSge == VecVSge::COLLECT) || (ixVSge == VecVSge::CLTDONE) || (ixVSge == VecVSge::EXPORT) ) { if (ixWznmVLocale == VecWznmVLocale::ENUS) { if (ixVSge == VecVSge::PARSE) retval = "parsing import/export structure"; else if (ixVSge == VecVSge::PRSDONE) retval = "import/export structure parsed"; else if (ixVSge == VecVSge::IMPORT) retval = "importing import/export structure (" + to_string(impcnt) + " records added)"; else if (ixVSge == VecVSge::REVERSE) retval = "reversing import/export structure import"; else if (ixVSge == VecVSge::COLLECT) retval = "collecting import/export structure for export"; else if (ixVSge == VecVSge::CLTDONE) retval = "import/export structure collected for export"; else if (ixVSge == VecVSge::EXPORT) retval = "exporting import/export structure"; }; } else if ( (ixVSge == VecVSge::PRSERR) || (ixVSge == VecVSge::IMPERR) ) { retval = lasterror; } else { retval = VecVSge::getSref(ixVSge); }; // IP getSquawk --- REND return retval; }; uint JobWznmIexIex::enterSgeIdle( DbsWznm* dbswznm , const bool reenter ) { uint retval = VecVSge::IDLE; fullpath = ""; xmlNotTxt = false; rectpath = ""; lineno = 0; impcnt = 0; icsWznmVIop.clear(); imeimimpexpcplx.clear(); return retval; }; void JobWznmIexIex::leaveSgeIdle( DbsWznm* dbswznm ) { // IP leaveSgeIdle --- INSERT }; uint JobWznmIexIex::enterSgeParse( DbsWznm* dbswznm , const bool reenter ) { uint retval; nextIxVSgeSuccess = VecVSge::PRSDONE; retval = nextIxVSgeSuccess; nextIxVSgeFailure = VecVSge::PRSERR; try { IexWznmIex::parseFromFile(fullpath, xmlNotTxt, rectpath, imeimimpexpcplx); } catch (SbeException& e) { if (e.ix == SbeException::PATHNF) e.vals["path"] = "<hidden>"; lasterror = e.getSquawk(VecWznmVError::getIx, VecWznmVError::getTitle, ixWznmVLocale); retval = nextIxVSgeFailure; }; return retval; }; void JobWznmIexIex::leaveSgeParse( DbsWznm* dbswznm ) { // IP leaveSgeParse --- INSERT }; uint JobWznmIexIex::enterSgePrserr( DbsWznm* dbswznm , const bool reenter ) { uint retval = VecVSge::PRSERR; // IP enterSgePrserr --- INSERT return retval; }; void JobWznmIexIex::leaveSgePrserr( DbsWznm* dbswznm ) { // IP leaveSgePrserr --- INSERT }; uint JobWznmIexIex::enterSgePrsdone( DbsWznm* dbswznm , const bool reenter ) { uint retval = VecVSge::PRSDONE; // IP enterSgePrsdone --- INSERT return retval; }; void JobWznmIexIex::leaveSgePrsdone( DbsWznm* dbswznm ) { // IP leaveSgePrsdone --- INSERT }; uint JobWznmIexIex::enterSgeImport( DbsWznm* dbswznm , const bool reenter ) { uint retval; nextIxVSgeSuccess = VecVSge::DONE; retval = nextIxVSgeSuccess; nextIxVSgeFailure = VecVSge::IMPERR; ImeitemIMImpexpcplx* iex = NULL; ImeitemIJMImpexpcplxTitle* iexJtit = NULL; ImeitemIMImpexp* ime = NULL; ImeitemIMImpexpcol* iel = NULL; ImeitemIJMImpexpcolStub* ielJstb = NULL; set<ubigint> irefs1; uint num2; // IP enterSgeImport.prep --- IBEGIN ListWznmMLocale lcls; dbswznm->tblwznmmlocale->loadRstBySQL("SELECT * FROM TblWznmMLocale", false, lcls); ImeitemIMImpexp* ime2 = NULL; ubigint refWznmMVersion; string preflcl; refWznmMVersion = xchg->getRefPreset(VecWznmVPreset::PREWZNMREFVER, jref); Wznm::getVerlclsref(dbswznm, refWznmMVersion, preflcl); ubigint refWznmMVector; string Prjshort; Prjshort = Wznm::getPrjshort(dbswznm, refWznmMVersion); // IP enterSgeImport.prep --- IEND try { // IP enterSgeImport.traverse --- RBEGIN // -- ImeIMImpexpcplx for (unsigned int ix0 = 0; ix0 < imeimimpexpcplx.nodes.size(); ix0++) { iex = imeimimpexpcplx.nodes[ix0]; iex->refWznmMVersion = refWznmMVersion; //iex->sref: TBL //iex->Short: TBL //iex->refJTitle: SUB //iex->Title: TBL //iex->Minversion: TBL //iex->Comment: TBL dbswznm->tblwznmmimpexpcplx->insertRec(iex); impcnt++; if (((iex->Title != "")) && iex->imeijmimpexpcplxtitle.nodes.empty()) { iexJtit = new ImeitemIJMImpexpcplxTitle(); iex->imeijmimpexpcplxtitle.nodes.push_back(iexJtit); iexJtit->refWznmMImpexpcplx = iex->ref; iexJtit->Title = iex->Title; }; for (unsigned int ix1 = 0; ix1 < iex->imeijmimpexpcplxtitle.nodes.size(); ix1++) { iexJtit = iex->imeijmimpexpcplxtitle.nodes[ix1]; iexJtit->refWznmMImpexpcplx = iex->ref; //if (iexJtit->srefX1RefWznmMLocale == "") iexJtit->srefX1RefWznmMLocale: CUSTOM DEFVAL if (iexJtit->srefX1RefWznmMLocale == "") iexJtit->srefX1RefWznmMLocale = preflcl; //iexJtit->x1RefWznmMLocale: RST for (unsigned int i = 0; i < lcls.nodes.size(); i++) { if (lcls.nodes[i]->sref == iexJtit->srefX1RefWznmMLocale) { iexJtit->x1RefWznmMLocale = lcls.nodes[i]->ref; break; }; }; if (iexJtit->x1RefWznmMLocale == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iexJtit->srefX1RefWznmMLocale}, {"iel","srefX1RefWznmMLocale"}, {"lineno",to_string(iexJtit->lineno)}}); //iexJtit->Title: TBL dbswznm->tblwznmjmimpexpcplxtitle->insertRec(iexJtit); impcnt++; if (ix1 == 0) { iex->refJTitle = iexJtit->ref; iex->Title = iexJtit->Title; dbswznm->tblwznmmimpexpcplx->updateRec(iex); }; }; irefs1.clear(); for (unsigned int ix1 = 0; ix1 < iex->imeimimpexp.nodes.size(); ix1++) { ime = iex->imeimimpexp.nodes[ix1]; if (irefs1.find(ime->iref) != irefs1.end()) throw SbeException(SbeException::IEX_IDIREF, {{"idiref",to_string(ime->iref)}, {"ime","ImeIMImpexp"}, {"lineno",to_string(ime->lineno)}}); ime->refWznmMImpexpcplx = iex->ref; //ime->supRefWznmMImpexp: IMPPP //ime->refWznmMTable: CUSTSQL dbswznm->tblwznmmtable->loadRefByVerSrf(refWznmMVersion, ime->srefRefWznmMTable, ime->refWznmMTable); if (ime->refWznmMTable == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",ime->srefRefWznmMTable}, {"iel","srefRefWznmMTable"}, {"lineno",to_string(ime->lineno)}}); //ime->sref: TBL //ime->rtrSrefsWznmMImpexpcol: TBL ime->ixWIop = VecWznmWMImpexpIop::getIx(ime->srefsIxWIop); //ime->Comment: TBL dbswznm->tblwznmmimpexp->insertRec(ime); impcnt++; num2 = 1; for (unsigned int ix2 = 0; ix2 < ime->imeimimpexpcol.nodes.size(); ix2++) { iel = ime->imeimimpexpcol.nodes[ix2]; iel->ixVBasetype = VecWznmVMImpexpcolBasetype::getIx(iel->srefIxVBasetype); if (iel->ixVBasetype == 0) throw SbeException(SbeException::IEX_VSREF, {{"vsref",iel->srefIxVBasetype}, {"iel","srefIxVBasetype"}, {"lineno",to_string(iel->lineno)}}); iel->ixWOccurrence = VecWznmWMImpexpcolOccurrence::getIx(iel->srefsIxWOccurrence); iel->imeRefWznmMImpexp = ime->ref; iel->imeNum = num2++; if (iel->srefRefWznmMTablecol != "") { //iel->refWznmMTablecol: CUSTSQL dbswznm->loadRefBySQL("SELECT ref FROM TblWznmMTablecol WHERE tblRefWznmMTable = " + to_string(ime->refWznmMTable) + " AND sref = '" + iel->srefRefWznmMTablecol + "'", iel->refWznmMTablecol); if (iel->refWznmMTablecol == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iel->srefRefWznmMTablecol}, {"iel","srefRefWznmMTablecol"}, {"lineno",to_string(iel->lineno)}}); }; //iel->sref: TBL //iel->Short: TBL //iel->refWznmMImpexp: IMPPP iel->ixVConvtype = VecWznmVMImpexpcolConvtype::getIx(iel->srefIxVConvtype); if (iel->ixVConvtype == 0) throw SbeException(SbeException::IEX_VSREF, {{"vsref",iel->srefIxVConvtype}, {"iel","srefIxVConvtype"}, {"lineno",to_string(iel->lineno)}}); //iel->Defval: TBL if (iel->srefRefWznmMPreset != "") { //iel->refWznmMPreset: CUSTSQL dbswznm->tblwznmmpreset->loadRefByVerSrf(refWznmMVersion, iel->srefRefWznmMPreset, iel->refWznmMPreset); if (iel->refWznmMPreset == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iel->srefRefWznmMPreset}, {"iel","srefRefWznmMPreset"}, {"lineno",to_string(iel->lineno)}}); }; //iel->refJStub: SUB if (iel->srefRefWznmMStub != "") { //iel->refWznmMStub: CUSTSQL dbswznm->loadRefBySQL("SELECT TblWznmMStub.ref FROM TblWznmMTable, TblWznmMStub WHERE TblWznmMTable.refWznmMVersion = " + to_string(refWznmMVersion) + " AND TblWznmMStub.refWznmMTable = TblWznmMTable.ref AND TblWznmMStub.sref = '" + iel->srefRefWznmMStub + "'", iel->refWznmMStub); if (iel->refWznmMStub == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iel->srefRefWznmMStub}, {"iel","srefRefWznmMStub"}, {"lineno",to_string(iel->lineno)}}); }; if (iel->srefRefWznmMVectoritem != "") { //iel->refWznmMVectoritem: CUSTSQL dbswznm->loadRefBySQL("SELECT TblWznmMVectoritem.ref FROM TblWznmMTablecol, TblWznmMVectoritem WHERE TblWznmMVectoritem.vecRefWznmMVector = TblWznmMTablecol.fctUref AND TblWznmMTablecol.ref = " + to_string(iel->refWznmMTablecol) + " AND TblWznmMVectoritem.sref = '" + iel->srefRefWznmMVectoritem + "'", iel->refWznmMVectoritem); if (iel->refWznmMVectoritem == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",iel->srefRefWznmMVectoritem}, {"iel","srefRefWznmMVectoritem"}, {"lineno",to_string(iel->lineno)}}); }; dbswznm->tblwznmmimpexpcol->insertRec(iel); impcnt++; if (((iel->srefRefWznmMStub != "")) && iel->imeijmimpexpcolstub.nodes.empty()) { ielJstb = new ImeitemIJMImpexpcolStub(); iel->imeijmimpexpcolstub.nodes.push_back(ielJstb); ielJstb->refWznmMImpexpcol = iel->ref; ielJstb->srefRefWznmMStub = iel->srefRefWznmMStub; }; if (iel->imeijmimpexpcolstub.nodes.size() > 0) { if (dbswznm->loadRefBySQL("SELECT TblWznmMTablecol2.fctUref FROM TblWznmMTablecol AS TblWznmMTablecol1, TblWznmMTablecol AS TblWznmMTablecol2 WHERE TblWznmMTablecol1.refWznmMRelation = TblWznmMTablecol2.refWznmMRelation AND TblWznmMTablecol1.tblRefWznmMTable = TblWznmMTablecol2.tblRefWznmMTable AND TblWznmMTablecol1.ref = " + to_string(iel->refWznmMTablecol) + " AND TblWznmMTablecol2.ixVBasetype = " + to_string(VecWznmVMTablecolBasetype::VECREF) + " AND TblWznmMTablecol2.sref LIKE '%VTbl'", refWznmMVector)) { for (unsigned int ix3 = 0; ix3 < iel->imeijmimpexpcolstub.nodes.size(); ix3++) { ielJstb = iel->imeijmimpexpcolstub.nodes[ix3]; ielJstb->refWznmMImpexpcol = iel->ref; if (ielJstb->srefX1RefWznmMVectoritem != "") { //ielJstb->x1RefWznmMVectoritem = CUSTSQL; dbswznm->loadRefBySQL("SELECT ref FROM TblWznmMVectoritem WHERE vecRefWznmMVector = " + to_string(refWznmMVector) + " AND sref = '" + ielJstb->srefX1RefWznmMVectoritem + "'", ielJstb->x1RefWznmMVectoritem); if (ielJstb->x1RefWznmMVectoritem == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",ielJstb->srefX1RefWznmMVectoritem}, {"iel","srefX1RefWznmMVectoritem"}, {"lineno",to_string(ielJstb->lineno)}}); }; //ielJstb->refWznmMStub = CUSTSQL; dbswznm->loadRefBySQL("SELECT TblWznmMStub.ref FROM TblWznmMTable, TblWznmMStub WHERE TblWznmMTable.refWznmMVersion = " + to_string(refWznmMVersion) + " AND TblWznmMStub.refWznmMTable = TblWznmMTable.ref AND TblWznmMStub.sref = '" + ielJstb->srefRefWznmMStub + "'", ielJstb->refWznmMStub); if (ielJstb->refWznmMStub == 0) throw SbeException(SbeException::IEX_TSREF, {{"tsref",ielJstb->srefRefWznmMStub}, {"iel","srefRefWznmMStub"}, {"lineno",to_string(ielJstb->lineno)}}); dbswznm->tblwznmjmimpexpcolstub->insertRec(ielJstb); impcnt++; if (ix3 == 0) { iel->refJStub = ielJstb->ref; iel->refWznmMStub = ielJstb->refWznmMStub; dbswznm->tblwznmmimpexpcol->updateRec(iel); }; }; }; }; }; }; }; // IP enterSgeImport.traverse --- REND // IP enterSgeImport.ppr --- IBEGIN for (unsigned int ix0 = 0; ix0 < imeimimpexpcplx.nodes.size(); ix0++) { iex = imeimimpexpcplx.nodes[ix0]; for (unsigned int ix1 = 0; ix1 < iex->imeimimpexp.nodes.size(); ix1++) { ime = iex->imeimimpexp.nodes[ix1]; if (ime->irefSupRefWznmMImpexp != 0) { for (unsigned int ix2 = 0; ix2 < iex->imeimimpexp.nodes.size(); ix2++) { ime2 = iex->imeimimpexp.nodes[ix2]; if (ime2->iref == ime->irefSupRefWznmMImpexp) { ime->supRefWznmMImpexp = ime2->ref; ime->supLvl = ime2->supLvl + 1; break; }; }; if (ime->irefSupRefWznmMImpexp == 0) throw SbeException(SbeException::IEX_IREF, {{"iref",to_string(ime->irefSupRefWznmMImpexp)}, {"iel","irefSupRefWznmMImpexp"}, {"lineno",to_string(ime->lineno)}}); else dbswznm->tblwznmmimpexp->updateRec(ime); }; for (unsigned int ix2 = 0; ix2 < ime->imeimimpexpcol.nodes.size(); ix2++) { iel = ime->imeimimpexpcol.nodes[ix2]; if (iel->irefRefWznmMImpexp != 0) { for (unsigned int ix3 = 0; ix3 < iex->imeimimpexp.nodes.size(); ix3++) { ime2 = iex->imeimimpexp.nodes[ix3]; if (ime2->iref == iel->irefRefWznmMImpexp) { iel->refWznmMImpexp = ime2->ref; break; }; }; if (iel->irefRefWznmMImpexp == 0) throw SbeException(SbeException::IEX_IREF, {{"iref",to_string(iel->irefRefWznmMImpexp)}, {"iel","irefRefWznmMImpexp"}, {"lineno",to_string(iel->lineno)}}); else dbswznm->tblwznmmimpexpcol->updateRec(iel); }; }; }; }; // IP enterSgeImport.ppr --- IEND } catch (SbeException& e) { lasterror = e.getSquawk(VecWznmVError::getIx, VecWznmVError::getTitle, ixWznmVLocale); retval = nextIxVSgeFailure; }; return retval; }; void JobWznmIexIex::leaveSgeImport( DbsWznm* dbswznm ) { // IP leaveSgeImport --- INSERT }; uint JobWznmIexIex::enterSgeImperr( DbsWznm* dbswznm , const bool reenter ) { uint retval = VecVSge::IMPERR; // IP enterSgeImperr --- INSERT return retval; }; void JobWznmIexIex::leaveSgeImperr( DbsWznm* dbswznm ) { // IP leaveSgeImperr --- INSERT }; uint JobWznmIexIex::enterSgeReverse( DbsWznm* dbswznm , const bool reenter ) { uint retval; nextIxVSgeSuccess = VecVSge::IDLE; retval = nextIxVSgeSuccess; ImeitemIMImpexpcplx* iex = NULL; ImeitemIJMImpexpcplxTitle* iexJtit = NULL; ImeitemIMImpexp* ime = NULL; ImeitemIMImpexpcol* iel = NULL; ImeitemIJMImpexpcolStub* ielJstb = NULL; // -- ImeIMImpexpcplx for (unsigned int ix0 = 0; ix0 < imeimimpexpcplx.nodes.size(); ix0++) { iex = imeimimpexpcplx.nodes[ix0]; if (iex->ref != 0) dbswznm->tblwznmmimpexpcplx->removeRecByRef(iex->ref); for (unsigned int ix1 = 0; ix1 < iex->imeijmimpexpcplxtitle.nodes.size(); ix1++) { iexJtit = iex->imeijmimpexpcplxtitle.nodes[ix1]; if (iexJtit->ref != 0) dbswznm->tblwznmjmimpexpcplxtitle->removeRecByRef(iexJtit->ref); }; for (unsigned int ix1 = 0; ix1 < iex->imeimimpexp.nodes.size(); ix1++) { ime = iex->imeimimpexp.nodes[ix1]; if (ime->ref != 0) dbswznm->tblwznmmimpexp->removeRecByRef(ime->ref); for (unsigned int ix2 = 0; ix2 < ime->imeimimpexpcol.nodes.size(); ix2++) { iel = ime->imeimimpexpcol.nodes[ix2]; if (iel->ref != 0) dbswznm->tblwznmmimpexpcol->removeRecByRef(iel->ref); for (unsigned int ix3 = 0; ix3 < iel->imeijmimpexpcolstub.nodes.size(); ix3++) { ielJstb = iel->imeijmimpexpcolstub.nodes[ix3]; if (ielJstb->ref != 0) dbswznm->tblwznmjmimpexpcolstub->removeRecByRef(ielJstb->ref); }; }; }; }; return retval; }; void JobWznmIexIex::leaveSgeReverse( DbsWznm* dbswznm ) { // IP leaveSgeReverse --- INSERT }; uint JobWznmIexIex::enterSgeCollect( DbsWznm* dbswznm , const bool reenter ) { uint retval; nextIxVSgeSuccess = VecVSge::CLTDONE; retval = nextIxVSgeSuccess; ImeitemIMImpexpcplx* iex = NULL; ImeitemIJMImpexpcplxTitle* iexJtit = NULL; ImeitemIMImpexp* ime = NULL; ImeitemIMImpexpcol* iel = NULL; ImeitemIJMImpexpcolStub* ielJstb = NULL; uint ixWznmVIop; vector<ubigint> refs; Stcch* stcch = new Stcch(false); // IP enterSgeCollect.traverse --- BEGIN // -- ImeIMImpexpcplx for (unsigned int ix0 = 0; ix0 < imeimimpexpcplx.nodes.size(); ix0++) { iex = imeimimpexpcplx.nodes[ix0]; if (iex->ref != 0) { }; if (getIxWznmVIop(icsWznmVIop, VecVIme::IMEIJMIMPEXPCPLXTITLE, ixWznmVIop)) { dbswznm->tblwznmjmimpexpcplxtitle->loadRefsByIex(iex->ref, false, refs); for (unsigned int i = 0; i < refs.size(); i++) if (refs[i] == iex->refJTitle) {refs[i] = refs[0]; refs[0] = iex->refJTitle; break;}; for (unsigned int i = 0; i < refs.size(); i++) iex->imeijmimpexpcplxtitle.nodes.push_back(new ImeitemIJMImpexpcplxTitle(dbswznm, refs[i])); }; for (unsigned int ix1 = 0; ix1 < iex->imeijmimpexpcplxtitle.nodes.size(); ix1++) { iexJtit = iex->imeijmimpexpcplxtitle.nodes[ix1]; if (iexJtit->ref != 0) { iexJtit->srefX1RefWznmMLocale = StubWznm::getStubLocSref(dbswznm, iexJtit->x1RefWznmMLocale, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch); }; }; if (getIxWznmVIop(icsWznmVIop, VecVIme::IMEIMIMPEXP, ixWznmVIop)) { dbswznm->tblwznmmimpexp->loadRefsByIex(iex->ref, false, refs); for (unsigned int i = 0; i < refs.size(); i++) iex->imeimimpexp.nodes.push_back(new ImeitemIMImpexp(dbswznm, refs[i])); }; for (unsigned int ix1 = 0; ix1 < iex->imeimimpexp.nodes.size(); ix1++) { ime = iex->imeimimpexp.nodes[ix1]; if (ime->ref != 0) { ime->iref = ix1+1; //ime->irefSupRefWznmMImpexp: IREF ime->srefRefWznmMTable = StubWznm::getStubTblStd(dbswznm, ime->refWznmMTable, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch); }; if (getIxWznmVIop(icsWznmVIop, VecVIme::IMEIMIMPEXPCOL, ixWznmVIop)) { dbswznm->tblwznmmimpexpcol->loadRefsByIme(ime->ref, false, refs); for (unsigned int i = 0; i < refs.size(); i++) ime->imeimimpexpcol.nodes.push_back(new ImeitemIMImpexpcol(dbswznm, refs[i])); }; for (unsigned int ix2 = 0; ix2 < ime->imeimimpexpcol.nodes.size(); ix2++) { iel = ime->imeimimpexpcol.nodes[ix2]; if (iel->ref != 0) { iel->srefRefWznmMTablecol = StubWznm::getStubTcoSref(dbswznm, iel->refWznmMTablecol, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch); //iel->irefRefWznmMImpexp: IREF iel->srefRefWznmMPreset = StubWznm::getStubPstStd(dbswznm, iel->refWznmMPreset, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch); iel->srefRefWznmMStub = StubWznm::getStubStbStd(dbswznm, iel->refWznmMStub, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch); iel->srefRefWznmMVectoritem = StubWznm::getStubVitSref(dbswznm, iel->refWznmMVectoritem, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch); }; if (getIxWznmVIop(icsWznmVIop, VecVIme::IMEIJMIMPEXPCOLSTUB, ixWznmVIop)) { dbswznm->tblwznmjmimpexpcolstub->loadRefsByIel(iel->ref, false, refs); for (unsigned int i = 0; i < refs.size(); i++) iel->imeijmimpexpcolstub.nodes.push_back(new ImeitemIJMImpexpcolStub(dbswznm, refs[i])); }; for (unsigned int ix3 = 0; ix3 < iel->imeijmimpexpcolstub.nodes.size(); ix3++) { ielJstb = iel->imeijmimpexpcolstub.nodes[ix3]; if (ielJstb->ref != 0) { ielJstb->srefX1RefWznmMVectoritem = StubWznm::getStubVitSref(dbswznm, ielJstb->x1RefWznmMVectoritem, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch); ielJstb->srefRefWznmMStub = StubWznm::getStubStbStd(dbswznm, ielJstb->refWznmMStub, ixWznmVLocale, Stub::VecVNonetype::VOID, stcch); }; }; }; }; }; // IP enterSgeCollect.traverse --- END // IP enterSgeCollect.ppr --- INSERT delete stcch; return retval; }; void JobWznmIexIex::leaveSgeCollect( DbsWznm* dbswznm ) { // IP leaveSgeCollect --- INSERT }; uint JobWznmIexIex::enterSgeCltdone( DbsWznm* dbswznm , const bool reenter ) { uint retval = VecVSge::CLTDONE; // IP enterSgeCltdone --- INSERT return retval; }; void JobWznmIexIex::leaveSgeCltdone( DbsWznm* dbswznm ) { // IP leaveSgeCltdone --- INSERT }; uint JobWznmIexIex::enterSgeExport( DbsWznm* dbswznm , const bool reenter ) { uint retval; nextIxVSgeSuccess = VecVSge::DONE; retval = nextIxVSgeSuccess; IexWznmIex::exportToFile(fullpath, xmlNotTxt, shorttags, imeimimpexpcplx); return retval; }; void JobWznmIexIex::leaveSgeExport( DbsWznm* dbswznm ) { // IP leaveSgeExport --- INSERT }; uint JobWznmIexIex::enterSgeDone( DbsWznm* dbswznm , const bool reenter ) { uint retval = VecVSge::DONE; // IP enterSgeDone --- INSERT return retval; }; void JobWznmIexIex::leaveSgeDone( DbsWznm* dbswznm ) { // IP leaveSgeDone --- INSERT };
32.769231
334
0.684133
mpsitech
44005351e0d4c83cc5ca5c08aee2c529b22f4080
40,782
cc
C++
src/bin/dhcp6/json_config_parser.cc
oss-mirror/isc-kea
e7bfb8886b0312a293e73846499095e7ec9686b9
[ "Apache-2.0" ]
273
2015-01-22T14:14:42.000Z
2022-03-13T10:27:44.000Z
src/bin/dhcp6/json_config_parser.cc
oss-mirror/isc-kea
e7bfb8886b0312a293e73846499095e7ec9686b9
[ "Apache-2.0" ]
104
2015-01-16T16:37:06.000Z
2021-08-08T19:38:45.000Z
src/bin/dhcp6/json_config_parser.cc
oss-mirror/isc-kea
e7bfb8886b0312a293e73846499095e7ec9686b9
[ "Apache-2.0" ]
133
2015-02-21T14:06:39.000Z
2022-02-27T08:56:40.000Z
// Copyright (C) 2012-2021 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <asiolink/io_address.h> #include <cc/data.h> #include <cc/command_interpreter.h> #include <config/command_mgr.h> #include <database/dbaccess_parser.h> #include <dhcp/libdhcp++.h> #include <dhcp6/json_config_parser.h> #include <dhcp6/dhcp6_log.h> #include <dhcp6/dhcp6_srv.h> #include <dhcp/iface_mgr.h> #include <dhcpsrv/cb_ctl_dhcp4.h> #include <dhcpsrv/cfg_option.h> #include <dhcpsrv/cfgmgr.h> #include <dhcpsrv/db_type.h> #include <dhcpsrv/pool.h> #include <dhcpsrv/subnet.h> #include <dhcpsrv/timer_mgr.h> #include <dhcpsrv/triplet.h> #include <dhcpsrv/parsers/client_class_def_parser.h> #include <dhcpsrv/parsers/dhcp_parsers.h> #include <dhcpsrv/parsers/duid_config_parser.h> #include <dhcpsrv/parsers/expiration_config_parser.h> #include <dhcpsrv/parsers/host_reservation_parser.h> #include <dhcpsrv/parsers/host_reservations_list_parser.h> #include <dhcpsrv/parsers/ifaces_config_parser.h> #include <dhcpsrv/parsers/multi_threading_config_parser.h> #include <dhcpsrv/parsers/option_data_parser.h> #include <dhcpsrv/parsers/dhcp_queue_control_parser.h> #include <dhcpsrv/parsers/simple_parser6.h> #include <dhcpsrv/parsers/shared_networks_list_parser.h> #include <dhcpsrv/parsers/sanity_checks_parser.h> #include <dhcpsrv/host_data_source_factory.h> #include <hooks/hooks_parser.h> #include <hooks/hooks_manager.h> #include <log/logger_support.h> #include <process/config_ctl_parser.h> #include <util/encode/hex.h> #include <util/strutil.h> #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> #include <iostream> #include <limits> #include <map> #include <netinet/in.h> #include <vector> #include <stdint.h> using namespace std; using namespace isc; using namespace isc::data; using namespace isc::dhcp; using namespace isc::asiolink; using namespace isc::hooks; using namespace isc::process; namespace { /// @brief Checks if specified directory exists. /// /// @param dir_path Path to a directory. /// @throw BadValue If the directory does not exist or is not a directory. void dirExists(const string& dir_path) { struct stat statbuf; if (stat(dir_path.c_str(), &statbuf) < 0) { isc_throw(BadValue, "Bad directory '" << dir_path << "': " << strerror(errno)); } if ((statbuf.st_mode & S_IFMT) != S_IFDIR) { isc_throw(BadValue, "'" << dir_path << "' is not a directory"); } } /// @brief Parser for list of RSOO options /// /// This parser handles a Dhcp6/relay-supplied-options entry. It contains a /// list of RSOO-enabled options which should be sent back to the client. /// /// The options on this list can be specified using an option code or option /// name. Therefore, the values on the list should always be enclosed in /// "quotes". class RSOOListConfigParser : public isc::data::SimpleParser { public: /// @brief parses parameters value /// /// Parses configuration entry (list of sources) and adds each element /// to the RSOO list. /// /// @param value pointer to the content of parsed values /// @param cfg server configuration (RSOO will be stored here) void parse(const SrvConfigPtr& cfg, const isc::data::ConstElementPtr& value) { try { BOOST_FOREACH(ConstElementPtr source_elem, value->listValue()) { std::string option_str = source_elem->stringValue(); // This option can be either code (integer) or name. Let's try code first int64_t code = 0; try { code = boost::lexical_cast<int64_t>(option_str); // Protect against the negative value and too high value. if (code < 0) { isc_throw(BadValue, "invalid option code value specified '" << option_str << "', the option code must be a" " non-negative value"); } else if (code > std::numeric_limits<uint16_t>::max()) { isc_throw(BadValue, "invalid option code value specified '" << option_str << "', the option code must not be" " greater than '" << std::numeric_limits<uint16_t>::max() << "'"); } } catch (const boost::bad_lexical_cast &) { // Oh well, it's not a number } if (!code) { const OptionDefinitionPtr def = LibDHCP::getOptionDef(DHCP6_OPTION_SPACE, option_str); if (def) { code = def->getCode(); } else { isc_throw(BadValue, "unable to find option code for the " " specified option name '" << option_str << "'" " while parsing the list of enabled" " relay-supplied-options"); } } cfg->getCfgRSOO()->enable(code); } } catch (const std::exception& ex) { // Rethrow exception with the appended position of the parsed // element. isc_throw(DhcpConfigError, ex.what() << " (" << value->getPosition() << ")"); } } }; /// @brief Parser that takes care of global DHCPv6 parameters and utility /// functions that work on global level. /// /// This class is a collection of utility method that either handle /// global parameters (see @ref parse), or conducts operations on /// global level (see @ref sanityChecks and @ref copySubnets6). /// /// See @ref parse method for a list of supported parameters. class Dhcp6ConfigParser : public isc::data::SimpleParser { public: /// @brief Sets global parameters in staging configuration /// /// @param global global configuration scope /// @param cfg Server configuration (parsed parameters will be stored here) /// /// Currently this method sets the following global parameters: /// /// - data-directory /// - decline-probation-period /// - dhcp4o6-port /// - user-context /// /// @throw DhcpConfigError if parameters are missing or /// or having incorrect values. void parse(const SrvConfigPtr& srv_config, const ConstElementPtr& global) { // Set the data directory for server id file. if (global->contains("data-directory")) { CfgMgr::instance().setDataDir(getString(global, "data-directory"), false); } // Set the probation period for decline handling. uint32_t probation_period = getUint32(global, "decline-probation-period"); srv_config->setDeclinePeriod(probation_period); // Set the DHCPv4-over-DHCPv6 interserver port. uint16_t dhcp4o6_port = getUint16(global, "dhcp4o6-port"); srv_config->setDhcp4o6Port(dhcp4o6_port); // Set the global user context. ConstElementPtr user_context = global->get("user-context"); if (user_context) { srv_config->setContext(user_context); } // Set the server's logical name std::string server_tag = getString(global, "server-tag"); srv_config->setServerTag(server_tag); } /// @brief Sets global parameters before other parameters are parsed. /// /// This method sets selected global parameters before other parameters /// are parsed. This is important when the behavior of the parsers /// run later depends on these global parameters. /// /// Currently this method sets the following global parameters: /// - ip-reservations-unique /// /// @param global global configuration scope /// @param cfg Server configuration (parsed parameters will be stored here) void parseEarly(const SrvConfigPtr& cfg, const ConstElementPtr& global) { // Set ip-reservations-unique flag. bool ip_reservations_unique = getBoolean(global, "ip-reservations-unique"); cfg->setIPReservationsUnique(ip_reservations_unique); } /// @brief Copies subnets from shared networks to regular subnets container /// /// @param from pointer to shared networks container (copy from here) /// @param dest pointer to cfg subnets6 (copy to here) /// @throw BadValue if any pointer is missing /// @throw DhcpConfigError if there are duplicates (or other subnet defects) void copySubnets6(const CfgSubnets6Ptr& dest, const CfgSharedNetworks6Ptr& from) { if (!dest || !from) { isc_throw(BadValue, "Unable to copy subnets: at least one pointer is null"); } const SharedNetwork6Collection* networks = from->getAll(); if (!networks) { // Nothing to copy. Technically, it should return a pointer to empty // container, but let's handle null pointer as well. return; } // Let's go through all the networks one by one for (auto net = networks->begin(); net != networks->end(); ++net) { // For each network go through all the subnets in it. const Subnet6Collection* subnets = (*net)->getAllSubnets(); if (!subnets) { // Shared network without subnets it weird, but we decided to // accept such configurations. continue; } // For each subnet, add it to a list of regular subnets. for (auto subnet = subnets->begin(); subnet != subnets->end(); ++subnet) { dest->add(*subnet); } } } /// @brief Conducts global sanity checks /// /// This method is very simple now, but more sanity checks are expected /// in the future. /// /// @param cfg - the parsed structure /// @param global global Dhcp4 scope /// @throw DhcpConfigError in case of issues found void sanityChecks(const SrvConfigPtr& cfg, const ConstElementPtr& global) { /// Global lifetime sanity checks cfg->sanityChecksLifetime("preferred-lifetime"); cfg->sanityChecksLifetime("valid-lifetime"); /// Shared network sanity checks const SharedNetwork6Collection* networks = cfg->getCfgSharedNetworks6()->getAll(); if (networks) { sharedNetworksSanityChecks(*networks, global->get("shared-networks")); } } /// @brief Sanity checks for shared networks /// /// This method verifies if there are no issues with shared networks. /// @param networks pointer to shared networks being checked /// @param json shared-networks element /// @throw DhcpConfigError if issues are encountered void sharedNetworksSanityChecks(const SharedNetwork6Collection& networks, ConstElementPtr json) { /// @todo: in case of errors, use json to extract line numbers. if (!json) { // No json? That means that the shared-networks was never specified // in the config. return; } // Used for names uniqueness checks. std::set<string> names; // Let's go through all the networks one by one for (auto net = networks.begin(); net != networks.end(); ++net) { string txt; // Let's check if all subnets have either the same interface // or don't have the interface specified at all. string iface = (*net)->getIface(); const Subnet6Collection* subnets = (*net)->getAllSubnets(); if (subnets) { bool rapid_commit = false; // For each subnet, add it to a list of regular subnets. for (auto subnet = subnets->begin(); subnet != subnets->end(); ++subnet) { // Rapid commit must either be enabled or disabled in all subnets // in the shared network. if (subnet == subnets->begin()) { // If this is the first subnet, remember the value. rapid_commit = (*subnet)->getRapidCommit(); } else { // Ok, this is the second or following subnets. The value // must match what was set in the first subnet. if (rapid_commit != (*subnet)->getRapidCommit()) { isc_throw(DhcpConfigError, "All subnets in a shared network " "must have the same rapid-commit value. Subnet " << (*subnet)->toText() << " has specified rapid-commit " << ( (*subnet)->getRapidCommit() ? "true" : "false") << ", but earlier subnet in the same shared-network" << " or the shared-network itself used rapid-commit " << (rapid_commit ? "true" : "false")); } } if (iface.empty()) { iface = (*subnet)->getIface(); continue; } if ((*subnet)->getIface().empty()) { continue; } if ((*subnet)->getIface() != iface) { isc_throw(DhcpConfigError, "Subnet " << (*subnet)->toText() << " has specified interface " << (*subnet)->getIface() << ", but earlier subnet in the same shared-network" << " or the shared-network itself used " << iface); } // Let's collect the subnets in case we later find out the // subnet doesn't have a mandatory name. txt += (*subnet)->toText() + " "; } } // Next, let's check name of the shared network. if ((*net)->getName().empty()) { isc_throw(DhcpConfigError, "Shared-network with subnets " << txt << " is missing mandatory 'name' parameter"); } // Is it unique? if (names.find((*net)->getName()) != names.end()) { isc_throw(DhcpConfigError, "A shared-network with " "name " << (*net)->getName() << " defined twice."); } names.insert((*net)->getName()); } } }; } // anonymous namespace namespace isc { namespace dhcp { /// @brief Initialize the command channel based on the staging configuration /// /// Only close the current channel, if the new channel configuration is /// different. This avoids disconnecting a client and hence not sending them /// a command result, unless they specifically alter the channel configuration. /// In that case the user simply has to accept they'll be disconnected. /// void configureCommandChannel() { // Get new socket configuration. ConstElementPtr sock_cfg = CfgMgr::instance().getStagingCfg()->getControlSocketInfo(); // Get current socket configuration. ConstElementPtr current_sock_cfg = CfgMgr::instance().getCurrentCfg()->getControlSocketInfo(); // Determine if the socket configuration has changed. It has if // both old and new configuration is specified but respective // data elements aren't equal. bool sock_changed = (sock_cfg && current_sock_cfg && !sock_cfg->equals(*current_sock_cfg)); // If the previous or new socket configuration doesn't exist or // the new configuration differs from the old configuration we // close the existing socket and open a new socket as appropriate. // Note that closing an existing socket means the client will not // receive the configuration result. if (!sock_cfg || !current_sock_cfg || sock_changed) { // Close the existing socket (if any). isc::config::CommandMgr::instance().closeCommandSocket(); if (sock_cfg) { // This will create a control socket and install the external // socket in IfaceMgr. That socket will be monitored when // Dhcp4Srv::receivePacket() calls IfaceMgr::receive4() and // callback in CommandMgr will be called, if necessary. isc::config::CommandMgr::instance().openCommandSocket(sock_cfg); } } } isc::data::ConstElementPtr configureDhcp6Server(Dhcpv6Srv& server, isc::data::ConstElementPtr config_set, bool check_only) { if (!config_set) { ConstElementPtr answer = isc::config::createAnswer(1, string("Can't parse NULL config")); return (answer); } LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_START) .arg(server.redactConfig(config_set)->str()); // Before starting any subnet operations, let's reset the subnet-id counter, // so newly recreated configuration starts with first subnet-id equal 1. Subnet::resetSubnetID(); // Close DHCP sockets and remove any existing timers. if (!check_only) { IfaceMgr::instance().closeSockets(); TimerMgr::instance()->unregisterTimers(); server.discardPackets(); server.getCBControl()->reset(); } // Revert any runtime option definitions configured so far and not committed. LibDHCP::revertRuntimeOptionDefs(); // Let's set empty container in case a user hasn't specified any configuration // for option definitions. This is equivalent to committing empty container. LibDHCP::setRuntimeOptionDefs(OptionDefSpaceContainer()); // Print the list of known backends. HostDataSourceFactory::printRegistered(); // Answer will hold the result. ConstElementPtr answer; // Rollback informs whether error occurred and original data // have to be restored to global storages. bool rollback = false; // Global parameter name in case of an error. string parameter_name; ElementPtr mutable_cfg; SrvConfigPtr srv_config; try { // Get the staging configuration. srv_config = CfgMgr::instance().getStagingCfg(); // This is a way to convert ConstElementPtr to ElementPtr. // We need a config that can be edited, because we will insert // default values and will insert derived values as well. mutable_cfg = boost::const_pointer_cast<Element>(config_set); // Relocate dhcp-ddns parameters that have moved to global scope. // Rule is that a global value overrides the dhcp-ddns value, so // we need to do this before we apply global defaults. // Note this is done for backward compatibility. srv_config->moveDdnsParams(mutable_cfg); // Move from reservation mode to new reservations flags. // @todo add warning BaseNetworkParser::moveReservationMode(mutable_cfg); // Set all default values if not specified by the user. SimpleParser6::setAllDefaults(mutable_cfg); // And now derive (inherit) global parameters to subnets, if not specified. SimpleParser6::deriveParameters(mutable_cfg); // In principle we could have the following code structured as a series // of long if else if clauses. That would give a marginal performance // boost, but would make the code less readable. We had serious issues // with the parser code debugability, so I decided to keep it as a // series of independent ifs. // This parser is used in several places. Dhcp6ConfigParser global_parser; // Apply global options in the staging config, e.g. ip-reservations-unique global_parser.parseEarly(srv_config, mutable_cfg); // Specific check for this global parameter. ConstElementPtr data_directory = mutable_cfg->get("data-directory"); if (data_directory) { parameter_name = "data-directory"; dirExists(data_directory->stringValue()); } // We need definitions first ConstElementPtr option_defs = mutable_cfg->get("option-def"); if (option_defs) { parameter_name = "option-def"; OptionDefListParser parser(AF_INET6); CfgOptionDefPtr cfg_option_def = srv_config->getCfgOptionDef(); parser.parse(cfg_option_def, option_defs); } ConstElementPtr option_datas = mutable_cfg->get("option-data"); if (option_datas) { parameter_name = "option-data"; OptionDataListParser parser(AF_INET6); CfgOptionPtr cfg_option = srv_config->getCfgOption(); parser.parse(cfg_option, option_datas); } ConstElementPtr mac_sources = mutable_cfg->get("mac-sources"); if (mac_sources) { parameter_name = "mac-sources"; MACSourcesListConfigParser parser; CfgMACSource& mac_source = srv_config->getMACSources(); parser.parse(mac_source, mac_sources); } ConstElementPtr control_socket = mutable_cfg->get("control-socket"); if (control_socket) { parameter_name = "control-socket"; ControlSocketParser parser; parser.parse(*srv_config, control_socket); } ConstElementPtr multi_threading = mutable_cfg->get("multi-threading"); if (multi_threading) { parameter_name = "multi-threading"; MultiThreadingConfigParser parser; parser.parse(*srv_config, multi_threading); } ConstElementPtr queue_control = mutable_cfg->get("dhcp-queue-control"); if (queue_control) { parameter_name = "dhcp-queue-control"; DHCPQueueControlParser parser; srv_config->setDHCPQueueControl(parser.parse(queue_control)); } ConstElementPtr hr_identifiers = mutable_cfg->get("host-reservation-identifiers"); if (hr_identifiers) { parameter_name = "host-reservation-identifiers"; HostReservationIdsParser6 parser; parser.parse(hr_identifiers); } ConstElementPtr server_id = mutable_cfg->get("server-id"); if (server_id) { parameter_name = "server-id"; DUIDConfigParser parser; const CfgDUIDPtr& cfg = srv_config->getCfgDUID(); parser.parse(cfg, server_id); } ConstElementPtr ifaces_config = mutable_cfg->get("interfaces-config"); if (ifaces_config) { parameter_name = "interfaces-config"; IfacesConfigParser parser(AF_INET6, check_only); CfgIfacePtr cfg_iface = srv_config->getCfgIface(); parser.parse(cfg_iface, ifaces_config); } ConstElementPtr sanity_checks = mutable_cfg->get("sanity-checks"); if (sanity_checks) { parameter_name = "sanity-checks"; SanityChecksParser parser; parser.parse(*srv_config, sanity_checks); } ConstElementPtr expiration_cfg = mutable_cfg->get("expired-leases-processing"); if (expiration_cfg) { parameter_name = "expired-leases-processing"; ExpirationConfigParser parser; parser.parse(expiration_cfg); } // The hooks-libraries configuration must be parsed after parsing // multi-threading configuration so that libraries are checked // for multi-threading compatibility. ConstElementPtr hooks_libraries = mutable_cfg->get("hooks-libraries"); if (hooks_libraries) { parameter_name = "hooks-libraries"; HooksLibrariesParser hooks_parser; HooksConfig& libraries = srv_config->getHooksConfig(); hooks_parser.parse(libraries, hooks_libraries); libraries.verifyLibraries(hooks_libraries->getPosition()); } // D2 client configuration. D2ClientConfigPtr d2_client_cfg; // Legacy DhcpConfigParser stuff below. ConstElementPtr dhcp_ddns = mutable_cfg->get("dhcp-ddns"); if (dhcp_ddns) { parameter_name = "dhcp-ddns"; // Apply defaults D2ClientConfigParser::setAllDefaults(dhcp_ddns); D2ClientConfigParser parser; d2_client_cfg = parser.parse(dhcp_ddns); } ConstElementPtr client_classes = mutable_cfg->get("client-classes"); if (client_classes) { parameter_name = "client-classes"; ClientClassDefListParser parser; ClientClassDictionaryPtr dictionary = parser.parse(client_classes, AF_INET6); srv_config->setClientClassDictionary(dictionary); } // Please move at the end when migration will be finished. ConstElementPtr lease_database = mutable_cfg->get("lease-database"); if (lease_database) { parameter_name = "lease-database"; db::DbAccessParser parser; std::string access_string; parser.parse(access_string, lease_database); CfgDbAccessPtr cfg_db_access = srv_config->getCfgDbAccess(); cfg_db_access->setLeaseDbAccessString(access_string); } ConstElementPtr hosts_database = mutable_cfg->get("hosts-database"); if (hosts_database) { parameter_name = "hosts-database"; db::DbAccessParser parser; std::string access_string; parser.parse(access_string, hosts_database); CfgDbAccessPtr cfg_db_access = srv_config->getCfgDbAccess(); cfg_db_access->setHostDbAccessString(access_string); } ConstElementPtr hosts_databases = mutable_cfg->get("hosts-databases"); if (hosts_databases) { parameter_name = "hosts-databases"; CfgDbAccessPtr cfg_db_access = srv_config->getCfgDbAccess(); db::DbAccessParser parser; for (auto it : hosts_databases->listValue()) { std::string access_string; parser.parse(access_string, it); cfg_db_access->setHostDbAccessString(access_string); } } // Keep relative orders of shared networks and subnets. ConstElementPtr shared_networks = mutable_cfg->get("shared-networks"); if (shared_networks) { parameter_name = "shared-networks"; /// We need to create instance of SharedNetworks6ListParser /// and parse the list of the shared networks into the /// CfgSharedNetworks6 object. One additional step is then to /// add subnets from the CfgSharedNetworks6 into CfgSubnets6 /// as well. SharedNetworks6ListParser parser; CfgSharedNetworks6Ptr cfg = srv_config->getCfgSharedNetworks6(); parser.parse(cfg, shared_networks); // We also need to put the subnets it contains into normal // subnets list. global_parser.copySubnets6(srv_config->getCfgSubnets6(), cfg); } ConstElementPtr subnet6 = mutable_cfg->get("subnet6"); if (subnet6) { parameter_name = "subnet6"; Subnets6ListConfigParser subnets_parser; // parse() returns number of subnets parsed. We may log it one day. subnets_parser.parse(srv_config, subnet6); } ConstElementPtr reservations = mutable_cfg->get("reservations"); if (reservations) { parameter_name = "reservations"; HostCollection hosts; HostReservationsListParser<HostReservationParser6> parser; parser.parse(SUBNET_ID_GLOBAL, reservations, hosts); for (auto h = hosts.begin(); h != hosts.end(); ++h) { srv_config->getCfgHosts()->add(*h); } } ConstElementPtr config_control = mutable_cfg->get("config-control"); if (config_control) { parameter_name = "config-control"; ConfigControlParser parser; ConfigControlInfoPtr config_ctl_info = parser.parse(config_control); CfgMgr::instance().getStagingCfg()->setConfigControlInfo(config_ctl_info); } ConstElementPtr rsoo_list = mutable_cfg->get("relay-supplied-options"); if (rsoo_list) { parameter_name = "relay-supplied-options"; RSOOListConfigParser parser; parser.parse(srv_config, rsoo_list); } ConstElementPtr compatibility = mutable_cfg->get("compatibility"); if (compatibility) { for (auto kv : compatibility->mapValue()) { if (kv.first == "lenient-option-parsing") { CfgMgr::instance().getStagingCfg()->setLenientOptionParsing( kv.second->boolValue()); } } } // Make parsers grouping. ConfigPair config_pair; const std::map<std::string, ConstElementPtr>& values_map = mutable_cfg->mapValue(); BOOST_FOREACH(config_pair, values_map) { parameter_name = config_pair.first; // These are converted to SimpleParser and are handled already above. if ((config_pair.first == "data-directory") || (config_pair.first == "option-def") || (config_pair.first == "option-data") || (config_pair.first == "mac-sources") || (config_pair.first == "control-socket") || (config_pair.first == "multi-threading") || (config_pair.first == "dhcp-queue-control") || (config_pair.first == "host-reservation-identifiers") || (config_pair.first == "server-id") || (config_pair.first == "interfaces-config") || (config_pair.first == "sanity-checks") || (config_pair.first == "expired-leases-processing") || (config_pair.first == "hooks-libraries") || (config_pair.first == "dhcp-ddns") || (config_pair.first == "client-classes") || (config_pair.first == "lease-database") || (config_pair.first == "hosts-database") || (config_pair.first == "hosts-databases") || (config_pair.first == "subnet6") || (config_pair.first == "shared-networks") || (config_pair.first == "reservations") || (config_pair.first == "config-control") || (config_pair.first == "relay-supplied-options") || (config_pair.first == "compatibility")) { continue; } // As of Kea 1.6.0 we have two ways of inheriting the global parameters. // The old method is used in JSON configuration parsers when the global // parameters are derived into the subnets and shared networks and are // being treated as explicitly specified. The new way used by the config // backend is the dynamic inheritance whereby each subnet and shared // network uses a callback function to return global parameter if it // is not specified at lower level. This callback uses configured globals. // We deliberately include both default and explicitly specified globals // so as the callback can access the appropriate global values regardless // whether they are set to a default or other value. if ( (config_pair.first == "renew-timer") || (config_pair.first == "rebind-timer") || (config_pair.first == "preferred-lifetime") || (config_pair.first == "min-preferred-lifetime") || (config_pair.first == "max-preferred-lifetime") || (config_pair.first == "valid-lifetime") || (config_pair.first == "min-valid-lifetime") || (config_pair.first == "max-valid-lifetime") || (config_pair.first == "decline-probation-period") || (config_pair.first == "dhcp4o6-port") || (config_pair.first == "server-tag") || (config_pair.first == "reservation-mode") || (config_pair.first == "reservations-global") || (config_pair.first == "reservations-in-subnet") || (config_pair.first == "reservations-out-of-pool") || (config_pair.first == "calculate-tee-times") || (config_pair.first == "t1-percent") || (config_pair.first == "t2-percent") || (config_pair.first == "cache-threshold") || (config_pair.first == "cache-max-age") || (config_pair.first == "loggers") || (config_pair.first == "hostname-char-set") || (config_pair.first == "hostname-char-replacement") || (config_pair.first == "ddns-send-updates") || (config_pair.first == "ddns-override-no-update") || (config_pair.first == "ddns-override-client-update") || (config_pair.first == "ddns-replace-client-name") || (config_pair.first == "ddns-generated-prefix") || (config_pair.first == "ddns-qualifying-suffix") || (config_pair.first == "ddns-update-on-renew") || (config_pair.first == "ddns-use-conflict-resolution") || (config_pair.first == "store-extended-info") || (config_pair.first == "statistic-default-sample-count") || (config_pair.first == "statistic-default-sample-age") || (config_pair.first == "ip-reservations-unique") || (config_pair.first == "parked-packet-limit")) { CfgMgr::instance().getStagingCfg()->addConfiguredGlobal(config_pair.first, config_pair.second); continue; } // Nothing to configure for the user-context. if (config_pair.first == "user-context") { continue; } // If we got here, no code handled this parameter, so we bail out. isc_throw(DhcpConfigError, "unsupported global configuration parameter: " << config_pair.first << " (" << config_pair.second->getPosition() << ")"); } // Reset parameter name. parameter_name = "<post parsing>"; // Apply global options in the staging config. global_parser.parse(srv_config, mutable_cfg); // This method conducts final sanity checks and tweaks. In particular, // it checks that there is no conflict between plain subnets and those // defined as part of shared networks. global_parser.sanityChecks(srv_config, mutable_cfg); // Validate D2 client configuration. if (!d2_client_cfg) { d2_client_cfg.reset(new D2ClientConfig()); } d2_client_cfg->validateContents(); srv_config->setD2ClientConfig(d2_client_cfg); } catch (const isc::Exception& ex) { LOG_ERROR(dhcp6_logger, DHCP6_PARSER_FAIL) .arg(parameter_name).arg(ex.what()); answer = isc::config::createAnswer(1, ex.what()); // An error occurred, so make sure that we restore original data. rollback = true; } catch (...) { // For things like bad_cast in boost::lexical_cast LOG_ERROR(dhcp6_logger, DHCP6_PARSER_EXCEPTION).arg(parameter_name); answer = isc::config::createAnswer(1, "undefined configuration" " processing error"); // An error occurred, so make sure that we restore original data. rollback = true; } if (check_only) { rollback = true; if (!answer) { answer = isc::config::createAnswer(0, "Configuration seems sane. Control-socket, hook-libraries, and D2 " "configuration were sanity checked, but not applied."); } } // So far so good, there was no parsing error so let's commit the // configuration. This will add created subnets and option values into // the server's configuration. // This operation should be exception safe but let's make sure. if (!rollback) { try { // Setup the command channel. configureCommandChannel(); // No need to commit interface names as this is handled by the // CfgMgr::commit() function. // Apply the staged D2ClientConfig, used to be done by parser commit D2ClientConfigPtr cfg; cfg = CfgMgr::instance().getStagingCfg()->getD2ClientConfig(); CfgMgr::instance().setD2ClientConfig(cfg); // This occurs last as if it succeeds, there is no easy way to // revert it. As a result, the failure to commit a subsequent // change causes problems when trying to roll back. HooksManager::prepareUnloadLibraries(); static_cast<void>(HooksManager::unloadLibraries()); const HooksConfig& libraries = CfgMgr::instance().getStagingCfg()->getHooksConfig(); libraries.loadLibraries(); } catch (const isc::Exception& ex) { LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(ex.what()); answer = isc::config::createAnswer(2, ex.what()); // An error occurred, so make sure to restore the original data. rollback = true; } catch (...) { // For things like bad_cast in boost::lexical_cast LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_EXCEPTION); answer = isc::config::createAnswer(2, "undefined configuration" " parsing error"); // An error occurred, so make sure to restore the original data. rollback = true; } } // Moved from the commit block to add the config backend indication. if (!rollback) { try { // If there are config backends, fetch and merge into staging config server.getCBControl()->databaseConfigFetch(srv_config, CBControlDHCPv6::FetchMode::FETCH_ALL); } catch (const isc::Exception& ex) { std::ostringstream err; err << "during update from config backend database: " << ex.what(); LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(err.str()); answer = isc::config::createAnswer(2, err.str()); // An error occurred, so make sure to restore the original data. rollback = true; } catch (...) { // For things like bad_cast in boost::lexical_cast std::ostringstream err; err << "during update from config backend database: " << "undefined configuration parsing error"; LOG_ERROR(dhcp6_logger, DHCP6_PARSER_COMMIT_FAIL).arg(err.str()); answer = isc::config::createAnswer(2, err.str()); // An error occurred, so make sure to restore the original data. rollback = true; } } // Rollback changes as the configuration parsing failed. if (rollback) { // Revert to original configuration of runtime option definitions // in the libdhcp++. LibDHCP::revertRuntimeOptionDefs(); return (answer); } LOG_INFO(dhcp6_logger, DHCP6_CONFIG_COMPLETE) .arg(CfgMgr::instance().getStagingCfg()-> getConfigSummary(SrvConfig::CFGSEL_ALL6)); // Everything was fine. Configuration is successful. answer = isc::config::createAnswer(0, "Configuration successful."); return (answer); } } // namespace dhcp } // namespace isc
42.569937
94
0.597568
oss-mirror
44007d6c50bd95a8ea0f81ef4a35f463cf0caffb
2,004
cxx
C++
src/SimpleCalCalib/TholdCI.cxx
fermi-lat/CalUtil
98b5b658257b5ffe2584cf786dd2e506173e2d8f
[ "BSD-3-Clause" ]
null
null
null
src/SimpleCalCalib/TholdCI.cxx
fermi-lat/CalUtil
98b5b658257b5ffe2584cf786dd2e506173e2d8f
[ "BSD-3-Clause" ]
null
null
null
src/SimpleCalCalib/TholdCI.cxx
fermi-lat/CalUtil
98b5b658257b5ffe2584cf786dd2e506173e2d8f
[ "BSD-3-Clause" ]
null
null
null
/** @file @author Zachary Fewtrell */ // LOCAL INCLUDES #include "CalUtil/SimpleCalCalib/TholdCI.h" // GLAST INCLUDES // EXTLIB INCLUDES // STD INCLUDES #include <sstream> #include <string> #include <fstream> using namespace CalUtil; using namespace std; namespace CalUtil { const short TholdCI::INVALID_THOLD = -5000; TholdCI::TholdCI() : m_fleThresh(FaceIdx::N_VALS, INVALID_THOLD), m_fheThresh(FaceIdx::N_VALS, INVALID_THOLD), m_lacThresh(FaceIdx::N_VALS, INVALID_THOLD), m_uldThresh(RngIdx::N_VALS, INVALID_THOLD), m_ped(RngIdx::N_VALS, INVALID_THOLD) { } void TholdCI::readTXT(const std::string &filename) { // open file ifstream infile(filename.c_str()); if (!infile.is_open()) throw runtime_error(string("Unable to open " + filename)); // loop through each line in file string line; unsigned short twr,lyr,col,face; float lac, fle, fhe; CalVec<RngNum, float> uld, ped; while (infile.good()) { getline(infile, line); if (infile.fail()) break; // bad get // check for comments if (line[0] == ';') continue; istringstream istrm(line); istrm >> twr >> lyr >> col >> face >> lac >> fle >> fhe >> uld[0] >> uld[1] >> uld[2] >> uld[3] >> ped[0] >> ped[1] >> ped[2] >> ped[3]; const FaceIdx faceIdx(twr, LyrNum(lyr), col, // the parenthesis are _very_ important. // see Scott Meyers "Effective STL" Item 6 (FaceNum(face))); m_fleThresh[faceIdx] = fle; m_fheThresh[faceIdx] = fhe; m_lacThresh[faceIdx] = lac; for (RngNum rng; rng.isValid(); rng++) { const RngIdx rngIdx(faceIdx,rng); m_uldThresh[rngIdx] = uld[rng]; m_ped[rngIdx] = ped[rng]; } // rng loop } // line loop } // readTXT() } // namespace CalUtil
25.367089
70
0.56487
fermi-lat
4400ac6a4b285923557ac5fb8ca4f0d259f3ca9e
774
cpp
C++
2stack_queue.cpp
xiaobinf/algorithm
85a0cfc72daf6da91c4d0f568e31be69d4f19bd9
[ "MIT" ]
null
null
null
2stack_queue.cpp
xiaobinf/algorithm
85a0cfc72daf6da91c4d0f568e31be69d4f19bd9
[ "MIT" ]
null
null
null
2stack_queue.cpp
xiaobinf/algorithm
85a0cfc72daf6da91c4d0f568e31be69d4f19bd9
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> #include <exception> using std::clog; using std::endl; /** * 用两个栈模拟队列操作 画好过程图 * @tparam T */ template <class T> class QStack{ public: QStack(){} ~QStack(){} T q_pop(); void q_push(T x); private: std::stack<T> s1; std::stack<T> s2; }; template <class T> T QStack::q_pop(){ if(s1.size()<=0){ while(s2.size()>0){ T& data=s2.top(); s2.pop(); s1.push(data); } } if(s1.size()==0){ clog<<"stack is empty"<<endl; throw std::exception(); } T head=s1.top(); s1.pop(); return head; } template <class T> void QStack::q_push(T x) { s2.push(x); } int main() { return 0; }
16.468085
38
0.484496
xiaobinf
44010427dfc62f2f560cc39530688bc9d5ee9cf0
478
cc
C++
abel/strings/internal/ostringstream.cc
Conun/abel
485ef38c917c0df3750242cc38966a2bcb163588
[ "BSD-3-Clause" ]
null
null
null
abel/strings/internal/ostringstream.cc
Conun/abel
485ef38c917c0df3750242cc38966a2bcb163588
[ "BSD-3-Clause" ]
null
null
null
abel/strings/internal/ostringstream.cc
Conun/abel
485ef38c917c0df3750242cc38966a2bcb163588
[ "BSD-3-Clause" ]
null
null
null
// #include <abel/strings/internal/ostringstream.h> namespace abel { namespace strings_internal { OStringStream::Buf::int_type OStringStream::overflow(int c) { assert(s_); if (!Buf::traits_type::eq_int_type(c, Buf::traits_type::eof())) s_->push_back(static_cast<char>(c)); return 1; } std::streamsize OStringStream::xsputn(const char* s, std::streamsize n) { assert(s_); s_->append(s, n); return n; } } // namespace strings_internal } // namespace abel
19.12
73
0.696653
Conun
4401838fbbaf23517ca138f45a07b2e3294e7e9f
887
cc
C++
netz/ether_support.cc
PariKhaleghi/BlackFish
dde6e4de00744be04848853e6f8d12cd4c54fd73
[ "BSD-3-Clause" ]
1
2022-03-03T08:47:33.000Z
2022-03-03T08:47:33.000Z
netz/ether_support.cc
PariKhaleghi/BlackFish
dde6e4de00744be04848853e6f8d12cd4c54fd73
[ "BSD-3-Clause" ]
null
null
null
netz/ether_support.cc
PariKhaleghi/BlackFish
dde6e4de00744be04848853e6f8d12cd4c54fd73
[ "BSD-3-Clause" ]
null
null
null
#ifdef OS_AIX #include <memory.h> #endif #ifdef OS_OPENBSD #include <memory.h> #endif #ifdef OS_LINUX #include <string.h> #endif #include "ether_support.h" #include "support.h" c_ether_header::c_ether_header(byte *ether_header) { header = (s_ether_header *)ether_header; } c_ether_header::c_ether_header(s_ether_header *ether_header) { header = ether_header; } byte *c_ether_header::get_raw() { return (byte *)header; } byte *c_ether_header::get_dst() { return header->dst; } void c_ether_header::set_dst(byte *dst) { memcpy(header->dst, dst, ETHER_ADDR_LEN); } byte *c_ether_header::get_src() { return header->src; } void c_ether_header::set_src(byte *src) { memcpy(header->src, src, ETHER_ADDR_LEN); } word c_ether_header::get_type() { return ntoh(header->type); } void c_ether_header::set_type(word type) { header->type = hton(type); }
14.783333
60
0.706877
PariKhaleghi
4402919f1922b8d1c7aa1b0aba90b53f65624833
1,803
cpp
C++
2course/Programming/examples/from_study_guide/5_1.cpp
posgen/OmsuMaterials
6132fe300154db97327667728c4cf3b0e19420e6
[ "Unlicense" ]
9
2017-04-03T08:52:58.000Z
2020-06-05T18:25:02.000Z
2course/Programming/examples/from_study_guide/5_1.cpp
posgen/OmsuMaterials
6132fe300154db97327667728c4cf3b0e19420e6
[ "Unlicense" ]
6
2018-02-07T18:26:27.000Z
2021-09-02T04:46:06.000Z
2course/Programming/examples/from_study_guide/5_1.cpp
posgen/OmsuMaterials
6132fe300154db97327667728c4cf3b0e19420e6
[ "Unlicense" ]
10
2018-11-12T18:18:47.000Z
2020-06-06T06:17:01.000Z
/* Определить функцию для вычисления по формуле Ньютона приблежённого значения арифметического квадратного корня. В формуле Ньютона итерации определяются по формуле r_[n+1] = (r_[n] + x / r_[n]) / 2 Версия для C++ */ #include <iostream> #include <cmath> #include <clocale> const double PRECISION = 0.000000001; /* Объявление функции с именем newton_root. Она принимает один аргумент типа double и возращает значение типа double. Объявление без описания тела функции (блок кода в фигурных скобках) - позволяет делать вызов этой функции в любом месте, до определения самой функции. */ double newton_root(double ); int main() { std::setlocale(LC_ALL, "RUS"); double x, result; std::cout << "Введите x: "; std::cin >> x; // вызываем функцию, передавая ей в качестве аргумента переменную x и сохраняя возращённый ею результат в переменной result result = newton_root(x); std::cout << "Корень из x: " << result; return 0; } /* Ниже производится определение функции. В отличие от объявления, здесь обязательно указание имени передаваемых аргументов. Имя аргумента используется только в теле функции. Стоит заметить, что отделение объявления и определения функции не является обязательным при записи всего в одном файле. */ double newton_root(double num) { double r_cur, r_next = num; /* Действительные числа (float, double) лучше сравнивать с некоторой заранее определённой точностью по числу знаков после запятой. num == 0.0 - не гарантирует, что сравнение будет истино даже если num = 0; */ if (num < PRECISION) return 0.0; do { r_cur = r_next; r_next = (r_cur + num / r_cur) / 2; } while ( abs(r_cur - r_next) > PRECISION ); return r_next; }
28.619048
127
0.688297
posgen
4403da96c1a053243a411d33ceecba44a494520e
20,089
hpp
C++
src/thirdparty/stlsoft/STLSoft/include/winstl/controls/listview_sequence.hpp
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
null
null
null
src/thirdparty/stlsoft/STLSoft/include/winstl/controls/listview_sequence.hpp
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
null
null
null
src/thirdparty/stlsoft/STLSoft/include/winstl/controls/listview_sequence.hpp
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
2
2020-11-04T03:07:09.000Z
2020-11-05T08:14:45.000Z
/* ///////////////////////////////////////////////////////////////////////// * File: winstl/controls/listview_sequence.hpp * * Purpose: Contains the listview_sequence class template. * * Created: 8th May 2003 * Updated: 19th February 2017 * * Thanks: To Pablo Aguilar for making the requisite feature requests. * * Home: http://stlsoft.org/ * * Copyright (c) 2003-2017, Matthew Wilson and Synesis Software * 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(s) of Matthew Wilson and Synesis Software nor the * names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ////////////////////////////////////////////////////////////////////// */ /** \file winstl/controls/listview_sequence.hpp * * \brief [C++ only] Definition of the winstl::listview_sequence class * (\ref group__library__Windows_Control "Windows Control" Library). */ #ifndef WINSTL_INCL_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE #define WINSTL_INCL_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION # define WINSTL_VER_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE_MAJOR 4 # define WINSTL_VER_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE_MINOR 3 # define WINSTL_VER_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE_REVISION 9 # define WINSTL_VER_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE_EDIT 88 #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////// * includes */ #ifndef WINSTL_INCL_WINSTL_H_WINSTL # include <winstl/winstl.h> #endif /* !WINSTL_INCL_WINSTL_H_WINSTL */ #ifdef STLSOFT_TRACE_INCLUDE # pragma message(__FILE__) #endif /* STLSOFT_TRACE_INCLUDE */ #ifndef STLSOFT_INCL_STLSOFT_COLLECTIONS_UTIL_HPP_COLLECTIONS # include <stlsoft/collections/util/collections.hpp> #endif /* !STLSOFT_INCL_STLSOFT_COLLECTIONS_UTIL_HPP_COLLECTIONS */ #ifndef STLSOFT_INCL_STLSOFT_MEMORY_HPP_AUTO_BUFFER # include <stlsoft/memory/auto_buffer.hpp> #endif /* !STLSOFT_INCL_STLSOFT_MEMORY_HPP_AUTO_BUFFER */ #ifndef WINSTL_INCL_WINSTL_MEMORY_HPP_PROCESSHEAP_ALLOCATOR # include <winstl/memory/processheap_allocator.hpp> #endif /* !WINSTL_INCL_WINSTL_MEMORY_HPP_PROCESSHEAP_ALLOCATOR */ #ifndef STLSOFT_INCL_STLSOFT_STRING_HPP_SHIM_STRING # include <stlsoft/string/shim_string.hpp> #endif /* !STLSOFT_INCL_STLSOFT_STRING_HPP_SHIM_STRING */ #ifndef STLSOFT_INCL_STLSOFT_STRING_HPP_SIMPLE_STRING # include <stlsoft/string/simple_string.hpp> #endif /* !STLSOFT_INCL_STLSOFT_STRING_HPP_SIMPLE_STRING */ #ifndef STLSOFT_INCL_STLSOFT_UTIL_STD_HPP_ITERATOR_HELPER # include <stlsoft/util/std/iterator_helper.hpp> #endif /* !STLSOFT_INCL_STLSOFT_UTIL_STD_HPP_ITERATOR_HELPER */ #ifndef WINSTL_INCL_WINSTL_CONTROLS_H_COMMCTRL_FUNCTIONS # include <winstl/controls/commctrl_functions.h> #endif /* !WINSTL_INCL_WINSTL_CONTROLS_H_COMMCTRL_FUNCTIONS */ #ifdef WINSTL_LISTVIEW_SEQUENCE_CUSTOM_STRING_TYPE typedef WINSTL_LISTVIEW_SEQUENCE_CUSTOM_STRING_TYPE lvs_string_t; #else /* ? WINSTL_LISTVIEW_SEQUENCE_CUSTOM_STRING_TYPE */ # ifdef STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT typedef STLSOFT_NS_QUAL(basic_simple_string)<TCHAR> lvs_string_t; # else typedef STLSOFT_NS_QUAL(basic_simple_string)< TCHAR , STLSOFT_NS_QUAL(stlsoft_char_traits)<TCHAR> , WINSTL_NS_QUAL(processheap_allocator)<TCHAR> > lvs_string_t; # endif /* STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT */ #endif /* WINSTL_LISTVIEW_SEQUENCE_CUSTOM_STRING_TYPE */ #ifndef WINSTL_INCL_WINSTL_SHIMS_ACCESS_HPP_STRING # include <winstl/shims/access/string.hpp> #endif /* !WINSTL_INCL_WINSTL_SHIMS_ACCESS_HPP_STRING */ #ifdef STLSOFT_CF_EXCEPTION_SUPPORT # ifndef STLSOFT_INCL_STLSOFT_CONVERSION_HPP_TRUNCATION_CAST # include <stlsoft/conversion/truncation_cast.hpp> # endif /* !STLSOFT_INCL_STLSOFT_CONVERSION_HPP_TRUNCATION_CAST */ #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ /* ///////////////////////////////////////////////////////////////////////// * namespace */ #ifndef WINSTL_NO_NAMESPACE # if defined(STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) /* There is no stlsoft namespace, so must define ::winstl */ namespace winstl { # else /* Define stlsoft::winstl_project */ namespace stlsoft { namespace winstl_project { # endif /* STLSOFT_NO_NAMESPACE */ #endif /* !WINSTL_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * typedefs */ #ifndef WINSTL_NO_NAMESPACE using ::lvs_string_t; #endif /* !WINSTL_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * classes */ /** Item class used by the listview_sequence class * * \ingroup group__library__Windows_Control */ //template<ss_typename_param_k S = lvs_string_t> class listview_sequence_item { public: // typedef S string_type; public: listview_sequence_item(HWND hwndListView, int iIndex) : m_hwndListView(hwndListView) , m_index(iIndex) {} public: lvs_string_t text(int iSubItem = 0) const { typedef STLSOFT_NS_QUAL(auto_buffer_old)< TCHAR , processheap_allocator<TCHAR> , 256 > buffer_t; ws_size_t cb = buffer_t::internal_size(); LV_ITEM item; item.mask = LVIF_TEXT; item.iItem = m_index; item.iSubItem = iSubItem; for(;; cb += buffer_t::internal_size()) { buffer_t buffer(cb); item.cchTextMax = static_cast<int>(cb); item.pszText = &buffer[0]; if(!ListView_GetItem(m_hwndListView, &item)) { item.cchTextMax = 0; break; } else { ss_size_t len = static_cast<ss_size_t>(lstrlen(item.pszText)); if(len + 1 < cb) { return lvs_string_t(item.pszText, len); } } } return lvs_string_t(); } int index() const { return m_index; } HWND hwnd() const { return m_hwndListView; } int image() const; int selected_image() const; ws_dword_t data() const { LV_ITEM item; item.mask = LVIF_PARAM; item.iItem = m_index; item.iSubItem = 0; return ListView_GetItem(m_hwndListView, &item) ? static_cast<ws_dword_t>(item.lParam) : 0; } /// The item's state UINT state(UINT mask = 0xffffffff) const { return ListView_GetItemState(m_hwndListView, m_index, mask); } private: HWND m_hwndListView; int m_index; }; /** Provides an STL-like sequence over the contents of a Windows List-view (<code>"SysListView32"</code>) * * \ingroup group__library__Windows_Control */ class listview_sequence : public STLSOFT_NS_QUAL(stl_collection_tag) { public: /// The value type typedef listview_sequence_item sequence_value_type; typedef sequence_value_type value_type; /// The size type typedef ss_size_t size_type; /// The difference type typedef ws_ptrdiff_t difference_type; /// typedef listview_sequence sequence_class_type; private: typedef int internal_index_type_; public: ss_explicit_k listview_sequence(HWND hwndListView) : m_hwndListView(hwndListView) {} public: /// const_iterator for the listview_sequence class const_iterator : public STLSOFT_NS_QUAL(iterator_base)<STLSOFT_NS_QUAL_STD(random_access_iterator_tag) , sequence_value_type , ws_ptrdiff_t , void // By-Value Temporary reference , sequence_value_type // By-Value Temporary reference > { typedef const_iterator class_type; public: typedef sequence_value_type value_type; public: const_iterator() : m_hwndListView(NULL) , m_index(-1) {} const_iterator(HWND hwndListView, int iIndex) : m_hwndListView(hwndListView) , m_index(iIndex) {} const_iterator(class_type const& rhs) : m_hwndListView(rhs.m_hwndListView) , m_index(rhs.m_index) {} class_type& operator =(class_type const& rhs) { m_hwndListView = rhs.m_hwndListView; m_index = rhs.m_index; return *this; } public: /// Dereference operator value_type operator *() const { return value_type(m_hwndListView, m_index); } bool operator ==(class_type const& rhs) const { WINSTL_MESSAGE_ASSERT("Comparing iterators from different listview_sequence instances!", m_hwndListView == rhs.m_hwndListView); return m_index == rhs.m_index; } bool operator !=(class_type const& rhs) const { WINSTL_MESSAGE_ASSERT("Comparing iterators from different listview_sequence instances!", m_hwndListView == rhs.m_hwndListView); return m_index != rhs.m_index; } /// Pre-increment operator class_type& operator ++() { WINSTL_MESSAGE_ASSERT("Attempting to increment an off-the-end iterator", m_index < ListView_GetItemCount(m_hwndListView)); ++m_index; return *this; } /// Post-increment operator class_type operator ++(int) { class_type ret(*this); operator ++(); return ret; } /// Pre-decrement operator class_type& operator --() { WINSTL_MESSAGE_ASSERT("Attempting to decrement an iterator at the start of the sequence", 0 < m_index); --m_index; return *this; } /// Post-decrement operator class_type operator --(int) { class_type ret(*this); operator --(); return ret; } // Random access operations /// Offset class_type& operator +=(difference_type index) { #ifdef STLSOFT_CF_EXCEPTION_SUPPORT m_index += stlsoft::truncation_cast<internal_index_type_>(index); #else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */ m_index += static_cast<internal_index_type_>(index); #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ return *this; } /// Offset class_type& operator -=(difference_type index) { #ifdef STLSOFT_CF_EXCEPTION_SUPPORT m_index -= stlsoft::truncation_cast<internal_index_type_>(index); #else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */ m_index -= static_cast<internal_index_type_>(index); #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ return *this; } /// Subscript operator value_type operator [](difference_type index) const { #ifdef STLSOFT_CF_EXCEPTION_SUPPORT return value_type(m_hwndListView, stlsoft::truncation_cast<internal_index_type_>(m_index + index)); #else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */ return value_type(m_hwndListView, static_cast<internal_index_type_>(m_index + index)); #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ } /// Calculate the distance between \c this and \c rhs difference_type distance(class_type const& rhs) const { return m_index - rhs.m_index; } /// Pointer subtraction class_type operator -(difference_type n) const { return class_type(*this) -= n; } /// Pointer addition class_type operator +(difference_type n) const { return class_type(*this) += n; } /// Pointer difference difference_type operator -(class_type const& rhs) const { return distance(rhs); } // Members private: HWND m_hwndListView; int m_index; }; #if defined(STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT) /// The non-mutating (const) reverse iterator type typedef STLSOFT_NS_QUAL(const_reverse_iterator_base)< const_iterator , value_type , value_type // By-Value Temporary reference category , void // By-Value Temporary reference category , difference_type > const_reverse_iterator; #endif /* STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT */ // State public: /// Returns the number of elements in the list-box size_type size() const { return static_cast<size_type>(ListView_GetItemCount(m_hwndListView)); } /// Indicates whether the list-box is empty ws_bool_t empty() const { return 0 == size(); } /// Returns the maximum number of items that the list-box can contain static size_type max_size() { return static_cast<size_type>(-1) / sizeof(LPCTSTR); } // Iteration public: const_iterator begin() const { return const_iterator(m_hwndListView, 0); } const_iterator end() const { return const_iterator(m_hwndListView, static_cast<int>(size())); } #if defined(STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT) /// Begins the reverse iteration /// /// \return An iterator representing the start of the reverse sequence const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } /// Ends the reverse iteration /// /// \return An iterator representing the end of the reverse sequence const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } #endif /* STLSOFT_LF_BIDIRECTIONAL_ITERATOR_SUPPORT */ // Accessors public: value_type operator [](size_type index) const { return value_type(m_hwndListView, static_cast<int>(index)); } private: HWND m_hwndListView; }; /* ///////////////////////////////////////////////////////////////////////// * shims */ inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_null(listview_sequence_item const& lvi) { return STLSOFT_NS_QUAL(c_str_ptr_null)(lvi.text()); } #ifdef UNICODE inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_null_w(listview_sequence_item const& lvi) #else /* ? UNICODE */ inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_null_a(listview_sequence_item const& lvi) #endif /* UNICODE */ { return STLSOFT_NS_QUAL(c_str_ptr_null)(lvi.text()); } inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, false, processheap_allocator<TCHAR> > c_str_ptr(listview_sequence_item const& lvi) { return STLSOFT_NS_QUAL(c_str_ptr)(lvi.text()); } #ifdef UNICODE inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_w(listview_sequence_item const& lvi) #else /* ? UNICODE */ inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_ptr_a(listview_sequence_item const& lvi) #endif /* UNICODE */ { return STLSOFT_NS_QUAL(c_str_ptr)(lvi.text()); } inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, false, processheap_allocator<TCHAR> > c_str_data(listview_sequence_item const& lvi) { return STLSOFT_NS_QUAL(c_str_data)(lvi.text()); } #ifdef UNICODE inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_data_w(listview_sequence_item const& lvi) #else /* ? UNICODE */ inline STLSOFT_NS_QUAL(basic_shim_string)<TCHAR, 64, true, processheap_allocator<TCHAR> > c_str_data_a(listview_sequence_item const& lvi) #endif /* UNICODE */ { return STLSOFT_NS_QUAL(c_str_data)(lvi.text()); } inline ws_size_t c_str_len(listview_sequence_item const& lvi) { return STLSOFT_NS_QUAL(c_str_len)(lvi.text()); } template< ss_typename_param_k S > inline S& operator <<(S& s, listview_sequence_item const& lvi) { s << lvi.text(); return s; } /* ///////////////////////////////////////////////////////////////////////// * namespace */ #ifndef WINSTL_NO_NAMESPACE # if defined(STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) } /* namespace winstl */ # else } /* namespace winstl_project */ } /* namespace stlsoft */ # endif /* STLSOFT_NO_NAMESPACE */ #endif /* !WINSTL_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * namespace * * The string access shims exist either in the stlsoft namespace, or in the * global namespace. This is required by the lookup rules. * */ #ifndef WINSTL_NO_NAMESPACE # if !defined(STLSOFT_NO_NAMESPACE) && \ !defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) namespace stlsoft { # else /* ? STLSOFT_NO_NAMESPACE */ /* There is no stlsoft namespace, so must define in the global namespace */ # endif /* !STLSOFT_NO_NAMESPACE */ using ::winstl::c_str_ptr_null; using ::winstl::c_str_ptr_null_a; using ::winstl::c_str_ptr_null_w; using ::winstl::c_str_ptr; using ::winstl::c_str_ptr_a; using ::winstl::c_str_ptr_w; using ::winstl::c_str_data; using ::winstl::c_str_data_a; using ::winstl::c_str_data_w; using ::winstl::c_str_len; # if !defined(STLSOFT_NO_NAMESPACE) && \ !defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) } /* namespace stlsoft */ # else /* ? STLSOFT_NO_NAMESPACE */ /* There is no stlsoft namespace, so must define in the global namespace */ # endif /* !STLSOFT_NO_NAMESPACE */ #endif /* !WINSTL_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * inclusion control */ #ifdef STLSOFT_CF_PRAGMA_ONCE_SUPPORT # pragma once #endif /* STLSOFT_CF_PRAGMA_ONCE_SUPPORT */ #endif /* !WINSTL_INCL_WINSTL_CONTROLS_HPP_LISTVIEW_SEQUENCE */ /* ///////////////////////////// end of file //////////////////////////// */
32.771615
141
0.636816
nneesshh
4403dfed513c5fdb39e812465f6013deb45634de
79,067
cpp
C++
trunk/win/Source/BT_Camera.cpp
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
460
2016-01-13T12:49:34.000Z
2022-02-20T04:10:40.000Z
trunk/win/Source/BT_Camera.cpp
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
24
2016-11-07T04:59:49.000Z
2022-03-14T06:34:12.000Z
trunk/win/Source/BT_Camera.cpp
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
148
2016-01-17T03:16:43.000Z
2022-03-17T12:20:36.000Z
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "BT_Common.h" #include "BT_CustomActor.h" #include "BT_DialogManager.h" #include "BT_AnimationManager.h" #include "BT_AutomatedTradeshowDemo.h" #include "BT_Camera.h" #include "BT_EventManager.h" #include "BT_FacebookWidgetJavaScriptAPI.h" #include "BT_FileSystemManager.h" #include "BT_JavaScriptAPI.h" #ifdef DXRENDER #include "BT_DXRender.h" #endif #include "BT_PbPersistenceHelpers.h" #include "BT_PhotoFrameActor.h" #include "BT_Pile.h" #include "BT_RaycastReports.h" #include "BT_RenderManager.h" #include "BT_SceneManager.h" #include "BT_Selection.h" #include "BT_StatsManager.h" #include "BT_TextManager.h" #include "BT_Util.h" #include "BT_WatchedObjects.h" #include "BT_WebActor.h" #include "BT_WindowsOS.h" #include "BumpTop.pb.h" #include "TwitterClient.h" #include "FacebookClient.h" // // RestoreOriginalPhoto control implementation // RestoreOriginalPhotoControl::RestoreOriginalPhotoControl() : _layout(NULL) , _hLayout(NULL) , _label(NULL) , _enabled(false) {} RestoreOriginalPhotoControl::~RestoreOriginalPhotoControl() {} void RestoreOriginalPhotoControl::init() { _layout = new OverlayLayout; _layout->getStyle().setOffset(Vec3(-0.13f, -0.05f, 0)); _label = new TextOverlay(QT_TR_NOOP("Undo Photo Crop")); _label->setAlpha(1.0f); _hLayout = new HorizontalOverlayLayout; _hLayout->getStyle().setBackgroundColor(ColorVal(60, 0, 0, 0)); _hLayout->getStyle().setPadding(AllEdges, 5.0f); _hLayout->getStyle().setPadding(RightEdge, 10.0f); _hLayout->getStyle().setSpacing(2.0f); _hLayout->addItem(_label); _hLayout->addMouseEventHandler(this); _layout->addItem(_hLayout); scnManager->registerOverlay(_layout); } void RestoreOriginalPhotoControl::show() { if (_enabled) return; _enabled = true; // If the control is not created, then create it // This is lazy initialization. if (!_layout) { init(); } fadeIn(); return; } bool RestoreOriginalPhotoControl::onMouseDown( MouseOverlayEvent& mouseEvent ) { if (!_enabled) return false; // Zoom to default camera position FileSystemActor* photo = dynamic_cast<FileSystemActor*>(cam->getHighlightedWatchedActor()); restoreOriginalPhoto(photo); return true; } bool RestoreOriginalPhotoControl::onMouseUp( MouseOverlayEvent& mouseEvent ) { if (!_enabled) return false; return true; } bool RestoreOriginalPhotoControl::onMouseMove( MouseOverlayEvent& mouseEvent ) { return false; } void RestoreOriginalPhotoControl::hide() { if (_enabled) { fadeOut(); _enabled = false; } } void RestoreOriginalPhotoControl::fadeIn() { _hLayout->finishAnimation(); float alpha = _hLayout->getStyle().getAlpha(); if (alpha < 1.0f) _hLayout->setAlphaAnim(alpha, 1.0f, 15); } void RestoreOriginalPhotoControl::fadeOut() { _hLayout->finishAnimation(); float alpha = _hLayout->getStyle().getAlpha(); if (alpha > 0.0f) _hLayout->setAlphaAnim(alpha, 0.0f, 15); } // // CameraOverlay implementation // void SlideShowControls::init() { _enabled = true; _facebookActor = getFacebookActor(false); if (_slideshowMenuContainer) //Already initialized { fadeIn(); return; } //Create Slideshow Menu Items _slideshowMenuContainer = new OverlayLayout; _slideshowMenuHLayout = new HorizontalOverlayLayout; _twitterContainer = new OverlayLayout; _twitterLayout = new VerticalOverlayLayout; _twitterImage = new ImageOverlay("pui.twitter"); _twitterLabel = new TextOverlay(QT_TR_NOOP("Twitter")); _facebookContainer = new OverlayLayout; _facebookLayout = new VerticalOverlayLayout; _facebookImage = new ImageOverlay("pui.facebook"); _facebookLabel = new TextOverlay(QT_TR_NOOP("Facebook")); _emailContainer = new OverlayLayout; _emailLayout = new VerticalOverlayLayout; _emailImage = new ImageOverlay("pui.email"); _emailLabel = new TextOverlay(QT_TR_NOOP("Email")); _printerContainer = new OverlayLayout; _printerLayout = new VerticalOverlayLayout; _printerImage = new ImageOverlay("pui.print"); _printerLabel = new TextOverlay(QT_TR_NOOP("Print")); _editContainer = new OverlayLayout; _editLayout = new VerticalOverlayLayout; _editImage = new ImageOverlay("pui.edit"); _editLabel = new TextOverlay(QT_TR_NOOP("Edit")); _dividerImage1 = new ImageOverlay("pui.divider"); _dividerImage2 = new ImageOverlay("pui.divider"); _dividerImage3 = new ImageOverlay("pui.divider"); _dividerImage4 = new ImageOverlay("pui.divider"); _dividerImage5 = new ImageOverlay("pui.divider"); _dividerImage6 = new ImageOverlay("pui.divider"); _closeContainer = new OverlayLayout; _closeLayout = new VerticalOverlayLayout; _closeImage = new ImageOverlay("pui.close"); _closeLabel = new TextOverlay(QT_TR_NOOP("Close")); _nextContainer = new OverlayLayout; _nextLayout = new VerticalOverlayLayout; _nextImage = new ImageOverlay("pui.next"); _prevContainer = new OverlayLayout; _prevLayout = new VerticalOverlayLayout; _prevImage = new ImageOverlay("pui.previous"); //Initialize Slideshow Menu Items _slideshowMenuContainer->getStyle().setOffset(Vec3(-0.5f, 0.02f, 0)); _slideshowMenuHLayout->getStyle().setBackgroundColor(ColorVal(195, 0, 0, 0)); _slideshowMenuHLayout->getStyle().setPadding(AllEdges,5.0f); FontDescription slideShowButtonFont(QT_NT("Tahoma bold"), 10); _twitterLabel->setFont(slideShowButtonFont); _facebookLabel->setFont(slideShowButtonFont); _emailLabel->setFont(slideShowButtonFont); _printerLabel->setFont(slideShowButtonFont); _editLabel->setFont(slideShowButtonFont); _closeLabel->setFont(slideShowButtonFont); _twitterLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0)); _facebookLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0)); _emailLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0)); _printerLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0)); _editLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0)); _closeLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0)); _nextLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0)); _prevLayout->getStyle().setBackgroundColor(ColorVal(0, 0, 0, 0)); _twitterLayout->getStyle().setPadding(TopBottomEdges, 10.0f); _twitterLayout->getStyle().setPadding(LeftRightEdges, 0.0f); _twitterLayout->getStyle().setSpacing(0.0f); _facebookLayout->getStyle().setPadding(TopBottomEdges, 10.0f); _facebookLayout->getStyle().setPadding(LeftRightEdges, 0.0f); _facebookLayout->getStyle().setSpacing(0.0f); _emailLayout->getStyle().setPadding(TopBottomEdges, 10.0f); _emailLayout->getStyle().setPadding(LeftRightEdges, 0.0f); _emailLayout->getStyle().setSpacing(0.0f); _printerLayout->getStyle().setPadding(TopBottomEdges, 10.0f); _printerLayout->getStyle().setPadding(LeftRightEdges, 0.0f); _printerLayout->getStyle().setSpacing(0.0f); _editLayout->getStyle().setPadding(TopBottomEdges, 10.0f); _editLayout->getStyle().setPadding(LeftRightEdges, 0.0f); _editLayout->getStyle().setSpacing(0.0f); _closeLayout->getStyle().setPadding(TopBottomEdges, 10.0f); _closeLayout->getStyle().setPadding(LeftRightEdges, 0.0f); _closeLayout->getStyle().setSpacing(0.0f); _nextLayout->getStyle().setPadding(TopBottomEdges, 10.0f); _nextLayout->getStyle().setPadding(LeftRightEdges, 0.0f); _nextLayout->getStyle().setSpacing(0.0f); _prevLayout->getStyle().setPadding(TopBottomEdges, 10.0f); _prevLayout->getStyle().setPadding(LeftRightEdges, 0.0f); _prevLayout->getStyle().setSpacing(0.0f); _dividerImage1->getStyle().setPadding(TopBottomEdges, 10.0f); _dividerImage1->getStyle().setPadding(LeftRightEdges, 0.0f); _dividerImage1->getStyle().setSpacing(0.0f); _dividerImage2->getStyle().setPadding(TopBottomEdges, 10.0f); _dividerImage2->getStyle().setPadding(LeftRightEdges, 0.0f); _dividerImage2->getStyle().setSpacing(0.0f); _dividerImage3->getStyle().setPadding(TopBottomEdges, 10.0f); _dividerImage3->getStyle().setPadding(LeftRightEdges, 0.0f); _dividerImage3->getStyle().setSpacing(0.0f); _dividerImage4->getStyle().setPadding(TopBottomEdges, 10.0f); _dividerImage4->getStyle().setPadding(LeftRightEdges, 0.0f); _dividerImage4->getStyle().setSpacing(0.0f); _dividerImage5->getStyle().setPadding(TopBottomEdges, 10.0f); _dividerImage5->getStyle().setPadding(LeftRightEdges, 0.0f); _dividerImage5->getStyle().setSpacing(0.0f); _dividerImage6->getStyle().setPadding(TopBottomEdges, 10.0f); _dividerImage6->getStyle().setPadding(LeftRightEdges, 0.0f); _dividerImage6->getStyle().setSpacing(0.0f); _twitterLayout->addItem(_twitterImage); _twitterLayout->addItem(_twitterLabel); _twitterContainer->addMouseEventHandler(this); _facebookLayout->addItem(_facebookImage); _facebookLayout->addItem(_facebookLabel); _facebookContainer->addMouseEventHandler(this); _emailLayout->addItem(_emailImage); _emailLayout->addItem(_emailLabel); _emailContainer->addMouseEventHandler(this); _printerLayout->addItem(_printerImage); _printerLayout->addItem(_printerLabel); _printerContainer->addMouseEventHandler(this); _editLayout->addItem(_editImage); _editLayout->addItem(_editLabel); _editContainer->addMouseEventHandler(this); _closeLayout->addItem(_closeImage); _closeLayout->addItem(_closeLabel); _closeContainer->addMouseEventHandler(this); _nextLayout->addItem(_nextImage); _nextContainer->addMouseEventHandler(this); _prevLayout->addItem(_prevImage); _prevContainer->addMouseEventHandler(this); _twitterContainer->addItem(_twitterLayout); _facebookContainer->addItem(_facebookLayout); _emailContainer->addItem(_emailLayout); _printerContainer->addItem(_printerLayout); _editContainer->addItem(_editLayout); _closeContainer->addItem(_closeLayout); _nextContainer->addItem(_nextLayout); _prevContainer->addItem(_prevLayout); /* See button hit boxes _twitterLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0)); _twitterImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0)); _twitterContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255)); _facebookLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0)); _facebookImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0)); _facebookContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255)); _emailLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0)); _emailImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0)); _emailContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255)); _prevImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0)); _prevContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255)); _nextImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0)); _nextContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255)); _printerLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0)); _printerImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0)); _printerContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255)); _editLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0)); _editImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0)); _editContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255)); _closeLabel->getStyle().setBackgroundColor(ColorVal(255,255,0,0)); _closeImage->getStyle().setBackgroundColor(ColorVal(255,0,255,0)); _closeContainer->getStyle().setBackgroundColor(ColorVal(255,0,0,255)); /**/ _slideshowMenuHLayout->addItem(_twitterContainer); _slideshowMenuHLayout->addItem(_dividerImage1); _slideshowMenuHLayout->addItem(_facebookContainer); _slideshowMenuHLayout->addItem(_dividerImage2); _slideshowMenuHLayout->addItem(_emailContainer); _slideshowMenuHLayout->addItem(_dividerImage3); _slideshowMenuHLayout->addItem(_prevContainer); _slideshowMenuHLayout->addItem(_nextContainer); _slideshowMenuHLayout->addItem(_dividerImage4); _slideshowMenuHLayout->addItem(_printerContainer); _slideshowMenuHLayout->addItem(_dividerImage5); _slideshowMenuHLayout->addItem(_editContainer); _slideshowMenuHLayout->addItem(_dividerImage6); _slideshowMenuHLayout->addItem(_closeContainer); _slideshowMenuContainer->addItem(_slideshowMenuHLayout); scnManager->registerOverlay(_slideshowMenuContainer); // NOTE: set the size animations _after_ they have been added to the layouts } SlideShowControls::SlideShowControls() { twitterClient = NULL; twitpicClient = NULL; facebookClient = NULL; _slideshowMenuContainer = NULL; _slideshowMenuHLayout = NULL; _twitterContainer = NULL; _twitterLayout = NULL; _twitterImage = NULL; _twitterLabel = NULL; _facebookContainer = NULL; _facebookLayout = NULL; _facebookImage = NULL; _facebookLabel = NULL; _emailContainer = NULL; _emailLayout = NULL; _emailImage = NULL; _emailLabel = NULL; _printerContainer = NULL; _printerLayout = NULL; _printerImage = NULL; _printerLabel = NULL; _editContainer = NULL; _editLayout = NULL; _editImage = NULL; _editLabel = NULL; _closeContainer = NULL; _closeLayout = NULL; _closeImage = NULL; _closeLabel = NULL; _prevContainer = NULL; _prevLayout = NULL; _prevImage = NULL; _nextContainer = NULL; _nextLayout = NULL; _nextImage = NULL; _dividerImage1 = NULL; _dividerImage2 = NULL; _dividerImage3 = NULL; _dividerImage4 = NULL; _dividerImage5 = NULL; _dividerImage6 = NULL; } SlideShowControls::~SlideShowControls() { // Scene manager automatically removes all unused overlays } void SlideShowControls::fadeIn() { _slideshowMenuHLayout->setAlphaAnim(_slideshowMenuHLayout->getStyle().getAlpha(), 1.0f, 25); } void SlideShowControls::fadeOut() { _slideshowMenuHLayout->finishAnimation(); float alpha = _slideshowMenuHLayout->getStyle().getAlpha(); if (alpha > 0.0f) _slideshowMenuHLayout->setAlphaAnim(alpha, 0.0f, 25); if(!evtManager->getACPowerStatus()) { //Battery power _slideshowMenuHLayout->setAlpha(0.0f); } SetCursor(LoadCursor(NULL, IDC_ARROW)); } void SlideShowControls::twitterAction() { BumpObject* currentActor = cam->getHighlightedWatchedActor(); if (!ftManager->hasInternetConnection()) { printUniqueError("TwitterActorImpl", QT_TRANSLATE_NOOP("TwitpicClient", "No internet connection detected")); return; } CustomActor * twit = scnManager->getCustomActor<TwitterActorImpl>(); if(twit) { //Twitter actor exists std::vector<BumpObject *> currentActor; currentActor.push_back(cam->getHighlightedWatchedActor()); twit->onDrop(currentActor); return; } else { //We need to open up our own connection to twitter (based on code from the onDrop event) if(!twitterClient) twitterClient = new TwitterClient(TWITTER_SERVER); if(!twitpicClient) twitpicClient = new TwitpicClient(TWITPIC_SERVER); BumpObject* currentActor = cam->getHighlightedWatchedActor(); if (twitterClient->initialize() && twitpicClient->initialize()) { if (currentActor->getObjectType() == ObjectType(BumpActor, FileSystem, Image)) { QString photoPath = dynamic_cast<FileSystemActor *>(currentActor)->getFullPath(); twitpicClient->uploadAndPostDeferMessage(photoPath); //tweet } else { // non-files are rejected printUniqueError("TwitterActorImpl", QT_TRANSLATE_NOOP("TwitpicClient", "Unsupported image file type")); } } } } void SlideShowControls::facebookAction() { if (!ftManager->hasInternetConnection()) { printUniqueError("FacebookActorImpl", QT_TRANSLATE_NOOP("FacebookClient", "No internet connection detected")); return; } bool wasOn = true; if(!_facebookActor) { _facebookActor = getFacebookActor(true); wasOn = false; } FacebookWidgetJavaScriptAPI* fbAPI = dynamic_cast<FacebookWidgetJavaScriptAPI*>(_facebookActor->getJavaScriptAPI()); //We found the facebook widget if(GLOBAL(settings).fbc_uid.isEmpty() && GLOBAL(settings).fbc_session.isEmpty() && GLOBAL(settings).fbc_secret.isEmpty()) { //User is not logged in fbAPI->launchLoginPage(); fbAPI->setPersistentStoreValue(QT_NT("last-page"),QT_NT("newsfeed")); _facebookActor->load(QT_NT("bumpwidget-facebook://newsfeed"), true); } //The reason we check twice is that the user could have cancelled the login process. if(!(GLOBAL(settings).fbc_uid.isEmpty() && GLOBAL(settings).fbc_session.isEmpty() && GLOBAL(settings).fbc_secret.isEmpty())) { //User has logged in vector<BumpObject *> watched; watched.push_back(cam->getHighlightedWatchedActor()); fbAPI->onDropEnter(watched); fbAPI->onDrop(); goFacebookAction(); } else { if(!wasOn) { FadeAndDeleteActor(_facebookActor); } } } WebActor * SlideShowControls::getFacebookActor(bool createIfNotExists) { vector<BumpObject *> webActors = scnManager->getBumpObjects(ObjectType(BumpActor, Webpage)); for (int i = 0; i < webActors.size(); ++i) { WebActor * actor = (WebActor *) webActors[i]; if (actor->isFacebookWidgetUrl()) { return actor; } } if(createIfNotExists) { Key_ToggleFacebookWidget(); vector<BumpObject *> webActors = scnManager->getBumpObjects(ObjectType(BumpActor, Webpage)); for (int i = 0; i < webActors.size(); ++i) { WebActor * actor = (WebActor *) webActors[i]; if (actor->isFacebookWidgetUrl()) { return actor; } } } return NULL; } void SlideShowControls::goFacebookAction() { cam->killAnimation(); Key_ToggleSlideShow(); _facebookActor->onLaunch(); } void SlideShowControls::printerAction(){ CustomActor * prnt = scnManager->getCustomActor<PrinterActorImpl>(); if(prnt) { //Printer actor exists std::vector<BumpObject *> currentActor; currentActor.push_back(cam->getHighlightedWatchedActor()); prnt->onDrop(currentActor); return; } else { //We need to open up our own connection to the printer (based on code from the onDrop event function) BumpObject * currentActor = cam->getHighlightedWatchedActor(); if (!(currentActor->getObjectType() == ObjectType(BumpActor, FileSystem, File))) { MessageClearPolicy clearPolicy; clearPolicy.setTimeout(2); scnManager->messages()->addMessage(new Message("PrinterActorImpl::onDrop", QT_TR_NOOP("You can only print files!"), Message::Ok, clearPolicy)); return; } dlgManager->clearState(); dlgManager->setPrompt(QT_TR_NOOP("Print these file(s) on your default printer?")); if (!dlgManager->promptDialog(DialogYesNo)) { dismiss("PrinterActorImpl::onDrop"); return; } QString filePath = dynamic_cast<FileSystemActor *>(currentActor)->getFullPath(); int result = (int) ShellExecute(winOS->GetWindowsHandle(), QT_NT(L"print"), (LPCTSTR) filePath.utf16(), NULL, NULL, SW_SHOWNORMAL); if (result <= 32) { MessageClearPolicy clearPolicy; clearPolicy.setTimeout(2); scnManager->messages()->addMessage(new Message("PrinterActorImpl::onDrop", QT_TR_NOOP("Could not print this file!"), Message::Ok, clearPolicy)); return; } else { // notify the user MessageClearPolicy clearPolicy; clearPolicy.setTimeout(3); Message * message = new Message("PrinterActorImpl::onDrop", QT_TR_NOOP("Printing file"), Message::Ok, clearPolicy); scnManager->messages()->addMessage(message); return; } } } void SlideShowControls::closeAction(){ Key_ToggleSlideShow(); } void SlideShowControls::emailAction(){ CustomActor * mail = scnManager->getCustomActor<EmailActorImpl>(); if(mail) { //Email actor exists std::vector<BumpObject *> currentActor; currentActor.push_back(cam->getHighlightedWatchedActor()); mail->onDrop(currentActor); return; } else { //We need to open up our own connection to email (based on code from the onDrop event function) std::vector<BumpObject *> currentActor; currentActor.push_back(cam->getHighlightedWatchedActor()); if (!CreateEmailWithSelectionAsAttachments(currentActor)) { MessageClearPolicy clearPolicy; clearPolicy.setTimeout(2); scnManager->messages()->addMessage(new Message("EmailActorImpl::onDrop", QT_TR_NOOP("Could not create email with these files\nas attachments!"), Message::Ok, clearPolicy)); } else { // notify the user MessageClearPolicy clearPolicy; clearPolicy.setTimeout(3); Message * message = new Message("EmailActorImpl::onDrop", QT_TR_NOOP("Creating new email"), Message::Ok, clearPolicy); scnManager->messages()->addMessage(message); } } } void SlideShowControls::nextAction(){ cam->highlightNextWatchedActor(true); } void SlideShowControls::prevAction(){ cam->highlightNextWatchedActor(false); } void SlideShowControls::editAction(){ assert(cam->getHighlightedWatchedActor() != NULL); BumpObject * currentActor = cam->getHighlightedWatchedActor(); if(currentActor->getObjectType() == ObjectType(BumpActor, FileSystem)) { fsManager->launchFile(dynamic_cast<FileSystemActor *>(currentActor)->getFullPath(),L"edit"); } } int SlideShowControls::getHeight() { return _slideshowMenuHLayout->getSize().y; } void *callbackManager(AnimationEntry *anim) { SlideShowControls *controls = (SlideShowControls *)anim->getCustomData(); switch (controls->pressed) { case SlideShowControls::TWITTER: controls->twitterAction(); break; case SlideShowControls::FACEBOOK: controls->facebookAction(); break; case SlideShowControls::EMAIL: controls->emailAction(); break; case SlideShowControls::EDIT: controls->editAction(); break; case SlideShowControls::CLOSE: controls->closeAction(); break; case SlideShowControls::NEXT: controls->nextAction(); break; case SlideShowControls::PREVIOUS: controls->prevAction(); break; case SlideShowControls::GOFACEBOOK: controls->goFacebookAction(); break; case SlideShowControls::PRINTER: controls->printerAction(); break; } return NULL; } bool SlideShowControls::onMouseDown( MouseOverlayEvent& mouseEvent ) { if (!_enabled) return true; //TODO: A lot of this code is parallel to the respective actors in customactor, if possible we should share these resources OverlayComponent * button = dynamic_cast<OverlayComponent *>(mouseEvent.getTarget()); if (dynamic_cast<OverlayLayout *>(button) == _twitterContainer) {//Twitter button pressed = TWITTER; } else if (dynamic_cast<OverlayLayout *>(button) == _facebookContainer) {//Facebook button pressed = FACEBOOK; } else if (dynamic_cast<OverlayLayout *>(button) == _emailContainer) {//Email button pressed = EMAIL; } else if (dynamic_cast<OverlayLayout *>(button) == _printerContainer) {//Printer button pressed = PRINTER; } else if (dynamic_cast<OverlayLayout *>(button) == _editContainer) {//Edit button pressed = EDIT; } else if (dynamic_cast<OverlayLayout *>(button) == _closeContainer) {//Close button pressed = CLOSE; } else if (dynamic_cast<OverlayLayout *>(button) == _prevContainer) {//Previous image button pressed = PREVIOUS; } else if (dynamic_cast<OverlayLayout *>(button) == _nextContainer) {//Next image button pressed = NEXT; } else { pressed = NOPRESS; } if(pressed != NOPRESS) { if(button->isAnimating()) { button->finishAnimation(); AnimationEntry a = AnimationEntry(button,NULL,this); callbackManager(&a); } button->setAlphaAnim(0.5f,1.0f,15,(FinishedCallBack)callbackManager, this); } return true; } bool SlideShowControls::onMouseUp( MouseOverlayEvent& mouseEvent ) { if (!_enabled) return false; // reset the color of the font OverlayComponent * button = mouseEvent.getTarget(); button->getStyle().setColor(ColorVal(255, 255, 255, 255)); if (!mouseEvent.intersectsTarget()) SetCursor(LoadCursor(NULL, IDC_ARROW)); return true; } bool SlideShowControls::onMouseMove( MouseOverlayEvent& mouseEvent ) { if (!_enabled) return false; return false; } void SlideShowControls::disable() { if (_slideshowMenuContainer) { fadeOut(); _enabled = false; } } // // ZoomOut control implementation // ZoomOutControl::ZoomOutControl() : _layout(NULL) , _hLayout(NULL) , _zoomOutLabel(NULL) , _enabled(false) {} ZoomOutControl::~ZoomOutControl() {} void ZoomOutControl::init() { _layout = new OverlayLayout; _layout->getStyle().setOffset(Vec3(-0.10f, -0.05f, 0)); _defaultText = QT_TR_NOOP("Reset Camera"); _zoomOutLabel = new TextOverlay(_defaultText); _zoomOutLabel->setAlpha(1.0f); _zoomOutLabel->getTextBuffer().pushFlag(TextPixmapBuffer::ForceLinearFiltering); _zoomOutLabel->getTextBuffer().pushFlag(TextPixmapBuffer::DisableClearType); _hLayout = new HorizontalOverlayLayout; _hLayout->getStyle().setBackgroundColor(ColorVal(60, 0, 0, 0)); _hLayout->getStyle().setPadding(AllEdges, 5.0f); _hLayout->getStyle().setPadding(RightEdge, 10.0f); _hLayout->getStyle().setSpacing(2.0f); _hLayout->addItem(_zoomOutLabel); _hLayout->addMouseEventHandler(this); _layout->addItem(_hLayout); scnManager->registerOverlay(_layout); } void ZoomOutControl::show() { if (_enabled) return; _enabled = true; // If the control is not created, then create it // This is lazy initialization. if (!_layout) { init(); } fadeIn(); return; } void ZoomOutControl::setText(QString text, Vec3 offset) { if (!_layout) { init(); _hLayout->finishAnimation(); if (!_enabled) // If not visible, set alpha to 0 since init() automatically sets alpha to 1 _hLayout->getStyle().setAlpha(0); } if (text == _zoomOutLabel->getText()) return; if (text.isEmpty()) { text = _defaultText; offset = Vec3(-0.10f, -0.05f, 0); } _zoomOutLabel->setText(text, false); _zoomOutLabel->setSize(_zoomOutLabel->getPreferredDimensions()); _hLayout->setSize(_hLayout->getPreferredDimensions()); _hLayout->reLayout(); _layout->getStyle().setOffset(offset); _layout->reLayout(); } bool ZoomOutControl::onMouseDown( MouseOverlayEvent& mouseEvent ) { if (!_enabled) return false; if (!WebActor::zoomOutFocusedWebActor()) //zoomOutFocusedWebActor will only zoom out when there is exactly one web actor focused / zoomed { cam->getZoomedObjects().clear(); cam->loadCameraFromPreset(GLOBAL(settings.cameraPreset)); } return true; } bool ZoomOutControl::onMouseUp( MouseOverlayEvent& mouseEvent ) { if (!_enabled) return false; return true; } bool ZoomOutControl::onMouseMove( MouseOverlayEvent& mouseEvent ) { return false; } void ZoomOutControl::hide() { if (_enabled) { cam->setTrackingWatchedActors(true); fadeOut(); _enabled = false; } } bool ZoomOutControl::isEnabled() { return _enabled; } void ZoomOutControl::fadeIn() { _hLayout->finishAnimation(); float alpha = _hLayout->getStyle().getAlpha(); if (alpha < 1.0f) _hLayout->setAlphaAnim(alpha, 1.0f, 15); } void ZoomOutControl_restoreText(AnimationEntry & entry) { ((ZoomOutControl *)entry.getCustomData())->setText(QString(), Vec3(0.0f)); // Restore text to "Reset Camera" } void ZoomOutControl::fadeOut() { _hLayout->finishAnimation(); float alpha = _hLayout->getStyle().getAlpha(); if (alpha > 0.0f) _hLayout->setAlphaAnim(alpha, 0.0f, 15, &ZoomOutControl_restoreText, this); } // // CornerInfoControl control implementation // CornerInfoControl::CornerInfoControl() : _layout(NULL) , _hLayout(NULL) , _zoomOutLabel(NULL) , _enabled(false) {} CornerInfoControl::~CornerInfoControl() {} void CornerInfoControl::init() { _enabled = true; if (_layout) { fadeIn(); return; } _layout = new OverlayLayout; _layout->getStyle().setOffset(Vec3(0.0f, -0.07f, 0)); _zoomOutLabel = new TextOverlay(""); _zoomOutLabel->getTextBuffer().pushFlag(TextPixmapBuffer::ForceLinearFiltering); _zoomOutLabel->getTextBuffer().pushFlag(TextPixmapBuffer::DisableClearType); _hLayout = new HorizontalOverlayLayout; _hLayout->getStyle().setBackgroundColor(ColorVal(80, 0, 0, 0)); _hLayout->getStyle().setPadding(AllEdges, 10.0f); _hLayout->getStyle().setPadding(TopEdge, 12.0f); _hLayout->getStyle().setCornerRadius(TopRightCorner|BottomRightCorner, 10.0f); _hLayout->getStyle().setCornerRadius(TopLeftCorner|BottomLeftCorner, 0.0f); _hLayout->getStyle().setSpacing(2.0f); _hLayout->addItem(_zoomOutLabel); _hLayout->addMouseEventHandler(this); _layout->addItem(_hLayout); scnManager->registerOverlay(_layout); } bool CornerInfoControl::onMouseDown( MouseOverlayEvent& mouseEvent ) { if (!_enabled) return false; return true; } bool CornerInfoControl::onMouseUp( MouseOverlayEvent& mouseEvent ) { if (!_enabled) return false; // If the demo is running stop it, otherwise disable the overlay Replayable * replay = scnManager->getReplayable(); if (replay != NULL) { AutomatedTradeshowDemo * demo = dynamic_cast<AutomatedTradeshowDemo *>(replay); if (demo->getPlayState() == replay->Running) { demo->quickStop(); setMessageText(QT_TR_NOOP("BumpTop Demo Scene\nTo refresh the scene hit F7\nTo start the automatic demo hit CTRL + F7")); } else disable(); } else disable(); return true; } bool CornerInfoControl::onMouseMove( MouseOverlayEvent& mouseEvent ) { return false; } void CornerInfoControl::disable() { if (_layout) { fadeOut(); _enabled = false; } } bool CornerInfoControl::isEnabled() { return _enabled; } void CornerInfoControl::fadeIn() { float alpha = _hLayout->getStyle().getAlpha(); if (alpha < 1.0f) _hLayout->setAlphaAnim(alpha, 1.0f, 15); } void CornerInfoControl::fadeOut() { float alpha = _hLayout->getStyle().getAlpha(); if (alpha > 0.0f) _hLayout->setAlphaAnim(alpha, 0.0f, 15); } void CornerInfoControl::setMessageText(QString text) { if (!_zoomOutLabel) return; _zoomOutLabel->setText(text); _hLayout->setSize(_hLayout->getPreferredDimensions()); } // // Camera implementation // const float Camera::SAME_POSITION_THRESHOLD = 0.0005f; Camera::Camera() : #ifndef DXRENDER _glProjMatrix(new GLdouble[16]) , _glMVMatrix(new GLdouble[16]) , _glViewport(new GLint[4]) , _isglDataDirty(false) , #endif _animationFinishData(NULL) , _currentCameraView(DefaultView) { _animationFinishCallback = NULL; // Default Values setOrientation(Vec3(0, 0, 0), Vec3(0, 1, 0), Vec3(0, 0, 1)); cameraIsFreeForm = false; #ifndef DXRENDER ZeroMemory(_glProjMatrix, 16 * sizeof(GLdouble)); ZeroMemory(_glMVMatrix, 16 * sizeof(GLdouble)); ZeroMemory(_glViewport, 4 * sizeof(GLint)); #endif // init the visible bounds visibleBounds.setEmpty(); } Camera::~Camera() { #ifndef DXRENDER SAFE_DELETE(_glProjMatrix); SAFE_DELETE(_glMVMatrix); SAFE_DELETE(_glViewport); #endif popAllWatchActors(); } Vec3 Camera::getEye() { return eye; } Vec3 Camera::getUp() { return up; } Vec3 Camera::getDir() { return dir; } void Camera::setEye(Vec3 newEye) { eye = newEye; #ifndef DXRENDER _isglDataDirty = true; #endif } void Camera::setDir(Vec3 newDir) { dir = newDir; dir.normalize(); #ifndef DXRENDER _isglDataDirty = true; #endif } void Camera::setUp(Vec3 newUp) { up = newUp; #ifndef DXRENDER _isglDataDirty = true; #endif } // Camera settings loaded from Scene file Vec3 Camera::getSavedEye() { return savedEye; } Vec3 Camera::getSavedDir() { return savedDir; } Vec3 Camera::getSavedUp() { return savedUp; } void Camera::storeCameraPosition(Vec3 newEye, Vec3 newDir, Vec3 newUp) { savedEye = newEye; savedDir = newDir; savedUp = newUp; } bool Camera::isCameraFreeForm() { return cameraIsFreeForm; } void Camera::setIsCameraFreeForm(bool isCameraFreeForm, bool showMessage) { if (!cameraIsFreeForm && isCameraFreeForm) { setCurrentCameraView(Camera::UserDefinedView); if (showMessage) printTimedUnique("Camera::setIsCameraFreeForm", 7, QT_TR_NOOP("Move the camera by using scroll wheel, double-click to focus or Ctrl + Shift W, A, S, D.")); } cameraIsFreeForm = isCameraFreeForm; } // This returns the camera eye when invoking ZoomToAngledBounds // This method is used for error checking in zooming. This // makes sure we don't fly out of the desktop box Vec3 Camera::getDefaultEye() { // Find out the region where this camera will look at Bounds bounds; for (int i = 0; i < 4; i++) { Vec3 wallsPos = GLOBAL(WallsPos)[i]; wallsPos.y = 0; bounds.include(wallsPos); } // Move the camera into position so it encapsulates the entire work area Vec3 oldEye = getEye(), oldUp = getUp(), oldDir = getDir(); Vec3 newEye, newDir, extents; bounds.getExtents(extents); float distZ = extents.z * 0.70f; float distX = extents.x * 0.70f; // Move the camera to look at that location Vec3 camView; camView.x = bounds.getMin().x + ((bounds.getMax().x - bounds.getMin().x) / 2); camView.z = bounds.getMin().z + ((bounds.getMax().z - bounds.getMin().z) / 2); float aspect = float(winOS->GetWindowWidth()) / float(winOS->GetWindowHeight()); float hFoV = bounds.getMax().z - bounds.getMin().z; float wFoV = bounds.getMax().x - bounds.getMin().x; float FoV = CAMERA_FOVY / 2; // 60 / 2 Deg on Y-axis float tanFoV = tan(FoV * (PI / 180)); float multiplier; // Fix the multiplier based on the aspect ratio, if needed (aspect ratio only if width is larger) if (wFoV / hFoV > aspect) { // Width is longer then the screen, use it multiplier = wFoV / aspect; }else{ // height is longer then the screen multiplier = hFoV; } // distance form the group camView.y = bounds.getMax().y + ((multiplier / 2) / tanFoV); return camView + Vec3(0, 10, -distZ); } Camera::PredefinedCameraViews Camera::getCurrentCameraView() { return _currentCameraView; } void Camera::setCurrentCameraView(PredefinedCameraViews view, bool makePersistent) { _currentCameraView = view; if (view == Camera::TopDownView) { zoomToTopDownView(); if (makePersistent) GLOBAL(settings).cameraPreset = QT_NT("oh"); } else if (view == Camera::BottomRightCornerView) { zoomToBottomRightCornerView(); if (makePersistent) GLOBAL(settings).cameraPreset = QT_NT("brc"); } else if (view == Camera::UserDefinedView) { // TODO: We should add code to zoom to the currently // user defined camera position. We do not store such // information in settings yet, so just return. return; } else { zoomToAngledView(); if (makePersistent) GLOBAL(settings).cameraPreset = QT_NT("def"); } if (makePersistent) winOS->SaveSettingsFile(); } void Camera::setOrientation(Vec3 Eye, Vec3 Up, Vec3 Dir) { // Set the orientation of the camera setEye(Eye); setUp(Up); setDir(Dir); } void Camera::unserialize(unsigned char *buf, uint &bufSz, int versionNumber) { Vec3 eye, dir, up; if (versionNumber >= 11 && SERIALIZE_READ_VEC3(&buf, eye, bufSz) && SERIALIZE_READ_VEC3(&buf, dir, bufSz) && SERIALIZE_READ_VEC3(&buf, up, bufSz)) { savedEye = eye; savedDir = dir; savedUp = up; } } void Camera::update(float elapsed) { // if we are watching a set of actors, check their bounds to // see if we need to update the camera if (!watchedActors.empty()) { WatchedObjects& watched = watchedActors.top(); if (!watched.highlightedActor) { // check the watched actors' bounds Bounds bounds = getActorsBounds(watched.actors, true); // ensure that we are not already zoomed to bounds float minMag = (bounds.getMin() - watched.bounds.getMin()).magnitudeSquared(); float maxMag = (bounds.getMax() - watched.bounds.getMax()).magnitudeSquared(); if (minMag > 0.005f || maxMag > 0.005f) { // zoom to bounds if (!GLOBAL(isBumpPhotoMode)) { if (isTrackingWatchedActors()) { zoomToBounds(bounds, false); } watched.bounds = bounds; } rndrManager->invalidateRenderer(); } } } // Check whether or not the ZoomOutControl needs to be rendered. if ((eye - orig).magnitude() < SAME_POSITION_THRESHOLD) { // Hide the ZoomOut control when the camera is at the origin if (zoomOutControl.isEnabled()) zoomOutControl.hide(); } else { if (isSlideshowModeActive() || GLOBAL(isInSharingMode) || GLOBAL(isInInfiniteDesktopMode)) { // Hide the ZoomOut control when we're in slideshow or sharing mode zoomOutControl.hide(); } else if (pathEye.size() > 0 && (pathEye.back() - orig).magnitude() < SAME_POSITION_THRESHOLD) { // If the camera is animating towards the origin, hide the ZoomOut control zoomOutControl.hide(); } else { // Otherwise, show the zoomOut control zoomOutControl.show(); } } #ifndef DXRENDER if (_isglDataDirty) readOGLMatrices(); #endif } // Bounds checking and adjusting bool Camera::adjustPointInDesktop(Vec3& origin, Vec3& destination, NxPlane& plane) { Vec3 direction = destination - origin; direction.normalize(); Ray ray(origin, direction); Box desktopBox = GetDesktopBox(GLOBAL(ZoomBuffer)); NxPlane planes[6]; desktopBox.computePlanes(planes); // For some reason, intersection will only work correctly if the normals of all the planes face to the inside of the desktop. // computePlanes() gives us these two planes (floor and ceiling) with the normals facing outwards. planes[2].normal *= -1.0f; planes[3].normal *= -1.0f; // Two hacks that help keep the rest of BumpTop looking as pretty as it used to be. // The first sets the y bound as the default camera position. // The second sets the floor y bound to be actually on the floor and not below it. planes[2].d = -getDefaultEye().y; planes[3].d = 5.0f; NxReal xMin, xMax, yMin, yMax, zMin, zMax, distance; xMin = desktopBox.GetCenter().x - desktopBox.GetExtents().x; xMax = desktopBox.GetCenter().x + desktopBox.GetExtents().x; yMin = desktopBox.GetCenter().y - desktopBox.GetExtents().y; yMax = getDefaultEye().y; // desktopBox.GetCenter().y + desktopBox.GetExtents().y; zMin = desktopBox.GetCenter().z - desktopBox.GetExtents().z; zMax = desktopBox.GetCenter().z + desktopBox.GetExtents().z; int index = -1; int count = 0; do { if (destination.x > xMax) { NxRayPlaneIntersect(ray, planes[1], distance, destination); destination.x = xMax; index = 1; } else if (destination.x < xMin) { NxRayPlaneIntersect(ray, planes[0], distance, destination); destination.x = xMin; index = 0; } if (destination.y > yMax) { NxRayPlaneIntersect(ray, planes[2], distance, destination); destination.y = yMax; index = 2; } else if (destination.y < yMin) { NxRayPlaneIntersect(ray, planes[3], distance, destination); destination.y = yMin; index = 3; } if (destination.z > zMax) { NxRayPlaneIntersect(ray, planes[5], distance, destination); destination.z = zMax; index = 5; } else if (destination.z < zMin) { NxRayPlaneIntersect(ray, planes[4], distance, destination); destination.z = zMin; index = 4; } count++; } while (index != -1 && count < 2); if (index == -1) return false; if (count == 2) { // This means we are stuck in such a position where the origin and // destination form a ray that completely exists outside of the // desktop box. We will need to handle this differently. // Project the point to the wall it intersected and use that new point. ray = Ray(destination, planes[index].normal); NxRayPlaneIntersect(ray, planes[index], distance, destination); } plane = planes[index]; return true; } // eyeDest: the position in world space of the destination the camera eye is to animate to // dirDest: the direction in world space of the destination the camera direction is to animate to // upDest: the up direction in world space of the destination the camera up direction is to animate to // timeStep: the amount of steps the animation should take to get to its destination // easeIn: whether or not the animation should start slow and speed into the animation // boundsCheck: whether or not to preform boundary checking // projectTail: whether or not to preform a projection of the tail end of the vector(made from the current eye position // and the eye destination) onto the plane it intersects. boundsCheck must be set to true for this to work. void Camera::animateToImpl(Vec3 eyeDest, Vec3 dirDest, Vec3 upDest, int timeStep, bool easeIn, bool boundsCheck, bool projectTail) { EaseFunctionType easeType; if (easeIn) easeType = Ease; else easeType = NoEase; int originalTimeStep = timeStep; dirDest.normalize(); upDest.normalize(); deque<Vec3> projectionPath; if (boundsCheck) { // Perform bounds-checking/adjusting Vec3 newEyeDest = eyeDest; NxPlane plane; // If the destination is outside the desktop, move it in, and only proceed in the body // of this if statement if we want to project the tail of the vector. if (adjustPointInDesktop(eye, eyeDest, plane) && projectTail) { // Project the destination point onto the plane the vector intersected and make an animation from // the point of intersection to this projected point NxReal dist; Ray ray(newEyeDest, plane.normal); NxRayPlaneIntersect(ray, plane, dist, newEyeDest); adjustPointInDesktop(eyeDest, newEyeDest, plane); float percentage = eyeDest.distance(newEyeDest) / (eye.distance(eyeDest) + eyeDest.distance(newEyeDest)); int projectedTimeStep = percentage * timeStep; timeStep -= projectedTimeStep; if (projectedTimeStep > 0) projectionPath = lerpRange(eyeDest, newEyeDest, projectedTimeStep, NoEase); } } if (timeStep > 0) { // Create an animation path over [timeStep] frames pathEye = lerpRange(eye, eyeDest, timeStep, easeType); } pathDir = lerpRange(dir, dirDest, originalTimeStep, easeType); pathUp = lerpRange(up, upDest, originalTimeStep, easeType); // Append, if necessary, the projected animation path to the normal path for (int n = 0; n < projectionPath.size(); n++) { pathEye.push_back(projectionPath[n]); } animManager->addAnimation(AnimationEntry(this, (FinishedCallBack) ReshapeTextAfterAnim, this)); } void Camera::animateTo(Vec3 eyeDest, Vec3 dirDest, Vec3 upDest, int timeStep, bool easeIn) { animateToImpl(eyeDest, dirDest, upDest, timeStep, easeIn, false, false); } void Camera::animateToWithBounds(Vec3 eyeDest, Vec3 dirDest, Vec3 upDest, int timeStep, bool easeIn) { animateToImpl(eyeDest, dirDest, upDest, timeStep, easeIn, true, false); } void Camera::animateToWithSliding(Vec3 eyeDest, Vec3 dirDest, Vec3 upDest, int timeStep, bool easeIn) { animateToImpl(eyeDest, dirDest, upDest, timeStep, easeIn, true, true); } void Camera::animateQuadratic(Vec3 eyeDest, Vec3 topDest, Vec3 dirDest, Vec3 upDest, int timeStep) { dirDest.normalize(); upDest.normalize(); // Create an animation path over [timeStep] frames pathEye = lerpQuardaticCurve(eye, topDest, eyeDest, timeStep); // pathEye = lerpQuardaticCurve(eye, eye + (eyeDest-eye)*1.1, eyeDest, timeStep); //quadratic overshoot animation, doesn't look that great pathDir = lerpRange(dir, dirDest, timeStep); pathUp = lerpRange(up, upDest, timeStep); animManager->addAnimation(AnimationEntry(this, (FinishedCallBack) ReshapeTextAfterAnim, NULL)); } void Camera::customAnimation(deque<Vec3> &eyeDest, deque<Vec3> &dirDest, deque<Vec3> &upDest) { // Set the new custom Path pathEye = eyeDest; pathDir = dirDest; pathUp = upDest; animManager->addAnimation(AnimationEntry(this, (FinishedCallBack) ReshapeTextAfterAnim, NULL)); } void Camera::setAnimationFinishCallback(void (* animationFinishCallback)(void *), void * animationFinishData) { _animationFinishCallback = animationFinishCallback; _animationFinishData = animationFinishData; } void Camera::animationFinishCallback() { if (_animationFinishCallback) _animationFinishCallback(_animationFinishData); _animationFinishData = NULL; _animationFinishCallback = NULL; } //Jumps immediately to where the camera is currently animating too. //Note: Leaves 1 frame of animation yet to go. Since clearing this causes a weird novodex bug (see below) void Camera::skipAnimation() { animManager->finishAnimation(this); /* if (pathEye.size() > 0) { // Get the very last animation frame coordinates setEye(pathEye.back()); setUp(pathUp.back()); setDir(pathDir.back()); //Clear all but the last frame of the animation path pathEye.erase(pathEye.begin(), pathEye.end() - 1); pathUp.erase(pathUp.begin(), pathUp.end() - 1); pathDir.erase(pathDir.begin(), pathDir.end() - 1); } //This cleaner version causes a weird bug. On second drop of icons, icons fall through the floor and keep falling. // Clear the animation paths //pathEye.clear(); //pathUp.clear(); //pathDir.clear(); */ } void Camera::scrollToPoint(Vec3 loc) { // Scroll to point doesn't make much sense in infinite desktop mode // so if a user tries to zoom in or move around we ignore those requests if (GLOBAL(isInInfiniteDesktopMode)) return; // Determine how far the camera is from the point we are moving to int facingWall = cameraIsFacingWall(); Vec3 camWallOrigin = Vec3(0, 75, 0); // update the visible bounds if necessary updateWatchedActorVisibleBounds(); } void Camera::scrollToOrigin() { if (GLOBAL(isInInfiniteDesktopMode)) { if (isWatchingActors()) { Vec3 center = getEyePositionToFitBounds(watchedActors.top().bounds); orig = center; } } // Scroll to the origin if (orig.distance(getEye()) < 125.0f) animateTo(orig, getDir(), getUp()); scrollToPoint(orig); // dismiss the free-form camera message dismiss("Camera::setIsCameraFreeForm"); } void Camera::setOrigin(Vec3 newOrig) { orig = newOrig; #ifndef DXRENDER _isglDataDirty = true; #endif } Vec3 Camera::getOrigin() { return orig; } void Camera::setSlideshow(bool active) { isSlideShow = active; } bool Camera::inSlideshow() { return isSlideShow; } void Camera::helperSetThumbnailDetail(BumpObject* actor, GLTextureDetail textureDetail, GLTextureLoadPriority priority) { if (hasWatchedActorHighlighted()) { assert(isWatchedActorHighlighted(actor)); if (actor->getObjectType() == ObjectType(BumpActor, FileSystem)) { FileSystemActor *fsActor = (FileSystemActor *)actor; bool drawBorder = true; if (fsActor->isFileSystemType(PhotoFrame)) { PhotoFrameActor* pfActor = (PhotoFrameActor*)fsActor; if (!pfActor->isSourceType(LocalImageSource)) return; drawBorder = false; } if (fsActor->isThumbnailized() && !fsActor->hasAnimatedTexture()) { QString texId = fsActor->getThumbnailID(); QString texPath = fsActor->getTargetPath(); bool isTrainingImage = texPath.startsWith(native(winOS->GetTrainingDirectory()), Qt::CaseInsensitive); // NOTE: workaround for ensuring that training images are always hi-resolution if (isTrainingImage) { dismiss("Camera::LoadingHiRes"); } else { if (!texMgr->hasTextureDetail(texId, textureDetail)) { // NOTE: we do not free the image data since that will happen when the thumbnail replaces this // image anyways (it takes time and this is a blocking call!) if (texMgr->loadBlockingTexture(GLTextureObject(Load|Reload, texId, texPath, textureDetail, priority, true, drawBorder), (textureDetail != HiResImage), false)) { rndrManager->invalidateRenderer(); dismiss("Camera::LoadingHiRes"); } else { printUniqueError("Camera::LoadingHiRes", QT_TR_NOOP("Could not load the full image!")); } } } } } } } void Camera::watchActor( BumpObject * object ) { if (!watchedActors.empty()) { WatchedObjects& watched = watchedActors.top(); vector<BumpObject *>::iterator iter = std::find(watched.actors.begin(), watched.actors.end(), object); if (iter == watched.actors.end()) { watched.actors.push_back(object); } } } void Camera::unwatchActor( BumpObject * object ) { if (!watchedActors.empty()) { WatchedObjects& watched = watchedActors.top(); vector<BumpObject *>::iterator iter = std::find(watched.actors.begin(), watched.actors.end(), object); if (iter != watched.actors.end()) { watched.actors.erase(iter); } } } void Camera::pushWatchActors( const vector<BumpObject *>& actors, bool groupPileItems) { // check if we are watching the exact actors aready if (!watchedActors.empty()) { WatchedObjects& watched = watchedActors.top(); if (watched.actors.size() == actors.size()) { // check each actor if they are the same bool identicalActors = true; for (int i = 0; i < actors.size(); ++i) { if (watched.actors[i] != actors[i]) { identicalActors = false; break; } } // if the same, return if (identicalActors) return; } // fade in existing items first // watchedActors.top().fadeInAll(); } if (!actors.empty()) { WatchedObjects wo(actors); orderSpatially2D(wo.actors, groupPileItems); wo.storeCamera(); watchedActors.push(wo); } } void Camera::popWatchActors() { if (!_onPopWatchActorsHandler.empty()) _onPopWatchActorsHandler(); if (!watchedActors.empty()) { if (watchedActors.top().highlightedActor) { if (scnManager->containsObject(watchedActors.top().highlightedActor)) { dismiss("Camera::LoadingHiRes"); assert(watchedActors.top().highlightedActor->getObjectType() == ObjectType(BumpActor, FileSystem)); FileSystemActor * fsActor = (FileSystemActor *) watchedActors.top().highlightedActor; fsActor->setMinThumbnailDetail(SampledImage); helperSetThumbnailDetail(watchedActors.top().highlightedActor, SampledImage, LowPriority); } else { // erase the highlight actor from the set to have their nameables restored _prevVisibleNameables.erase(watchedActors.top().highlightedActor); } } // fade in items first // watchedActors.top().fadeInAll(); // XXX: HACKY way to get around not reseting the view angled // `on no objects with walls down WatchedObjects wo(watchedActors.top()); wo.restoreCamera(); if (watchedActors.size() > 1 || GLOBAL(DrawWalls)) { watchedActors.pop(); } else if (!watchedActors.empty()) { watchedActors.top().highlightedActor = NULL; } // finish logging slideshow time if we were in slideshow at all statsManager->finishTimer(statsManager->getStats().bt.window.slideshowTime); // dismiss the slideshow message if there is one dismiss("Key_ToggleSlideShow"); } // fade in the slideshow controls slideShowControls.disable(); } void Camera::popAllWatchActors() { while (!watchedActors.empty()) { if (watchedActors.top().highlightedActor) { if (scnManager->containsObject(watchedActors.top().highlightedActor)) { dismiss("Camera::LoadingHiRes"); assert(watchedActors.top().highlightedActor->getObjectType() == ObjectType(BumpActor, FileSystem)); FileSystemActor * fsActor = (FileSystemActor *) watchedActors.top().highlightedActor; fsActor->setMinThumbnailDetail(SampledImage); helperSetThumbnailDetail(watchedActors.top().highlightedActor, SampledImage, LowPriority); } else { // erase the highlight actor from the set to have their nameables restored _prevVisibleNameables.erase(watchedActors.top().highlightedActor); } } watchedActors.pop(); } // dismiss the slideshow message if there is one dismiss("Key_ToggleSlideShow"); } void * LoadNextHighResThumbnailAfterAnim(AnimationEntry *animEntry) { BumpObject * actor = (BumpObject *) animEntry->getCustomData(); if (scnManager->containsObject(actor)) { assert(actor->getObjectType() == ObjectType(BumpActor, FileSystem)); FileSystemActor * fsActor = (FileSystemActor *) actor; fsActor->setMinThumbnailDetail(HiResImage); cam->helperSetThumbnailDetail(actor, HiResImage, LowPriority); } return NULL; } void * LoadHighResImageAfterAnim(AnimationEntry *animEntry) { BumpObject * actor = (BumpObject *) animEntry->getCustomData(); if (scnManager->containsObject(actor)) { assert(actor->getObjectType() == ObjectType(BumpActor, FileSystem)); FileSystemActor * fsActor = (FileSystemActor *) actor; fsActor->setMinThumbnailDetail(HiResImage); cam->helperSetThumbnailDetail(actor, HiResImage, LowPriority); /* BumpObject * nextObj = cam->getNextHighlightWatchedActor(true); nextObj->finishAnimation(); nextObj->setPoseAnim(nextObj->getGlobalPose(), nextObj->getGlobalPose(), 50); animManager->addAnimation(AnimationEntry(cam, (FinishedCallBack) LoadNextHighResThumbnailAfterAnim, (void *) nextObj)); */ } return NULL; } void * SetupActorForSlideshow(AnimationEntry *animEntry) { if (!isSlideshowModeActive()) return NULL; Vec3 newEye, newUp, newDir; cam->zoomToOrientedActorBoundsAttributes(cam->getHighlightedWatchedActor(), newEye, newUp, newDir); cam->setEye(newEye); cam->setUp(newUp); cam->setDir(newDir); LoadHighResImageAfterAnim(animEntry); return NULL; } void Camera::rehighlightWatchedActor() { // ensure items are being watched if (watchedActors.empty()) return; WatchedObjects& watched = watchedActors.top(); if (!watched.highlightedActor) return; // clear existing animation pathEye.clear(); pathDir.clear(); pathUp.clear(); // get the new camera attributes Vec3 newEye, newUp, newDir; zoomToOrientedActorBoundsAttributes(watched.highlightedActor, newEye, newUp, newDir); // add animation to get the movement from the previous to new actor const int timeStep = watched.highlightedActor ? 85 : 75; animateTo(newEye, newDir, newUp, timeStep); } void Camera::highlightWatchedActor( BumpObject * actor, BumpObject * nextActor ) { static BumpObject * prevActor = NULL; static bool prevActorWasOn = true; // re-enable previously disabled photo frames if (prevActor && prevActor->isObjectType(ObjectType(BumpActor, FileSystem, PhotoFrame))) { // When the slideshow is being ended, this function will be called with NULL,NULL. We check for this here because in certain cases // prevActor can be a dangling pointer (zoom in on photoframe and hit delete key) if (prevActorWasOn) { if (!dynamic_cast<PhotoFrameActor *>(prevActor)->isUpdating()) dynamic_cast<PhotoFrameActor *>(prevActor)->enableUpdate(); } } // disable photo frames from updating while if (actor && actor->isObjectType(ObjectType(BumpActor, FileSystem, PhotoFrame))) { //Current actor is a photoframe prevActorWasOn = dynamic_cast<PhotoFrameActor *>(actor)->isUpdating(); prevActor = actor; if (dynamic_cast<PhotoFrameActor *>(actor)->isUpdating()) dynamic_cast<PhotoFrameActor *>(actor)->disableUpdate(); } // ensure items are being watched if (watchedActors.empty()) return; WatchedObjects& watched = watchedActors.top(); // ensure different actor if (actor == watched.highlightedActor) return; // ensure that the actor is currently being watched vector<BumpObject *>::const_iterator actorIter = find(watched.actors.begin(), watched.actors.end(), actor); if (actorIter == watched.actors.end()) return; // init the camera controls if not already slideShowControls.init(); // get the eye position for both the previous and new actor (top of curve) Vec3 bothActorsEye(eye); bool bothActorsPinned = false; if (watched.highlightedActor) { // animate to zoom to fit the previous and the new actor Bounds watchedBounds; watchedBounds.combine(watched.highlightedActor->getBoundingBox()); watchedBounds.combine(actor->getBoundingBox()); bothActorsEye = getEyePositionToFitBounds(watchedBounds); bothActorsPinned = watched.highlightedActor->isPinned() && actor->isPinned(); } // clear existing animation pathEye.clear(); pathDir.clear(); pathUp.clear(); // get the new camera attributes Vec3 newEye, newUp, newDir; zoomToOrientedActorBoundsAttributes(actor, newEye, newUp, newDir); // determine if we should lerp or slerp the eye (in any other context...) // we do this by checking if the angles between the new and old up vecs differ too greatly, // or if both items are pinned bool lerp = bothActorsPinned; float theta = acos(up.dot(newUp) / (up.magnitude() * newUp.magnitude())); float maxAngleDiff = PI / 4.0f; // 45 degrees if (theta >= maxAngleDiff) { lerp = true; } // add animation to get the movement from the previous to new actor const int timeStep = watched.highlightedActor ? 85 : 75; if (lerp || !watched.highlightedActor) pathEye = lerpRange(eye, newEye, timeStep); else { pathEye = lerpQuardaticFittingCurve(eye, bothActorsEye, newEye, timeStep, SoftEase); } pathDir = lerpRange(dir, newDir, timeStep, SoftEase); pathUp = lerpRange(up, newUp, timeStep, SoftEase); // update the highlighted actor // (we must do this before we fade out the other actors) watched.highlightedActor = actor; // if it's a filesystem actor if (!(actor->getObjectType() == ObjectType(BumpActor, FileSystem, PhotoFrame))) printUnique("Camera::LoadingHiRes", QT_TR_NOOP("Loading full image")); { deque<Vec3> eyePath = pathEye; deque<Vec3> dirPath = pathDir; deque<Vec3> upPath = pathUp; animManager->removeAnimation(this); pathEye = eyePath; pathDir = dirPath; pathUp = upPath; animManager->addAnimation(AnimationEntry(this, (FinishedCallBack) SetupActorForSlideshow, (void *) watched.highlightedActor)); } // fade in the highlighted actor // watched.fadeOutAllButHighlighted(timeStep); // fade out all the nameables // NOTE: we only do this for the first highlight, which is why we test if // the next actor is NULL. if (!nextActor) { storePreviousVisibleNameables(true); } if (actor->getObjectType() == ObjectType(BumpActor, FileSystem, Image) && actor->getObjectType() != ObjectType(BumpActor, FileSystem, PhotoFrame)) { FileSystemActor* photo = dynamic_cast<FileSystemActor*>(actor); if (hasOriginalPhoto(photo)) { getRestoreOriginalPhotoControl()->show(); } else { getRestoreOriginalPhotoControl()->hide(); } } else { getRestoreOriginalPhotoControl()->hide(); } } int Camera::cameraIsFacingWall() { // Check if camera is pointing to a wall // Construct ray going through the camera eye and camera direction Ray camRay(getEye(), getDir()); tuple<int, NxReal, Vec3, NxPlane> t = RayIntersectDesktop(camRay); int wallIndex = t.get<0>(); return wallIndex; } void Camera::lookAtWall(NxActorWrapper* wall, Vec3& positionOut, Vec3& directionOut) { assert(wall); positionOut = Vec3(0, 75, 0); directionOut = wall->getGlobalPosition(); directionOut.y = 20; directionOut -= positionOut; directionOut.normalize(); // Move the camera back to get the entire wall positionOut += -(directionOut * 100); adjustPointToInsideWalls(positionOut); _currentCameraView = WallView; } bool Camera::isWatchingActors() const { return !watchedActors.empty(); } bool Camera::isTrackingWatchedActors() const { return isWatchingActors() && watchedActors.top().trackActors; } void Camera::setTrackingWatchedActors(bool state) { if (isTrackingWatchedActors()) { watchedActors.top().trackActors = state; } } bool Camera::isWatchedActorHighlighted( BumpObject * object ) const { return (!watchedActors.empty() && watchedActors.top().highlightedActor == object); } bool Camera::hasWatchedActorHighlighted() const { return (!watchedActors.empty() && watchedActors.top().highlightedActor); } BumpObject * Camera::getHighlightedWatchedActor() const { if (hasWatchedActorHighlighted()) { return watchedActors.top().highlightedActor; } return NULL; } void Camera::highlightNextWatchedActor(bool forward) { if (!_onHighlightNextWatchedActorHandler.empty()) _onHighlightNextWatchedActorHandler(forward); // ensure items are being watched if (watchedActors.empty()) return; WatchedObjects& watched = watchedActors.top(); // ensure there is an actor being highlighted if (!watched.highlightedActor) return; // ensure that there are other items to highlight int num = watched.actors.size(); if (num <= 1) return; // find it in the watched list for (int i = 0; i < num; ++i) { if (watched.actors[i] == watched.highlightedActor) { int index = i; int nextIndex = i; int prevIndex = i; if (forward) { prevIndex = (i+num-1) % num; index = (i+1) % num; nextIndex = (i+2) % num; } else { prevIndex = (i+1) % num; index = (i+num-1) % num; nextIndex = (i+num-2) % num; } // pop the high-res image for the currently highlighted actor assert(watched.highlightedActor->getObjectType() == ObjectType(BumpActor, FileSystem)); FileSystemActor * fsActor = (FileSystemActor *) watched.highlightedActor; fsActor->setMinThumbnailDetail(SampledImage); helperSetThumbnailDetail(watched.highlightedActor, SampledImage, HighPriority); // load the next item (and preload the next next item) highlightWatchedActor(watched.actors[index], watched.actors[nextIndex]); return; } } } Vec3 Camera::getEyePositionToFitBounds(const Bounds& bounds) { // save camera orientation Vec3 tempEye(eye); Vec3 tempUp(up); Vec3 tempDir(dir); // calculate new eye position to fit bounds Vec3 newEye = zoomToBounds(bounds, false); // restore camera orientation setEye(tempEye); setUp(tempUp); setDir(tempDir); return newEye; } void Camera::zoomToIncludeObjects(vector<BumpObject*> objs) { Bounds bounds = getActorsBounds(objs); zoomToBounds(bounds); } Vec3 Camera::zoomToTopDownView() { setIsCameraFreeForm(false); // calculate how high the camera must be to view the whole desktop Box desktopBox = GetDesktopBox(); float aspect = desktopBox.extents.x / desktopBox.extents.z; float invAspect = 1.0f / aspect; float xFov = 60.0f / 2.0f; float yFov = xFov / aspect; int depth = desktopBox.extents.z; int height = ((invAspect - 0.022f) * depth) / tan(yFov * (PI / 180)); Vec3 newEye(0, height, 0); setOrigin(newEye); animateTo(newEye, Vec3(0, -1, 0), Vec3(0, 0, 1)); return newEye; } Vec3 Camera::zoomToAngledView() { setIsCameraFreeForm(false); // calculate how high the camera must be to view the whole desktop Box desktopBox = GetDesktopBox(); float aspect = desktopBox.extents.x / desktopBox.extents.z; float invAspect = 1.0f / aspect; float xFov = 60.0f / 2.0f; float yFov = xFov / aspect; int depth = desktopBox.extents.z; int height = ((invAspect - 0.022f) * depth) / tan(yFov * (PI / 180)); Vec3 newEye = Vec3(0, height, 0); Vec3 newDir = Vec3(0, -1, 0); Vec3 newUp = Vec3(0, 0, 1); // get the rotated centroid point relative to the bottom wall edge float angle = 18.0f; Quat ori(angle, Vec3(-1,0,0)); ori.rotate(newEye); ori.rotate(newDir); ori.rotate(newUp); // offset to be flush with the bottom wall edge Vec3 bottomWallEdgePt(0, 0, -depth); Vec3 rotatedBottomWallEdgePt(-newUp * depth); Vec3 diff = rotatedBottomWallEdgePt - bottomWallEdgePt; newEye -= diff; setOrigin(newEye); animateTo(newEye, newDir, newUp); return newEye; } Vec3 Camera::zoomToBottomRightCornerView() { setIsCameraFreeForm(false); Vec3 center, extents; Vec3 newEye, direction, up; Bounds wall; vector<NxActorWrapper*> walls = GLOBAL(Walls); // bottom wall wall = walls[1]->getBoundingBox(); wall.getCenter(center); wall.getExtents(extents); newEye = center - Vec3(extents.x * 0.8, 0 , 0); newEye.z = 0; newEye.z = center.z * 0.8; setOrigin(newEye); // right wall wall = walls[2]->getBoundingBox(); wall.getCenter(center); wall.getExtents(extents); direction = -newEye; direction.x = center.x / -2; up.cross(direction, Vec3(0, 1, 0)); up.cross(up, direction); animateTo(newEye, direction, up); return newEye; } void Camera::zoomToOrientedActorBoundsAttributes(BumpObject * actor, Vec3& eye, Vec3& up, Vec3& dir, float buffer, const Vec3 & screenSize) { // get the values up = actor->getGlobalOrientation() * Vec3(0, 1, 0); dir = actor->getGlobalOrientation() * Vec3(0, 0, 1); up.normalize(); up.y = abs(up.y); dir.normalize(); // check if the direction of the frame is aligned to the direction to the actor // if not, it is backwards, so flip the direction. we do this in a hacky fashion // by checking if the dot of the actor direction and the origin (offsetted high, // so that the items on the floor are accounted for) are "opposite". Vec3 actorWorldDir = actor->getGlobalPosition(); actorWorldDir -= Vec3(0, getEye().y, 0); if (actorWorldDir.dot(dir) < 0) dir.setNegative(); eye = actor->getGlobalPosition(); Box box = actor->getBox(); float width = float(winOS->GetWindowWidth()); float height = float(winOS->GetWindowHeight()); float aspect = width / height; float hFoV = box.extents.y; float wFoV = box.extents.x; float zoomHeight = box.extents.y; float zoomWidth = box.extents.x; Vec3 effectiveScreenSize = Vec3(screenSize.x, screenSize.y, screenSize.z); if(isSlideshowModeActive()) { effectiveScreenSize.x = width*0.95; //leave a bit of buffer effectiveScreenSize.y = height*0.95 - slideShowControls.getHeight(); } if (!effectiveScreenSize.isZero()) { #ifdef DXRENDER wFoV *= dxr->viewport.Width / effectiveScreenSize.x; hFoV *= dxr->viewport.Height / effectiveScreenSize.y; #else wFoV *= _glViewport[2] / effectiveScreenSize.x; hFoV *= _glViewport[3] / effectiveScreenSize.y; #endif } float FoV = 60.0f / 2; // 60 / 2 Deg on Y-axis float tanFoV = tan(FoV * (PI / 180)); // Fix the multiplier based on the aspect ratio, if needed (aspect ratio only if width is larger) float multiplier; if (wFoV / hFoV > aspect) { // Width is longer then the screen, use it multiplier = wFoV / aspect; }else{ // height is longer then the screen multiplier = hFoV; } // distance from the actor eye -= (dir * (multiplier * NxMath::max(1.1f, buffer) / tanFoV)); // translate the camera down by the slideshow overlay height if we're in slideshow mode if(isSlideshowModeActive()) { //The greater of zoomHeight and zoomWidth will in effect represent the height of the screen in bumptop world units //if we multiply this value by the ratio of the overlay to the screen, we get the real-world size of the overlay, //and we can offset the camera accordingly float slideShowOverlayToScreenRatio = slideShowControls.getHeight()/height; float offsetDistance = zoomHeight * slideShowOverlayToScreenRatio; eye -= (up * offsetDistance); } #ifndef DXRENDER _isglDataDirty = true; #endif } Bounds Camera::getActorsBounds( const vector<BumpObject *>& objects, bool flatten/*=False*/ ) { Bounds bounds, aabb; Vec3 center, extents; float maxY = 0.0f; for (uint i = 0; i < objects.size(); i++) { if (objects[i]->isBumpObjectType(BumpPile) || objects[i]->isBumpObjectType(BumpActor)) { if (!scnManager->containsObject(objects[i])) continue; // determine the max bounds of the if (objects[i]->isBumpObjectType(BumpPile)) { Pile * p = (Pile *) objects[i]; if (p->getNumItems() > 0) { Bounds pileBounds = p->getPileBounds(); Vec3 pileCenter, pileExtents; pileBounds.getCenter(pileCenter); pileBounds.getExtents(pileExtents); if (p->getPileState() == Grid) maxY = NxMath::max(pileCenter.y, maxY); else maxY = NxMath::max(pileExtents.y, maxY); } } else { maxY = NxMath::max(objects[i]->getDims().z, maxY); } aabb = objects[i]->getBoundingBox(); if (!objects[i]->isPinned() && flatten) { // flatten the bounds? aabb.getCenter(center); aabb.getExtents(extents); if (!((objects[i]->isBumpObjectType(BumpPile)) && (((Pile *) objects[i])->getPileState() == Grid))) { center.y = 0; } extents.y = 0; aabb.setCenterExtents(center, extents); } bounds.combine(aabb); } } if (flatten) { bounds.getCenter(center); bounds.getExtents(extents); center.y = extents.y = maxY; bounds.setCenterExtents(center, extents); } return bounds; } void Camera::updateWatchedActorVisibleBounds() { // reset the visible bounds visibleBounds.setEmpty(); // get the view corners in world space (v/w are near/far clipping pane points) // // 0-------1 <----- v[] and w[] index // | | // 3-------2 Vec3 v[4], w[4], pt[4], dir; window2world(0, 0, v[0], w[0]); window2world(winOS->GetWindowWidth(), 0, v[1], w[1]); window2world(winOS->GetWindowWidth(), winOS->GetWindowHeight(), v[2], w[2]); window2world(0, winOS->GetWindowHeight(), v[3], w[3]); // get the floor bounds of the corner points float dist; Ray r; NxPlane floor = NxPlane(Vec3(0,0,0), Vec3(0,1,0)); for (int i = 0; i < 4; i++) { // Project this ray to the floor dir = w[i]-v[i]; dir.normalize(); r = Ray(v[i], dir); NxRayPlaneIntersect(r, floor, dist, pt[i]); } // when in bounded mode, use the bottom points X as the top points X if (!GLOBAL(isInInfiniteDesktopMode)) { pt[0].x = pt[3].x; pt[1].x = pt[2].x; } for (int i = 0; i < 4; ++i) { // add the point to the bounds pt[i].y = 0; visibleBounds.include(pt[i]); } } ZoomOutControl* Camera::getZoomOutControl() { return &zoomOutControl; } RestoreOriginalPhotoControl* Camera::getRestoreOriginalPhotoControl() { return &restoreOriginalPhotoControl; } void Camera::pointCameraTo(Vec3 pt) { pointCameraTo(pt, true); } // Reorient the camera to point to a location the user clicked void Camera::pointCameraTo(Vec3 pt, bool executeWindowToWorld) { if (!GLOBAL(isInInfiniteDesktopMode))// || isCameraFreeForm() || GLOBAL(settings).enableDebugKeys) { Vec3 pointOnPlane = pt; // Determine what point in the bumptop desktop the mouse has clicked if (executeWindowToWorld) { Vec3 closePoint, farPoint, dir; window2world(pt.x, pt.y, closePoint, farPoint); dir = farPoint - closePoint; dir.normalize(); Ray theRay = Ray(closePoint, dir); // Get unbounded box and planes making up the desktop tuple <int, NxReal, Vec3, NxPlane> t = RayIntersectDesktop(theRay); pointOnPlane = t.get<2>(); } // Make sure the point is inside the bumptop desktop Box desktopBox = GetDesktopBox(0); if (desktopBox.GetExtents().y + desktopBox.GetCenter().y < pointOnPlane.y) { return; } // Determine new camera eye Vec3 newEye = getEye(); if (getEye().distanceSquared(getDefaultEye()) < 0.005) newEye.y = GLOBAL(WallHeight) * 0.8; //Determine the new direction based on the point on the plane Vec3 newDir; newDir = pointOnPlane - newEye; newDir.normalize(); //Determine new up vector Vec3 newUp; newUp.cross(newDir, Vec3(0,1,0)); newUp.cross(newUp, newDir); // Animate to new direction animateTo(newEye, newDir, newUp); storeCameraPosition(newEye, newDir, newUp); } else { } } // This method is used to load a camera preset. // It is called when bumptop is initialized or whenever the // bumptop settings are modified void Camera::loadCameraFromPreset(QString cameraPreset) { // get the new preset PredefinedCameraViews newCameraPreset = Camera::DefaultView; if (cameraPreset.startsWith("oh")) newCameraPreset = Camera::TopDownView; else if (cameraPreset.startsWith(QT_NT("brc"))) newCameraPreset = Camera::BottomRightCornerView; // don't do anything if the walls haven't been created yet? vector<NxActorWrapper*> walls = GLOBAL(Walls); assert(!walls.empty()); if (walls.empty()) return; // if we are zoomed in on any object, we should zoom back out first popAllWatchActors(); WebActor::zoomOutFocusedWebActor(); // apply the camera change setCurrentCameraView(newCameraPreset); } void Camera::onAnimTick() { // Get the next Step if (!pathEye.empty()) { setEye(pathEye.front()); pathEye.pop_front(); } if (!pathDir.empty()) { setDir(pathDir.front()); pathDir.pop_front(); } if (!pathUp.empty()) { setUp(pathUp.front()); pathUp.pop_front(); } // Force the camera to be upright, always if (up.y < 0.0) up.y = 0.0; // Calculate the Right vector right.cross(up, dir); } void Camera::onAnimFinished() { #ifndef DXRENDER // NOTE: we update the OGL matrices so that picking works and everything // after the camera view has moved _isglDataDirty = true; readOGLMatrices(); #endif // restore the visibility of the previously hidden nameables if (!hasWatchedActorHighlighted() && !(getZoomedObjects().size() == 1 && getZoomedObjects().front()->getObjectType() == ObjectType(BumpActor,Webpage))) restorePreviousVisibleNameables(false); animationFinishCallback(); } void Camera::killAnimation() { pathEye.clear(); pathDir.clear(); pathUp.clear(); // Remove ourself from the animation queue animManager->removeAnimation(this); setAnimationState(NoAnim); } void Camera::finishAnimation() { // Jump to the end of each animation if (!pathEye.empty()) setEye(pathEye.back()); if (!pathDir.empty()) setDir(pathDir.back()); if (!pathUp.empty()) setUp(pathUp.back()); pathEye.clear(); pathDir.clear(); pathUp.clear(); animationFinishCallback(); } void Camera::revertAnimation() { // Jump to the beginning of each animation if (!pathEye.empty()) setEye(pathEye.front()); if (!pathDir.empty()) setDir(pathDir.front()); if (!pathUp.empty()) setUp(pathUp.front()); killAnimation(); } bool Camera::isAnimating( uint animType /*= SizeAnim | AlphaAnim | PoseAnim*/ ) { bool animRunning = false; // Check the different types of anims if (animType & PoseAnim && (!pathEye.empty() || !pathDir.empty() || !pathUp.empty())) animRunning = true; // Check animation Paths return animRunning; } #ifndef DXRENDER void Camera::readOGLMatrices() { // We shouldn't have to call switchToPerspective here, but // it's a workaround so we have the most up-to-date view matrix switchToPerspective(); glGetDoublev (GL_PROJECTION_MATRIX, _glProjMatrix); glGetDoublev (GL_MODELVIEW_MATRIX, _glMVMatrix); _glViewport[2] = winOS->GetWindowWidth(); _glViewport[3] = winOS->GetWindowHeight(); _isglDataDirty = false; } GLdouble * Camera::glModelViewMatrix() const { return _glMVMatrix; } GLdouble * Camera::glProjectionMatrix() const { return _glProjMatrix; } GLint * Camera::glViewport() const { return _glViewport; } void Camera::markglDataDirty() { _isglDataDirty = true; } #endif void Camera::setOnHighlightNextWatchedActorHandler( boost::function<void(bool)> onHighlightNextWatchedActorHandler ) { _onHighlightNextWatchedActorHandler = onHighlightNextWatchedActorHandler; } void Camera::setOnPopWatchActorsHandler( boost::function<void()> onPopWatchActorsHandler ) { _onPopWatchActorsHandler = onPopWatchActorsHandler; } // Call with temporary to temporarily hide or restore texts according to last // call of storePreviousVisibleNameables without temporary flag void Camera::restorePreviousVisibleNameables(bool skipAnimation, bool temporary) { set<BumpObject *>::iterator iter = _prevVisibleNameables.begin(); while (iter != _prevVisibleNameables.end()) { if (scnManager->containsObject(*iter)) { if (skipAnimation) (*iter)->showText(true); else (*iter)->showTextAnimated(25); } iter++; } if (!temporary) _prevVisibleNameables.clear(); } void Camera::storePreviousVisibleNameables(bool skipAnimation, bool temporary) { if (temporary) { // hide text for items that were previously hidden before restorePreviousVisibleNameables called with temporary set<BumpObject *>::iterator iter = _prevVisibleNameables.begin(); while (iter != _prevVisibleNameables.end()) { if (scnManager->containsObject(*iter) && !(*iter)->isTextHidden()) (*iter)->hideText(skipAnimation); iter++; } } else { // restore the existing nameables first just in case restorePreviousVisibleNameables(true); assert(_prevVisibleNameables.empty()); vector<BumpObject *> objs = scnManager->getBumpObjects(); for (int i = 0; i < objs.size(); ++i) { if (!objs[i]->isTextHidden()) { _prevVisibleNameables.insert(objs[i]); objs[i]->hideText(skipAnimation); } } } } CornerInfoControl * Camera::getCornerInfoControl() { return &cornerInfoControl; } QList<BumpObject*>& Camera::getZoomedObjects() { return zoomedObjects; } bool Camera::serializeToPb(PbCamera * pbCamera) { assert(pbCamera); toPbVec3(getEye(), pbCamera->mutable_eye()); toPbVec3(getDir(), pbCamera->mutable_dir()); toPbVec3(getUp(), pbCamera->mutable_up()); return true; } bool Camera::deserializeFromPb(const PbCamera * pbCamera) { assert(pbCamera); if (pbCamera->has_eye()) { savedEye = fromPbVec3(pbCamera->eye()); } if (pbCamera->has_dir()){ savedDir = fromPbVec3(pbCamera->dir()); } if (pbCamera->has_up()) { savedUp = fromPbVec3(pbCamera->up()); } return true; }
28.441367
176
0.700634
dyzmapl
4404caf10481aafdc607b1ccbd70358f2688c0a2
15,851
cc
C++
GeneratorInterface/SherpaInterface/src/SherpackUtilities.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
GeneratorInterface/SherpaInterface/src/SherpackUtilities.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
GeneratorInterface/SherpaInterface/src/SherpackUtilities.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "GeneratorInterface/SherpaInterface/interface/SherpackUtilities.h" #include <unistd.h> #include <cstdlib> namespace spu { // functions for inflating (and deflating) //~ /* Compress from file source to file dest until EOF on source. //~ def() returns Z_OK on success, Z_MEM_ERROR if memory could not be //~ allocated for processing, Z_STREAM_ERROR if an invalid compression //~ level is supplied, Z_VERSION_ERROR if the version of zlib.h and the //~ version of the library linked do not match, or Z_ERRNO if there is //~ an error reading or writing the files. */ int def(FILE *source, FILE *dest, int level) { int ret, flush; unsigned have; z_stream strm; unsigned char in[CHUNK]; unsigned char out[CHUNK]; /* allocate deflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; ret = deflateInit(&strm, level); if (ret != Z_OK) return ret; /* compress until end of file */ do { strm.avail_in = fread(in, 1, CHUNK, source); if (ferror(source)) { (void)deflateEnd(&strm); return Z_ERRNO; } flush = feof(source) ? Z_FINISH : Z_NO_FLUSH; strm.next_in = in; /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = deflate(&strm, flush); /* no bad return value */ assert(ret != Z_STREAM_ERROR); /* state not clobbered */ have = CHUNK - strm.avail_out; if (fwrite(out, 1, have, dest) != have || ferror(dest)) { (void)deflateEnd(&strm); return Z_ERRNO; } } while (strm.avail_out == 0); assert(strm.avail_in == 0); /* all input will be used */ /* done when last data in file processed */ } while (flush != Z_FINISH); assert(ret == Z_STREAM_END); /* stream will be complete */ /* clean up and return */ (void)deflateEnd(&strm); return Z_OK; } /* Decompress from file source to file dest until stream ends or EOF. inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be allocated for processing, Z_DATA_ERROR if the deflate data is invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and the version of the library linked do not match, or Z_ERRNO if there is an error reading or writing the files. */ int inf(FILE *source, FILE *dest) { int ret; unsigned have; z_stream strm; unsigned char in[CHUNK]; unsigned char out[CHUNK]; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; //~ ret = inflateInit(&strm,15); ret = inflateInit2(&strm, (16 + MAX_WBITS)); if (ret != Z_OK) return ret; /* decompress until deflate stream ends or end of file */ do { strm.avail_in = fread(in, 1, CHUNK, source); if (ferror(source)) { (void)inflateEnd(&strm); return Z_ERRNO; } if (strm.avail_in == 0) break; strm.next_in = in; /* run inflate() on input until output buffer not full */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = inflate(&strm, Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); /* state not clobbered */ switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; [[fallthrough]]; case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strm); return ret; } have = CHUNK - strm.avail_out; if (fwrite(out, 1, have, dest) != have || ferror(dest)) { (void)inflateEnd(&strm); return Z_ERRNO; } } while (strm.avail_out == 0); /* done when inflate() says it's done */ } while (ret != Z_STREAM_END); /* clean up and return */ (void)inflateEnd(&strm); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } /* report a zlib or i/o error */ void zerr(int ret) { fputs("zpipe: ", stderr); switch (ret) { case Z_ERRNO: if (ferror(stdin)) fputs("error reading stdin\n", stderr); if (ferror(stdout)) fputs("error writing stdout\n", stderr); break; case Z_STREAM_ERROR: fputs("invalid compression level\n", stderr); break; case Z_DATA_ERROR: fputs("invalid or incomplete deflate data\n", stderr); break; case Z_MEM_ERROR: fputs("out of memory\n", stderr); break; case Z_VERSION_ERROR: fputs("zlib version mismatch!\n", stderr); } } /* compress or decompress from stdin to stdout */ int Unzip(std::string infile, std::string outfile) { ///////////////////////////////////////////// /////////////// BUG FIX FOR MPI ///////////// ///////////////////////////////////////////// const char *tmpdir = std::getenv("TMPDIR"); if (tmpdir && (strlen(tmpdir) > 50)) { setenv("TMPDIR", "/tmp", true); } ///////////////////////////////////////////// ///////////////////////////////////////////// ///////////////////////////////////////////// int ret; FILE *in = fopen(infile.c_str(), "r"); if (!in) return -1; FILE *out = fopen(outfile.c_str(), "w"); if (!out) return -2; /* avoid end-of-line conversions */ SET_BINARY_MODE(in); SET_BINARY_MODE(out); ret = inf(in, out); if (ret != Z_OK) zerr(ret); fclose(in); fclose(out); return ret; } // functions for untaring Sherpacks /* Parse an octal number, ignoring leading and trailing nonsense. */ int parseoct(const char *p, size_t n) { int i = 0; while (*p < '0' || *p > '7') { ++p; --n; } while (*p >= '0' && *p <= '7' && n > 0) { i *= 8; i += *p - '0'; ++p; --n; } return (i); } /* Returns true if this is 512 zero bytes. */ int is_end_of_archive(const char *p) { int n; for (n = 511; n >= 0; --n) if (p[n] != '\0') return (0); return (1); } /* Create a directory, including parent directories as necessary. */ void create_dir(char *pathname, int mode) { char *p; int r; /* Strip trailing '/' */ if (pathname[strlen(pathname) - 1] == '/') pathname[strlen(pathname) - 1] = '\0'; /* Try creating the directory. */ r = mkdir(pathname, mode); if (r != 0) { /* On failure, try creating parent directory. */ p = strrchr(pathname, '/'); if (p != nullptr) { *p = '\0'; create_dir(pathname, 0755); *p = '/'; r = mkdir(pathname, mode); } } if (r != 0) fprintf(stderr, "Could not create directory %s\n", pathname); } /* Create a file, including parent directory as necessary. */ FILE *create_file(char *pathname, int mode) { FILE *f; f = fopen(pathname, "w+"); if (f == nullptr) { /* Try creating parent dir and then creating file. */ char *p = strrchr(pathname, '/'); if (p != nullptr) { *p = '\0'; create_dir(pathname, 0755); *p = '/'; f = fopen(pathname, "w+"); } } return (f); } /* Verify the tar checksum. */ int verify_checksum(const char *p) { int n, u = 0; for (n = 0; n < 512; ++n) { if (n < 148 || n > 155) /* Standard tar checksum adds unsigned bytes. */ u += ((unsigned char *)p)[n]; else u += 0x20; } return (u == parseoct(p + 148, 8)); } /* Extract a tar archive. */ void Untar(FILE *a, const char *path) { bool longpathname = false; bool longlinkname = false; char newlongpathname[512]; char newlonglinkname[512]; char buff[512]; FILE *f = nullptr; size_t bytes_read; int filesize; printf("Extracting from %s\n", path); for (;;) { bytes_read = fread(buff, 1, 512, a); if (bytes_read < 512) { fprintf(stderr, "Short read on %s: expected 512, got %d\n", path, (int)bytes_read); return; } if (is_end_of_archive(buff)) { printf("End of %s\n", path); return; } if (!verify_checksum(buff)) { fprintf(stderr, "Checksum failure\n"); return; } filesize = parseoct(buff + 124, 12); // printf("%c %d\n",buff[156],filesize); switch (buff[156]) { case '1': printf(" Ignoring hardlink %s\n", buff); break; case '2': if (longpathname && longlinkname) { longlinkname = false; longpathname = false; printf(" Extracting symlink %s\n", newlongpathname); symlink(newlonglinkname, newlongpathname); } else if (longpathname) { longpathname = false; printf(" Extracting symlink %s\n", newlongpathname); symlink(buff + 157, newlongpathname); } else if (longlinkname) { longlinkname = false; printf(" Extracting symlink %s\n", buff); symlink(newlonglinkname, buff); } else { printf(" Extracting symlink %s\n", buff); symlink(buff + 157, buff); } break; case '3': printf(" Ignoring character device %s\n", buff); break; case '4': printf(" Ignoring block device %s\n", buff); break; case '5': if (!longpathname) { int endposition = -1; for (int k = 99; k >= 0; k--) { if (buff[k] == '\0') endposition = k; } if (endposition == -1) { //~ printf("OLDNAME : %s\n",buff); longpathname = true; for (int k = 0; k < 100; k++) { newlongpathname[k] = buff[k]; } newlongpathname[100] = '\0'; //~ printf("NEWNAME : %s\n",newlongpathname); } } if (longpathname) { printf(" Extracting dir %s\n", newlongpathname); create_dir(newlongpathname, parseoct(buff + 100, 8)); longpathname = false; } else { printf(" Extracting dir %s\n", buff); create_dir(buff, parseoct(buff + 100, 8)); } //~ printf(" Extracting dir %s\n", buff); //~ create_dir(buff, parseoct(buff + 100, 8)); filesize = 0; break; case '6': printf(" Ignoring FIFO %s\n", buff); break; case 'L': longpathname = true; //~ printf(" Long Filename found 0 %s\n", buff); //~ printf(" Long Filename found 100 %s\n", buff+100); //~ printf(" Long Filename found 108 %s\n", buff+108); //~ printf(" Long Filename found 116 %s\n", buff+116); //~ printf(" Long Filename found 124 %s\n", buff+124); //~ printf(" Long Filename found 136 %s\n", buff+136); //~ printf(" Long Filename found 148 %s\n", buff+148); //~ printf(" Long Filename found 156 %s\n", buff+156); //~ printf(" Long Filename found 157 %s\n", buff+157); //~ printf(" Long Filename found 158 %s\n", buff+158); //~ printf(" Long Filename found 159 %s\n", buff+159); //~ printf(" Long Filename found 257 %s\n", buff+257); //~ printf(" Long Filename found 263 %s\n", buff+263); //~ printf(" Long Filename found 265 %s\n", buff+265); //~ printf(" Long Filename found 297 %s\n", buff+297); //~ printf(" Long Filename found 329 %s\n", buff+329); //~ printf(" Long Filename found 337 %s\n", buff+337); //~ printf(" Long Filename found 345 %s\n", buff+345); //~ printf(" Long Filename found 346 %s\n", buff+346); //~ printf(" Long Filename found 347 %s\n", buff+347); break; case 'K': longlinkname = true; break; default: if (!longpathname) { int endposition = -1; for (int k = 99; k >= 0; k--) { if (buff[k] == '\0') endposition = k; } if (endposition == -1) { //~ printf("OLDNAME : %s\n",buff); longpathname = true; for (int k = 0; k < 100; k++) { newlongpathname[k] = buff[k]; } newlongpathname[100] = '\0'; //~ printf("NEWNAME : %s\n",newlongpathname); } } if (longpathname) { printf(" Extracting file %s\n", newlongpathname); f = create_file(newlongpathname, parseoct(buff + 100, 8)); longpathname = false; } else { printf(" Extracting file %s\n", buff); f = create_file(buff, parseoct(buff + 100, 8)); } break; } if (longlinkname || longpathname) { if (buff[156] == 'K') { for (int ll = 0; ll < 512; ll++) { printf("%c", buff[ll]); } printf("\n"); bytes_read = fread(buff, 1, 512, a); for (int ll = 0; ll < 512; ll++) { printf("%c", buff[ll]); } printf("\n"); for (int k = 0; k < filesize; k++) { newlonglinkname[k] = buff[k]; } newlonglinkname[filesize] = '\0'; for (int k = filesize + 1; k < 512; k++) { newlonglinkname[k] = '0'; } //~ printf("NEW LinkNAME: %s\n",newlonglinkname); } else if (buff[156] == 'L') { bytes_read = fread(buff, 1, 512, a); for (int k = 0; k < filesize; k++) { newlongpathname[k] = buff[k]; } newlongpathname[filesize] = '\0'; for (int k = filesize + 1; k < 512; k++) { newlongpathname[k] = '0'; } //~ printf("NEW FILENAME: %s\n",newlongpathname); } } //~ //~ if (longpathname) { //~ bytes_read = fread(buff, 1, 512, a); //~ for (int k=0; k<filesize; k++){ //~ newlongpathname[k]=buff[k]; //~ } //~ newlongpathname[filesize]='\0'; //~ for (int k=filesize+1; k<512; k++){ //~ newlongpathname[k]='0'; //~ } //~ printf("NEW FILENAME: %s\n",newlongpathname); //~ //~ } //~ else if (!longpathname && !longlinkname) { if (!longpathname && !longlinkname) { while (filesize > 0) { bytes_read = fread(buff, 1, 512, a); if (bytes_read < 512) { fprintf(stderr, "Short read on %s: Expected 512, got %d\n", path, (int)bytes_read); return; } if (filesize < 512) bytes_read = filesize; if (f != nullptr) { if (fwrite(buff, 1, bytes_read, f) != bytes_read) { fprintf(stderr, "Failed write\n"); fclose(f); f = nullptr; } } filesize -= bytes_read; } if (f != nullptr) { fclose(f); f = nullptr; } } } } // function for calculating the MD5 checksum of a file void md5_File(std::string filename, char *result) { char buffer[4096]; MD5_CTX md5; MD5_Init(&md5); //Open File int fd = open(filename.c_str(), O_RDONLY); int nb_read; while ((nb_read = read(fd, buffer, 4096 - 1))) { MD5_Update(&md5, buffer, nb_read); memset(buffer, 0, 4096); } unsigned char tmp[MD5_DIGEST_LENGTH]; MD5_Final(tmp, &md5); //Convert the result for (int k = 0; k < MD5_DIGEST_LENGTH; ++k) { sprintf(result + k * 2, "%02x", tmp[k]); } } } // End namespace spu
31.202756
95
0.507854
ckamtsikis
4405819af9694991e962881bc68366cfcf3778a2
116
cpp
C++
src/virtual_call_in_destructor_link.cpp
geoffviola/undefined_behavior_study
c405fa766284473c5b3c9ce415c18bcc2bba227c
[ "Apache-2.0" ]
9
2017-03-18T09:15:36.000Z
2020-05-24T18:00:37.000Z
src/virtual_call_in_destructor_link.cpp
geoffviola/undefined_behavior_study
c405fa766284473c5b3c9ce415c18bcc2bba227c
[ "Apache-2.0" ]
1
2018-06-19T19:36:19.000Z
2018-10-15T16:49:29.000Z
src/virtual_call_in_destructor_link.cpp
geoffviola/undefined_behavior_study
c405fa766284473c5b3c9ce415c18bcc2bba227c
[ "Apache-2.0" ]
3
2017-03-18T01:44:49.000Z
2022-01-04T03:22:02.000Z
#include <cstdlib> #include "virtual_call_in_destructor_lib.hpp" int main() { Child c; return EXIT_SUCCESS; }
12.888889
45
0.732759
geoffviola
440766b9513511298f9600103484d10624b58b09
2,063
cpp
C++
library/src/main/jni/_onload.cpp
badpx/IndexBitmap
d940d56a31ce7f0ee717d12132c4c51c2fd6520b
[ "Apache-2.0" ]
11
2015-08-24T13:29:10.000Z
2020-07-18T08:10:55.000Z
library/src/main/jni/_onload.cpp
badpx/IndexBitmap
d940d56a31ce7f0ee717d12132c4c51c2fd6520b
[ "Apache-2.0" ]
3
2016-03-28T10:23:15.000Z
2018-11-02T02:13:00.000Z
library/src/main/jni/_onload.cpp
badpx/IndexBitmap
d940d56a31ce7f0ee717d12132c4c51c2fd6520b
[ "Apache-2.0" ]
4
2016-01-09T10:42:03.000Z
2019-05-02T03:04:37.000Z
#include <android/log.h> #include "baseutils.h" #include "_onload.h" #include "skbitmap_helper.h" #define LOCAL_DEBUG 0 static JNINativeMethod methods[] = { { "nativeInit", "(Landroid/graphics/Bitmap;[I)Z", (void*)Init }, { "nativeGetBytesPerPixel", "(Landroid/graphics/Bitmap;)I", (void*)GetBytesPerPixel }, { "nativeGetPalette", "(Landroid/graphics/Bitmap;[I)I", (void*)GetPalette }, { "nativeChangePalette", "(Landroid/graphics/Bitmap;[I)I", (void*)ChangePalette }, { "nativeIndex8FakeToAlpha8", "(Landroid/graphics/Bitmap;Z)I", (void*)Index8FakeToAlpha8 }, { "nativeGetConfig", "(Landroid/graphics/Bitmap;)I", (void*)GetConfig }, { "nativeSetConfig", "(Landroid/graphics/Bitmap;I)I", (void*)SetConfig }, { "nativeGetIndex8Config", "()I", (void*)GetIndex8Config }, }; jint registerNativeMethods(JNIEnv* env, const char *class_name, JNINativeMethod *methods, int num_methods) { int result = 0; jclass clazz = env->FindClass(class_name); if (LIKELY(clazz)) { result = env->RegisterNatives(clazz, methods, num_methods); if (UNLIKELY(result < 0)) { LOGE("registerNativeMethods failed(class=%s)", class_name); } } else { LOGE("registerNativeMethods: class'%s' not found", class_name); } return result; } static int register_native_methods(JNIEnv *env) { LOGV("register native method:"); if (registerNativeMethods(env, PACKAGE_NAME, methods, NUM_ARRAY_ELEMENTS(methods)) < 0) { return JNI_ERR; } return JNI_OK; } jint JNI_OnLoad(JavaVM *vm, void *) { #if LOCAL_DEBUG LOGI("JNI_OnLoad"); #endif JNIEnv *env; if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) { return JNI_ERR; } if (!setupLibrary(env)) { #if LOCAL_DEBUG LOGF("setup library failed!"); #endif return JNI_ERR; } // register native methods if (register_native_methods(env) != JNI_OK) { return JNI_ERR; } setVM(vm); #if LOCAL_DEBUG LOGI("JNI_OnLoad:finshed:result=%d", result); #endif return JNI_VERSION_1_6; }
28.652778
108
0.672807
badpx
44076f00c9acc115ab70c1121a76857ad79248c9
438
hpp
C++
i23dSFM/matching/matcher_type.hpp
zyxrrr/GraphSfM
1af22ec17950ffc8a5c737a6a46f4465c40aa470
[ "BSD-3-Clause" ]
null
null
null
i23dSFM/matching/matcher_type.hpp
zyxrrr/GraphSfM
1af22ec17950ffc8a5c737a6a46f4465c40aa470
[ "BSD-3-Clause" ]
null
null
null
i23dSFM/matching/matcher_type.hpp
zyxrrr/GraphSfM
1af22ec17950ffc8a5c737a6a46f4465c40aa470
[ "BSD-3-Clause" ]
1
2019-02-18T09:49:32.000Z
2019-02-18T09:49:32.000Z
// Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once namespace i23dSFM{ namespace matching{ enum EMatcherType { BRUTE_FORCE_L2, ANN_L2, CASCADE_HASHING_L2, BRUTE_FORCE_HAMMING }; } // namespace matching } // namespace i23dSFM
19.909091
70
0.730594
zyxrrr
44091448f0282afc5ca5f79268da2865dfb7cf86
2,683
cpp
C++
tests/IDL_Test/Double_Inherited_Component/ComponentC_exec.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
10
2016-07-20T00:55:50.000Z
2020-10-04T19:07:10.000Z
tests/IDL_Test/Double_Inherited_Component/ComponentC_exec.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
13
2016-09-27T14:08:27.000Z
2020-11-11T10:45:56.000Z
tests/IDL_Test/Double_Inherited_Component/ComponentC_exec.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
12
2016-04-20T09:57:02.000Z
2021-12-24T17:23:45.000Z
// -*- C++ -*- #include "ComponentC_exec.h" #include "ace/Log_Msg.h" namespace CIAO_connector_test_C_Impl { //============================================================ // Pulse generator //============================================================ ComponentC_exec_i::ComponentC_exec_i (void) : topic_name_c_ (""), topic_name_b_ (""), topic_name_a_ (""), topic_name_c_has_been_set_ (false), topic_name_b_has_been_set_ (false), topic_name_a_has_been_set_ (false) { } ComponentC_exec_i::~ComponentC_exec_i (void) { } // Port operations. void ComponentC_exec_i::topic_name_c (const char * topic_name) { this->topic_name_c_ = topic_name; this->topic_name_c_has_been_set_ = true; } char * ComponentC_exec_i::topic_name_c (void) { return CORBA::string_dup (this->topic_name_c_.in ()); } void ComponentC_exec_i::topic_name_b (const char * topic_name) { this->topic_name_b_ = topic_name; this->topic_name_b_has_been_set_ = true; } char * ComponentC_exec_i::topic_name_b (void) { return CORBA::string_dup (this->topic_name_b_.in ()); } void ComponentC_exec_i::topic_name_a (const char * topic_name) { this->topic_name_a_ = topic_name; this->topic_name_a_has_been_set_ = true; } char * ComponentC_exec_i::topic_name_a (void) { return CORBA::string_dup (this->topic_name_a_.in ()); } // Operations from Components::SessionComponent. void ComponentC_exec_i::set_session_context ( ::Components::SessionContext_ptr ctx) { this->context_ = ::connector_test::CCM_C_Context::_narrow (ctx); if ( ::CORBA::is_nil (this->context_.in ())) { throw ::CORBA::INTERNAL (); } } void ComponentC_exec_i::configuration_complete (void) { } void ComponentC_exec_i::ccm_activate (void) { } void ComponentC_exec_i::ccm_passivate (void) { } void ComponentC_exec_i::ccm_remove (void) { if (!this->topic_name_c_has_been_set_) ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR : Topic name C has not been set\n"))); if (!this->topic_name_b_has_been_set_) ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR : Topic name B has not been set\n"))); if (!this->topic_name_a_has_been_set_) ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR : Topic name A has not been set\n"))); } extern "C" INHERITED_COMPONENTS_EXEC_Export ::Components::EnterpriseComponent_ptr create_ComponentC_Impl (void) { ::Components::EnterpriseComponent_ptr retval = ::Components::EnterpriseComponent::_nil (); ACE_NEW_NORETURN ( retval, ComponentC_exec_i ); return retval; } }
23.330435
83
0.642564
qinwang13
44092bd71c2f0ce667e15f64d5aa0e72fa9551b3
1,654
cc
C++
testPrograms/tPartialIO.cc
yahoo/Pluton
82bbab17c0013d87063b398ec777d5977f353d0a
[ "MIT" ]
8
2015-05-22T21:27:17.000Z
2017-03-19T06:07:41.000Z
testPrograms/tPartialIO.cc
YahooArchive/Pluton
82bbab17c0013d87063b398ec777d5977f353d0a
[ "MIT" ]
null
null
null
testPrograms/tPartialIO.cc
YahooArchive/Pluton
82bbab17c0013d87063b398ec777d5977f353d0a
[ "MIT" ]
6
2015-10-16T08:40:00.000Z
2016-11-14T06:48:09.000Z
#include <iostream> #include <sys/time.h> #include <assert.h> #include <stdlib.h> #include <pluton/client.h> using namespace std; // Force a service to be left in a partially read request state, then // send a new request to ensure that it resets properly. const char* SK = "system.echo.0.raw"; int main(int argc, char** argv) { assert(argc == 2); const char* goodPath = argv[1]; int res; pluton::client C; if (!C.initialize(goodPath)) { cout << "Failed: " << C.getFault().getMessage("Failed: C.initialize()") << endl; exit(1); } C.setDebug(true); C.setTimeoutMilliSeconds(1); pluton::clientRequest R; static const int bufSize = 1000 * 1000 * 60; // 60MB ought to timeout after 1MS char* buf = new char[bufSize]; R.setRequestData(buf, bufSize); if (!C.addRequest(SK, R)) { cout << "Failed Addr 1: " << C.getFault().getMessage("C.addRequest() 1") << endl; exit(2); } res = C.executeAndWaitAll(); if (res != 0) { cout << "Failed: Expected T/O from executeAndWaitAll: " << res << endl; exit(3); } // Now do a second request to make sure the service isn't broken C.setTimeoutMilliSeconds(4000); // Make the t/o really small R.setRequestData(buf, 0); if (!C.addRequest(SK, R)) { cout << "Failed: AddR 2: " << C.getFault().getMessage("C.addRequest() 2") << endl; exit(4); } res = C.executeAndWaitAll(); if (res <= 0) { cout << "Failed: E&W2 " << res << " " << C.getFault().getMessage("executeAndWaitAll") << endl; exit(5); } if (R.hasFault()) { cout << "Failed: request Faulted: " << R.getFaultText() << endl; exit(6); } return(0); }
22.657534
98
0.613664
yahoo
440947b52022a63dc706d779cb986d0c140b6777
1,756
hpp
C++
lib/boost_1.78.0/boost/spirit/home/x3/support/traits/variant_has_substitute.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
29
2021-11-19T11:28:22.000Z
2022-03-29T00:26:51.000Z
lib/boost_1.78.0/boost/spirit/home/x3/support/traits/variant_has_substitute.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
4
2020-12-07T22:56:32.000Z
2021-07-17T22:13:37.000Z
lib/boost_1.78.0/boost/spirit/home/x3/support/traits/variant_has_substitute.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
17
2018-07-30T12:45:42.000Z
2022-01-10T11:18:30.000Z
/*============================================================================= Copyright (c) 2001-2014 Joel de Guzman http://spirit.sourceforge.net/ 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) =============================================================================*/ #if !defined(BOOST_SPIRIT_X3_VARIANT_HAS_SUBSTITUTE_APR_18_2014_925AM) #define BOOST_SPIRIT_X3_VARIANT_HAS_SUBSTITUTE_APR_18_2014_925AM #include <boost/spirit/home/x3/support/traits/is_substitute.hpp> #include <boost/mpl/find.hpp> namespace boost { namespace spirit { namespace x3 { namespace traits { template <typename Variant, typename T> struct variant_has_substitute_impl { // Find a type from the Variant that can be a substitute for T. // return true_ if one is found, else false_ typedef Variant variant_type; typedef typename variant_type::types types; typedef typename mpl::end<types>::type end; typedef typename mpl::find<types, T>::type iter_1; typedef typename mpl::eval_if< is_same<iter_1, end>, mpl::find_if<types, traits::is_substitute<T, mpl::_1>>, mpl::identity<iter_1> >::type iter; typedef mpl::not_<is_same<iter, end>> type; }; template <typename Variant, typename T> struct variant_has_substitute : variant_has_substitute_impl<Variant, T>::type {}; template <typename T> struct variant_has_substitute<unused_type, T> : mpl::true_ {}; template <typename T> struct variant_has_substitute<unused_type const, T> : mpl::true_ {}; }}}} #endif
33.769231
80
0.617882
LaudateCorpus1
440c76a7e19e24f569b9e5d005423be112be567a
12,648
cpp
C++
iree/compiler/Transforms/Sequencer/LowerSequencerDialect.cpp
so-man/iree
36be189aa74d6f5bc7eb665e5a7baf3effaca12d
[ "Apache-2.0" ]
null
null
null
iree/compiler/Transforms/Sequencer/LowerSequencerDialect.cpp
so-man/iree
36be189aa74d6f5bc7eb665e5a7baf3effaca12d
[ "Apache-2.0" ]
null
null
null
iree/compiler/Transforms/Sequencer/LowerSequencerDialect.cpp
so-man/iree
36be189aa74d6f5bc7eb665e5a7baf3effaca12d
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 "iree/compiler/IR/Dialect.h" #include "iree/compiler/IR/Ops.h" #include "iree/compiler/IR/Sequencer/HLDialect.h" #include "iree/compiler/IR/Sequencer/HLOps.h" #include "iree/compiler/IR/Sequencer/LLDialect.h" #include "iree/compiler/IR/Sequencer/LLOps.h" #include "iree/compiler/IR/StructureOps.h" #include "iree/compiler/Utils/TypeConversionUtils.h" #include "third_party/llvm/llvm/include/llvm/ADT/ArrayRef.h" #include "third_party/llvm/llvm/include/llvm/ADT/DenseMap.h" #include "third_party/llvm/llvm/include/llvm/ADT/SmallVector.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Module.h" #include "mlir/IR/OperationSupport.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Transforms/DialectConversion.h" #include "mlir/Transforms/Utils.h" namespace mlir { namespace iree_compiler { namespace { template <typename SrcOp> class SequencerLoweringPattern : public OpConversionPattern<SrcOp> { public: SequencerLoweringPattern(MLIRContext *context, TypeConverter &typeConverter) : OpConversionPattern<SrcOp>(context), typeConverter_(typeConverter) {} protected: TypeConverter &typeConverter_; }; // Returns an integer scalar memref containing the offset specified by |indices| // within |type|. Value *computeOffset(Location loc, Value *reference, Value *indices, OpBuilder &builder) { auto referenceType = reference->getType().cast<ShapedType>(); auto *shapeMemRef = builder .create<IREESeq::LL::AllocHeapOp>( loc, MemRefType::get({referenceType.getRank()}, builder.getIntegerType(32)), ArrayRef<Value *>{}) .getResult(); builder.create<IREESeq::LL::ShapeOp>(loc, reference, shapeMemRef); auto *resultMemRef = builder .create<IREESeq::LL::AllocHeapOp>( loc, MemRefType::get({}, builder.getIntegerType(32)), ArrayRef<Value *>{}) .getResult(); auto elementSizeAttr = builder.getIntegerAttr( builder.getIntegerType(8), referenceType.getElementTypeBitWidth() / 8); builder.create<IREESeq::LL::ComputeOffsetOp>( loc, shapeMemRef, elementSizeAttr, indices, resultMemRef); return resultMemRef; } // Returns a tuple of (offset, length) integer scalar memrefs with the range // specified by |indices| and |lengths| within |type|. std::pair<Value *, Value *> computeRange(Location loc, Value *reference, Value *indices, Value *lengths, OpBuilder &builder) { auto referenceType = reference->getType().cast<ShapedType>(); auto *shapeMemRef = builder .create<IREESeq::LL::AllocHeapOp>( loc, MemRefType::get({referenceType.getRank()}, builder.getIntegerType(32)), ArrayRef<Value *>{}) .getResult(); builder.create<IREESeq::LL::ShapeOp>(loc, reference, shapeMemRef); auto *offsetMemRef = builder .create<IREESeq::LL::AllocHeapOp>( loc, MemRefType::get({}, builder.getIntegerType(32)), ArrayRef<Value *>{}) .getResult(); auto *lengthMemRef = builder .create<IREESeq::LL::AllocHeapOp>( loc, MemRefType::get({}, builder.getIntegerType(32)), ArrayRef<Value *>{}) .getResult(); auto elementSizeAttr = builder.getIntegerAttr( builder.getIntegerType(8), referenceType.getElementTypeBitWidth() / 8); builder.create<IREESeq::LL::ComputeRangeOp>(loc, shapeMemRef, elementSizeAttr, indices, lengths, offsetMemRef, lengthMemRef); return {offsetMemRef, lengthMemRef}; } struct LowerSliceOpPattern : public SequencerLoweringPattern<IREESeq::HL::SliceOp> { using SequencerLoweringPattern::SequencerLoweringPattern; PatternMatchResult matchAndRewrite( IREESeq::HL::SliceOp op, ArrayRef<Value *> operands, ConversionPatternRewriter &rewriter) const override { OperandAdaptor<IREESeq::HL::SliceOp> operandAdaptor(operands); auto range = computeRange(op.getLoc(), operandAdaptor.src(), operandAdaptor.indices(), operandAdaptor.lengths(), rewriter); rewriter.replaceOpWithNewOp<IREESeq::LL::DynamicSliceOp>( op, typeConverter_.convertType(op.getType()), ArrayRef<Value *>{operandAdaptor.src(), range.first, range.second}, op.getAttrs()); return matchSuccess(); } }; struct LowerShapeOpPattern : public SequencerLoweringPattern<IREESeq::HL::ShapeOp> { using SequencerLoweringPattern::SequencerLoweringPattern; PatternMatchResult matchAndRewrite( IREESeq::HL::ShapeOp op, ArrayRef<Value *> operands, ConversionPatternRewriter &rewriter) const override { auto *shapeMemRef = rewriter .create<IREESeq::LL::AllocHeapOp>( op.getLoc(), MemRefType::get({op.getType().cast<ShapedType>().getRank()}, rewriter.getIntegerType(64)), ArrayRef<Value *>{}) .getResult(); op.replaceAllUsesWith(shapeMemRef); rewriter.replaceOpWithNewOp<IREESeq::LL::ShapeOp>(op, operands[0], shapeMemRef); return matchSuccess(); } }; struct LowerCopyOpPattern : public SequencerLoweringPattern<IREESeq::HL::CopyOp> { using SequencerLoweringPattern::SequencerLoweringPattern; PatternMatchResult matchAndRewrite( IREESeq::HL::CopyOp op, ArrayRef<Value *> operands, ConversionPatternRewriter &rewriter) const override { OperandAdaptor<IREESeq::HL::CopyOp> operandAdaptor(operands); auto *srcOffsetMemRef = computeOffset(op.getLoc(), operandAdaptor.src(), operandAdaptor.srcIndices(), rewriter); auto dstRange = computeRange(op.getLoc(), operandAdaptor.dst(), operandAdaptor.dstIndices(), operandAdaptor.lengths(), rewriter); rewriter.replaceOpWithNewOp<IREESeq::LL::DynamicCopyOp>( op, operandAdaptor.src(), srcOffsetMemRef, operandAdaptor.dst(), dstRange.first, dstRange.second); return matchSuccess(); } }; struct LowerFillOpPattern : public SequencerLoweringPattern<IREESeq::HL::FillOp> { using SequencerLoweringPattern::SequencerLoweringPattern; PatternMatchResult matchAndRewrite( IREESeq::HL::FillOp op, ArrayRef<Value *> operands, ConversionPatternRewriter &rewriter) const override { OperandAdaptor<IREESeq::HL::FillOp> operandAdaptor(operands); auto dstRange = computeRange(op.getLoc(), operandAdaptor.dst(), operandAdaptor.dstIndices(), operandAdaptor.lengths(), rewriter); rewriter.replaceOpWithNewOp<IREESeq::LL::DynamicFillOp>( op, operandAdaptor.value(), operandAdaptor.dst(), dstRange.first, dstRange.second); return matchSuccess(); } }; struct LowerBranchOpPattern : public SequencerLoweringPattern<IREESeq::HL::BranchOp> { using SequencerLoweringPattern< IREESeq::HL::BranchOp>::SequencerLoweringPattern; PatternMatchResult matchAndRewrite( IREESeq::HL::BranchOp op, ArrayRef<Value *> properOperands, ArrayRef<Block *> destinations, ArrayRef<ArrayRef<Value *>> operands, ConversionPatternRewriter &rewriter) const override { rewriter.replaceOpWithNewOp<IREESeq::LL::BranchOp>(op, destinations[0], operands[0]); return matchSuccess(); } }; struct LowerCondCondBranchOpPattern : public SequencerLoweringPattern<IREESeq::HL::CondBranchOp> { using SequencerLoweringPattern< IREESeq::HL::CondBranchOp>::SequencerLoweringPattern; PatternMatchResult matchAndRewrite( IREESeq::HL::CondBranchOp op, ArrayRef<Value *> properOperands, ArrayRef<Block *> destinations, ArrayRef<ArrayRef<Value *>> operands, ConversionPatternRewriter &rewriter) const override { rewriter.replaceOpWithNewOp<IREESeq::LL::CondBranchOp>( op, properOperands[0], destinations[IREESeq::HL::CondBranchOp::trueIndex], operands[IREESeq::HL::CondBranchOp::trueIndex], destinations[IREESeq::HL::CondBranchOp::falseIndex], operands[IREESeq::HL::CondBranchOp::falseIndex]); return matchSuccess(); } }; // Rewrites an op into one with all the same operands, results, and attributes. // Operands and results in the ops must have the same order and attributes must // have the same name. They must also be constructed properly by the default // builders. template <typename SRC, typename DST> struct LowerIdenticalOpPattern : public SequencerLoweringPattern<SRC> { using SequencerLoweringPattern<SRC>::SequencerLoweringPattern; PatternMatchResult matchAndRewrite( SRC op, ArrayRef<Value *> operands, ConversionPatternRewriter &rewriter) const override { SmallVector<Type, 8> originalResultTypes{ op.getOperation()->getResultTypes()}; SmallVector<Type, 8> resultTypes; if (failed(this->typeConverter_.convertTypes(originalResultTypes, resultTypes))) { op.emitOpError() << "Failed to convert result types"; return this->matchFailure(); } rewriter.replaceOpWithNewOp<DST>(op, resultTypes, operands, op.getAttrs()); return this->matchSuccess(); } }; } // namespace class LowerSequencerDialectPass : public ModulePass<LowerSequencerDialectPass> { public: void runOnModule() override { auto *ctx = &getContext(); LLTypeConverter typeConverter(ctx); OwningRewritePatternList patterns; patterns.insert< LowerIdenticalOpPattern<IREE::ConstantOp, IREESeq::LL::ConstantOp>, LowerIdenticalOpPattern<IREESeq::HL::DispatchOp, IREESeq::LL::DynamicDispatchOp>, LowerShapeOpPattern, LowerCopyOpPattern, LowerSliceOpPattern, LowerBranchOpPattern, LowerCondCondBranchOpPattern>(ctx, typeConverter); #define IDENTICAL_OP_LOWERING(op_name) \ LowerIdenticalOpPattern<IREESeq::HL::op_name, IREESeq::LL::op_name> patterns.insert< IDENTICAL_OP_LOWERING(AllocHeapOp), IDENTICAL_OP_LOWERING(CloneOp), IDENTICAL_OP_LOWERING(ReshapeOp), IDENTICAL_OP_LOWERING(CallOp), IDENTICAL_OP_LOWERING(ReturnOp)>(ctx, typeConverter); #undef IDENTICAL_OP_LOWERING mlir::populateFuncOpTypeConversionPattern(patterns, ctx, typeConverter); ConversionTarget target(*ctx); target.addLegalDialect<IREELLSequencerDialect>(); target.addDynamicallyLegalOp<FuncOp>([&](FuncOp op) { return typeConverter.isSignatureLegal(op.getType()); }); target.addLegalOp<ModuleOp, ModuleTerminatorOp, IREE::MultiArchExecutableOp>(); target.markOpRecursivelyLegal<IREE::MultiArchExecutableOp>(); if (failed(applyFullConversion(getModule(), target, patterns, &typeConverter))) { return signalPassFailure(); } } }; std::unique_ptr<OpPassBase<ModuleOp>> createLowerSequencerDialectPass() { return std::make_unique<LowerSequencerDialectPass>(); } static PassRegistration<LowerSequencerDialectPass> pass( "iree-lower-sequencer-dialect", "Lowers the IREE HL sequencer dialect to the LL sequencer dialect."); } // namespace iree_compiler } // namespace mlir
41.605263
80
0.67228
so-man
440d7c861defadb803bd8ec0c6833afed1f8e277
1,165
cpp
C++
libraries/fc/src/crypto/openssl.cpp
SophiaTX/SophiaTx-Blockchain
c964691c020962ad1aba8263c0d8a78a9fa27e45
[ "MIT" ]
8
2018-07-25T20:42:43.000Z
2019-03-11T03:14:09.000Z
libraries/fc/src/crypto/openssl.cpp
SophiaTX/SophiaTx-Blockchain
c964691c020962ad1aba8263c0d8a78a9fa27e45
[ "MIT" ]
13
2018-07-25T17:41:28.000Z
2019-01-25T13:38:11.000Z
libraries/fc/src/crypto/openssl.cpp
SophiaTX/SophiaTx-Blockchain
c964691c020962ad1aba8263c0d8a78a9fa27e45
[ "MIT" ]
11
2018-07-25T14:34:13.000Z
2019-05-03T13:29:37.000Z
#include <fc/crypto/openssl.hpp> #include <fc/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <cstdlib> #include <string> #include <stdlib.h> namespace fc { struct openssl_scope { static ENGINE* eng; openssl_scope() { ENGINE_load_rdrand(); ENGINE* eng = ENGINE_by_id("rdrand"); if(NULL == eng) { clean_up_engine(); return; } if(!ENGINE_init(eng)) { clean_up_engine(); return; } if(!ENGINE_set_default(eng, ENGINE_METHOD_RAND)) { clean_up_engine(); } } ~openssl_scope() { FIPS_mode_set(0); CONF_modules_unload(1); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); clean_up_engine(); } void clean_up_engine() { if(eng != NULL) { ENGINE_finish(eng); ENGINE_free(eng); } ENGINE_cleanup(); } }; ENGINE* openssl_scope::eng; int init_openssl() { static openssl_scope ossl; return 0; } }
17.923077
60
0.498712
SophiaTX
440e8c81f92ce8229a8463756046dc9995685f1b
5,679
cpp
C++
build_linux/moc_addressbookpage.cpp
bitcrystal2/bitcrystal_v20_last_linux_branch
a5d759e9b5134502a28483fea3567894eec08e7f
[ "MIT" ]
null
null
null
build_linux/moc_addressbookpage.cpp
bitcrystal2/bitcrystal_v20_last_linux_branch
a5d759e9b5134502a28483fea3567894eec08e7f
[ "MIT" ]
null
null
null
build_linux/moc_addressbookpage.cpp
bitcrystal2/bitcrystal_v20_last_linux_branch
a5d759e9b5134502a28483fea3567894eec08e7f
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'addressbookpage.h' ** ** Created: Thu Dec 25 23:31:32 2014 ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../src/qt/addressbookpage.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'addressbookpage.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_AddressBookPage[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 17, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: signature, parameters, type, tag, flags 22, 17, 16, 16, 0x05, 43, 17, 16, 16, 0x05, 66, 17, 16, 16, 0x05, // slots: signature, parameters, type, tag, flags 92, 85, 16, 16, 0x0a, 102, 16, 16, 16, 0x08, 129, 16, 16, 16, 0x08, 153, 16, 16, 16, 0x08, 178, 16, 16, 16, 0x08, 203, 16, 16, 16, 0x08, 230, 16, 16, 16, 0x08, 250, 16, 16, 16, 0x08, 274, 16, 16, 16, 0x08, 294, 16, 16, 16, 0x08, 309, 16, 16, 16, 0x08, 335, 16, 16, 16, 0x08, 360, 354, 16, 16, 0x08, 397, 383, 16, 16, 0x08, 0 // eod }; static const char qt_meta_stringdata_AddressBookPage[] = { "AddressBookPage\0\0addr\0signMessage(QString)\0" "verifyMessage(QString)\0sendCoins(QString)\0" "retval\0done(int)\0on_deleteAddress_clicked()\0" "on_newAddress_clicked()\0" "on_copyAddress_clicked()\0" "on_signMessage_clicked()\0" "on_verifyMessage_clicked()\0" "onSendCoinsAction()\0on_showQRCode_clicked()\0" "onCopyLabelAction()\0onEditAction()\0" "on_exportButton_clicked()\0selectionChanged()\0" "point\0contextualMenu(QPoint)\0parent,begin,\0" "selectNewAddress(QModelIndex,int,int)\0" }; void AddressBookPage::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); AddressBookPage *_t = static_cast<AddressBookPage *>(_o); switch (_id) { case 0: _t->signMessage((*reinterpret_cast< QString(*)>(_a[1]))); break; case 1: _t->verifyMessage((*reinterpret_cast< QString(*)>(_a[1]))); break; case 2: _t->sendCoins((*reinterpret_cast< QString(*)>(_a[1]))); break; case 3: _t->done((*reinterpret_cast< int(*)>(_a[1]))); break; case 4: _t->on_deleteAddress_clicked(); break; case 5: _t->on_newAddress_clicked(); break; case 6: _t->on_copyAddress_clicked(); break; case 7: _t->on_signMessage_clicked(); break; case 8: _t->on_verifyMessage_clicked(); break; case 9: _t->onSendCoinsAction(); break; case 10: _t->on_showQRCode_clicked(); break; case 11: _t->onCopyLabelAction(); break; case 12: _t->onEditAction(); break; case 13: _t->on_exportButton_clicked(); break; case 14: _t->selectionChanged(); break; case 15: _t->contextualMenu((*reinterpret_cast< const QPoint(*)>(_a[1]))); break; case 16: _t->selectNewAddress((*reinterpret_cast< const QModelIndex(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; default: ; } } } const QMetaObjectExtraData AddressBookPage::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject AddressBookPage::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_AddressBookPage, qt_meta_data_AddressBookPage, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &AddressBookPage::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *AddressBookPage::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *AddressBookPage::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_AddressBookPage)) return static_cast<void*>(const_cast< AddressBookPage*>(this)); return QDialog::qt_metacast(_clname); } int AddressBookPage::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 17) qt_static_metacall(this, _c, _id, _a); _id -= 17; } return _id; } // SIGNAL 0 void AddressBookPage::signMessage(QString _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void AddressBookPage::verifyMessage(QString _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void AddressBookPage::sendCoins(QString _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } QT_END_MOC_NAMESPACE
35.49375
168
0.619827
bitcrystal2
440eadb4249244c03db0b3fe9843fed07ecc809f
5,964
cpp
C++
luogu/4463/me.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
luogu/4463/me.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
luogu/4463/me.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=530000; const int MOD=998244353; inline int read(){ int x=0,f=0; char ch=getchar(); while(ch<'0'||ch>'9') f|=(ch=='-'),ch=getchar(); while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); return f==0 ? x : -x; } inline void write(int x){ if(x<0) {x=~(x-1); putchar('-');} if(x>9) write(x/10); putchar(x%10+'0'); } typedef vector<int> Poly; void write_Poly(Poly A){ for(register int i=0;i<(int)A.size();++i) write(A[i]),printf(" "); puts(""); } int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;} int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;} #define mul(a,b) (ll)(a)*(b)%MOD void Add(int &x,int y){x+=y; if(x>=MOD) x-=MOD;} void Sub(int &x,int y){x-=y; if(x<0) x+=MOD;} void Mul(int &x,int y){x=1ll*x*y%MOD;} int qpow(int x,int y){ int ret=1; while(y){ if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1; } return ret; } int Inv(int x){return qpow(x,MOD-2);} int inv[N]; namespace FFT{ int rev[N<<1],G[N<<1],IG[N<<1]; int init(int n){ int len=1; while(len<n) len<<=1; rev[0]=0; rev[len-1]=len-1; for(register int i=1;i<len-1;++i) rev[i]=(rev[i>>1]>>1)+(i&1 ? len>>1 : 0); for(register int i=1;i<=len;i<<=1){ G[i]=qpow(3,(MOD-1)/i); IG[i]=qpow(G[i],MOD-2); } return len; } void ntt(int *a,int len,int flag){ for(register int i=0;i<len;++i) if(i<rev[i]) swap(a[i],a[rev[i]]); for(register int h=1;h<len;h<<=1){ int wn=(flag==1 ? G[h<<1] : IG[h<<1]); for(register int i=0;i<len;i+=(h<<1)){ int W=1,tmp1,tmp2; for(register int j=i;j<i+h;++j){ tmp1=a[j], tmp2=mul(a[j+h],W); a[j]=add(tmp1,tmp2); a[j+h]=sub(tmp1,tmp2); W=mul(W,wn); } } } if(flag==-1){ int invlen=qpow(len,MOD-2); for(register int i=0;i<len;++i) a[i]=mul(a[i],invlen); } } void multi(int *a,int *b,int len) { ntt(a,len,1); ntt(b,len,1); for(register int i=0;i<len;++i) a[i]=mul(a[i],b[i]); ntt(a,len,-1); } } Poly operator + (Poly A,Poly B){ int len=max((int)A.size(),(int)B.size()); A.resize(len); B.resize(len); for(register int i=0;i<len;++i) Add(A[i],B[i]); return A; } Poly operator - (Poly A,Poly B){ int len=max((int)A.size(),(int)B.size()); A.resize(len); B.resize(len); for(register int i=0;i<len;++i) Sub(A[i],B[i]); return A; } Poly operator * (Poly A,Poly B){ static int a[N<<1],b[N<<1]; int M=(int)A.size()+(int)B.size()-1; int len=FFT::init(M); A.resize(len); B.resize(len); for(register int i=0;i<len;++i) a[i]=A[i],b[i]=B[i]; FFT::multi(a,b,len); A.resize(M); for(register int i=0;i<M;++i) A[i]=a[i]; return A; } void reverse(Poly &A){ for(register int i=0;i<(int)A.size()/2;++i){ swap(A[i],A[(int)A.size()-1-i]); } } void Inverse(Poly A,Poly &B,int n){ static int a[N<<1],b[N<<1]; if(n==1){ B[0]=Inv(A[0]); return; } int mid=(n+1)/2; Inverse(A,B,mid); int len=FFT::init(n<<1); for(register int i=0;i<len;++i) a[i]=b[i]=0; for(register int i=0;i<n;++i) a[i]=A[i]; for(register int i=0;i<mid;++i) b[i]=B[i]; FFT::ntt(a,len,1); FFT::ntt(b,len,1); for(register int i=0;i<len;++i){ b[i]=mul(b[i],sub(2,mul(a[i],b[i]))); } FFT::ntt(b,len,-1); for(register int i=0;i<n;++i) B[i]=b[i]; } Poly Polynomial_Inverse(Poly A){ Poly B; B.resize(A.size()); Inverse(A,B,(int)A.size()); return B; } Poly operator / (Poly A,Poly B){ reverse(A); reverse(B); int Len=A.size()-B.size()+1; A.resize(Len); B.resize(Len); B=Polynomial_Inverse(B); Poly D=A*B; D.resize(Len); reverse(D); return D; } Poly operator % (Poly A,Poly B){ Poly D=A/B; D=D*B; Poly R=A-D; R.resize((int)B.size()-1); return R; } Poly Integral(Poly A){//jifen A.resize(A.size()+1); for(register int i=(int)A.size()-1;i>=1;i--) A[i]=mul(inv[i],A[i-1]); A[0]=0; return A; } Poly Derivate(Poly A){//qiudao for(register int i=0;i<(int)A.size()-1;++i) A[i]=mul(i+1,A[i+1]); A.resize(A.size()-1); return A; } Poly Polynomial_ln(Poly A){ Poly AA=Derivate(A); A=Polynomial_Inverse(A); Poly B=A*AA; B.resize(AA.size()); B=Integral(B); return B; } void EXP(Poly A,Poly &B,int n){ static int a[N<<1],b[N<<1],lnb[N<<1]; if(n==1){ B.push_back(1); return; } int mid=(n+1)/2; EXP(A,B,mid); B.resize(n); Poly lnB=Polynomial_ln(B); int len=FFT::init(n+n); for(register int i=0;i<len;++i) a[i]=0,b[i]=0,lnb[i]=0; for(register int i=0;i<n;++i) a[i]=A[i],lnb[i]=lnB[i];//important!! "ln in MOD x^n" for(register int i=0;i<mid;++i) b[i]=B[i]; FFT::ntt(a,len,1); FFT::ntt(b,len,1); FFT::ntt(lnb,len,1); for(register int i=0;i<len;++i){ b[i]=mul(b[i],sub(a[i]+1,lnb[i])); } FFT::ntt(b,len,-1); for(register int i=0;i<n;++i) B[i]=b[i]; } Poly Polynomial_Exp(Poly A){ Poly B; EXP(A,B,A.size()); return B; } int n,k,fac[N],ifac[N]; Poly f,f1; signed main(){ inv[0]=1; inv[1]=1; for(register int i=2;i<N;++i) inv[i]=mul(MOD-MOD/i,inv[MOD%i]); k=read(); n=read(); fac[0]=1; for(int i=1;i<=n+1;i++) fac[i]=mul(fac[i-1],i); ifac[0]=1; for(int i=1;i<=n+1;i++) ifac[i]=mul(ifac[i-1],inv[i]); f.resize(n+1); f1.resize(n+1); for(int i=0,tmp=k+1;i<=n;i++,Mul(tmp,k+1)) f1[i]=ifac[i+1],f[i]=mul(ifac[i+1],tmp); f=f*Polynomial_Inverse(f1); f[0]=0; f.resize(n+1); for(int i=1;i<=n;i++){ Mul(f[i],fac[i-1]);//*i!/i if(i&1^1) f[i]=MOD-f[i]; } f=Polynomial_Exp(f); printf("%lld\n",mul(f[n],fac[n])); return 0; }
26.986425
88
0.504359
jinzhengyu1212
440f30946cab250c0db8709e14985c206ca8c50e
3,501
cpp
C++
node/silkworm/downloader/messages/InboundNewBlockHashes.cpp
elmato/silkworm
711c73547cd1f7632ff02d5f86dfac5b0d249344
[ "Apache-2.0" ]
null
null
null
node/silkworm/downloader/messages/InboundNewBlockHashes.cpp
elmato/silkworm
711c73547cd1f7632ff02d5f86dfac5b0d249344
[ "Apache-2.0" ]
null
null
null
node/silkworm/downloader/messages/InboundNewBlockHashes.cpp
elmato/silkworm
711c73547cd1f7632ff02d5f86dfac5b0d249344
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 The Silkworm 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 "InboundNewBlockHashes.hpp" #include <algorithm> #include <silkworm/common/log.hpp> #include <silkworm/downloader/internals/random_number.hpp> #include <silkworm/downloader/packets/RLPEth66PacketCoding.hpp> #include <silkworm/downloader/rpc/send_message_by_id.hpp> namespace silkworm { InboundNewBlockHashes::InboundNewBlockHashes(const sentry::InboundMessage& msg, WorkingChain& wc, SentryClient& s) : InboundMessage(), working_chain_(wc), sentry_(s) { if (msg.id() != sentry::MessageId::NEW_BLOCK_HASHES_66) throw std::logic_error("InboundNewBlockHashes received wrong InboundMessage"); reqId_ = RANDOM_NUMBER.generate_one(); // for trace purposes peerId_ = string_from_H512(msg.peer_id()); ByteView data = string_view_to_byte_view(msg.data()); // copy for consumption rlp::success_or_throw(rlp::decode(data, packet_)); SILK_TRACE << "Received message " << *this; } void InboundNewBlockHashes::execute() { using namespace std; SILK_TRACE << "Processing message " << *this; // todo: Erigon apparently processes this message even if it is not in a fetching phase BUT is in request-chaining // mode - do we need the same? BlockNum max = working_chain_.top_seen_block_height(); for (size_t i = 0; i < packet_.size(); i++) { Hash hash = packet_[i].hash; // save announcement working_chain_.save_external_announce(hash); if (working_chain_.has_link(hash)) continue; // request header GetBlockHeadersPacket66 reply; reply.requestId = RANDOM_NUMBER.generate_one(); reply.request.origin = hash; reply.request.amount = 1; reply.request.skip = 0; reply.request.reverse = false; Bytes rlp_encoding; rlp::encode(rlp_encoding, reply); auto msg_reply = std::make_unique<sentry::OutboundMessageData>(); msg_reply->set_id(sentry::MessageId::GET_BLOCK_HEADERS_66); msg_reply->set_data(rlp_encoding.data(), rlp_encoding.length()); // copy // send msg_reply SILK_TRACE << "Replying to " << identify(*this) << " with send_message_by_id, content: " << reply; rpc::SendMessageById rpc(peerId_, std::move(msg_reply)); rpc.do_not_throw_on_failure(); sentry_.exec_remotely(rpc); [[maybe_unused]] sentry::SentPeers peers = rpc.reply(); SILK_TRACE << "Received rpc result of " << identify(*this) << ": " << std::to_string(peers.peers_size()) + " peer(s)"; // calculate top seen block height max = std::max(max, packet_[i].number); } working_chain_.top_seen_block_height(max); } uint64_t InboundNewBlockHashes::reqId() const { return reqId_; } std::string InboundNewBlockHashes::content() const { std::stringstream content; content << packet_; return content.str(); } } // namespace silkworm
34.663366
118
0.690089
elmato
44118ee6351d2431365729ada9faca38a9a5433e
1,036
cpp
C++
bitriejoin-ed/main.cpp
TsinghuaDatabaseGroup/Similarity-Search-and-Join
0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc
[ "BSD-2-Clause" ]
14
2018-01-29T06:54:06.000Z
2021-07-09T18:18:51.000Z
bitriejoin-ed/main.cpp
TsinghuaDatabaseGroup/similarity
0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc
[ "BSD-2-Clause" ]
null
null
null
bitriejoin-ed/main.cpp
TsinghuaDatabaseGroup/similarity
0fba32f030ca9e466d1aed9d3c7dcf59ea3e88dc
[ "BSD-2-Clause" ]
11
2018-04-11T04:56:40.000Z
2021-12-17T04:00:22.000Z
#include <stdio.h> #include <vector> #include <string> #include <iostream> #include <fstream> #include "BiTrieSelfJoin.h" #include "common/time.h" using namespace std; extern long long resultNum; void LoadStrings(vector<char*>& strings, char* filename) { ifstream in(filename); if (in.fail()) { cerr << "Can not open \"" << filename << "\"" << endl; exit(0); } string line; while (getline(in, line, '\n')) { int len = line.size(); while (len>0 && (line[len-1]=='\n' || line[len-1]=='\r')) --len; char* newBuf = (char*)malloc(len+1); memcpy(newBuf, line.c_str(), len); newBuf[len] = 0; strings.push_back(newBuf); } in.close(); } int main(int argc, char **argv) { if (argc != 3) return -1; log_start(); char* filename = argv[1]; int ed = atoi(argv[2]); vector<char*> strings; LoadStrings(strings,filename); BiTrieSelfJoin triejoin; triejoin.edjoin(strings, ed); for (unsigned int i=0; i<strings.size(); ++i) free(strings[i]); cout << resultNum << endl; cout << resultNum << endl; return 0; }
19.54717
66
0.632239
TsinghuaDatabaseGroup
4413384da82d02d06b480f9a45319d7c23c375d5
11,826
cpp
C++
SwordsmanAndSpiders/Classes/common/SixCatsLogger.cpp
beardog-ukr/vigilant-couscous
57f00950b567cb6adf2e0a06f02925ee271012fe
[ "Unlicense" ]
null
null
null
SwordsmanAndSpiders/Classes/common/SixCatsLogger.cpp
beardog-ukr/vigilant-couscous
57f00950b567cb6adf2e0a06f02925ee271012fe
[ "Unlicense" ]
null
null
null
SwordsmanAndSpiders/Classes/common/SixCatsLogger.cpp
beardog-ukr/vigilant-couscous
57f00950b567cb6adf2e0a06f02925ee271012fe
[ "Unlicense" ]
null
null
null
#include "SixCatsLogger.h" #include <iostream> // cout using namespace std; #define LOCAL_C6_DEBUG 1 // --- ------------------------------------------------------------------------ SixCatsLogger::SixCatsLogger() { selfSetup(); } // --- ------------------------------------------------------------------------ SixCatsLogger::SixCatsLogger(LogLevel inLogLevel) { selfSetup(); logLevel = inLogLevel; } // --- ------------------------------------------------------------------------ SixCatsLogger::~SixCatsLogger() { #ifdef LOCAL_C6_DEBUG cout << "SixCatsLogger obj destroyed" << endl; #endif // ifdef LOCAL_C6_DEBUG } // --- ------------------------------------------------------------------------ void SixCatsLogger::selfSetup() { setLogLevel(SixCatsLogger::Critical); } // --- ------------------------------------------------------------------------ void SixCatsLogger::setLogLevel(LogLevel inLogLevel) { logLevel = inLogLevel; // } // --- ------------------------------------------------------------------------ void SixCatsLogger::write(LogLevel messageLevel, const string str) { if (messageLevel > logLevel) { return; } cout << str << endl; } // --- ------------------------------------------------------------------------ string SixCatsLogger::composeLine(const string& metaInfo, const string& message) const { const string tmps = metaInfo + " >> " + message; return tmps; } // --- ------------------------------------------------------------------------ void SixCatsLogger::c(const string& message) { write(Critical, message); } // --- ------------------------------------------------------------------------ void SixCatsLogger::c(const string& metaInfo, const string& message) { write(Critical, composeLine(metaInfo, message)); } // --- ------------------------------------------------------------------------ void SixCatsLogger::w(const string& message) { write(Warning, message); } // --- ------------------------------------------------------------------------ void SixCatsLogger::w(const string& metaInfo, const string& message) { write(Warning, composeLine(metaInfo, message)); } // --- ------------------------------------------------------------------------ void SixCatsLogger::i(const string& message) { write(Info, message); } // --- ------------------------------------------------------------------------ void SixCatsLogger::i(const string& metaInfo, const string& message) { write(Info, composeLine(metaInfo, message)); } // --- ------------------------------------------------------------------------ void SixCatsLogger::d(const string& message) { write(Debug, message); } // --- ------------------------------------------------------------------------ void SixCatsLogger::d(const string& metaInfo, const string& message) { write(Debug, composeLine(metaInfo, message)); } // --- ------------------------------------------------------------------------ void SixCatsLogger::t(const string& metaInfo, const string& message) { write(Trace, composeLine(metaInfo, message)); } // --- ------------------------------------------------------------------------ void SixCatsLogger::t(const string& message) { write(Trace, message); } // --- ------------------------------------------------------------------------ void SixCatsLogger::f(const string& metaInfo, const string& message) { write(Flood, composeLine(metaInfo, message)); } // --- ------------------------------------------------------------------------ void SixCatsLogger::f(const string& message) { write(Flood, message); } // --- ------------------------------------------------------------------------ void SixCatsLogger::writeL(LogLevel messageLevel, std::function<void(std::ostringstream&)>makeMessage) { if (messageLevel > logLevel) { return; } ostringstream s; makeMessage(s); write(messageLevel, s.str()); } void SixCatsLogger::writeL(LogLevel messageLevel, const string & metaInfo, std::function<void(std::ostringstream&)>makeMessage) { if (messageLevel > logLevel) { return; } ostringstream s; makeMessage(s); write(messageLevel, composeLine(metaInfo, s.str())); } // --- ------------------------------------------------------------------------ void SixCatsLogger::c(std::function<void(std::ostringstream&)>makeMessage) { writeL(Critical, makeMessage); } void SixCatsLogger::w(std::function<void(std::ostringstream&)>makeMessage) { writeL(Warning, makeMessage); } void SixCatsLogger::i(std::function<void(std::ostringstream&)>makeMessage) { writeL(Info, makeMessage); } void SixCatsLogger::d(std::function<void(std::ostringstream&)>makeMessage) { writeL(Debug, makeMessage); } void SixCatsLogger::t(std::function<void(std::ostringstream&)>makeMessage) { writeL(Trace, makeMessage); } void SixCatsLogger::f(std::function<void(std::ostringstream&)>makeMessage) { writeL(Flood, makeMessage); } // --- ------------------------------------------------------------------------ void SixCatsLogger::c(const string & metaInfo, std::function<void(std::ostringstream&)>makeMessage) { writeL(Critical, metaInfo, makeMessage); } void SixCatsLogger::w(const string & metaInfo, std::function<void(std::ostringstream&)>makeMessage) { writeL(Warning, metaInfo, makeMessage); } void SixCatsLogger::i(const string & metaInfo, std::function<void(std::ostringstream&)>makeMessage) { writeL(Info, metaInfo, makeMessage); } void SixCatsLogger::d(const string & metaInfo, std::function<void(std::ostringstream&)>makeMessage) { writeL(Debug, metaInfo, makeMessage); } void SixCatsLogger::t(const string & metaInfo, std::function<void(std::ostringstream&)>makeMessage) { writeL(Trace, metaInfo, makeMessage); } void SixCatsLogger::f(const string & metaInfo, std::function<void(std::ostringstream&)>makeMessage) { writeL(Flood, metaInfo, makeMessage); } // --- ------------------------------------------------------------------------ void c6c(SixCatsLogger *logger, const string message) { if (logger == 0) { return; } logger->c(message); } // --- ------------------------------------------------------------------------ void c6c(SixCatsLogger *logger, const string metaInfo, const string message) { if (logger == 0) { return; } logger->c(metaInfo, message); } // --- ------------------------------------------------------------------------ void c6w(SixCatsLogger *logger, const string message) { if (logger == 0) { return; } logger->w(message); } // --- ------------------------------------------------------------------------ void c6w(SixCatsLogger *logger, const string metaInfo, const string message) { if (logger == 0) { return; } logger->w(metaInfo, message); } // --- ------------------------------------------------------------------------ void c6i(SixCatsLogger *logger, const string message) { if (logger == 0) { return; } logger->i(message); } // --- ------------------------------------------------------------------------ void c6i(SixCatsLogger *logger, const string metaInfo, const string message) { if (logger == 0) { return; } logger->i(metaInfo, message); } // --- ------------------------------------------------------------------------ void c6d(SixCatsLogger *logger, const string message) { if (logger == 0) { return; } logger->d(message); } // --- ------------------------------------------------------------------------ void c6d(SixCatsLogger *logger, const string metaInfo, const string message) { if (logger == 0) { return; } logger->d(metaInfo, message); } // --- ------------------------------------------------------------------------ void c6t(SixCatsLogger *logger, const string message) { if (logger == 0) { return; } logger->t(message); } // --- ------------------------------------------------------------------------ void c6t(SixCatsLogger *logger, const string metaInfo, const string message) { if (logger == 0) { return; } logger->t(metaInfo, message); } // --- ------------------------------------------------------------------------ void c6f(SixCatsLogger *logger, const string message) { if (logger == 0) { return; } logger->f(message); } // --- ------------------------------------------------------------------------ void c6f(SixCatsLogger *logger, const string metaInfo, const string message) { if (logger == 0) { return; } logger->f(metaInfo, message); } // --- ------------------------------------------------------------------------ void c6c(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->c(makeMessage); } void c6w(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->w(makeMessage); } void c6i(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->i(makeMessage); } void c6d(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->d(makeMessage); } void c6t(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->t(makeMessage); } void c6f(SixCatsLogger *logger, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->f(makeMessage); } // --- ------------------------------------------------------------------------ void c6c(SixCatsLogger *logger, const string metaInfo, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->c(metaInfo, makeMessage); } void c6w(SixCatsLogger *logger, const string metaInfo, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->w(metaInfo, makeMessage); } void c6i(SixCatsLogger *logger, const string metaInfo, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->i(metaInfo, makeMessage); } void c6d(SixCatsLogger *logger, const string metaInfo, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->d(metaInfo, makeMessage); } void c6t(SixCatsLogger *logger, const string metaInfo, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->t(metaInfo, makeMessage); } void c6f(SixCatsLogger *logger, const string metaInfo, std::function<void(std::ostringstream&)>makeMessage) { if (logger == 0) { return; } logger->f(metaInfo, makeMessage); } // --- ------------------------------------------------------------------------ // --- ------------------------------------------------------------------------
26.635135
89
0.457551
beardog-ukr
4414cf77cd013dbe998caff4cc57ff4f5edc1b0e
36,416
cpp
C++
dlib/test/matrix4.cpp
oms1226/dlib-19.13
0bb55d112324edb700a42a3e6baca09c03967754
[ "MIT" ]
null
null
null
dlib/test/matrix4.cpp
oms1226/dlib-19.13
0bb55d112324edb700a42a3e6baca09c03967754
[ "MIT" ]
null
null
null
dlib/test/matrix4.cpp
oms1226/dlib-19.13
0bb55d112324edb700a42a3e6baca09c03967754
[ "MIT" ]
null
null
null
// Copyright (C) 2010 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #include <dlib/matrix.h> #include <sstream> #include <string> #include <cstdlib> #include <ctime> #include <vector> #include "../stl_checked.h" #include "../array.h" #include "../rand.h" #include "tester.h" #include <dlib/memory_manager_stateless.h> #include <dlib/array2d.h> namespace { using namespace test; using namespace dlib; using namespace std; logger dlog("test.matrix4"); void matrix_test ( ) /*! ensures - runs tests on the matrix stuff compliance with the specs !*/ { print_spinner(); { matrix<double,3,3> m = round(10*randm(3,3)); matrix<double,3,1> v = round(10*randm(3,1)); DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m )); DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m )); } { matrix<double,3,3> m = round(10*randm(3,3)); matrix<double,1,3> v = round(10*randm(1,3)); DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m )); DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m )); } { matrix<double> m = round(10*randm(3,3)); matrix<double,1,3> v = round(10*randm(1,3)); DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m )); DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m )); } { matrix<double> m = round(10*randm(3,3)); matrix<double,0,3> v = round(10*randm(1,3)); DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m )); DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m )); } { matrix<double> m = round(10*randm(3,3)); matrix<double,1,0> v = round(10*randm(1,3)); DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m )); DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m )); } { matrix<double> m = round(10*randm(3,3)); matrix<double,3,0> v = round(10*randm(3,1)); DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m )); DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m )); } { matrix<double> m = round(10*randm(3,3)); matrix<double,0,1> v = round(10*randm(3,1)); DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m )); DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m )); } { matrix<double,3,3> m = round(10*randm(3,3)); matrix<double,3,0> v = round(10*randm(3,1)); DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m )); DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m )); } { matrix<double,3,3> m = round(10*randm(3,3)); matrix<double,0,1> v = round(10*randm(3,1)); DLIB_TEST(equal( m*diagm(v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( scale_columns(m,v) , m*tmp(diagm(v)) )); DLIB_TEST(equal( diagm(v)*m , tmp(diagm(v))*m )); DLIB_TEST(equal( scale_rows(m,v) , tmp(diagm(v))*m )); } { matrix<double,3,5> m = round(10*randm(3,5)); matrix<double,0,1> v1 = round(10*randm(5,1)); matrix<double,0,1> v2 = round(10*randm(3,1)); DLIB_TEST(equal( m*diagm(v1) , m*tmp(diagm(v1)) )); DLIB_TEST(equal( scale_columns(m,v1) , m*tmp(diagm(v1)) )); DLIB_TEST(equal( diagm(v2)*m , tmp(diagm(v2))*m )); DLIB_TEST(equal( scale_rows(m,v2) , tmp(diagm(v2))*m )); } { matrix<double,3,5> m = round(10*randm(3,5)); matrix<double,5,1> v1 = round(10*randm(5,1)); matrix<double,3,1> v2 = round(10*randm(3,1)); DLIB_TEST(equal( m*diagm(v1) , m*tmp(diagm(v1)) )); DLIB_TEST(equal( scale_columns(m,v1) , m*tmp(diagm(v1)) )); DLIB_TEST(equal( diagm(v2)*m , tmp(diagm(v2))*m )); DLIB_TEST(equal( scale_rows(m,v2) , tmp(diagm(v2))*m )); } } void test_stuff() { print_spinner(); { matrix<double> m(3,3), lr(3,3), ud(3,3); m = 1,2,3, 4,5,6, 7,8,9; lr = 3,2,1, 6,5,4, 9,8,7; ud = 7,8,9, 4,5,6, 1,2,3; DLIB_TEST(lr == fliplr(m)); DLIB_TEST(ud == flipud(m)); } { matrix<double> m(3,2), lr(3,2), ud(3,2); m = 1,2, 3,4, 5,6; lr = 2,1, 4,3, 6,5; ud = 5,6, 3,4, 1,2; DLIB_TEST(lr == fliplr(m)); DLIB_TEST(ud == flipud(m)); } { matrix<int> a, b; a = matrix_cast<int>(round(10*randm(3,3))); b = a; b *= b; DLIB_TEST(b == a*a); } { matrix<double> m(2,3), m2(2,3); m = 1,2,3, 4,5,6; m2 = 3,4,5, 6,7,8; DLIB_TEST(m + 2 == m2); DLIB_TEST(2 + m == m2); m += 2; DLIB_TEST(m == m2); m -= 2; m2 = 0,1,2, 3,4,5; DLIB_TEST(m - 1 == m2); m -= 1; DLIB_TEST(m == m2); m += 1; m2 = 5,4,3, 2,1,0; DLIB_TEST(6 - m == m2); } { matrix<float> m(2,3), m2(2,3); m = 1,2,3, 4,5,6; m2 = 3,4,5, 6,7,8; DLIB_TEST(m + 2 == m2); DLIB_TEST(2 + m == m2); m += 2; DLIB_TEST(m == m2); m -= 2; m2 = 0,1,2, 3,4,5; DLIB_TEST(m - 1 == m2); m -= 1; DLIB_TEST(m == m2); m += 1; m2 = 5,4,3, 2,1,0; DLIB_TEST(6 - m == m2); } { matrix<int> m(2,3), m2(2,3); m = 1,2,3, 4,5,6; m2 = 3,4,5, 6,7,8; DLIB_TEST(m + 2 == m2); DLIB_TEST(2 + m == m2); m += 2; DLIB_TEST(m == m2); m -= 2; m2 = 0,1,2, 3,4,5; DLIB_TEST(m - 1 == m2); m -= 1; DLIB_TEST(m == m2); m += 1; m2 = 5,4,3, 2,1,0; DLIB_TEST(6 - m == m2); } { matrix<int,2,3> m, m2; m = 1,2,3, 4,5,6; m2 = 3,4,5, 6,7,8; DLIB_TEST(m + 2 == m2); DLIB_TEST(2 + m == m2); m += 2; DLIB_TEST(m == m2); m -= 2; m2 = 0,1,2, 3,4,5; DLIB_TEST(m - 1 == m2); m -= 1; DLIB_TEST(m == m2); m += 1; m2 = 5,4,3, 2,1,0; DLIB_TEST(6 - m == m2); } { matrix<double> m(2,3), m2(3,2); m = 1,2,3, 4,5,6; m2 = 2,5, 3,6, 4,7; DLIB_TEST(trans(m+1) == m2); DLIB_TEST(trans(m)+1 == m2); DLIB_TEST(1+trans(m) == m2); DLIB_TEST(1+m-1 == m); m = trans(m+1); DLIB_TEST(m == m2); m = trans(m-1); DLIB_TEST(trans(m+1) == m2); m = trans(m)+1; DLIB_TEST(m == m2); } { matrix<double> d(3,1), di(3,1); matrix<double> m(3,3); m = 1,2,3, 4,5,6, 7,8,9; d = 1,2,3; di = 1, 1/2.0, 1/3.0; DLIB_TEST(inv(diagm(d)) == diagm(di)); DLIB_TEST(pinv(diagm(d)) == diagm(di)); DLIB_TEST(inv(diagm(d))*m == tmp(diagm(di))*m); DLIB_TEST(m*inv(diagm(d)) == m*tmp(diagm(di))); DLIB_TEST(equal(inv(diagm(d)) + m , tmp(diagm(di)) + m)); DLIB_TEST(equal(m + inv(diagm(d)) , tmp(diagm(di)) + m)); DLIB_TEST((m + identity_matrix<double>(3) == m + tmp(identity_matrix<double>(3)))); DLIB_TEST((m + identity_matrix<double,3>() == m + tmp(identity_matrix<double,3>()))); DLIB_TEST((m + 2*identity_matrix<double>(3) == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((m + 2*identity_matrix<double,3>() == m + 2*tmp(identity_matrix<double,3>()))); DLIB_TEST((m + identity_matrix<double>(3)*2 == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((m + identity_matrix<double,3>()*2 == m + 2*tmp(identity_matrix<double,3>()))); DLIB_TEST((identity_matrix<double>(3) + m == m + tmp(identity_matrix<double>(3)))); DLIB_TEST((identity_matrix<double,3>() + m == m + tmp(identity_matrix<double,3>()))); DLIB_TEST((2*identity_matrix<double>(3) + m == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((2*identity_matrix<double,3>() + m == m + 2*tmp(identity_matrix<double,3>()))); } { matrix<double,3,1> d(3,1), di(3,1); matrix<double,3,3> m(3,3); m = 1,2,3, 4,5,6, 7,8,9; d = 1,2,3; di = 1, 1/2.0, 1/3.0; DLIB_TEST(equal(inv(diagm(d)) , diagm(di))); DLIB_TEST(equal(inv(diagm(d)) , diagm(di))); DLIB_TEST(equal(inv(diagm(d))*m , tmp(diagm(di))*m)); DLIB_TEST(equal(m*inv(diagm(d)) , m*tmp(diagm(di)))); DLIB_TEST_MSG(equal(inv(diagm(d)) + m , tmp(diagm(di)) + m), (inv(diagm(d)) + m) - (tmp(diagm(di)) + m) ); DLIB_TEST(equal(m + inv(diagm(d)) , tmp(diagm(di)) + m)); DLIB_TEST((m + identity_matrix<double>(3) == m + tmp(identity_matrix<double>(3)))); DLIB_TEST((m + identity_matrix<double,3>() == m + tmp(identity_matrix<double,3>()))); DLIB_TEST((m + 2*identity_matrix<double>(3) == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((m + 2*identity_matrix<double,3>() == m + 2*tmp(identity_matrix<double,3>()))); DLIB_TEST((m + identity_matrix<double>(3)*2 == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((m + identity_matrix<double,3>()*2 == m + 2*tmp(identity_matrix<double,3>()))); DLIB_TEST((identity_matrix<double>(3) + m == m + tmp(identity_matrix<double>(3)))); DLIB_TEST((identity_matrix<double,3>() + m == m + tmp(identity_matrix<double,3>()))); DLIB_TEST((2*identity_matrix<double>(3) + m == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((2*identity_matrix<double,3>() + m == m + 2*tmp(identity_matrix<double,3>()))); } { matrix<double,1,3> d(1,3), di(1,3); matrix<double,3,3> m(3,3); m = 1,2,3, 4,5,6, 7,8,9; d = 1,2,3; di = 1, 1/2.0, 1/3.0; DLIB_TEST(equal(inv(diagm(d)) , diagm(di))); DLIB_TEST(equal(inv(diagm(d)) , diagm(di))); DLIB_TEST(equal(inv(diagm(d))*m , tmp(diagm(di))*m)); DLIB_TEST(equal(m*inv(diagm(d)) , m*tmp(diagm(di)))); DLIB_TEST(equal(inv(diagm(d)) + m , tmp(diagm(di)) + m)); DLIB_TEST(equal(m + inv(diagm(d)) , tmp(diagm(di)) + m)); DLIB_TEST((m + identity_matrix<double>(3) == m + tmp(identity_matrix<double>(3)))); DLIB_TEST((m + identity_matrix<double,3>() == m + tmp(identity_matrix<double,3>()))); DLIB_TEST((m + 2*identity_matrix<double>(3) == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((m + 2*identity_matrix<double,3>() == m + 2*tmp(identity_matrix<double,3>()))); DLIB_TEST((m + identity_matrix<double>(3)*2 == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((m + identity_matrix<double,3>()*2 == m + 2*tmp(identity_matrix<double,3>()))); DLIB_TEST((identity_matrix<double>(3) + m == m + tmp(identity_matrix<double>(3)))); DLIB_TEST((identity_matrix<double,3>() + m == m + tmp(identity_matrix<double,3>()))); DLIB_TEST((2*identity_matrix<double>(3) + m == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((2*identity_matrix<double,3>() + m == m + 2*tmp(identity_matrix<double,3>()))); } { matrix<double,1,0> d(1,3), di(1,3); matrix<double,0,3> m(3,3); m = 1,2,3, 4,5,6, 7,8,9; d = 1,2,3; di = 1, 1/2.0, 1/3.0; DLIB_TEST(equal(inv(diagm(d)) , diagm(di))); DLIB_TEST(equal(inv(diagm(d)) , diagm(di))); DLIB_TEST(equal(inv(diagm(d))*m , tmp(diagm(di))*m)); DLIB_TEST(equal(m*inv(diagm(d)) , m*tmp(diagm(di)))); DLIB_TEST(equal(inv(diagm(d)) + m , tmp(diagm(di)) + m)); DLIB_TEST(equal(m + inv(diagm(d)) , tmp(diagm(di)) + m)); DLIB_TEST((m + identity_matrix<double>(3) == m + tmp(identity_matrix<double>(3)))); DLIB_TEST((m + identity_matrix<double,3>() == m + tmp(identity_matrix<double,3>()))); DLIB_TEST((m + 2*identity_matrix<double>(3) == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((m + 2*identity_matrix<double,3>() == m + 2*tmp(identity_matrix<double,3>()))); DLIB_TEST((m + identity_matrix<double>(3)*2 == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((m + identity_matrix<double,3>()*2 == m + 2*tmp(identity_matrix<double,3>()))); DLIB_TEST((identity_matrix<double>(3) + m == m + tmp(identity_matrix<double>(3)))); DLIB_TEST((identity_matrix<double,3>() + m == m + tmp(identity_matrix<double,3>()))); DLIB_TEST((2*identity_matrix<double>(3) + m == m + 2*tmp(identity_matrix<double>(3)))); DLIB_TEST((2*identity_matrix<double,3>() + m == m + 2*tmp(identity_matrix<double,3>()))); } { matrix<double,3,1> d1, d2; d1 = 1,2,3; d2 = 2,3,4; matrix<double,3,3> ans; ans = 2, 0, 0, 0, 6, 0, 0, 0, 12; DLIB_TEST(ans == diagm(d1)*diagm(d2)); } dlib::rand rnd; for (int i = 0; i < 1; ++i) { matrix<double> d1 = randm(4,1,rnd); matrix<double,5,1> d2 = randm(5,1,rnd); matrix<double,4,5> m = randm(4,5,rnd); DLIB_TEST_MSG(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*m*diagm(d2)), pointwise_multiply(d1*trans(d2), m) - diagm(d1)*m*diagm(d2) ); DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*(m*diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , (diagm(d1)*m)*diagm(d2))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*m*inv(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*(m*inv(diagm(d2))))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , (inv(diagm(d1))*m)*inv(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*m*(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*(m*(diagm(d2))))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , (inv(diagm(d1))*m)*(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*m*inv(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*(m*inv(diagm(d2))))); DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , ((diagm(d1))*m)*inv(diagm(d2)))); } for (int i = 0; i < 1; ++i) { matrix<double,4,1> d1 = randm(4,1,rnd); matrix<double,5,1> d2 = randm(5,1,rnd); matrix<double,4,5> m = randm(4,5,rnd); DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*m*diagm(d2))); DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*(m*diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , (diagm(d1)*m)*diagm(d2))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*m*inv(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*(m*inv(diagm(d2))))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , (inv(diagm(d1))*m)*inv(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*m*(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*(m*(diagm(d2))))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , (inv(diagm(d1))*m)*(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*m*inv(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*(m*inv(diagm(d2))))); DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , ((diagm(d1))*m)*inv(diagm(d2)))); } for (int i = 0; i < 1; ++i) { matrix<double,4,1> d1 = randm(4,1,rnd); matrix<double,5,1> d2 = randm(5,1,rnd); matrix<double,0,0> m = randm(4,5,rnd); DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*m*diagm(d2))); DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , diagm(d1)*(m*diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(d1*trans(d2), m) , (diagm(d1)*m)*diagm(d2))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*m*inv(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , inv(diagm(d1))*(m*inv(diagm(d2))))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans(reciprocal(d2)), m) , (inv(diagm(d1))*m)*inv(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*m*(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , inv(diagm(d1))*(m*(diagm(d2))))); DLIB_TEST(equal(pointwise_multiply(reciprocal(d1)*trans((d2)), m) , (inv(diagm(d1))*m)*(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*m*inv(diagm(d2)))); DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , (diagm(d1))*(m*inv(diagm(d2))))); DLIB_TEST(equal(pointwise_multiply((d1)*trans(reciprocal(d2)), m) , ((diagm(d1))*m)*inv(diagm(d2)))); } { for (int i = 0; i < 5; ++i) { matrix<double> m = randm(3,4) + 1; DLIB_TEST(equal(1.0/m , reciprocal(m))); DLIB_TEST(equal(0.0/m , zeros_matrix<double>(3,4))); } } { matrix<int> m(2,3); m = 1,2,3, 4,5,6; matrix<int> M(2,3); M = m; DLIB_TEST(upperbound(m,6) == M); DLIB_TEST(upperbound(m,60) == M); DLIB_TEST(lowerbound(m,-2) == M); DLIB_TEST(lowerbound(m,0) == M); M = 2,2,3, 4,5,6; DLIB_TEST(lowerbound(m,2) == M); M = 0,0,0, 0,0,0; DLIB_TEST(upperbound(m,0) == M); M = 1,2,3, 3,3,3; DLIB_TEST(upperbound(m,3) == M); } { matrix<double,9,5> A = randm(9,5); matrix<double> B = A; orthogonalize(A); orthogonalize(B); DLIB_TEST(equal(A,B)); } } template < long D1, long D2, long D3, long D4 > void test_conv() { dlog << LINFO << D1 << " " << D2 << " " << D3 << " " << D4; matrix<int,D1,D1> a(1,1); matrix<int,D2,D2> b(2,2); matrix<int,D3,D3> c(3,3); matrix<int,D4,D1> d(4,1); a = 4; b = 1,2, 3,4; c = 1,2,3, 4,5,6, 7,8,9; d = 1, 2, 3, 4; matrix<int> temp(4,4), temp2; temp = 1, 4, 7, 6, 7, 23, 33, 24, 19, 53, 63, 42, 21, 52, 59, 36; DLIB_TEST(conv(b,c) == temp); DLIB_TEST(conv(c,b) == temp); DLIB_TEST(xcorr(c,flip(b)) == temp); temp.set_size(2,2); temp = 23, 33, 53, 63; DLIB_TEST(conv_same(b,c) == temp); DLIB_TEST(xcorr_same(b,flip(c)) == temp); temp2.set_size(2,2); temp2 = 63, 53, 33, 23; DLIB_TEST(flip(temp) == temp2); DLIB_TEST(flip(temp) == fliplr(flipud(temp))); DLIB_TEST(conv_valid(b,c).nr() == 0); DLIB_TEST(conv_valid(b,c).nc() == 0); DLIB_TEST(conv_valid(c,b) == temp); DLIB_TEST(xcorr_valid(c,flip(b)) == temp); temp.set_size(1,1); temp = 16; DLIB_TEST(conv(a,a) == temp); DLIB_TEST(conv_same(a,a) == temp); DLIB_TEST(conv_valid(a,a) == temp); DLIB_TEST(xcorr(a,a) == temp); DLIB_TEST(xcorr_same(a,a) == temp); DLIB_TEST(xcorr_valid(a,a) == temp); temp.set_size(0,0); DLIB_TEST(conv(temp,temp).nr() == 0); DLIB_TEST(conv(temp,temp).nc() == 0); DLIB_TEST(conv_same(temp,temp).nr() == 0); DLIB_TEST(conv_same(temp,temp).nc() == 0); DLIB_TEST_MSG(conv_valid(temp,temp).nr() == 0, conv_valid(temp,temp).nr()); DLIB_TEST(conv_valid(temp,temp).nc() == 0); DLIB_TEST(conv(c,temp).nr() == 0); DLIB_TEST(conv(c,temp).nc() == 0); DLIB_TEST(conv_same(c,temp).nr() == 0); DLIB_TEST(conv_same(c,temp).nc() == 0); DLIB_TEST(conv_valid(c,temp).nr() == 0); DLIB_TEST(conv_valid(c,temp).nc() == 0); DLIB_TEST(conv(temp,c).nr() == 0); DLIB_TEST(conv(temp,c).nc() == 0); DLIB_TEST(conv_same(temp,c).nr() == 0); DLIB_TEST(conv_same(temp,c).nc() == 0); DLIB_TEST(conv_valid(temp,c).nr() == 0); DLIB_TEST(conv_valid(temp,c).nc() == 0); temp.set_size(5,2); temp = 1, 2, 5, 8, 9, 14, 13, 20, 12, 16; DLIB_TEST(conv(b,d) == temp); DLIB_TEST(xcorr(b,flip(d)) == temp); temp.set_size(2,2); temp = 9, 14, 13, 20; DLIB_TEST(conv_same(b,d) == temp); DLIB_TEST(xcorr_same(b,flip(d)) == temp); DLIB_TEST(conv_valid(b,d).nr() == 0); DLIB_TEST(xcorr_valid(b,flip(d)).nr() == 0); DLIB_TEST_MSG(conv_valid(b,d).nc() == 0, conv_valid(b,d).nc()); DLIB_TEST(xcorr_valid(b,flip(d)).nc() == 0); temp.set_size(5,5); temp = 1, 4, 10, 12, 9, 8, 26, 56, 54, 36, 30, 84, 165, 144, 90, 56, 134, 236, 186, 108, 49, 112, 190, 144, 81; DLIB_TEST(conv(c,c) == temp); DLIB_TEST(xcorr(c,flip(c)) == temp); matrix<int> temp3 = c; temp3 = conv(temp3,c); DLIB_TEST(temp3 == temp); temp3 = c; temp3 = conv(c,temp3); DLIB_TEST(temp3 == temp); temp.set_size(3,3); temp = 26, 56, 54, 84, 165, 144, 134, 236, 186; DLIB_TEST(conv_same(c,c) == temp); DLIB_TEST(xcorr_same(c,flip(c)) == temp); temp3 = c; temp3 = conv_same(c,temp3); DLIB_TEST(temp3 == temp); temp3 = c; temp3 = conv_same(temp3,c); DLIB_TEST(temp3 == temp); temp.set_size(1,1); temp = 165; DLIB_TEST(conv_valid(c,c) == temp); DLIB_TEST(xcorr_valid(c,flip(c)) == temp); temp3 = c; temp3 = conv_valid(c,temp3); DLIB_TEST(temp3 == temp); temp3 = c; temp3 = conv_valid(temp3,c); DLIB_TEST(temp3 == temp); dlib::rand rnd; for (int i = 0; i < 3; ++i) { matrix<complex<int> > a, b; a = complex_matrix(matrix_cast<int>(round(20*randm(2,7,rnd))), matrix_cast<int>(round(20*randm(2,7,rnd)))); b = complex_matrix(matrix_cast<int>(round(20*randm(3,2,rnd))), matrix_cast<int>(round(20*randm(3,2,rnd)))); DLIB_TEST(xcorr(a,b) == conv(a, flip(conj(b)))); DLIB_TEST(xcorr_valid(a,b) == conv_valid(a, flip(conj(b)))); DLIB_TEST(xcorr_same(a,b) == conv_same(a, flip(conj(b)))); } for (int i = 0; i < 30; ++i) { auto nr1 = rnd.get_integer_in_range(1,30); auto nc1 = rnd.get_integer_in_range(1,30); auto nr2 = rnd.get_integer_in_range(1,30); auto nc2 = rnd.get_integer_in_range(1,30); matrix<double> a, b; a = randm(nr1,nc1,rnd); b = randm(nr2,nc2,rnd); DLIB_TEST(max(abs(xcorr(a,b) - xcorr_fft(a,b))) < 1e-12); } } void test_complex() { matrix<complex<double> > a, b; a = complex_matrix(linspace(1,7,7), linspace(2,8,7)); b = complex_matrix(linspace(4,10,7), linspace(2,8,7)); DLIB_TEST(mean(a) == complex<double>(4, 5)); } void test_setsubs() { { matrix<double> m(3,3); m = 0; set_colm(m,0) += 1; set_rowm(m,0) += 1; set_subm(m,1,1,2,2) += 5; matrix<double> m2(3,3); m2 = 2, 1, 1, 1, 5, 5, 1, 5, 5; DLIB_TEST(m == m2); set_colm(m,0) -= 1; set_rowm(m,0) -= 1; set_subm(m,1,1,2,2) -= 5; m2 = 0; DLIB_TEST(m == m2); matrix<double,1,3> r; matrix<double,3,1> c; matrix<double,2,2> b; r = 1,2,3; c = 2, 3, 4; b = 2,3, 4,5; set_colm(m,1) += c; set_rowm(m,1) += r; set_subm(m,1,1,2,2) += b; m2 = 0, 2, 0, 1, 7, 6, 0, 8, 5; DLIB_TEST(m2 == m); set_colm(m,1) -= c; set_rowm(m,1) -= r; set_subm(m,1,1,2,2) -= b; m2 = 0; DLIB_TEST(m2 == m); // check that the code path for destructive aliasing works right. m = 2*identity_matrix<double>(3); set_colm(m,1) += m*c; m2 = 2, 4, 0, 0, 8, 0, 0, 8, 2; DLIB_TEST(m == m2); m = 2*identity_matrix<double>(3); set_colm(m,1) -= m*c; m2 = 2, -4, 0, 0, -4, 0, 0, -8, 2; DLIB_TEST(m == m2); m = 2*identity_matrix<double>(3); set_rowm(m,1) += r*m; m2 = 2, 0, 0, 2, 6, 6, 0, 0, 2; DLIB_TEST(m == m2); m = 2*identity_matrix<double>(3); set_rowm(m,1) -= r*m; m2 = 2, 0, 0, -2, -2, -6, 0, 0, 2; DLIB_TEST(m == m2); m = identity_matrix<double>(3); const rectangle rect(0,0,1,1); set_subm(m,rect) += subm(m,rect)*b; m2 = 3, 3, 0, 4, 6, 0, 0, 0, 1; DLIB_TEST(m == m2); m = identity_matrix<double>(3); set_subm(m,rect) -= subm(m,rect)*b; m2 = -1, -3, 0, -4, -4, 0, 0, 0, 1; DLIB_TEST(m == m2); } { matrix<double,1,1> a, b; a = 2; b = 3; DLIB_TEST(dot(a,b) == 6); } { matrix<double,1,1> a; matrix<double,0,1> b(1); a = 2; b = 3; DLIB_TEST(dot(a,b) == 6); DLIB_TEST(dot(b,a) == 6); } { matrix<double,1,1> a; matrix<double,1,0> b(1); a = 2; b = 3; DLIB_TEST(dot(a,b) == 6); DLIB_TEST(dot(b,a) == 6); } } template <typename T> std::vector<int> tovect1(const T& m) { std::vector<int> temp; for (typename T::const_iterator i = m.begin(); i != m.end(); ++i) { temp.push_back(*i); } return temp; } template <typename T> std::vector<int> tovect2(const T& m) { std::vector<int> temp; for (typename T::const_iterator i = m.begin(); i != m.end(); i++) { temp.push_back(*i); } return temp; } template <typename T> std::vector<int> tovect3(const T& m_) { matrix<int> m(m_); std::vector<int> temp; for (matrix<int>::iterator i = m.begin(); i != m.end(); ++i) { temp.push_back(*i); } return temp; } template <typename T> std::vector<int> tovect4(const T& m_) { matrix<int> m(m_); std::vector<int> temp; for (matrix<int>::iterator i = m.begin(); i != m.end(); i++) { temp.push_back(*i); } return temp; } void test_iterators() { matrix<int> m(3,2); m = 1,2,3, 4,5,6; std::vector<int> v1 = tovect1(m); std::vector<int> v2 = tovect2(m); std::vector<int> v3 = tovect3(m); std::vector<int> v4 = tovect4(m); std::vector<int> v5 = tovect1(m+m); std::vector<int> v6 = tovect2(m+m); std::vector<int> v7 = tovect3(m+m); std::vector<int> v8 = tovect4(m+m); std::vector<int> a1, a2; for (int i = 1; i <= 6; ++i) { a1.push_back(i); a2.push_back(i*2); } DLIB_TEST(max(abs(mat(v1) - mat(a1))) == 0); DLIB_TEST(max(abs(mat(v2) - mat(a1))) == 0); DLIB_TEST(max(abs(mat(v3) - mat(a1))) == 0); DLIB_TEST(max(abs(mat(v4) - mat(a1))) == 0); DLIB_TEST(max(abs(mat(v5) - mat(a2))) == 0); DLIB_TEST(max(abs(mat(v6) - mat(a2))) == 0); DLIB_TEST(max(abs(mat(v7) - mat(a2))) == 0); DLIB_TEST(max(abs(mat(v8) - mat(a2))) == 0); } void test_linpiece() { matrix<double,0,1> temp = linpiece(5, linspace(-1, 9, 2)); DLIB_CASSERT(temp.size() == 1,""); DLIB_CASSERT(std::abs(temp(0) - 6) < 1e-13,""); temp = linpiece(5, linspace(-1, 9, 6)); DLIB_CASSERT(temp.size() == 5,""); DLIB_CASSERT(std::abs(temp(0) - 2) < 1e-13,""); DLIB_CASSERT(std::abs(temp(1) - 2) < 1e-13,""); DLIB_CASSERT(std::abs(temp(2) - 2) < 1e-13,""); DLIB_CASSERT(std::abs(temp(3) - 0) < 1e-13,""); DLIB_CASSERT(std::abs(temp(4) - 0) < 1e-13,""); temp = linpiece(4, linspace(-1, 9, 6)); DLIB_CASSERT(temp.size() == 5,""); DLIB_CASSERT(std::abs(temp(0) - 2) < 1e-13,""); DLIB_CASSERT(std::abs(temp(1) - 2) < 1e-13,""); DLIB_CASSERT(std::abs(temp(2) - 1) < 1e-13,""); DLIB_CASSERT(std::abs(temp(3) - 0) < 1e-13,""); DLIB_CASSERT(std::abs(temp(4) - 0) < 1e-13,""); temp = linpiece(40, linspace(-1, 9, 6)); DLIB_CASSERT(temp.size() == 5,""); DLIB_CASSERT(std::abs(temp(0) - 2) < 1e-13,""); DLIB_CASSERT(std::abs(temp(1) - 2) < 1e-13,""); DLIB_CASSERT(std::abs(temp(2) - 2) < 1e-13,""); DLIB_CASSERT(std::abs(temp(3) - 2) < 1e-13,""); DLIB_CASSERT(std::abs(temp(4) - 2) < 1e-13,""); temp = linpiece(-40, linspace(-1, 9, 6)); DLIB_CASSERT(temp.size() == 5,""); DLIB_CASSERT(std::abs(temp(0) - 0) < 1e-13,""); DLIB_CASSERT(std::abs(temp(1) - 0) < 1e-13,""); DLIB_CASSERT(std::abs(temp(2) - 0) < 1e-13,""); DLIB_CASSERT(std::abs(temp(3) - 0) < 1e-13,""); DLIB_CASSERT(std::abs(temp(4) - 0) < 1e-13,""); temp = linpiece(0, linspace(-1, 9, 6)); DLIB_CASSERT(temp.size() == 5,""); DLIB_CASSERT(std::abs(temp(0) - 1) < 1e-13,""); DLIB_CASSERT(std::abs(temp(1) - 0) < 1e-13,""); DLIB_CASSERT(std::abs(temp(2) - 0) < 1e-13,""); DLIB_CASSERT(std::abs(temp(3) - 0) < 1e-13,""); DLIB_CASSERT(std::abs(temp(4) - 0) < 1e-13,""); } class matrix_tester : public tester { public: matrix_tester ( ) : tester ("test_matrix4", "Runs tests on the scale_rows and scale_columns functions.") {} void perform_test ( ) { test_iterators(); test_setsubs(); test_conv<0,0,0,0>(); test_conv<1,2,3,4>(); test_stuff(); for (int i = 0; i < 10; ++i) matrix_test(); test_complex(); test_linpiece(); } } a; }
32.514286
127
0.445436
oms1226
4416385c2761b7381dc71d4febc132e85afb83a3
1,993
cc
C++
src/flpr/Stmt_Tree.cc
apthorpe/FLPR
9620f28ad1cde553eb8ffa7f2685683763530acb
[ "BSD-3-Clause" ]
null
null
null
src/flpr/Stmt_Tree.cc
apthorpe/FLPR
9620f28ad1cde553eb8ffa7f2685683763530acb
[ "BSD-3-Clause" ]
null
null
null
src/flpr/Stmt_Tree.cc
apthorpe/FLPR
9620f28ad1cde553eb8ffa7f2685683763530acb
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2019, Triad National Security, LLC. All rights reserved. This is open source software; you can redistribute it and/or modify it under the terms of the BSD-3 License. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL. Full text of the BSD-3 License can be found in the LICENSE file of the repository. */ /*! \file Stmt_Tree.cc */ #include "flpr/Stmt_Tree.hh" #include <cassert> #include <ostream> namespace FLPR { namespace Stmt { void cover_branches(Stmt_Tree::reference st) { // Scan to first non-empty branch auto b1 = st.branches().begin(); while (b1 != st.branches().end() && (*b1)->token_range.empty()) ++b1; if (b1 == st.branches().end()) return; // No valid ranges to cover st->token_range.clear(); st->token_range.set_it((*b1)->token_range.it()); st->token_range.push_back((*b1)->token_range); for (b1 = std::next(b1); b1 != st.branches().end(); ++b1) { st->token_range.push_back((*b1)->token_range); } } void hoist_back(Stmt_Tree &t, Stmt_Tree &&donor) { if (!donor) return; if ((*donor)->syntag == Syntax_Tags::HOIST) { for (auto &&b : donor->branches()) { auto new_loc = t->branches().emplace(t->branches().end(), std::move(b)); new_loc->link(new_loc, t.root()); } } else { t.graft_back(std::move(donor)); } } std::ostream &operator<<(std::ostream &os, ST_Node_Data const &nd) { return Syntax_Tags::print(os, nd.syntag); } int get_label_do_label(Stmt_Tree const &t) { auto c = t.ccursor(); if (FLPR::Syntax_Tags::SG_DO_STMT == c->syntag) c.down(); if (FLPR::Syntax_Tags::SG_LABEL_DO_STMT != c->syntag) { return 0; } c.down().next().down(); assert(FLPR::Syntax_Tags::SG_INT_LITERAL_CONSTANT == c->syntag); assert(c->token_range.size() == 1); return std::stoi(c->token_range.front().text()); } } // namespace Stmt } // namespace FLPR
29.308824
78
0.658304
apthorpe
4417d0ef2e9a7297d1318a1d2c05a48759ea1c43
27,908
cpp
C++
src/openms/source/FORMAT/IdXMLFile.cpp
liangoaix/OpenMS
cccbc5d872320f197091596db275f35b4d0458cd
[ "Zlib", "Apache-2.0" ]
null
null
null
src/openms/source/FORMAT/IdXMLFile.cpp
liangoaix/OpenMS
cccbc5d872320f197091596db275f35b4d0458cd
[ "Zlib", "Apache-2.0" ]
null
null
null
src/openms/source/FORMAT/IdXMLFile.cpp
liangoaix/OpenMS
cccbc5d872320f197091596db275f35b4d0458cd
[ "Zlib", "Apache-2.0" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2013. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Andreas Bertsch $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/SYSTEM/File.h> #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/CONCEPT/PrecisionWrapper.h> #include <iostream> #include <fstream> #include <limits> using namespace std; using namespace OpenMS::Internal; namespace OpenMS { IdXMLFile::IdXMLFile() : XMLHandler("", "1.2"), XMLFile("/SCHEMAS/IdXML_1_2.xsd", "1.2"), last_meta_(0), document_id_(), prot_id_in_run_(false) { } void IdXMLFile::load(const String& filename, vector<ProteinIdentification>& protein_ids, vector<PeptideIdentification>& peptide_ids) { String document_id; load(filename, protein_ids, peptide_ids, document_id); } void IdXMLFile::load(const String& filename, vector<ProteinIdentification>& protein_ids, vector<PeptideIdentification>& peptide_ids, String& document_id) { //Filename for error messages in XMLHandler file_ = filename; protein_ids.clear(); peptide_ids.clear(); prot_ids_ = &protein_ids; pep_ids_ = &peptide_ids; document_id_ = &document_id; parse_(filename, this); //reset members prot_ids_ = 0; pep_ids_ = 0; last_meta_ = 0; parameters_.clear(); param_ = ProteinIdentification::SearchParameters(); id_ = ""; prot_id_ = ProteinIdentification(); pep_id_ = PeptideIdentification(); prot_hit_ = ProteinHit(); pep_hit_ = PeptideHit(); proteinid_to_accession_.clear(); } void IdXMLFile::store(String filename, const vector<ProteinIdentification>& protein_ids, const vector<PeptideIdentification>& peptide_ids, const String& document_id) { //open stream std::ofstream os(filename.c_str()); if (!os) { throw Exception::UnableToCreateFile(__FILE__, __LINE__, __PRETTY_FUNCTION__, filename); } os.precision(writtenDigits<double>(0.0)); //write header os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; os << "<?xml-stylesheet type=\"text/xsl\" href=\"http://open-ms.sourceforge.net/XSL/IdXML.xsl\" ?>\n"; os << "<IdXML version=\"" << getVersion() << "\""; if (document_id != "") { os << " id=\"" << document_id << "\""; } os << " xsi:noNamespaceSchemaLocation=\"http://open-ms.sourceforge.net/SCHEMAS/IdXML_1_2.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"; //look up different search parameters vector<ProteinIdentification::SearchParameters> params; for (vector<ProteinIdentification>::const_iterator it = protein_ids.begin(); it != protein_ids.end(); ++it) { if (find(params.begin(), params.end(), it->getSearchParameters()) == params.end()) { params.push_back(it->getSearchParameters()); } } //write search parameters for (Size i = 0; i != params.size(); ++i) { os << "\t<SearchParameters " << "id=\"SP_" << i << "\" " << "db=\"" << writeXMLEscape(params[i].db) << "\" " << "db_version=\"" << writeXMLEscape(params[i].db_version) << "\" " << "taxonomy=\"" << writeXMLEscape(params[i].taxonomy) << "\" "; if (params[i].mass_type == ProteinIdentification::MONOISOTOPIC) { os << "mass_type=\"monoisotopic\" "; } else if (params[i].mass_type == ProteinIdentification::AVERAGE) { os << "mass_type=\"average\" "; } os << "charges=\"" << params[i].charges << "\" "; if (params[i].enzyme == ProteinIdentification::TRYPSIN) { os << "enzyme=\"trypsin\" "; } if (params[i].enzyme == ProteinIdentification::PEPSIN_A) { os << "enzyme=\"pepsin_a\" "; } if (params[i].enzyme == ProteinIdentification::PROTEASE_K) { os << "enzyme=\"protease_k\" "; } if (params[i].enzyme == ProteinIdentification::CHYMOTRYPSIN) { os << "enzyme=\"chymotrypsin\" "; } else if (params[i].enzyme == ProteinIdentification::NO_ENZYME) { os << "enzyme=\"no_enzyme\" "; } else if (params[i].enzyme == ProteinIdentification::UNKNOWN_ENZYME) { os << "enzyme=\"unknown_enzyme\" "; } os << "missed_cleavages=\"" << params[i].missed_cleavages << "\" " << "precursor_peak_tolerance=\"" << params[i].precursor_tolerance << "\" " << "peak_mass_tolerance=\"" << params[i].peak_mass_tolerance << "\" " << ">\n"; //modifications for (Size j = 0; j != params[i].fixed_modifications.size(); ++j) { os << "\t\t<FixedModification name=\"" << writeXMLEscape(params[i].fixed_modifications[j]) << "\" />\n"; //Add MetaInfo, when modifications has it (Andreas) } for (Size j = 0; j != params[i].variable_modifications.size(); ++j) { os << "\t\t<VariableModification name=\"" << writeXMLEscape(params[i].variable_modifications[j]) << "\" />\n"; //Add MetaInfo, when modifications has it (Andreas) } writeUserParam_("UserParam", os, params[i], 4); os << "\t</SearchParameters>\n"; } //empty search parameters if (params.empty()) { os << "<SearchParameters charges=\"+0, +0\" id=\"ID_1\" db_version=\"0\" mass_type=\"monoisotopic\" peak_mass_tolerance=\"0.0\" precursor_peak_tolerance=\"0.0\" db=\"Unknown\"/>\n"; } UInt prot_count = 0; map<String, UInt> accession_to_id; //Identifiers of protein identifications that are already written vector<String> done_identifiers; //write ProteinIdentification Runs for (Size i = 0; i < protein_ids.size(); ++i) { done_identifiers.push_back(protein_ids[i].getIdentifier()); os << "\t<IdentificationRun "; os << "date=\"" << protein_ids[i].getDateTime().getDate() << "T" << protein_ids[i].getDateTime().getTime() << "\" "; os << "search_engine=\"" << writeXMLEscape(protein_ids[i].getSearchEngine()) << "\" "; os << "search_engine_version=\"" << writeXMLEscape(protein_ids[i].getSearchEngineVersion()) << "\" "; //identifier for (Size j = 0; j != params.size(); ++j) { if (params[j] == protein_ids[i].getSearchParameters()) { os << "search_parameters_ref=\"SP_" << j << "\" "; break; } } os << ">\n"; os << "\t\t<ProteinIdentification "; os << "score_type=\"" << writeXMLEscape(protein_ids[i].getScoreType()) << "\" "; if (protein_ids[i].isHigherScoreBetter()) { os << "higher_score_better=\"true\" "; } else { os << "higher_score_better=\"false\" "; } os << "significance_threshold=\"" << protein_ids[i].getSignificanceThreshold() << "\" >\n"; //write protein hits for (Size j = 0; j < protein_ids[i].getHits().size(); ++j) { os << "\t\t\t<ProteinHit "; os << "id=\"PH_" << prot_count << "\" "; accession_to_id[protein_ids[i].getHits()[j].getAccession()] = prot_count++; os << "accession=\"" << writeXMLEscape(protein_ids[i].getHits()[j].getAccession()) << "\" "; os << "score=\"" << protein_ids[i].getHits()[j].getScore() << "\" "; // os << "coverage=\"" << protein_ids[i].getHits()[j].getCoverage() // << "\" "; os << "sequence=\"" << writeXMLEscape(protein_ids[i].getHits()[j].getSequence()) << "\" >\n"; writeUserParam_("UserParam", os, protein_ids[i].getHits()[j], 4); os << "\t\t\t</ProteinHit>\n"; } // add ProteinGroup info to metavalues (hack) MetaInfoInterface meta = protein_ids[i]; addProteinGroups_(meta, protein_ids[i].getProteinGroups(), "protein_group", accession_to_id); addProteinGroups_(meta, protein_ids[i].getIndistinguishableProteins(), "indistinguishable_proteins", accession_to_id); writeUserParam_("UserParam", os, meta, 3); os << "\t\t</ProteinIdentification>\n"; //write PeptideIdentifications Size count_wrong_id(0); Size count_empty(0); for (Size l = 0; l < peptide_ids.size(); ++l) { if (peptide_ids[l].getIdentifier() != protein_ids[i].getIdentifier()) { ++count_wrong_id; continue; } else if (peptide_ids[l].getHits().size() == 0) { ++count_empty; continue; } os << "\t\t<PeptideIdentification "; os << "score_type=\"" << writeXMLEscape(peptide_ids[l].getScoreType()) << "\" "; if (peptide_ids[l].isHigherScoreBetter()) { os << "higher_score_better=\"true\" "; } else { os << "higher_score_better=\"false\" "; } os << "significance_threshold=\"" << peptide_ids[l].getSignificanceThreshold() << "\" "; // mz if (peptide_ids[l].hasMZ()) { os << "MZ=\"" << peptide_ids[l].getMZ() << "\" "; } // rt if (peptide_ids[l].hasRT()) { os << "RT=\"" << peptide_ids[l].getRT() << "\" "; } // spectrum_reference DataValue dv = peptide_ids[l].getMetaValue("spectrum_reference"); if (dv != DataValue::EMPTY) { os << "spectrum_reference=\"" << writeXMLEscape(dv.toString()) << "\" "; } os << ">\n"; // write peptide hits for (Size j = 0; j < peptide_ids[l].getHits().size(); ++j) { os << "\t\t\t<PeptideHit "; os << "score=\"" << precisionWrapper(peptide_ids[l].getHits()[j].getScore()) << "\" "; os << "sequence=\"" << peptide_ids[l].getHits()[j].getSequence() << "\" "; os << "charge=\"" << peptide_ids[l].getHits()[j].getCharge() << "\" "; if (peptide_ids[l].getHits()[j].getAABefore() != ' ') { os << "aa_before=\"" << writeXMLEscape(peptide_ids[l].getHits()[j].getAABefore()) << "\" "; } if (peptide_ids[l].getHits()[j].getAAAfter() != ' ') { os << "aa_after=\"" << writeXMLEscape(peptide_ids[l].getHits()[j].getAAAfter()) << "\" "; } if (peptide_ids[l].getHits()[j].getProteinAccessions().size() != 0) { String accs = ""; for (Size m = 0; m < peptide_ids[l].getHits()[j].getProteinAccessions().size(); ++m) { if (accs != "") { accs = accs + " "; } accs = accs + "PH_" + accession_to_id[peptide_ids[l].getHits()[j].getProteinAccessions()[m]]; } os << "protein_refs=\"" << accs << "\" "; } os << ">\n"; writeUserParam_("UserParam", os, peptide_ids[l].getHits()[j], 4); os << "\t\t\t</PeptideHit>\n"; } // do not write "spectrum_reference" since it is written as attribute already MetaInfoInterface tmp = peptide_ids[l]; tmp.removeMetaValue("spectrum_reference"); writeUserParam_("UserParam", os, tmp, 3); os << "\t\t</PeptideIdentification>\n"; } os << "\t</IdentificationRun>\n"; // on more than one protein Ids (=runs) there must be wrong mappings and the message would be useless. However, a single run should not have wrong mappings! if (count_wrong_id && protein_ids.size() == 1) LOG_WARN << "Omitted writing of " << count_wrong_id << " peptide identifications due to wrong protein mapping." << std::endl; if (count_empty) LOG_WARN << "Omitted writing of " << count_empty << " peptide identifications due to empty hits." << std::endl; } //empty protein ids parameters if (protein_ids.empty()) { os << "<IdentificationRun date=\"1900-01-01T01:01:01.0Z\" search_engine=\"Unknown\" search_parameters_ref=\"ID_1\" search_engine_version=\"0\"/>\n"; } for (Size i = 0; i < peptide_ids.size(); ++i) { if (find(done_identifiers.begin(), done_identifiers.end(), peptide_ids[i].getIdentifier()) == done_identifiers.end()) { warning(STORE, String("Omitting peptide identification because of missing ProteinIdentification with identifier '") + peptide_ids[i].getIdentifier() + "' while writing '" + filename + "'!"); } } //write footer os << "</IdXML>\n"; //close stream os.close(); //reset members prot_ids_ = 0; pep_ids_ = 0; last_meta_ = 0; parameters_.clear(); param_ = ProteinIdentification::SearchParameters(); id_ = ""; prot_id_ = ProteinIdentification(); pep_id_ = PeptideIdentification(); prot_hit_ = ProteinHit(); pep_hit_ = PeptideHit(); proteinid_to_accession_.clear(); } void IdXMLFile::startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) { String tag = sm_.convert(qname); //START if (tag == "IdXML") { //check file version against schema version String file_version = ""; prot_id_in_run_ = false; optionalAttributeAsString_(file_version, attributes, "version"); if (file_version == "") file_version = "1.0"; //default version is 1.0 if (file_version.toDouble() > version_.toDouble()) { warning(LOAD, "The XML file (" + file_version + ") is newer than the parser (" + version_ + "). This might lead to undefined program behavior."); } //document id String document_id = ""; optionalAttributeAsString_(document_id, attributes, "id"); (*document_id_) = document_id; } //SEARCH PARAMETERS else if (tag == "SearchParameters") { //store id id_ = attributeAsString_(attributes, "id"); //reset parameters param_ = ProteinIdentification::SearchParameters(); //load parameters param_.db = attributeAsString_(attributes, "db"); param_.db_version = attributeAsString_(attributes, "db_version"); optionalAttributeAsString_(param_.taxonomy, attributes, "taxonomy"); param_.charges = attributeAsString_(attributes, "charges"); optionalAttributeAsUInt_(param_.missed_cleavages, attributes, "missed_cleavages"); param_.peak_mass_tolerance = attributeAsDouble_(attributes, "peak_mass_tolerance"); param_.precursor_tolerance = attributeAsDouble_(attributes, "precursor_peak_tolerance"); //mass type String mass_type = attributeAsString_(attributes, "mass_type"); if (mass_type == "monoisotopic") { param_.mass_type = ProteinIdentification::MONOISOTOPIC; } else if (mass_type == "average") { param_.mass_type = ProteinIdentification::AVERAGE; } //enzyme String enzyme; optionalAttributeAsString_(enzyme, attributes, "enzyme"); if (enzyme == "trypsin") { param_.enzyme = ProteinIdentification::TRYPSIN; } else if (enzyme == "pepsin_a") { param_.enzyme = ProteinIdentification::PEPSIN_A; } else if (enzyme == "protease_k") { param_.enzyme = ProteinIdentification::PROTEASE_K; } else if (enzyme == "chymotrypsin") { param_.enzyme = ProteinIdentification::CHYMOTRYPSIN; } else if (enzyme == "no_enzyme") { param_.enzyme = ProteinIdentification::NO_ENZYME; } else if (enzyme == "unknown_enzyme") { param_.enzyme = ProteinIdentification::UNKNOWN_ENZYME; } last_meta_ = &param_; } else if (tag == "FixedModification") { param_.fixed_modifications.push_back(attributeAsString_(attributes, "name")); //change this line as soon as there is a MetaInfoInterface for modifications (Andreas) last_meta_ = 0; } else if (tag == "VariableModification") { param_.variable_modifications.push_back(attributeAsString_(attributes, "name")); //change this line as soon as there is a MetaInfoInterface for modifications (Andreas) last_meta_ = 0; } // RUN else if (tag == "IdentificationRun") { pep_id_ = PeptideIdentification(); prot_id_ = ProteinIdentification(); prot_id_.setSearchEngine(attributeAsString_(attributes, "search_engine")); prot_id_.setSearchEngineVersion(attributeAsString_(attributes, "search_engine_version")); //search parameters String ref = attributeAsString_(attributes, "search_parameters_ref"); if (parameters_.find(ref) == parameters_.end()) { fatalError(LOAD, String("Invalid search parameters reference '") + ref + "'"); } prot_id_.setSearchParameters(parameters_[ref]); //date prot_id_.setDateTime(DateTime::fromString(String(attributeAsString_(attributes, "date")).toQString(), "yyyy-MM-ddThh:mm:ss")); //set identifier prot_id_.setIdentifier(prot_id_.getSearchEngine() + '_' + attributeAsString_(attributes, "date")); } //PROTEINS else if (tag == "ProteinIdentification") { prot_id_.setScoreType(attributeAsString_(attributes, "score_type")); //optional significance threshold double tmp(0.0); optionalAttributeAsDouble_(tmp, attributes, "significance_threshold"); if (tmp != 0.0) { prot_id_.setSignificanceThreshold(tmp); } //score orientation prot_id_.setHigherScoreBetter(asBool_(attributeAsString_(attributes, "higher_score_better"))); last_meta_ = &prot_id_; } else if (tag == "ProteinHit") { prot_hit_ = ProteinHit(); String accession = attributeAsString_(attributes, "accession"); prot_hit_.setAccession(accession); prot_hit_.setScore(attributeAsDouble_(attributes, "score")); //sequence String tmp; optionalAttributeAsString_(tmp, attributes, "sequence"); prot_hit_.setSequence(tmp); last_meta_ = &prot_hit_; //insert id and accession to map proteinid_to_accession_[attributeAsString_(attributes, "id")] = accession; } //PEPTIDES else if (tag == "PeptideIdentification") { // check whether a prot id has been given, add "empty" one to list else if (!prot_id_in_run_) { prot_ids_->push_back(prot_id_); prot_id_in_run_ = true; // set to true, cause we have created one; will be reset for next run } //set identifier pep_id_.setIdentifier(prot_ids_->back().getIdentifier()); pep_id_.setScoreType(attributeAsString_(attributes, "score_type")); //optional significance threshold double tmp(0.0); optionalAttributeAsDouble_(tmp, attributes, "significance_threshold"); if (tmp != 0.0) { pep_id_.setSignificanceThreshold(tmp); } //score orientation pep_id_.setHigherScoreBetter(asBool_(attributeAsString_(attributes, "higher_score_better"))); //MZ double tmp2 = -numeric_limits<double>::max(); optionalAttributeAsDouble_(tmp2, attributes, "MZ"); if (tmp2 != -numeric_limits<double>::max()) { pep_id_.setMZ(tmp2); } //RT tmp2 = -numeric_limits<double>::max(); optionalAttributeAsDouble_(tmp2, attributes, "RT"); if (tmp2 != -numeric_limits<double>::max()) { pep_id_.setRT(tmp2); } Int tmp3 = -numeric_limits<Int>::max(); optionalAttributeAsInt_(tmp3, attributes, "spectrum_reference"); if (tmp3 != -numeric_limits<Int>::max()) { pep_id_.setMetaValue("spectrum_reference", tmp3); } last_meta_ = &pep_id_; } else if (tag == "PeptideHit") { pep_hit_ = PeptideHit(); pep_hit_.setCharge(attributeAsInt_(attributes, "charge")); pep_hit_.setScore(attributeAsDouble_(attributes, "score")); pep_hit_.setSequence(AASequence::fromString(String(attributeAsString_(attributes, "sequence")))); //aa_before String tmp; optionalAttributeAsString_(tmp, attributes, "aa_before"); if (!tmp.empty()) { pep_hit_.setAABefore(tmp[0]); } //aa_after tmp = ""; optionalAttributeAsString_(tmp, attributes, "aa_after"); if (!tmp.empty()) { pep_hit_.setAAAfter(tmp[0]); } //parse optional protein ids to determine accessions const XMLCh* refs = attributes.getValue(sm_.convert("protein_refs")); if (refs != 0) { String accession_string = sm_.convert(refs); accession_string.trim(); vector<String> accessions; accession_string.split(' ', accessions); if (accession_string != "" && accessions.empty()) { accessions.push_back(accession_string); } for (vector<String>::const_iterator it = accessions.begin(); it != accessions.end(); ++it) { map<String, String>::const_iterator it2 = proteinid_to_accession_.find(*it); if (it2 != proteinid_to_accession_.end()) { pep_hit_.addProteinAccession(it2->second); } else { fatalError(LOAD, String("Invalid protein reference '") + *it + "'"); } } } last_meta_ = &pep_hit_; } //USERPARAM else if (tag == "UserParam") { if (last_meta_ == 0) { fatalError(LOAD, "Unexpected tag 'UserParam'!"); } String name = attributeAsString_(attributes, "name"); String type = attributeAsString_(attributes, "type"); String value = attributeAsString_(attributes, "value"); if (type == "string") { last_meta_->setMetaValue(name, value); } else if (type == "float") { last_meta_->setMetaValue(name, value.toDouble()); } else if (type == "int") { last_meta_->setMetaValue(name, value.toInt()); } else { fatalError(LOAD, String("Invalid UserParam type '") + type + "' of parameter '" + name + "'"); } } } void IdXMLFile::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) { String tag = sm_.convert(qname); // START if (tag == "IdXML") { prot_id_in_run_ = false; } // SEARCH PARAMETERS else if (tag == "SearchParameters") { last_meta_ = 0; parameters_[id_] = param_; } else if (tag == "FixedModification") { last_meta_ = &param_; } else if (tag == "VariableModification") { last_meta_ = &param_; } // PROTEIN IDENTIFICATIONS else if (tag == "ProteinIdentification") { // post processing of ProteinGroups (hack) getProteinGroups_(prot_id_.getProteinGroups(), "protein_group"); getProteinGroups_(prot_id_.getIndistinguishableProteins(), "indistinguishable_proteins"); prot_ids_->push_back(prot_id_); prot_id_ = ProteinIdentification(); last_meta_ = 0; prot_id_in_run_ = true; } else if (tag == "IdentificationRun") { if (prot_ids_->size() == 0) prot_ids_->push_back(prot_id_); // add empty <ProteinIdentification> if there was none so far (thats where the IdentificationRun parameters are stored) prot_id_ = ProteinIdentification(); last_meta_ = 0; prot_id_in_run_ = false; } else if (tag == "ProteinHit") { prot_id_.insertHit(prot_hit_); last_meta_ = &prot_id_; } //PEPTIDES else if (tag == "PeptideIdentification") { pep_ids_->push_back(pep_id_); pep_id_ = PeptideIdentification(); last_meta_ = 0; } else if (tag == "PeptideHit") { pep_id_.insertHit(pep_hit_); last_meta_ = &pep_id_; } } void IdXMLFile::addProteinGroups_( MetaInfoInterface& meta, const vector<ProteinIdentification::ProteinGroup>& groups, const String& group_name, const map<String, UInt>& accession_to_id) { for (Size g = 0; g < groups.size(); ++g) { String name = group_name + "_" + String(g); if (meta.metaValueExists(name)) { warning(LOAD, String("Metavalue '") + name + "' already exists. Overwriting..."); } String accessions; for (StringList::const_iterator acc_it = groups[g].accessions.begin(); acc_it != groups[g].accessions.end(); ++acc_it) { if (acc_it != groups[g].accessions.begin()) accessions += ","; map<String, UInt>::const_iterator pos = accession_to_id.find(*acc_it); if (pos != accession_to_id.end()) { accessions += "PH_" + String(pos->second); } else { fatalError(LOAD, String("Invalid protein reference '") + *acc_it + "'"); } } String value = String(groups[g].probability) + "," + accessions; meta.setMetaValue(name, value); } } void IdXMLFile::getProteinGroups_(vector<ProteinIdentification::ProteinGroup>& groups, const String& group_name) { groups.clear(); Size g_id = 0; String current_meta = group_name + "_" + String(g_id); while (last_meta_->metaValueExists(current_meta)) { // convert to proper ProteinGroup ProteinIdentification::ProteinGroup g; StringList values; String(last_meta_->getMetaValue(current_meta)).split(',', values); if (values.size() < 2) { fatalError(LOAD, String("Invalid UserParam for ProteinGroups (not enough values)'")); } g.probability = values[0].toDouble(); for (Size i_ind = 1; i_ind < values.size(); ++i_ind) { g.accessions.push_back(proteinid_to_accession_[values[i_ind]]); } groups.push_back(g); last_meta_->removeMetaValue(current_meta); current_meta = group_name + "_" + String(++g_id); } } } // namespace OpenMS
35.326582
198
0.597212
liangoaix
441b00f8c3305aaf2d905c922a5aa42be9464bb5
6,510
cpp
C++
src/utils.cpp
imikejackson/bingocpp
6ba00a490c8cb46edebfd78f56b1604a76d668e9
[ "Apache-2.0" ]
13
2019-03-14T09:54:02.000Z
2021-09-26T14:01:30.000Z
src/utils.cpp
imikejackson/bingocpp
6ba00a490c8cb46edebfd78f56b1604a76d668e9
[ "Apache-2.0" ]
35
2019-08-29T19:12:05.000Z
2021-07-15T22:17:53.000Z
src/utils.cpp
imikejackson/bingocpp
6ba00a490c8cb46edebfd78f56b1604a76d668e9
[ "Apache-2.0" ]
9
2018-10-18T02:43:03.000Z
2021-09-02T22:08:39.000Z
/*! * \file utils.cc * * \author Ethan Adams * \date * * This file contains utility functions for doing and testing * sybolic regression problems in the bingo package */ #include <vector> #include <numeric> #include "BingoCpp/utils.h" namespace bingo { const int kPartialWindowSize = 7; const int kPartialEdgeSize = 3; const int kDerivativeOrder = 1; void set_break_points(const Eigen::ArrayXXd &x, std::vector<int> *break_points) { for (int i = 0; i < x.rows(); ++i) { if (std::isnan(x(i))) { break_points->push_back(i); } } break_points->push_back(x.rows()); } void update_return_values (int start, const Eigen::ArrayXXd &x_segment, const Eigen::ArrayXXd &time_deriv, Eigen::ArrayXXd *x_return, Eigen::ArrayXXd *time_deriv_return) { if (start == 0) { x_return->resize(x_segment.rows(), x_segment.cols()); *x_return << x_segment; time_deriv_return->resize(time_deriv.rows(), time_deriv.cols()); *time_deriv_return << time_deriv; } else { Eigen::ArrayXXd x_temp = *x_return; x_return->resize(x_return->rows() + x_segment.rows(), x_return->cols()); *x_return << x_temp, x_segment; Eigen::ArrayXXd deriv_temp = *time_deriv_return; time_deriv_return->resize(time_deriv_return->rows() + time_deriv.rows(), time_deriv_return->cols()); *time_deriv_return << deriv_temp, time_deriv; } } Eigen::ArrayXXd shave_edges_and_nan_from_array ( const Eigen::ArrayXXd &filtered_data) { return filtered_data.block(kPartialEdgeSize, 0, filtered_data.rows() - kPartialWindowSize, filtered_data.cols()); } InputAndDeriviative CalculatePartials(const Eigen::ArrayXXd &x) { std::vector<int> break_points; set_break_points(x, &break_points); int start = 0; int return_value_rows = (x.rows() - kPartialEdgeSize) * break_points.size(); Eigen::ArrayXXd x_return(return_value_rows, x.cols()); Eigen::ArrayXXd time_deriv_return(x_return.rows(), x_return.cols()); for (std::vector<int>::iterator break_point = break_points.begin(); break_point != break_points.end(); break_point ++) { Eigen::ArrayXXd x_segment = x.block(start, 0, *break_point - start, x.cols()); Eigen::ArrayXXd time_deriv(x_segment.rows(), x_segment.cols()); for (int col = 0; col < x_segment.cols(); col ++) { time_deriv.col(col) = SavitzkyGolay(x_segment.col(col), kPartialWindowSize, kPartialEdgeSize, kDerivativeOrder); } Eigen::ArrayXXd deriv_temp = shave_edges_and_nan_from_array(time_deriv); Eigen::ArrayXXd x_temp = shave_edges_and_nan_from_array(x_segment); update_return_values(start, x_temp, deriv_temp, &x_return, &time_deriv_return); start = *break_point + 1; } return std::make_pair(x_return, time_deriv_return); } double GramPoly(double eval_point, double num_points, double polynomial_order, double derivative_order) { double result = 0; if (polynomial_order > 0) { result = (4. * polynomial_order - 2.) / (polynomial_order * (2. * num_points - polynomial_order + 1.)) * (eval_point * GramPoly(eval_point, num_points, polynomial_order - 1., derivative_order) + derivative_order * GramPoly(eval_point, num_points, polynomial_order - 1., derivative_order - 1.)) - ((polynomial_order - 1.) * (2. * num_points + polynomial_order)) / (polynomial_order * (2. * num_points - polynomial_order + 1.)) * GramPoly(eval_point, num_points, polynomial_order - 2, derivative_order); } else if (polynomial_order == 0 && derivative_order == 0) { result = 1.; } else { result = 0.; } return result; } double GenFact(double a, double b) { int fact = 1; for (int i = a - b + 1; i < a + 1; ++i) { fact *= i; } return fact; } double GramWeight(double eval_point_start, double eval_point_end, double num_points, double ploynomial_order, double derivative_order) { double weight = 0; for (int i = 0; i < ploynomial_order + 1; ++i) { weight += (2. * i + 1.) * GenFact(2. * num_points, i) / GenFact(2. * num_points + i + 1, i + 1) * GramPoly(eval_point_start, num_points, i, 0) * GramPoly(eval_point_end, num_points, i, derivative_order); } return weight; } Eigen::ArrayXXd convolution(const Eigen::ArrayXXd &data_points, int half_filter_size, const Eigen::ArrayXXd &weights) { int data_points_center = 0; int w_ind = 0; int data_points_len = data_points.rows(); Eigen::ArrayXXd convolution(data_points_len, 1); for (int i = 0; i < data_points_len; ++i) { if (i < half_filter_size) { data_points_center = half_filter_size; w_ind = i; } else if (data_points_len - i <= half_filter_size) { data_points_center = data_points_len - half_filter_size - 1; w_ind = 2 * half_filter_size + 1 - (data_points_len - i); } else { data_points_center = i; w_ind = half_filter_size; } convolution(i) = 0; for (int j = half_filter_size * -1; j < half_filter_size + 1; ++j) { convolution(i) += data_points(data_points_center + j) * weights(j + half_filter_size, w_ind); } } return convolution; } Eigen::ArrayXXd SavitzkyGolay(Eigen::ArrayXXd y, int window_size, int polynomial_order, int derivative_order) { int m = (window_size - 1) / 2; Eigen::ArrayXXd weights(2 * m + 1, 2 * m + 1); for (int i = m * -1; i < m + 1; ++i) { for (int j = m * -1; j < m + 1; ++j) { weights(i + m, j + m) = GramWeight(i, j, m, polynomial_order, derivative_order); } } return convolution(y, m, weights); } } // namespace bingo
34.812834
84
0.57235
imikejackson
441b4b5e949c2f83acb085cd7d0de23fc52b0032
4,831
hpp
C++
src/xalanc/XSLT/ElemVariable.hpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
24
2015-07-29T22:49:17.000Z
2022-03-25T10:14:17.000Z
src/xalanc/XSLT/ElemVariable.hpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
14
2019-05-10T16:25:50.000Z
2021-11-24T18:04:47.000Z
src/xalanc/XSLT/ElemVariable.hpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
28
2015-04-20T15:50:51.000Z
2022-01-26T14:56:55.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. */ #if !defined(XALAN_ELEMVARIABLE_HEADER_GUARD) #define XALAN_ELEMVARIABLE_HEADER_GUARD // Base include file. Must be first. #include "XSLTDefinitions.hpp" // Base class header file. #include "ElemTemplateElement.hpp" #include <xalanc/XPath/XObject.hpp> #include <xalanc/XSLT/Constants.hpp> namespace XALAN_CPP_NAMESPACE { class XPath; class ElemVariable : public ElemTemplateElement { public: typedef ElemTemplateElement ParentType; /** * Construct an object corresponding to an "xsl:variable" element * * @param constructionContext context for construction of object * @param stylesheetTree stylesheet containing element * @param atts list of attributes for element * @param lineNumber line number in document * @param columnNumber column number in document */ ElemVariable( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const AttributeListType& atts, XalanFileLoc lineNumber, XalanFileLoc columnNumber); virtual ~ElemVariable(); /** * Determines if this is a top level variable. * * @return true if it is a top level variable */ bool isTopLevel() const { return m_isTopLevel; } // These methods are inherited from ElemTemplateElement ... virtual const XalanQName& getNameAttribute() const; virtual void addToStylesheet( StylesheetConstructionContext& constructionContext, Stylesheet& theStylesheet); virtual const XalanDOMString& getElementName() const; #if !defined(XALAN_RECURSIVE_STYLESHEET_EXECUTION) const ElemTemplateElement* startElement(StylesheetExecutionContext& executionContext) const; void endElement(StylesheetExecutionContext& executionContext) const; #else virtual void execute(StylesheetExecutionContext& executionContext) const; #endif const XObjectPtr getValue( StylesheetExecutionContext& executionContext, XalanNode* sourceNode) const; virtual void setParentNodeElem(ElemTemplateElement* theParent); virtual const XPath* getXPath(XalanSize_t index) const; protected: /** * Construct an object corresponding to an "xsl:variable" element * * @param constructionContext context for construction of object * @param stylesheetTree stylesheet containing element * @param atts list of attributes for element * @param lineNumber line number in document * @param columnNumber column number in document */ ElemVariable( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const AttributeListType& atts, XalanFileLoc lineNumber, XalanFileLoc columnNumber, int xslToken); /** * Do common initialization. * * @param constructionContext context for construction of object * @param stylesheetTree stylesheet containing element * @param atts list of attributes for element */ void init( StylesheetConstructionContext& constructionContext, Stylesheet& stylesheetTree, const AttributeListType& atts); const XalanQName* m_qname; private: // not implemented ElemVariable(const ElemVariable &); ElemVariable& operator=(const ElemVariable &); const XPath* m_selectPattern; bool m_isTopLevel; XObjectPtr m_value; XalanNode* m_varContext; }; } #endif // XALAN_ELEMVARIABLE_HEADER_GUARD
27.293785
75
0.64438
ulisesten
441baafe9de38c21838a96f15a14d248a133ce2f
289
cc
C++
atcoder/arc118/a.cc
kamal1316/competitive-programming
1443fb4bd1c92c2acff64ba2828abb21b067e6e0
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
atcoder/arc118/a.cc
diegordzr/competitive-programming
1443fb4bd1c92c2acff64ba2828abb21b067e6e0
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
atcoder/arc118/a.cc
diegordzr/competitive-programming
1443fb4bd1c92c2acff64ba2828abb21b067e6e0
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://atcoder.jp/contests/arc118/tasks/arc118_a #include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<ll>; int main() { cin.tie(0), ios::sync_with_stdio(0); ll t, n; cin >> t >> n; ll m = (n * 100 - 1) / t + 1; cout << m + n - 1 << '\n'; }
19.266667
52
0.567474
kamal1316
441ca79e12934443171f1c455f51c3b45f822afc
33,013
cpp
C++
src/solvers/flattening/bv_utils.cpp
mauguignard/cbmc
70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5
[ "BSD-4-Clause" ]
null
null
null
src/solvers/flattening/bv_utils.cpp
mauguignard/cbmc
70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5
[ "BSD-4-Clause" ]
2
2018-02-14T16:11:37.000Z
2018-02-23T18:12:27.000Z
src/solvers/flattening/bv_utils.cpp
mauguignard/cbmc
70cfdd5d7c62d47269bae2277ff89a9ce66ff0b5
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #include "bv_utils.h" #include <cassert> #include <util/arith_tools.h> bvt bv_utilst::build_constant(const mp_integer &n, std::size_t width) { std::string n_str=integer2binary(n, width); CHECK_RETURN(n_str.size() == width); bvt result; result.resize(width); for(std::size_t i=0; i<width; i++) result[i]=const_literal(n_str[width-i-1]=='1'); return result; } literalt bv_utilst::is_one(const bvt &bv) { PRECONDITION(!bv.empty()); bvt tmp; tmp=bv; tmp.erase(tmp.begin(), tmp.begin()+1); return prop.land(is_zero(tmp), bv[0]); } void bv_utilst::set_equal(const bvt &a, const bvt &b) { PRECONDITION(a.size() == b.size()); for(std::size_t i=0; i<a.size(); i++) prop.set_equal(a[i], b[i]); } bvt bv_utilst::extract(const bvt &a, std::size_t first, std::size_t last) { // preconditions PRECONDITION(first < a.size()); PRECONDITION(last < a.size()); PRECONDITION(first <= last); bvt result=a; result.resize(last+1); if(first!=0) result.erase(result.begin(), result.begin()+first); POSTCONDITION(result.size() == last - first + 1); return result; } bvt bv_utilst::extract_msb(const bvt &a, std::size_t n) { // preconditions PRECONDITION(n <= a.size()); bvt result=a; result.erase(result.begin(), result.begin()+(result.size()-n)); POSTCONDITION(result.size() == n); return result; } bvt bv_utilst::extract_lsb(const bvt &a, std::size_t n) { // preconditions PRECONDITION(n <= a.size()); bvt result=a; result.resize(n); return result; } bvt bv_utilst::concatenate(const bvt &a, const bvt &b) const { bvt result; result.resize(a.size()+b.size()); for(std::size_t i=0; i<a.size(); i++) result[i]=a[i]; for(std::size_t i=0; i<b.size(); i++) result[i+a.size()]=b[i]; return result; } /// If s is true, selects a otherwise selects b bvt bv_utilst::select(literalt s, const bvt &a, const bvt &b) { PRECONDITION(a.size() == b.size()); bvt result; result.resize(a.size()); for(std::size_t i=0; i<result.size(); i++) result[i]=prop.lselect(s, a[i], b[i]); return result; } bvt bv_utilst::extension( const bvt &bv, std::size_t new_size, representationt rep) { std::size_t old_size=bv.size(); PRECONDITION(old_size != 0); bvt result=bv; result.resize(new_size); literalt extend_with= (rep==representationt::SIGNED && !bv.empty())?bv[old_size-1]: const_literal(false); for(std::size_t i=old_size; i<new_size; i++) result[i]=extend_with; return result; } /// Generates the encoding of a full adder. The optimal encoding is the /// default. /// \par parameters: a, b, carry_in are the literals representing inputs /// \return return value is the literal for the sum, carry_out gets the output /// carry // The optimal encoding is the default as it gives a reduction in space // and small performance gains #define OPTIMAL_FULL_ADDER literalt bv_utilst::full_adder( const literalt a, const literalt b, const literalt carry_in, literalt &carry_out) { #ifdef OPTIMAL_FULL_ADDER if(prop.has_set_to() && prop.cnf_handled_well()) { literalt x; literalt y; int constantProp = -1; if(a.is_constant()) { x = b; y = carry_in; constantProp = (a.is_true()) ? 1 : 0; } else if(b.is_constant()) { x = a; y = carry_in; constantProp = (b.is_true()) ? 1 : 0; } else if(carry_in.is_constant()) { x = a; y = b; constantProp = (carry_in.is_true()) ? 1 : 0; } literalt sum; // Rely on prop.l* to do further constant propagation if(constantProp == 1) { // At least one input bit is 1 carry_out = prop.lor(x, y); sum = prop.lequal(x, y); } else if(constantProp == 0) { // At least one input bit is 0 carry_out = prop.land(x, y); sum = prop.lxor(x, y); } else { carry_out = prop.new_variable(); sum = prop.new_variable(); // Any two inputs 1 will set the carry_out to 1 prop.lcnf(!a, !b, carry_out); prop.lcnf(!a, !carry_in, carry_out); prop.lcnf(!b, !carry_in, carry_out); // Any two inputs 0 will set the carry_out to 0 prop.lcnf(a, b, !carry_out); prop.lcnf(a, carry_in, !carry_out); prop.lcnf(b, carry_in, !carry_out); // If both carry out and sum are 1 then all inputs are 1 prop.lcnf(a, !sum, !carry_out); prop.lcnf(b, !sum, !carry_out); prop.lcnf(carry_in, !sum, !carry_out); // If both carry out and sum are 0 then all inputs are 0 prop.lcnf(!a, sum, carry_out); prop.lcnf(!b, sum, carry_out); prop.lcnf(!carry_in, sum, carry_out); // If all of the inputs are 1 or all are 0 it sets the sum prop.lcnf(!a, !b, !carry_in, sum); prop.lcnf(a, b, carry_in, !sum); } return sum; } else // NOLINT(readability/braces) #endif // OPTIMAL_FULL_ADDER { // trivial encoding carry_out=carry(a, b, carry_in); return prop.lxor(prop.lxor(a, b), carry_in); } } // Daniel's carry optimisation #define COMPACT_CARRY literalt bv_utilst::carry(literalt a, literalt b, literalt c) { #ifdef COMPACT_CARRY if(prop.has_set_to() && prop.cnf_handled_well()) { // propagation possible? const auto const_count = a.is_constant() + b.is_constant() + c.is_constant(); // propagation is possible if two or three inputs are constant if(const_count>=2) return prop.lor(prop.lor( prop.land(a, b), prop.land(a, c)), prop.land(b, c)); // it's also possible if two of a,b,c are the same if(a==b) return a; else if(a==c) return a; else if(b==c) return b; // the below yields fewer clauses and variables, // but doesn't propagate anything at all bvt clause; literalt x=prop.new_variable(); /* carry_correct: LEMMA ( a OR b OR NOT x) AND ( a OR NOT b OR c OR NOT x) AND ( a OR NOT b OR NOT c OR x) AND (NOT a OR b OR c OR NOT x) AND (NOT a OR b OR NOT c OR x) AND (NOT a OR NOT b OR x) IFF (x=((a AND b) OR (a AND c) OR (b AND c))); */ prop.lcnf(a, b, !x); prop.lcnf(a, !b, c, !x); prop.lcnf(a, !b, !c, x); prop.lcnf(!a, b, c, !x); prop.lcnf(!a, b, !c, x); prop.lcnf(!a, !b, x); return x; } else #endif // COMPACT_CARRY { // trivial encoding bvt tmp; tmp.push_back(prop.land(a, b)); tmp.push_back(prop.land(a, c)); tmp.push_back(prop.land(b, c)); return prop.lor(tmp); } } void bv_utilst::adder( bvt &sum, const bvt &op, literalt carry_in, literalt &carry_out) { PRECONDITION(sum.size() == op.size()); carry_out=carry_in; for(std::size_t i=0; i<sum.size(); i++) { sum[i] = full_adder(sum[i], op[i], carry_out, carry_out); } } literalt bv_utilst::carry_out( const bvt &op0, const bvt &op1, literalt carry_in) { PRECONDITION(op0.size() == op1.size()); literalt carry_out=carry_in; for(std::size_t i=0; i<op0.size(); i++) carry_out=carry(op0[i], op1[i], carry_out); return carry_out; } bvt bv_utilst::add_sub_no_overflow( const bvt &op0, const bvt &op1, bool subtract, representationt rep) { bvt sum=op0; adder_no_overflow(sum, op1, subtract, rep); return sum; } bvt bv_utilst::add_sub(const bvt &op0, const bvt &op1, bool subtract) { PRECONDITION(op0.size() == op1.size()); literalt carry_in=const_literal(subtract); literalt carry_out; bvt result=op0; bvt tmp_op1=subtract?inverted(op1):op1; adder(result, tmp_op1, carry_in, carry_out); return result; } bvt bv_utilst::add_sub(const bvt &op0, const bvt &op1, literalt subtract) { const bvt op1_sign_applied= select(subtract, inverted(op1), op1); bvt result=op0; literalt carry_out; adder(result, op1_sign_applied, subtract, carry_out); return result; } literalt bv_utilst::overflow_add( const bvt &op0, const bvt &op1, representationt rep) { if(rep==representationt::SIGNED) { // An overflow occurs if the signs of the two operands are the same // and the sign of the sum is the opposite. literalt old_sign=op0[op0.size()-1]; literalt sign_the_same=prop.lequal(op0[op0.size()-1], op1[op1.size()-1]); bvt result=add(op0, op1); return prop.land(sign_the_same, prop.lxor(result[result.size()-1], old_sign)); } else if(rep==representationt::UNSIGNED) { // overflow is simply carry-out return carry_out(op0, op1, const_literal(false)); } else UNREACHABLE; } literalt bv_utilst::overflow_sub( const bvt &op0, const bvt &op1, representationt rep) { if(rep==representationt::SIGNED) { // We special-case x-INT_MIN, which is >=0 if // x is negative, always representable, and // thus not an overflow. literalt op1_is_int_min=is_int_min(op1); literalt op0_is_negative=op0[op0.size()-1]; return prop.lselect(op1_is_int_min, !op0_is_negative, overflow_add(op0, negate(op1), representationt::SIGNED)); } else if(rep==representationt::UNSIGNED) { // overflow is simply _negated_ carry-out return !carry_out(op0, inverted(op1), const_literal(true)); } else UNREACHABLE; } void bv_utilst::adder_no_overflow( bvt &sum, const bvt &op, bool subtract, representationt rep) { const bvt tmp_op=subtract?inverted(op):op; if(rep==representationt::SIGNED) { // an overflow occurs if the signs of the two operands are the same // and the sign of the sum is the opposite literalt old_sign=sum[sum.size()-1]; literalt sign_the_same= prop.lequal(sum[sum.size()-1], tmp_op[tmp_op.size()-1]); literalt carry; adder(sum, tmp_op, const_literal(subtract), carry); // result of addition in sum prop.l_set_to_false( prop.land(sign_the_same, prop.lxor(sum[sum.size()-1], old_sign))); } else { INVARIANT( rep == representationt::UNSIGNED, "representation has either value signed or unsigned"); literalt carry_out; adder(sum, tmp_op, const_literal(subtract), carry_out); prop.l_set_to(carry_out, subtract); } } void bv_utilst::adder_no_overflow(bvt &sum, const bvt &op) { literalt carry_out=const_literal(false); adder(sum, op, carry_out, carry_out); prop.l_set_to_false(carry_out); // enforce no overflow } bvt bv_utilst::shift(const bvt &op, const shiftt s, const bvt &dist) { std::size_t d=1, width=op.size(); bvt result=op; for(std::size_t stage=0; stage<dist.size(); stage++) { if(dist[stage]!=const_literal(false)) { bvt tmp=shift(result, s, d); for(std::size_t i=0; i<width; i++) result[i]=prop.lselect(dist[stage], tmp[i], result[i]); } d=d<<1; } return result; } bvt bv_utilst::shift(const bvt &src, const shiftt s, std::size_t dist) { bvt result; result.resize(src.size()); // 'dist' is user-controlled, and thus arbitary. // We thus must guard against the case in which i+dist overflows. // We do so by considering the case dist>=src.size(). for(std::size_t i=0; i<src.size(); i++) { literalt l; switch(s) { case shiftt::SHIFT_LEFT: // no underflow on i-dist because of condition dist<=i l=(dist<=i?src[i-dist]:const_literal(false)); break; case shiftt::SHIFT_ARIGHT: // src.size()-i won't underflow as i<src.size() // Then, if dist<src.size()-i, then i+dist<src.size() l=(dist<src.size()-i?src[i+dist]:src[src.size()-1]); // sign bit break; case shiftt::SHIFT_LRIGHT: // src.size()-i won't underflow as i<src.size() // Then, if dist<src.size()-i, then i+dist<src.size() l=(dist<src.size()-i?src[i+dist]:const_literal(false)); break; case shiftt::ROTATE_LEFT: // prevent overflows by using dist%src.size() l=src[(src.size()+i-(dist%src.size()))%src.size()]; break; case shiftt::ROTATE_RIGHT: // prevent overflows by using dist%src.size() l=src[(i+(dist%src.size()))%src.size()]; break; default: UNREACHABLE; } result[i]=l; } return result; } bvt bv_utilst::negate(const bvt &bv) { bvt result=inverted(bv); literalt carry_out; incrementer(result, const_literal(true), carry_out); return result; } bvt bv_utilst::negate_no_overflow(const bvt &bv) { prop.l_set_to_false(overflow_negate(bv)); return negate(bv); } literalt bv_utilst::overflow_negate(const bvt &bv) { // a overflow on unary- can only happen with the smallest // representable number 100....0 bvt zeros(bv); zeros.erase(--zeros.end()); return prop.land(bv[bv.size()-1], !prop.lor(zeros)); } void bv_utilst::incrementer( bvt &bv, literalt carry_in, literalt &carry_out) { carry_out=carry_in; Forall_literals(it, bv) { literalt new_carry=prop.land(carry_out, *it); *it=prop.lxor(*it, carry_out); carry_out=new_carry; } } bvt bv_utilst::incrementer(const bvt &bv, literalt carry_in) { bvt result=bv; literalt carry_out; incrementer(result, carry_in, carry_out); return result; } bvt bv_utilst::inverted(const bvt &bv) { bvt result=bv; Forall_literals(it, result) *it=!*it; return result; } bvt bv_utilst::wallace_tree(const std::vector<bvt> &pps) { PRECONDITION(!pps.empty()); if(pps.size()==1) return pps.front(); else if(pps.size()==2) return add(pps[0], pps[1]); else { std::vector<bvt> new_pps; std::size_t no_full_adders=pps.size()/3; // add groups of three partial products using CSA for(std::size_t i=0; i<no_full_adders; i++) { const bvt &a=pps[i*3+0], &b=pps[i*3+1], &c=pps[i*3+2]; INVARIANT(a.size() == b.size(), "groups should be of equal size"); INVARIANT(a.size() == c.size(), "groups should be of equal size"); bvt s(a.size()), t(a.size()); for(std::size_t bit=0; bit<a.size(); bit++) { // \todo reformulate using full_adder s[bit]=prop.lxor(a[bit], prop.lxor(b[bit], c[bit])); t[bit]=(bit==0)?const_literal(false): carry(a[bit-1], b[bit-1], c[bit-1]); } new_pps.push_back(s); new_pps.push_back(t); } // pass onwards up to two remaining partial products for(std::size_t i=no_full_adders*3; i<pps.size(); i++) new_pps.push_back(pps[i]); POSTCONDITION(new_pps.size() < pps.size()); return wallace_tree(new_pps); } } bvt bv_utilst::unsigned_multiplier(const bvt &_op0, const bvt &_op1) { #if 1 bvt op0=_op0, op1=_op1; if(is_constant(op1)) std::swap(op0, op1); bvt product; product.resize(op0.size()); for(std::size_t i=0; i<product.size(); i++) product[i]=const_literal(false); for(std::size_t sum=0; sum<op0.size(); sum++) if(op0[sum]!=const_literal(false)) { bvt tmpop; tmpop.reserve(op0.size()); for(std::size_t idx=0; idx<sum; idx++) tmpop.push_back(const_literal(false)); for(std::size_t idx=sum; idx<op0.size(); idx++) tmpop.push_back(prop.land(op1[idx-sum], op0[sum])); product=add(product, tmpop); } return product; #else // Wallace tree multiplier. This is disabled, as runtimes have // been observed to go up by 5%-10%, and on some models even by 20%. // build the usual quadratic number of partial products bvt op0=_op0, op1=_op1; if(is_constant(op1)) std::swap(op0, op1); std::vector<bvt> pps; pps.reserve(op0.size()); for(std::size_t bit=0; bit<op0.size(); bit++) if(op0[bit]!=const_literal(false)) { bvt pp; pp.reserve(op0.size()); // zeros according to weight for(std::size_t idx=0; idx<bit; idx++) pp.push_back(const_literal(false)); for(std::size_t idx=bit; idx<op0.size(); idx++) pp.push_back(prop.land(op1[idx-bit], op0[bit])); pps.push_back(pp); } if(pps.empty()) return zeros(op0.size()); else return wallace_tree(pps); #endif } bvt bv_utilst::unsigned_multiplier_no_overflow( const bvt &op0, const bvt &op1) { bvt _op0=op0, _op1=op1; PRECONDITION(_op0.size() == _op1.size()); if(is_constant(_op1)) _op0.swap(_op1); bvt product; product.resize(_op0.size()); for(std::size_t i=0; i<product.size(); i++) product[i]=const_literal(false); for(std::size_t sum=0; sum<op0.size(); sum++) if(op0[sum]!=const_literal(false)) { bvt tmpop; tmpop.reserve(product.size()); for(std::size_t idx=0; idx<sum; idx++) tmpop.push_back(const_literal(false)); for(std::size_t idx=sum; idx<product.size(); idx++) tmpop.push_back(prop.land(op1[idx-sum], op0[sum])); adder_no_overflow(product, tmpop); for(std::size_t idx=op1.size()-sum; idx<op1.size(); idx++) prop.l_set_to_false(prop.land(op1[idx], op0[sum])); } return product; } bvt bv_utilst::signed_multiplier(const bvt &op0, const bvt &op1) { if(op0.empty() || op1.empty()) return bvt(); literalt sign0=op0[op0.size()-1]; literalt sign1=op1[op1.size()-1]; bvt neg0=cond_negate(op0, sign0); bvt neg1=cond_negate(op1, sign1); bvt result=unsigned_multiplier(neg0, neg1); literalt result_sign=prop.lxor(sign0, sign1); return cond_negate(result, result_sign); } bvt bv_utilst::cond_negate(const bvt &bv, const literalt cond) { bvt neg_bv=negate(bv); bvt result; result.resize(bv.size()); for(std::size_t i=0; i<bv.size(); i++) result[i]=prop.lselect(cond, neg_bv[i], bv[i]); return result; } bvt bv_utilst::absolute_value(const bvt &bv) { PRECONDITION(!bv.empty()); return cond_negate(bv, bv[bv.size()-1]); } bvt bv_utilst::cond_negate_no_overflow(const bvt &bv, literalt cond) { prop.l_set_to_true(prop.limplies(cond, !overflow_negate(bv))); return cond_negate(bv, cond); } bvt bv_utilst::signed_multiplier_no_overflow( const bvt &op0, const bvt &op1) { if(op0.empty() || op1.empty()) return bvt(); literalt sign0=op0[op0.size()-1]; literalt sign1=op1[op1.size()-1]; bvt neg0=cond_negate_no_overflow(op0, sign0); bvt neg1=cond_negate_no_overflow(op1, sign1); bvt result=unsigned_multiplier_no_overflow(neg0, neg1); prop.l_set_to_false(result[result.size() - 1]); literalt result_sign=prop.lxor(sign0, sign1); return cond_negate_no_overflow(result, result_sign); } bvt bv_utilst::multiplier( const bvt &op0, const bvt &op1, representationt rep) { switch(rep) { case representationt::SIGNED: return signed_multiplier(op0, op1); case representationt::UNSIGNED: return unsigned_multiplier(op0, op1); } UNREACHABLE; } bvt bv_utilst::multiplier_no_overflow( const bvt &op0, const bvt &op1, representationt rep) { switch(rep) { case representationt::SIGNED: return signed_multiplier_no_overflow(op0, op1); case representationt::UNSIGNED: return unsigned_multiplier_no_overflow(op0, op1); } UNREACHABLE; } void bv_utilst::signed_divider( const bvt &op0, const bvt &op1, bvt &res, bvt &rem) { if(op0.empty() || op1.empty()) return; bvt _op0(op0), _op1(op1); literalt sign_0=_op0[_op0.size()-1]; literalt sign_1=_op1[_op1.size()-1]; bvt neg_0=negate(_op0), neg_1=negate(_op1); for(std::size_t i=0; i<_op0.size(); i++) _op0[i]=(prop.lselect(sign_0, neg_0[i], _op0[i])); for(std::size_t i=0; i<_op1.size(); i++) _op1[i]=(prop.lselect(sign_1, neg_1[i], _op1[i])); unsigned_divider(_op0, _op1, res, rem); bvt neg_res=negate(res), neg_rem=negate(rem); literalt result_sign=prop.lxor(sign_0, sign_1); for(std::size_t i=0; i<res.size(); i++) res[i]=prop.lselect(result_sign, neg_res[i], res[i]); for(std::size_t i=0; i<res.size(); i++) rem[i]=prop.lselect(sign_0, neg_rem[i], rem[i]); } void bv_utilst::divider( const bvt &op0, const bvt &op1, bvt &result, bvt &remainer, representationt rep) { PRECONDITION(prop.has_set_to()); switch(rep) { case representationt::SIGNED: signed_divider(op0, op1, result, remainer); break; case representationt::UNSIGNED: unsigned_divider(op0, op1, result, remainer); break; } } void bv_utilst::unsigned_divider( const bvt &op0, const bvt &op1, bvt &res, bvt &rem) { std::size_t width=op0.size(); // check if we divide by a power of two #if 0 { std::size_t one_count=0, non_const_count=0, one_pos=0; for(std::size_t i=0; i<op1.size(); i++) { literalt l=op1[i]; if(l.is_true()) { one_count++; one_pos=i; } else if(!l.is_false()) non_const_count++; } if(non_const_count==0 && one_count==1 && one_pos!=0) { // it is a power of two! res=shift(op0, LRIGHT, one_pos); // remainder is just a mask rem=op0; for(std::size_t i=one_pos; i<rem.size(); i++) rem[i]=const_literal(false); return; } } #endif // Division by zero test. // Note that we produce a non-deterministic result in // case of division by zero. SMT-LIB now says the following: // bvudiv returns a vector of all 1s if the second operand is 0 // bvurem returns its first operand if the second operand is 0 literalt is_not_zero=prop.lor(op1); // free variables for result of division res.resize(width); rem.resize(width); for(std::size_t i=0; i<width; i++) { res[i]=prop.new_variable(); rem[i]=prop.new_variable(); } // add implications bvt product= unsigned_multiplier_no_overflow(res, op1); // res*op1 + rem = op0 bvt sum=product; adder_no_overflow(sum, rem); literalt is_equal=equal(sum, op0); prop.l_set_to_true(prop.limplies(is_not_zero, is_equal)); // op1!=0 => rem < op1 prop.l_set_to_true( prop.limplies( is_not_zero, lt_or_le(false, rem, op1, representationt::UNSIGNED))); // op1!=0 => res <= op0 prop.l_set_to_true( prop.limplies( is_not_zero, lt_or_le(true, res, op0, representationt::UNSIGNED))); } #ifdef COMPACT_EQUAL_CONST // TODO : use for lt_or_le as well /// The equal_const optimisation will be used on this bit-vector. /// \par parameters: A bit-vector of a variable that is to be registered. /// \return None. void bv_utilst::equal_const_register(const bvt &var) { PRECONDITION(!is_constant(var)); equal_const_registered.insert(var); return; } /// The obvious recursive comparison, the interesting thing is that it is cached /// so the literals are shared between constants. /// \param Bit:vectors for a variable and a const to compare, note that /// to avoid significant amounts of copying these are mutable and consumed. /// \return The literal that is true if and only if all the bits in var and /// const are equal. literalt bv_utilst::equal_const_rec(bvt &var, bvt &constant) { std::size_t size = var.size(); PRECONDITION(size != 0); PRECONDITION(size == constant.size()); PRECONDITION(is_constant(constant)); if(size == 1) { literalt comp = prop.lequal(var[size - 1], constant[size - 1]); var.pop_back(); constant.pop_back(); return comp; } else { var_constant_pairt index(var, constant); equal_const_cachet::iterator entry = equal_const_cache.find(index); if(entry != equal_const_cache.end()) { return entry->second; } else { literalt comp = prop.lequal(var[size - 1], constant[size - 1]); var.pop_back(); constant.pop_back(); literalt rec = equal_const_rec(var, constant); literalt compare = prop.land(rec, comp); equal_const_cache.insert( std::pair<var_constant_pairt, literalt>(index, compare)); return compare; } } } /// An experimental encoding, aimed primarily at variable position access to /// constant arrays. These generate a lot of comparisons of the form var = /// small_const . It will introduce some additional literals and for variables /// that have only a few comparisons with constants this may result in a net /// increase in formula size. It is hoped that a 'sufficently advanced /// preprocessor' will remove these. /// \param Bit:vectors for a variable and a const to compare. /// \return The literal that is true if and only if they are equal. literalt bv_utilst::equal_const(const bvt &var, const bvt &constant) { std::size_t size = constant.size(); PRECONDITION(var.size() == size); PRECONDITION(!is_constant(var)); PRECONDITION(is_constant(constant)); PRECONDITION(size >= 2); // These get modified : be careful! bvt var_upper; bvt var_lower; bvt constant_upper; bvt constant_lower; /* Split the constant based on a change in parity * This is based on the observation that most constants are small, * so combinations of the lower bits are heavily used but the upper * bits are almost always either all 0 or all 1. */ literalt top_bit = constant[size - 1]; std::size_t split = size - 1; var_upper.push_back(var[size - 1]); constant_upper.push_back(constant[size - 1]); for(split = size - 2; split != 0; --split) { if(constant[split] != top_bit) { break; } else { var_upper.push_back(var[split]); constant_upper.push_back(constant[split]); } } for(std::size_t i = 0; i <= split; ++i) { var_lower.push_back(var[i]); constant_lower.push_back(constant[i]); } // Check we have split the array correctly INVARIANT( var_upper.size() + var_lower.size() == size, "lower size plus upper size should equal the total size"); INVARIANT( constant_upper.size() + constant_lower.size() == size, "lower size plus upper size should equal the total size"); literalt top_comparison = equal_const_rec(var_upper, constant_upper); literalt bottom_comparison = equal_const_rec(var_lower, constant_lower); return prop.land(top_comparison, bottom_comparison); } #endif /// Bit-blasting ID_equal and use in other encodings. /// \param op0: Lhs bitvector to compare /// \param op1: Rhs bitvector to compare /// \return The literal that is true if and only if they are equal. literalt bv_utilst::equal(const bvt &op0, const bvt &op1) { PRECONDITION(op0.size() == op1.size()); #ifdef COMPACT_EQUAL_CONST // simplify_expr should put the constant on the right // but bit-level simplification may result in the other cases if(is_constant(op0) && !is_constant(op1) && op0.size() > 2 && equal_const_registered.find(op1) != equal_const_registered.end()) return equal_const(op1, op0); else if(!is_constant(op0) && is_constant(op1) && op0.size() > 2 && equal_const_registered.find(op0) != equal_const_registered.end()) return equal_const(op0, op1); #endif bvt equal_bv; equal_bv.resize(op0.size()); for(std::size_t i=0; i<op0.size(); i++) equal_bv[i]=prop.lequal(op0[i], op1[i]); return prop.land(equal_bv); } /// To provide a bitwise model of < or <=. /// \par parameters: bvts for each input and whether they are signed and whether /// a model of < or <= is required. /// \return A literalt that models the value of the comparison. /* Some clauses are not needed for correctness but they remove models (effectively setting "don't care" bits) and so may be worth including.*/ // #define INCLUDE_REDUNDANT_CLAUSES // Saves space but slows the solver // There is a variant that uses the xor as an auxiliary that should improve both // #define COMPACT_LT_OR_LE literalt bv_utilst::lt_or_le( bool or_equal, const bvt &bv0, const bvt &bv1, representationt rep) { PRECONDITION(bv0.size() == bv1.size()); literalt top0=bv0[bv0.size()-1], top1=bv1[bv1.size()-1]; #ifdef COMPACT_LT_OR_LE if(prop.has_set_to() && prop.cnf_handled_well()) { bvt compareBelow; // 1 if a compare is needed below this bit literalt result; size_t start; size_t i; compareBelow.resize(bv0.size()); Forall_literals(it, compareBelow) { (*it) = prop.new_variable(); } result = prop.new_variable(); if(rep==SIGNED) { INVARIANT( bv0.size() >= 2, "signed bitvectors should have at least two bits"); start = compareBelow.size() - 2; literalt firstComp=compareBelow[start]; // When comparing signs we are comparing the top bit #ifdef INCLUDE_REDUNDANT_CLAUSES prop.l_set_to_true(compareBelow[start + 1]) #endif // Four cases... prop.lcnf(top0, top1, firstComp); // + + compare needed prop.lcnf(top0, !top1, !result); // + - result false and no compare needed prop.lcnf(!top0, top1, result); // - + result true and no compare needed prop.lcnf(!top0, !top1, firstComp); // - - negated compare needed #ifdef INCLUDE_REDUNDANT_CLAUSES prop.lcnf(top0, !top1, !firstComp); prop.lcnf(!top0, top1, !firstComp); #endif } else { // Unsigned is much easier start = compareBelow.size() - 1; prop.l_set_to_true(compareBelow[start]); } // Determine the output // \forall i . cb[i] & -a[i] & b[i] => result // \forall i . cb[i] & a[i] & -b[i] => -result i = start; do { prop.lcnf(!compareBelow[i], bv0[i], !bv1[i], result); prop.lcnf(!compareBelow[i], !bv0[i], bv1[i], !result); } while(i-- != 0); // Chain the comparison bit // \forall i != 0 . cb[i] & a[i] & b[i] => cb[i-1] // \forall i != 0 . cb[i] & -a[i] & -b[i] => cb[i-1] for(i = start; i > 0; i--) { prop.lcnf(!compareBelow[i], !bv0[i], !bv1[i], compareBelow[i-1]); prop.lcnf(!compareBelow[i], bv0[i], bv1[i], compareBelow[i-1]); } #ifdef INCLUDE_REDUNDANT_CLAUSES // Optional zeroing of the comparison bit when not needed // \forall i != 0 . -c[i] => -c[i-1] // \forall i != 0 . c[i] & -a[i] & b[i] => -c[i-1] // \forall i != 0 . c[i] & a[i] & -b[i] => -c[i-1] for(i = start; i > 0; i--) { prop.lcnf(compareBelow[i], !compareBelow[i-1]); prop.lcnf(!compareBelow[i], bv0[i], !bv1[i], !compareBelow[i-1]); prop.lcnf(!compareBelow[i], !bv0[i], bv1[i], !compareBelow[i-1]); } #endif // The 'base case' of the induction is the case when they are equal prop.lcnf(!compareBelow[0], !bv0[0], !bv1[0], (or_equal)?result:!result); prop.lcnf(!compareBelow[0], bv0[0], bv1[0], (or_equal)?result:!result); return result; } else #endif { literalt carry= carry_out(bv0, inverted(bv1), const_literal(true)); literalt result; if(rep==representationt::SIGNED) result=prop.lxor(prop.lequal(top0, top1), carry); else { INVARIANT( rep == representationt::UNSIGNED, "representation has either value signed or unsigned"); result = !carry; } if(or_equal) result=prop.lor(result, equal(bv0, bv1)); return result; } } literalt bv_utilst::unsigned_less_than( const bvt &op0, const bvt &op1) { #ifdef COMPACT_LT_OR_LE return lt_or_le(false, op0, op1, UNSIGNED); #else // A <= B iff there is an overflow on A-B return !carry_out(op0, inverted(op1), const_literal(true)); #endif } literalt bv_utilst::signed_less_than( const bvt &bv0, const bvt &bv1) { return lt_or_le(false, bv0, bv1, representationt::SIGNED); } literalt bv_utilst::rel( const bvt &bv0, irep_idt id, const bvt &bv1, representationt rep) { if(id==ID_equal) return equal(bv0, bv1); else if(id==ID_notequal) return !equal(bv0, bv1); else if(id==ID_le) return lt_or_le(true, bv0, bv1, rep); else if(id==ID_lt) return lt_or_le(false, bv0, bv1, rep); else if(id==ID_ge) return lt_or_le(true, bv1, bv0, rep); // swapped else if(id==ID_gt) return lt_or_le(false, bv1, bv0, rep); // swapped else UNREACHABLE; } bool bv_utilst::is_constant(const bvt &bv) { forall_literals(it, bv) if(!it->is_constant()) return false; return true; } void bv_utilst::cond_implies_equal( literalt cond, const bvt &a, const bvt &b) { PRECONDITION(a.size() == b.size()); if(prop.cnf_handled_well()) { for(std::size_t i=0; i<a.size(); i++) { prop.lcnf(!cond, a[i], !b[i]); prop.lcnf(!cond, !a[i], b[i]); } } else { prop.limplies(cond, equal(a, b)); } return; } literalt bv_utilst::verilog_bv_has_x_or_z(const bvt &src) { bvt odd_bits; odd_bits.reserve(src.size()/2); // check every odd bit for(std::size_t i=0; i<src.size(); i++) { if(i%2!=0) odd_bits.push_back(src[i]); } return prop.lor(odd_bits); } bvt bv_utilst::verilog_bv_normal_bits(const bvt &src) { bvt even_bits; even_bits.reserve(src.size()/2); // get every even bit for(std::size_t i=0; i<src.size(); i++) { if(i%2==0) even_bits.push_back(src[i]); } return even_bits; }
24.044428
80
0.635144
mauguignard
441ef84eec24ed4bd0a7a825dc092d97482d7940
15,080
hpp
C++
RZExternal/src/FitSDKRelease_20/fit_three_d_sensor_calibration_mesg.hpp
roznet/tennisstats
6283326c0a8cadaeff98b45f8aeff1a32429fa06
[ "MIT" ]
1
2020-08-04T07:29:47.000Z
2020-08-04T07:29:47.000Z
RZExternal/src/FitSDKRelease_20/fit_three_d_sensor_calibration_mesg.hpp
roznet/tennisstats
6283326c0a8cadaeff98b45f8aeff1a32429fa06
[ "MIT" ]
null
null
null
RZExternal/src/FitSDKRelease_20/fit_three_d_sensor_calibration_mesg.hpp
roznet/tennisstats
6283326c0a8cadaeff98b45f8aeff1a32429fa06
[ "MIT" ]
1
2019-06-05T08:27:18.000Z
2019-06-05T08:27:18.000Z
//////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Garmin Canada Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2018 Garmin Canada Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 20.80Release // Tag = production/akw/20.80.00-0-g64ad259 //////////////////////////////////////////////////////////////////////////////// #if !defined(FIT_THREE_D_SENSOR_CALIBRATION_MESG_HPP) #define FIT_THREE_D_SENSOR_CALIBRATION_MESG_HPP #include "fit_mesg.hpp" namespace fit { class ThreeDSensorCalibrationMesg : public Mesg { public: class FieldDefNum final { public: static const FIT_UINT8 Timestamp = 253; static const FIT_UINT8 SensorType = 0; static const FIT_UINT8 CalibrationFactor = 1; static const FIT_UINT8 CalibrationDivisor = 2; static const FIT_UINT8 LevelShift = 3; static const FIT_UINT8 OffsetCal = 4; static const FIT_UINT8 OrientationMatrix = 5; static const FIT_UINT8 Invalid = FIT_FIELD_NUM_INVALID; }; ThreeDSensorCalibrationMesg(void) : Mesg(Profile::MESG_THREE_D_SENSOR_CALIBRATION) { } ThreeDSensorCalibrationMesg(const Mesg &mesg) : Mesg(mesg) { } /////////////////////////////////////////////////////////////////////// // Checks the validity of timestamp field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsTimestampValid() const { const Field* field = GetField(253); if( FIT_NULL == field ) { return FIT_FALSE; } return field->IsValueValid(); } /////////////////////////////////////////////////////////////////////// // Returns timestamp field // Units: s // Comment: Whole second part of the timestamp /////////////////////////////////////////////////////////////////////// FIT_DATE_TIME GetTimestamp(void) const { return GetFieldUINT32Value(253, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Set timestamp field // Units: s // Comment: Whole second part of the timestamp /////////////////////////////////////////////////////////////////////// void SetTimestamp(FIT_DATE_TIME timestamp) { SetFieldUINT32Value(253, timestamp, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Checks the validity of sensor_type field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsSensorTypeValid() const { const Field* field = GetField(0); if( FIT_NULL == field ) { return FIT_FALSE; } return field->IsValueValid(); } /////////////////////////////////////////////////////////////////////// // Returns sensor_type field // Comment: Indicates which sensor the calibration is for /////////////////////////////////////////////////////////////////////// FIT_SENSOR_TYPE GetSensorType(void) const { return GetFieldENUMValue(0, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Set sensor_type field // Comment: Indicates which sensor the calibration is for /////////////////////////////////////////////////////////////////////// void SetSensorType(FIT_SENSOR_TYPE sensorType) { SetFieldENUMValue(0, sensorType, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Checks the validity of calibration_factor field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsCalibrationFactorValid() const { const Field* field = GetField(1); if( FIT_NULL == field ) { return FIT_FALSE; } return field->IsValueValid(); } /////////////////////////////////////////////////////////////////////// // Returns calibration_factor field // Comment: Calibration factor used to convert from raw ADC value to degrees, g, etc. /////////////////////////////////////////////////////////////////////// FIT_UINT32 GetCalibrationFactor(void) const { return GetFieldUINT32Value(1, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Set calibration_factor field // Comment: Calibration factor used to convert from raw ADC value to degrees, g, etc. /////////////////////////////////////////////////////////////////////// void SetCalibrationFactor(FIT_UINT32 calibrationFactor) { SetFieldUINT32Value(1, calibrationFactor, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Checks the validity of accel_cal_factor field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsAccelCalFactorValid() const { const Field* field = GetField(1); if( FIT_NULL == field ) { return FIT_FALSE; } if( !CanSupportSubField( field, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_ACCEL_CAL_FACTOR ) ) { return FIT_FALSE; } return field->IsValueValid(0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_ACCEL_CAL_FACTOR); } /////////////////////////////////////////////////////////////////////// // Returns accel_cal_factor field // Units: g // Comment: Accelerometer calibration factor /////////////////////////////////////////////////////////////////////// FIT_UINT32 GetAccelCalFactor(void) const { return GetFieldUINT32Value(1, 0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_ACCEL_CAL_FACTOR); } /////////////////////////////////////////////////////////////////////// // Set accel_cal_factor field // Units: g // Comment: Accelerometer calibration factor /////////////////////////////////////////////////////////////////////// void SetAccelCalFactor(FIT_UINT32 accelCalFactor) { SetFieldUINT32Value(1, accelCalFactor, 0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_ACCEL_CAL_FACTOR); } /////////////////////////////////////////////////////////////////////// // Checks the validity of gyro_cal_factor field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsGyroCalFactorValid() const { const Field* field = GetField(1); if( FIT_NULL == field ) { return FIT_FALSE; } if( !CanSupportSubField( field, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_GYRO_CAL_FACTOR ) ) { return FIT_FALSE; } return field->IsValueValid(0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_GYRO_CAL_FACTOR); } /////////////////////////////////////////////////////////////////////// // Returns gyro_cal_factor field // Units: deg/s // Comment: Gyro calibration factor /////////////////////////////////////////////////////////////////////// FIT_UINT32 GetGyroCalFactor(void) const { return GetFieldUINT32Value(1, 0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_GYRO_CAL_FACTOR); } /////////////////////////////////////////////////////////////////////// // Set gyro_cal_factor field // Units: deg/s // Comment: Gyro calibration factor /////////////////////////////////////////////////////////////////////// void SetGyroCalFactor(FIT_UINT32 gyroCalFactor) { SetFieldUINT32Value(1, gyroCalFactor, 0, (FIT_UINT16) Profile::THREE_D_SENSOR_CALIBRATION_MESG_CALIBRATION_FACTOR_FIELD_GYRO_CAL_FACTOR); } /////////////////////////////////////////////////////////////////////// // Checks the validity of calibration_divisor field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsCalibrationDivisorValid() const { const Field* field = GetField(2); if( FIT_NULL == field ) { return FIT_FALSE; } return field->IsValueValid(); } /////////////////////////////////////////////////////////////////////// // Returns calibration_divisor field // Units: counts // Comment: Calibration factor divisor /////////////////////////////////////////////////////////////////////// FIT_UINT32 GetCalibrationDivisor(void) const { return GetFieldUINT32Value(2, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Set calibration_divisor field // Units: counts // Comment: Calibration factor divisor /////////////////////////////////////////////////////////////////////// void SetCalibrationDivisor(FIT_UINT32 calibrationDivisor) { SetFieldUINT32Value(2, calibrationDivisor, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Checks the validity of level_shift field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsLevelShiftValid() const { const Field* field = GetField(3); if( FIT_NULL == field ) { return FIT_FALSE; } return field->IsValueValid(); } /////////////////////////////////////////////////////////////////////// // Returns level_shift field // Comment: Level shift value used to shift the ADC value back into range /////////////////////////////////////////////////////////////////////// FIT_UINT32 GetLevelShift(void) const { return GetFieldUINT32Value(3, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Set level_shift field // Comment: Level shift value used to shift the ADC value back into range /////////////////////////////////////////////////////////////////////// void SetLevelShift(FIT_UINT32 levelShift) { SetFieldUINT32Value(3, levelShift, 0, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Returns number of offset_cal /////////////////////////////////////////////////////////////////////// FIT_UINT8 GetNumOffsetCal(void) const { return GetFieldNumValues(4, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Checks the validity of offset_cal field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsOffsetCalValid(FIT_UINT8 index) const { const Field* field = GetField(4); if( FIT_NULL == field ) { return FIT_FALSE; } return field->IsValueValid(index); } /////////////////////////////////////////////////////////////////////// // Returns offset_cal field // Comment: Internal calibration factors, one for each: xy, yx, zx /////////////////////////////////////////////////////////////////////// FIT_SINT32 GetOffsetCal(FIT_UINT8 index) const { return GetFieldSINT32Value(4, index, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Set offset_cal field // Comment: Internal calibration factors, one for each: xy, yx, zx /////////////////////////////////////////////////////////////////////// void SetOffsetCal(FIT_UINT8 index, FIT_SINT32 offsetCal) { SetFieldSINT32Value(4, offsetCal, index, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Returns number of orientation_matrix /////////////////////////////////////////////////////////////////////// FIT_UINT8 GetNumOrientationMatrix(void) const { return GetFieldNumValues(5, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Checks the validity of orientation_matrix field // Returns FIT_TRUE if field is valid /////////////////////////////////////////////////////////////////////// FIT_BOOL IsOrientationMatrixValid(FIT_UINT8 index) const { const Field* field = GetField(5); if( FIT_NULL == field ) { return FIT_FALSE; } return field->IsValueValid(index); } /////////////////////////////////////////////////////////////////////// // Returns orientation_matrix field // Comment: 3 x 3 rotation matrix (row major) /////////////////////////////////////////////////////////////////////// FIT_FLOAT32 GetOrientationMatrix(FIT_UINT8 index) const { return GetFieldFLOAT32Value(5, index, FIT_SUBFIELD_INDEX_MAIN_FIELD); } /////////////////////////////////////////////////////////////////////// // Set orientation_matrix field // Comment: 3 x 3 rotation matrix (row major) /////////////////////////////////////////////////////////////////////// void SetOrientationMatrix(FIT_UINT8 index, FIT_FLOAT32 orientationMatrix) { SetFieldFLOAT32Value(5, orientationMatrix, index, FIT_SUBFIELD_INDEX_MAIN_FIELD); } }; } // namespace fit #endif // !defined(FIT_THREE_D_SENSOR_CALIBRATION_MESG_HPP)
38.865979
148
0.455504
roznet
441fe1eb48a9368cde796d97fb901abdda65153d
131
hxx
C++
src/Providers/UNIXProviders/StatisticsService/UNIX_StatisticsService_DARWIN.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/StatisticsService/UNIX_StatisticsService_DARWIN.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/StatisticsService/UNIX_StatisticsService_DARWIN.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_DARWIN #ifndef __UNIX_STATISTICSSERVICE_PRIVATE_H #define __UNIX_STATISTICSSERVICE_PRIVATE_H #endif #endif
10.916667
42
0.854962
brunolauze
44257a709f843bc41bafe52d1f430e34b1949c6c
3,097
cpp
C++
componentLibraries/devLibraries/SocketComponents/SocketComponents.cpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
componentLibraries/devLibraries/SocketComponents/SocketComponents.cpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
componentLibraries/devLibraries/SocketComponents/SocketComponents.cpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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. The full license is available in the file LICENSE. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ // Include your component code code files here // If you have lots of them you can include them in separate .h files and then include those files here instead. #include "SocketIOTestComponent.hpp" // You need to include ComponentEssentials.h in order to gain access to the register function and the Factory types // Also use the hopsan namespace #include "ComponentEssentials.h" using namespace hopsan; // When you load your model into Hopsan, the register_contents() function bellow will be called // It will register YOUR components into the Hopsan ComponentFactory extern "C" DLLEXPORT void register_contents(ComponentFactory* pComponentFactory, NodeFactory* /*pNodeFactory*/) { // ========== Register Components ========== // Use the registerCreatorFunction(KeyValue, Function) in the component factory to register components // The KeyValue is a text string with the TypeName of the component. // This value must be unique for every component in Hopsan. // If a typename is already in use, your component will not be added. // Suggestion, let the KeyValue (TypeName) be the same as your Class name // If that name is already in use, use something similar pComponentFactory->registerCreatorFunction("SocketIOTestComponent", SocketIOTestComponent::Creator); // ========== Register Custom Nodes (if any) ========== // This is not yet supported } // When you load your model into Hopsan, the get_hopsan_info() function bellow will be called // This information is used to make sure that your component and the hopsan core have the same version extern "C" DLLEXPORT void get_hopsan_info(HopsanExternalLibInfoT *pHopsanExternalLibInfo) { // Change the name of the lib to something unique // You can include numbers in your name to indicate library version (if you want) pHopsanExternalLibInfo->libName = (char*)"HopsanExampleComponentLibrary"; // Leave these two lines as they are pHopsanExternalLibInfo->hopsanCoreVersion = (char*)HOPSANCOREVERSION; pHopsanExternalLibInfo->libCompiledDebugRelease = (char*)DEBUGRELEASECOMPILED; }
44.242857
115
0.7165
mjfwest
4427714e79e4d907d2f904bd9bca476c91aa1681
2,194
hpp
C++
src/vec3.hpp
chrismile/reshade-grabber
0a24c65d8699106b94ace644748e67cdb1081024
[ "BSD-3-Clause" ]
null
null
null
src/vec3.hpp
chrismile/reshade-grabber
0a24c65d8699106b94ace644748e67cdb1081024
[ "BSD-3-Clause" ]
null
null
null
src/vec3.hpp
chrismile/reshade-grabber
0a24c65d8699106b94ace644748e67cdb1081024
[ "BSD-3-Clause" ]
null
null
null
/* * BSD 2-Clause License * * Copyright (c) 2021, Christoph Neuhauser * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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. */ #ifndef RESHADE_GRABBER_VEC3_HPP #define RESHADE_GRABBER_VEC3_HPP struct vec3 { union{ struct { float x, y, z; }; float data[3]; }; vec3(float x, float y, float z) : x(x), y(y), z(z) {} }; inline vec3 normalize(const vec3& p) { float invLength = 1.0f / std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z); return vec3(invLength * p.x, invLength * p.y, invLength * p.z); } inline vec3 cross(const vec3& p, const vec3& q) { return vec3(p.y * q.z - p.z * q.y, p.z * q.x - p.x * q.z, p.x * q.y - p.y * q.x); } inline vec3 operator+(const vec3& p, const vec3& q) { return vec3(p.x + q.x, p.y + q.y, p.z + q.z); } inline vec3 operator-(const vec3& p, const vec3& q) { return vec3(p.x - q.x, p.y - q.y, p.z - q.z); } #endif //RESHADE_GRABBER_VEC3_HPP
37.186441
85
0.696901
chrismile
44278245c46eed251cd16bc42256d0e38cec4437
11,053
hpp
C++
include/unifex/detail/concept_macros.hpp
hnakamur/libunifex
30e04053d90a35f277dc5ab3dc156ac75caa91da
[ "Apache-2.0" ]
null
null
null
include/unifex/detail/concept_macros.hpp
hnakamur/libunifex
30e04053d90a35f277dc5ab3dc156ac75caa91da
[ "Apache-2.0" ]
null
null
null
include/unifex/detail/concept_macros.hpp
hnakamur/libunifex
30e04053d90a35f277dc5ab3dc156ac75caa91da
[ "Apache-2.0" ]
1
2021-07-29T13:33:13.000Z
2021-07-29T13:33:13.000Z
/* * Copyright 2019-present Facebook, 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. */ #pragma once #include <type_traits> #include <unifex/config.hpp> #include <unifex/type_traits.hpp> #if defined(_MSC_VER) && !defined(__clang__) #define UNIFEX_WORKAROUND_MSVC_779763 // FATAL_UNREACHABLE calling constexpr function via template parameter #define UNIFEX_WORKAROUND_MSVC_780775 // Incorrect substitution in function template return type #endif #define UNIFEX_PP_CAT_(X, ...) X ## __VA_ARGS__ #define UNIFEX_PP_CAT(X, ...) UNIFEX_PP_CAT_(X, __VA_ARGS__) #define UNIFEX_PP_CAT2_(X, ...) X ## __VA_ARGS__ #define UNIFEX_PP_CAT2(X, ...) UNIFEX_PP_CAT2_(X, __VA_ARGS__) #define UNIFEX_PP_CAT3_(X, ...) X ## __VA_ARGS__ #define UNIFEX_PP_CAT3(X, ...) UNIFEX_PP_CAT3_(X, __VA_ARGS__) #define UNIFEX_PP_CAT4_(X, ...) X ## __VA_ARGS__ #define UNIFEX_PP_CAT4(X, ...) UNIFEX_PP_CAT4_(X, __VA_ARGS__) #define UNIFEX_PP_EVAL_(X, ARGS) X ARGS #define UNIFEX_PP_EVAL(X, ...) UNIFEX_PP_EVAL_(X, (__VA_ARGS__)) #define UNIFEX_PP_EVAL2_(X, ARGS) X ARGS #define UNIFEX_PP_EVAL2(X, ...) UNIFEX_PP_EVAL2_(X, (__VA_ARGS__)) #define UNIFEX_PP_EXPAND(...) __VA_ARGS__ #define UNIFEX_PP_EAT(...) #define UNIFEX_PP_CHECK(...) UNIFEX_PP_EXPAND(UNIFEX_PP_CHECK_N(__VA_ARGS__, 0,)) #define UNIFEX_PP_CHECK_N(x, n, ...) n #define UNIFEX_PP_PROBE(x) x, 1, #define UNIFEX_PP_PROBE_N(x, n) x, n, #define UNIFEX_PP_IS_PAREN(x) UNIFEX_PP_CHECK(UNIFEX_PP_IS_PAREN_PROBE x) #define UNIFEX_PP_IS_PAREN_PROBE(...) UNIFEX_PP_PROBE(~) // The final UNIFEX_PP_EXPAND here is to avoid // https://stackoverflow.com/questions/5134523/msvc-doesnt-expand-va-args-correctly #define UNIFEX_PP_COUNT(...) \ UNIFEX_PP_EXPAND(UNIFEX_PP_COUNT_(__VA_ARGS__, \ 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, \ 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, \ 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, \ 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, \ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,)) \ /**/ #define UNIFEX_PP_COUNT_( \ _01, _02, _03, _04, _05, _06, _07, _08, _09, _10, \ _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, \ _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, \ _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, \ _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, N, ...) \ N \ /**/ #define UNIFEX_PP_IIF(BIT) UNIFEX_PP_CAT_(UNIFEX_PP_IIF_, BIT) #define UNIFEX_PP_IIF_0(TRUE, ...) __VA_ARGS__ #define UNIFEX_PP_IIF_1(TRUE, ...) TRUE #define UNIFEX_PP_LPAREN ( #define UNIFEX_PP_NOT(BIT) UNIFEX_PP_CAT_(UNIFEX_PP_NOT_, BIT) #define UNIFEX_PP_NOT_0 1 #define UNIFEX_PP_NOT_1 0 #define UNIFEX_PP_EMPTY() #define UNIFEX_PP_COMMA() , #define UNIFEX_PP_LBRACE() { #define UNIFEX_PP_RBRACE() } #define UNIFEX_PP_COMMA_IIF(X) \ UNIFEX_PP_IIF(X)(UNIFEX_PP_EMPTY, UNIFEX_PP_COMMA)() \ /**/ #define UNIFEX_PP_FOR_EACH(M, ...) \ UNIFEX_PP_FOR_EACH_N(UNIFEX_PP_COUNT(__VA_ARGS__), M, __VA_ARGS__) #define UNIFEX_PP_FOR_EACH_N(N, M, ...) \ UNIFEX_PP_CAT2(UNIFEX_PP_FOR_EACH_, N)(M, __VA_ARGS__) #define UNIFEX_PP_FOR_EACH_1(M, _1) \ M(_1) #define UNIFEX_PP_FOR_EACH_2(M, _1, _2) \ M(_1) M(_2) #define UNIFEX_PP_FOR_EACH_3(M, _1, _2, _3) \ M(_1) M(_2) M(_3) #define UNIFEX_PP_FOR_EACH_4(M, _1, _2, _3, _4) \ M(_1) M(_2) M(_3) M(_4) #define UNIFEX_PP_FOR_EACH_5(M, _1, _2, _3, _4, _5) \ M(_1) M(_2) M(_3) M(_4) M(_5) #define UNIFEX_PP_FOR_EACH_6(M, _1, _2, _3, _4, _5, _6) \ M(_1) M(_2) M(_3) M(_4) M(_5) M(_6) #define UNIFEX_PP_FOR_EACH_7(M, _1, _2, _3, _4, _5, _6, _7) \ M(_1) M(_2) M(_3) M(_4) M(_5) M(_6) M(_7) #define UNIFEX_PP_FOR_EACH_8(M, _1, _2, _3, _4, _5, _6, _7, _8) \ M(_1) M(_2) M(_3) M(_4) M(_5) M(_6) M(_7) M(_8) #define UNIFEX_PP_PROBE_EMPTY_PROBE_UNIFEX_PP_PROBE_EMPTY \ UNIFEX_PP_PROBE(~) \ #define UNIFEX_PP_PROBE_EMPTY() #define UNIFEX_PP_IS_NOT_EMPTY(...) \ UNIFEX_PP_EVAL( \ UNIFEX_PP_CHECK, \ UNIFEX_PP_CAT( \ UNIFEX_PP_PROBE_EMPTY_PROBE_, \ UNIFEX_PP_PROBE_EMPTY __VA_ARGS__ ())) \ /**/ #define UNIFEX_PP_TAIL(_, ...) __VA_ARGS__ #define UNIFEX_CONCEPT_FRAGMENT_REQS_M0(REQ) \ UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_(REQ)(REQ) #define UNIFEX_CONCEPT_FRAGMENT_REQS_M1(REQ) UNIFEX_PP_EXPAND REQ #define UNIFEX_CONCEPT_FRAGMENT_REQS_(...) \ { UNIFEX_PP_FOR_EACH(UNIFEX_CONCEPT_FRAGMENT_REQS_M, __VA_ARGS__) } #define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_(REQ) \ UNIFEX_PP_CAT3(UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_, \ UNIFEX_PP_EVAL(UNIFEX_PP_CHECK, UNIFEX_PP_CAT3( \ UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_PROBE_, \ REQ))) \ /**/ #define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_PROBE_requires UNIFEX_PP_PROBE_N(~, 1) #define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_PROBE_noexcept UNIFEX_PP_PROBE_N(~, 2) #define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_PROBE_typename UNIFEX_PP_PROBE_N(~, 3) #define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_0 UNIFEX_PP_EXPAND #define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_1 UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_OR_NOEXCEPT #define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_2 UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_OR_NOEXCEPT #define UNIFEX_CONCEPT_FRAGMENT_REQS_SELECT_3 UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_OR_NOEXCEPT #define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_OR_NOEXCEPT(REQ) \ UNIFEX_PP_CAT4( \ UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_, \ REQ) #define UNIFEX_PP_EAT_TYPENAME_PROBE_typename UNIFEX_PP_PROBE(~) #define UNIFEX_PP_EAT_TYPENAME_SELECT_(X,...) \ UNIFEX_PP_CAT3(UNIFEX_PP_EAT_TYPENAME_SELECT_, \ UNIFEX_PP_EVAL(UNIFEX_PP_CHECK, UNIFEX_PP_CAT3( \ UNIFEX_PP_EAT_TYPENAME_PROBE_, \ X))) #define UNIFEX_PP_EAT_TYPENAME_(...) \ UNIFEX_PP_EVAL2(UNIFEX_PP_EAT_TYPENAME_SELECT_, __VA_ARGS__,)(__VA_ARGS__) #define UNIFEX_PP_EAT_TYPENAME_SELECT_0(...) __VA_ARGS__ #define UNIFEX_PP_EAT_TYPENAME_SELECT_1(...) \ UNIFEX_PP_CAT3(UNIFEX_PP_EAT_TYPENAME_, __VA_ARGS__) #define UNIFEX_PP_EAT_TYPENAME_typename #if UNIFEX_CXX_CONCEPTS || defined(UNIFEX_DOXYGEN_INVOKED) #define UNIFEX_CONCEPT concept #define UNIFEX_CONCEPT_FRAGMENT(NAME, ...) \ concept NAME = UNIFEX_PP_CAT(UNIFEX_CONCEPT_FRAGMENT_REQS_, __VA_ARGS__) #define UNIFEX_CONCEPT_FRAGMENT_REQS_requires(...) \ requires(__VA_ARGS__) UNIFEX_CONCEPT_FRAGMENT_REQS_ #define UNIFEX_CONCEPT_FRAGMENT_REQS_M(REQ) \ UNIFEX_PP_CAT2(UNIFEX_CONCEPT_FRAGMENT_REQS_M, UNIFEX_PP_IS_PAREN(REQ))(REQ); #define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_requires(...) \ requires __VA_ARGS__ #define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_typename(...) \ typename UNIFEX_PP_EAT_TYPENAME_(__VA_ARGS__) #define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_noexcept(...) \ { __VA_ARGS__ } noexcept #define UNIFEX_FRAGMENT(NAME, ...) \ NAME<__VA_ARGS__> #else #define UNIFEX_CONCEPT inline constexpr bool #define UNIFEX_CONCEPT_FRAGMENT(NAME, ...) \ auto NAME ## UNIFEX_CONCEPT_FRAGMENT_impl_ \ UNIFEX_CONCEPT_FRAGMENT_REQS_ ## __VA_ARGS__> {} \ template <typename... As> \ char NAME ## UNIFEX_CONCEPT_FRAGMENT_( \ ::unifex::_concept::tag<As...> *, \ decltype(&NAME ## UNIFEX_CONCEPT_FRAGMENT_impl_<As...>)); \ char (&NAME ## UNIFEX_CONCEPT_FRAGMENT_(...))[2] \ /**/ #define M(ARG) ARG, #if defined(_MSC_VER) && !defined(__clang__) #define UNIFEX_CONCEPT_FRAGMENT_TRUE(...) \ ::unifex::_concept::true_<decltype( \ UNIFEX_PP_FOR_EACH(UNIFEX_CONCEPT_FRAGMENT_REQS_M, __VA_ARGS__) \ void())>() #else #define UNIFEX_CONCEPT_FRAGMENT_TRUE(...) \ !(decltype(UNIFEX_PP_FOR_EACH(UNIFEX_CONCEPT_FRAGMENT_REQS_M, __VA_ARGS__) \ void(), \ false){}) #endif #define UNIFEX_CONCEPT_FRAGMENT_REQS_requires(...) \ (__VA_ARGS__) -> std::enable_if_t<UNIFEX_CONCEPT_FRAGMENT_REQS_2_ #define UNIFEX_CONCEPT_FRAGMENT_REQS_2_(...) \ UNIFEX_CONCEPT_FRAGMENT_TRUE(__VA_ARGS__) #define UNIFEX_CONCEPT_FRAGMENT_REQS_M(REQ) \ UNIFEX_PP_CAT2(UNIFEX_CONCEPT_FRAGMENT_REQS_M, UNIFEX_PP_IS_PAREN(REQ))(REQ), #define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_requires(...) \ ::unifex::requires_<__VA_ARGS__> #define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_typename(...) \ static_cast<::unifex::_concept::tag<__VA_ARGS__> *>(nullptr) #if defined(__GNUC__) && !defined(__clang__) // GCC can't mangle noexcept expressions, so just check that the // expression is well-formed. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70790 #define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_noexcept(...) \ __VA_ARGS__ #else #define UNIFEX_CONCEPT_FRAGMENT_REQS_REQUIRES_noexcept(...) \ ::unifex::requires_<noexcept(__VA_ARGS__)> #endif #define UNIFEX_FRAGMENT(NAME, ...) \ (1u==sizeof(NAME ## UNIFEX_CONCEPT_FRAGMENT_( \ static_cast<::unifex::_concept::tag<__VA_ARGS__> *>(nullptr), nullptr))) #endif //////////////////////////////////////////////////////////////////////////////// // UNIFEX_TEMPLATE // Usage: // UNIFEX_TEMPLATE(typename A, typename B) // (requires Concept1<A> UNIFEX_AND Concept2<B>) // void foo(A a, B b) // {} #if UNIFEX_CXX_CONCEPTS #define UNIFEX_TEMPLATE(...) \ template <__VA_ARGS__> UNIFEX_PP_EXPAND \ /**/ #define UNIFEX_AND && \ /**/ #else #define UNIFEX_TEMPLATE(...) \ template <__VA_ARGS__ UNIFEX_TEMPLATE_SFINAE_AUX_ \ /**/ #define UNIFEX_AND && UNIFEX_true_, int> = 0, std::enable_if_t< \ /**/ #endif #define UNIFEX_TEMPLATE_SFINAE(...) \ template <__VA_ARGS__ UNIFEX_TEMPLATE_SFINAE_AUX_ \ /**/ #define UNIFEX_TEMPLATE_SFINAE_AUX_(...) , \ bool UNIFEX_true_ = true, \ std::enable_if_t< \ UNIFEX_PP_CAT(UNIFEX_TEMPLATE_SFINAE_AUX_3_, __VA_ARGS__) && UNIFEX_true_, \ int> = 0> \ /**/ #define UNIFEX_TEMPLATE_SFINAE_AUX_3_requires #include <unifex/detail/prologue.hpp> namespace unifex { namespace _concept { template <typename...> struct tag; template <class> inline constexpr bool true_() { return true; } } // namespace _concept #if defined(__clang__) || defined(_MSC_VER) template <bool B> std::enable_if_t<B> requires_() {} #else template <bool B> inline constexpr std::enable_if_t<B, int> requires_ = 0; #endif #if UNIFEX_CXX_CONCEPTS template <typename Fn, typename... As> concept // callable = // requires (Fn&& fn, As&&... as) { ((Fn&&) fn)((As&&) as...); }; #else template <typename Fn, typename... As> UNIFEX_CONCEPT // callable = // sizeof(decltype(_is_callable::_try_call(static_cast<Fn(*)(As...)>(nullptr)))) == sizeof(_is_callable::yes_type); #endif } // namespace unifex #include <unifex/detail/epilogue.hpp>
36.003257
108
0.722157
hnakamur
4427ad39d40e59376a5945a389a38c6d6adad970
1,654
hpp
C++
include/mainMenu/CharacterSelector.hpp
LeandreBl/cautious-fiesta
21a08135253f6fea51835d81cce4a9920113fd18
[ "Apache-2.0" ]
3
2019-10-30T16:22:54.000Z
2020-12-10T20:23:40.000Z
include/mainMenu/CharacterSelector.hpp
LeandreBl/cautious-fiesta
21a08135253f6fea51835d81cce4a9920113fd18
[ "Apache-2.0" ]
63
2019-10-06T12:05:11.000Z
2019-12-09T16:22:46.000Z
include/mainMenu/CharacterSelector.hpp
LeandreBl/cautious-fiesta
21a08135253f6fea51835d81cce4a9920113fd18
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include <filesystem> #include <Vnavbar.hpp> #include "CharacterCreator.hpp" namespace cf { class CharacterSelector : public sfs::GameObject { public: CharacterSelector(const std::string &directory, const std::string &filename) noexcept : _navbar(nullptr) , _image(nullptr) , _name(nullptr) , _creator(nullptr) , _directory(directory) , _filename(filename) , _hat(nullptr){}; void start(sfs::Scene &scene) noexcept; void update(sfs::Scene &scene) noexcept; Character charaterSelected() noexcept { if (_creator != nullptr) { auto newCharacter = _creator->createCharacter(); if (newCharacter.getName() != "noName") { addCharacter(newCharacter); writeCharacterInFile(); } return newCharacter; } float characterSelected = _characters.size() * _navbar->getValue(); return _characters.at((int)characterSelected); }; void addCharacter(const Character &character) noexcept { _characters.emplace_back(character); }; void loadCharactersFromFile() noexcept; void writeCharacterInFile() noexcept; void addCharacterFromCreateButton() noexcept { if (_creator != nullptr) { auto _new = _creator->createCharacter(); if (_new.getName() != "noName") { _characters.emplace_back(_new); writeCharacterInFile(); _creator->destroy(); _creator = nullptr; } } } protected: std::vector<Character> _characters; sfs::Vnavbar *_navbar; sfs::Sprite *_image; sfs::Text *_name; CharacterCreation *_creator; std::filesystem::path _directory; std::filesystem::path _filename; std::vector<Text *> _stats; sfs::Sprite *_hat; }; } // namespace cf
24.686567
86
0.709794
LeandreBl
4429aa9c53aa7fe991c3f8ed433f72345f0c99c6
40,689
cc
C++
test/allocator/test_epoch_zone_heap.cc
LaudateCorpus1/gull
21dde19295f1f1c65458a27729d9e241ef6e0e57
[ "MIT" ]
8
2017-01-31T21:15:37.000Z
2021-05-26T01:10:32.000Z
test/allocator/test_epoch_zone_heap.cc
LaudateCorpus1/gull
21dde19295f1f1c65458a27729d9e241ef6e0e57
[ "MIT" ]
9
2020-03-26T13:27:23.000Z
2022-03-30T17:02:19.000Z
test/allocator/test_epoch_zone_heap.cc
LaudateCorpus1/gull
21dde19295f1f1c65458a27729d9e241ef6e0e57
[ "MIT" ]
7
2019-10-11T04:43:22.000Z
2022-02-18T05:49:53.000Z
/* * (c) Copyright 2016-2021 Hewlett Packard Enterprise Development Company LP. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the * GNU Lesser General Public License Version 3, or (at your option) * later with exceptions included below, or under the terms of the * MIT license (Expat) available in COPYING file in the source tree. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As an exception, the copyright holders of this Library grant you permission * to (i) compile an Application with the Library, and (ii) distribute the * Application containing code generated by the Library and added to the * Application during this compilation process under terms of your choice, * provided you also meet the terms and conditions of the Application license. * */ #include <unistd.h> // sleep #include <list> #include <random> #include <limits> #include <vector> #include <thread> #include <chrono> #include <gtest/gtest.h> #include "nvmm/memory_manager.h" #include "test_common/test.h" using namespace nvmm; // random number and string generator std::random_device r; std::default_random_engine e1(r()); uint64_t rand_uint64(uint64_t min = 0, uint64_t max = std::numeric_limits<uint64_t>::max()) { std::uniform_int_distribution<uint64_t> uniform_dist(min, max); return uniform_dist(e1); } // regular free TEST(EpochZoneHeap, Free) { PoolId pool_id = 1; size_t size = 128 * 1024 * 1024LLU; // 128 MB MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); // allocate & free GlobalPtr ptr = heap->Alloc(sizeof(int)); heap->Free(ptr); // allocate again, because of immediate free, the new ptr should be the same // as the previous ptr GlobalPtr ptr1 = heap->Alloc(sizeof(int)); EXPECT_EQ(ptr, ptr1); heap->Free(ptr1); // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // delayed free TEST(EpochZoneHeap, DelayedFree) { PoolId pool_id = 1; size_t size = 128 * 1024 * 1024LLU; // 128 MB MemoryManager *mm = MemoryManager::GetInstance(); EpochManager *em = EpochManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); EpochCounter e1; GlobalPtr ptr1; // allocate & delayed free { EpochOp op(em); e1 = op.reported_epoch(); std::cout << "first epoch " << e1 << std::endl; ptr1 = heap->Alloc(op, sizeof(int)); heap->Free(op, ptr1); // allocate again, because of delayed free, the new ptr should be // different from t he // previous ptr GlobalPtr ptr2 = heap->Alloc(op, sizeof(int)); EXPECT_NE(ptr1, ptr2); heap->Free(op, ptr2); } // wait a few epoches and make sure the background thread picks up this // chunk and frees it EpochCounter e2; while (1) { { // Begin epoch in a new scope block so that we exit the epoch when // we out of scope and don't block others when we then sleep. { EpochOp op(em); e2 = op.reported_epoch(); } if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) { std::cout << "sleeping at epoch " << e2 << std::endl; sleep(1); // making sure the background thread wakes up in this // epoch break; } } } while (1) { { EpochOp op(em); EpochCounter e3 = op.reported_epoch(); if (e3 > e2) { break; } } } // now the ptr that was delayed freed must have been actually freed { EpochOp op(em); std::cout << "final epoch " << op.reported_epoch() << std::endl; GlobalPtr ptr2 = heap->Alloc(op, sizeof(int)); EXPECT_EQ(ptr1, ptr2); heap->Free(ptr2); } // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // // Simple Resize // Test case : // 1. Create heap // 2. Allocate it completely. Verify if allocation is from shelf 0 // 3. Resize heap // 4. Allocat, Verify if the allocation is from shelf 1 // TEST(EpochZoneHeap, Resize) { PoolId pool_id = 1; size_t min_alloc_size = 128; size_t heap_size = min_alloc_size * 1024 * 1024LLU; // 128 MB size_t allocated_size = 0; size_t alloc_size = 1024 * 1024LLU; // 1MB per alloc GlobalPtr ptr[512]; int i = 0; MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); // You should be able allocate (allocated_size - alloc_size) from the heap. do { ptr[i] = heap->Alloc(alloc_size); allocated_size += alloc_size; EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),1); i++; } while(allocated_size < (heap_size - alloc_size)); // Loop until last item. // Just do one more allocation in case we are able to allocate entire heap ptr[i] = heap->Alloc(alloc_size); if(ptr[i] != 0) i++; allocated_size = heap_size; heap_size = heap_size * 2; EXPECT_EQ(NO_ERROR, heap->Resize(heap_size)); EXPECT_EQ(heap->Size(), heap_size); do { ptr[i] = heap->Alloc(alloc_size); allocated_size += alloc_size; EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),2); i++; } while(allocated_size < (heap_size - alloc_size)); // Loop until last item. ptr[i] = heap->Alloc(alloc_size); if(ptr[i]==0) i--; do{ heap->Free(ptr[i--]); }while(i>=0); // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // Resize multiple times in a loop TEST(EpochZoneHeap, MultipleResize) { PoolId pool_id = 1; size_t min_alloc_size = 128; size_t heap_size = min_alloc_size * 1024 * 1024LLU; // 128 MB size_t resize_size = heap_size; size_t alloc_size = heap_size/2 ; int total_shelfs = 96; GlobalPtr ptr[512]; GlobalPtr ptr_fail; int i = 0, j = 0; MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); #ifdef LFSWORKAROUND total_shelfs = 4; #endif for(i=0;i<total_shelfs;i++) { ptr[i] = heap->Alloc(alloc_size); EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),i+1); ptr_fail = heap->Alloc(alloc_size); EXPECT_EQ(ptr_fail,(GlobalPtr)0); heap_size += resize_size; EXPECT_EQ(heap->Resize(heap_size), NO_ERROR); EXPECT_EQ(heap->Size(), heap_size); } ptr[i] = heap->Alloc(alloc_size); EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),i+1); ptr_fail = heap->Alloc(alloc_size); EXPECT_EQ(ptr_fail,(GlobalPtr)0); heap->Free(ptr[i]); ptr[i] = heap->Alloc(alloc_size); EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),i+1); for(j=0;j<total_shelfs;j++) { heap->Free(ptr[j]); } // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); #ifdef LFSWORKAROUND sleep(10); #endif } #ifndef LFSWORKAROUND // Resize multiple times in a loop TEST(EpochZoneHeap, MultipleResizeBoundary) { PoolId pool_id = 1; size_t min_alloc_size = 128; size_t heap_size = min_alloc_size * 1024LLU; // 128 KB size_t resize_size = heap_size; size_t alloc_size = heap_size/2 ; uint32_t total_resize_count = 126; GlobalPtr ptr[512]; GlobalPtr ptr_fail; uint32_t i = 0, j = 0; MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); // total_shelfs-1,as we have one shelf already created for(i=0;i<total_resize_count;i++) { ptr[i] = heap->Alloc(alloc_size); EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((uint32_t)ptr[i].GetShelfId().GetShelfIndex(),i+1); ptr_fail = heap->Alloc(alloc_size); EXPECT_EQ(ptr_fail,(GlobalPtr)0); heap_size += resize_size; EXPECT_EQ(heap->Resize(heap_size), NO_ERROR); EXPECT_EQ(heap->Size(), heap_size); } ptr[i] = heap->Alloc(alloc_size); EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((uint32_t)ptr[i].GetShelfId().GetShelfIndex(),i+1); ptr_fail = heap->Alloc(alloc_size); EXPECT_EQ(ptr_fail,(GlobalPtr)0); heap->Free(ptr[i]); ptr[i] = heap->Alloc(alloc_size); EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((uint32_t)ptr[i].GetShelfId().GetShelfIndex(),i+1); for(j=0;j<(total_resize_count + 1);j++) { heap->Free(ptr[j]); } // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // Resize multiple times in a loop - until it fails. // Failure should be graceful TEST(EpochZoneHeap, MultipleResizeBoundaryFail) { PoolId pool_id = 1; size_t min_alloc_size = 128; size_t heap_size = min_alloc_size * 1024LLU; // 128 KB size_t resize_size = heap_size; size_t alloc_size = heap_size/2 ; uint32_t total_resize_count = 126; GlobalPtr ptr[512]; GlobalPtr ptr_fail; uint32_t i = 0, j = 0; MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); // total_shelfs-2,as we have one shelf already created // and one more shelf for header for(i=0;i<total_resize_count;i++) { ptr[i] = heap->Alloc(alloc_size); EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((uint32_t)ptr[i].GetShelfId().GetShelfIndex(),i+1); ptr_fail = heap->Alloc(alloc_size); EXPECT_EQ(ptr_fail,(GlobalPtr)0); heap_size += resize_size; EXPECT_EQ(heap->Resize(heap_size), NO_ERROR); EXPECT_EQ(heap->Size(), heap_size); } heap_size += resize_size; EXPECT_EQ(heap->Resize(heap_size), HEAP_RESIZE_FAILED); for(j=0;j<total_resize_count;j++) { heap->Free(ptr[j]); } // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } #endif // Resize to a smaller size than the current size, it should not do // anything and just return success. TEST(EpochZoneHeap, SmallerResize) { PoolId pool_id = 1; int min_alloc_size = 128; size_t alloc_size = 1024 * 1024LLU; size_t heap_size = min_alloc_size * alloc_size; // 128 MB size_t new_size = heap_size/2; GlobalPtr ptr[512]; int i = 0; MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); for(i=0;i<min_alloc_size-1;i++) { ptr[i] = heap->Alloc(alloc_size); EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),1); } ptr[i] = heap->Alloc(alloc_size); EXPECT_EQ(ptr[i],(GlobalPtr)0); // Since new size is lesser, resize wont do anything EXPECT_EQ(NO_ERROR, heap->Resize(new_size)); std::cout<<"Total heap size= " <<heap->Size()<<std::endl; EXPECT_EQ(heap->Size(), heap_size); // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // Resize to add a new shelf which is non power of 2, // EpochZoneHeap creates a shelf of size power of 2. TEST(EpochZoneHeap, PowerOfTwoResize) { PoolId pool_id = 1; int min_alloc_size = 128; size_t alloc_size = 1024 * 1024LLU; size_t heap_size = min_alloc_size * alloc_size; // 128 MB size_t new_size = 2 * heap_size - 10; GlobalPtr ptr[512]; int i = 0; MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); for(i=0;i<min_alloc_size-1;i++) { ptr[i] = heap->Alloc(alloc_size); EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),1); } ptr[i] = heap->Alloc(alloc_size); EXPECT_EQ(ptr[i],(GlobalPtr)0); // Since new size is lesser, resize wont do anything EXPECT_EQ(NO_ERROR, heap->Resize(new_size)); std::cout<<"Total heap size= " <<heap->Size()<<std::endl; EXPECT_EQ(heap->Size(), heap_size * 2); // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // Verify the offset allocation method TEST(EpochZoneHeap, OffsetAllocResize) { PoolId pool_id = 1; int min_alloc_size = 128; size_t alloc_size = 1024 * 1024LLU; size_t allocated_size = 0; size_t heap_size = min_alloc_size * alloc_size; // 128 MB Offset ptr[512]; int i = 0; MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); // We will be able to allocate (min_alloc_size - 1) objects of alloc_size // in a heap size (min_alloc_size * alloc_size) do { ptr[i] = heap->AllocOffset(alloc_size); allocated_size += alloc_size; std::cout <<"ptr = "<<ptr[i]<<std::endl; EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)((GlobalPtr)ptr[i]).GetShelfId().GetShelfIndex(),0); } while(allocated_size < (heap_size - alloc_size)); // Loop until last item. ptr[i] = heap->Alloc(alloc_size); EXPECT_EQ(ptr[i],(GlobalPtr)0); heap_size = heap_size * 2; EXPECT_EQ(NO_ERROR, heap->Resize(heap_size)); std::cout<<"Total heap size= " <<heap->Size()<<std::endl; EXPECT_EQ(heap->Size(), heap_size); allocated_size = heap_size; do { ptr[i] = heap->AllocOffset(alloc_size); allocated_size += alloc_size; std::cout <<"ptr = "<<ptr[i]<<std::endl; EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)((GlobalPtr)ptr[i]).GetShelfId().GetShelfIndex(),1); } while(allocated_size < (heap_size - alloc_size)); // Loop until last item. // Free loop do{ heap->Free(ptr[i--]); }while(i>=0); // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // Allocate from heap, Resize from heap1, New space should be available heap1 TEST(EpochZoneHeap, AllocResize) { PoolId pool_id = 1; size_t min_alloc_size = 128; size_t heap_size = min_alloc_size * 1024 * 1024LLU; // 128 MB size_t allocated_size = 0; size_t alloc_size = 1024 * 1024LLU; // 1MB per alloc GlobalPtr ptr[512]; int i = 0; MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); // You should be able allocate (allocated_size - alloc_size) from the heap. do { ptr[i] = heap->Alloc(alloc_size); allocated_size += alloc_size; EXPECT_NE(ptr[i],(GlobalPtr)0); EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),1); i++; } while(allocated_size < (heap_size - alloc_size)); // Loop until last item. // Just do one more allocation in case we are able to allocate entire heap ptr[i] = heap->Alloc(alloc_size); if(ptr[i] != 0) i++; // Open a new heap data structure and resize Heap *heap1; EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap1)); EXPECT_EQ(NO_ERROR, heap1->Open()); heap_size = heap_size * 2; EXPECT_EQ(NO_ERROR, heap1->Resize(heap_size)); // Allocate from new heap data structure ptr[i] = heap->Alloc(alloc_size); EXPECT_EQ((int)ptr[i].GetShelfId().GetShelfIndex(),2); // Both heap and heap1 should report same size EXPECT_EQ(heap->Size(),heap1->Size()); std::cout<<"Allocated , gptr = "<<ptr[i]<<std::endl; // Allocated the data items from heap, free it using heap1 do { heap1->Free(ptr[i]); i--; } while (i>=0); EXPECT_EQ(NO_ERROR, heap->Close()); EXPECT_EQ(NO_ERROR, heap1->Close()); delete heap; delete heap1; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); } // DelayedFree Resize test TEST(EpochZoneHeap, DelayedFreeResize) { PoolId pool_id = 1; size_t heap_size = 128 * 1024 * 1024LLU; // 128 MB size_t alloc_size = heap_size / 2; MemoryManager *mm = MemoryManager::GetInstance(); EpochManager *em = EpochManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); EpochCounter e1; GlobalPtr ptr1, ptr3; // allocate & delayed free { EpochOp op(em); e1 = op.reported_epoch(); std::cout << "first epoch " << e1 << std::endl; ptr1 = heap->Alloc(op, alloc_size); EXPECT_NE((GlobalPtr)0,ptr1); heap->Free(op, ptr1); // allocate again, because of delayed free, free will not happen // and the alloc will fail. GlobalPtr ptr2 = heap->Alloc(op, alloc_size); EXPECT_EQ((GlobalPtr)0, ptr2); // First shelf is full, Resize and create one more shelf heap->Resize(heap_size * 2); // Alloc from next shelf ptr3 = heap->Alloc(op, alloc_size); EXPECT_NE((GlobalPtr)0,ptr3); heap->Free(op, ptr3); // allocate again, because of delayed free, free will not happen // and the alloc will fail. ptr2 = heap->Alloc(op, alloc_size); EXPECT_EQ((GlobalPtr)0, ptr2); } // wait a few epoches and make sure the background thread picks up this // chunk and frees it EpochCounter e2; while (1) { { // Begin epoch in a new scope block so that we exit the epoch when // we out of scope and don't block others when we then sleep. { EpochOp op(em); e2 = op.reported_epoch(); } if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) { std::cout << "sleeping at epoch " << e2 << std::endl; sleep(2); // making sure the background thread wakes up in this // epoch break; } } } while (1) { { EpochOp op(em); EpochCounter e3 = op.reported_epoch(); if (e3 > e2) { break; } } } // now the ptr that was delayed freed must have been actually freed { EpochOp op(em); std::cout << "final epoch " << op.reported_epoch() << std::endl; // Alloc should from first shelf. Verify. GlobalPtr ptr2 = heap->Alloc(op, alloc_size); EXPECT_EQ(ptr1, ptr2); // Alloc should from next shelf. Verify. GlobalPtr ptr4 = heap->Alloc(op, alloc_size); EXPECT_EQ(ptr3, ptr4); heap->Free(ptr2); heap->Free(ptr4); } // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } #ifndef LFSWORKAROUND // Multiple DelayedFree Resize test TEST(EpochZoneHeap, MultipleDelayedFreeResize) { PoolId pool_id = 1; size_t shelf_size = 128 * 1024 * 1024LLU; // 128 MB size_t heap_size = shelf_size; size_t alloc_size = heap_size / 4; const int total_shelf = 16; int total_allocs; MemoryManager *mm = MemoryManager::GetInstance(); EpochManager *em = EpochManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); EpochCounter e1; GlobalPtr ptr; std::cout<<"Going to resize the heap"<<std::endl; for (int i = 0;i<total_shelf; i++) { heap_size += shelf_size; EXPECT_EQ(NO_ERROR,heap->Resize(heap_size)); std::cout<<"Resize: "<<i<<" Done" <<std::endl; } // allocate & delayed free { EpochOp op(em); e1 = op.reported_epoch(); std::cout << "first epoch " << e1 << std::endl; total_allocs = 0; while (1){ ptr = heap->Alloc(op, alloc_size); if(ptr == 0) break; total_allocs++; heap->Free(op, ptr); } EXPECT_GE (total_allocs, total_shelf * 3); // allocate again, because of delayed free, free will not happen // and the alloc will fail. ptr = heap->Alloc(op, alloc_size); EXPECT_EQ((GlobalPtr)0, ptr); } // wait a few epoches and make sure the background thread picks up this // chunk and frees it EpochCounter e2; while (1) { { // Begin epoch in a new scope block so that we exit the epoch when // we out of scope and don't block others when we then sleep. { EpochOp op(em); e2 = op.reported_epoch(); } if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) { std::cout << "sleeping at epoch " << e2 << std::endl; sleep(2); // making sure the background thread wakes up in this // epoch break; } } } while (1) { { EpochOp op(em); EpochCounter e3 = op.reported_epoch(); if (e3 > e2) { break; } } } // now the ptr that was delayed freed must have been actually freed { EpochOp op(em); std::cout << "final epoch " << op.reported_epoch() << std::endl; // Alloc should from first shelf. Verify. for(int i = 0;i < total_allocs;i++) { GlobalPtr ptr = heap->Alloc(op, alloc_size); EXPECT_NE(ptr,(GlobalPtr)0); heap->Free(op, ptr); } // This allocate should fail ptr = heap->Alloc(op, alloc_size); EXPECT_EQ((GlobalPtr)0, ptr); } // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // Multiple DelayedFree Resize test - Close test TEST(EpochZoneHeap, MultipleDelayedFreeResizeClose) { PoolId pool_id = 1; size_t shelf_size = 128 * 1024 * 1024LLU; // 128 MB size_t heap_size = shelf_size; size_t alloc_size = heap_size / 4; const int total_shelf = 16; int total_allocs; MemoryManager *mm = MemoryManager::GetInstance(); EpochManager *em = EpochManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, heap_size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, heap_size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); EpochCounter e1; GlobalPtr ptr; std::cout<<"Going to resize the heap"<<std::endl; for (int i = 0;i<total_shelf; i++) { heap_size += shelf_size; EXPECT_EQ(NO_ERROR,heap->Resize(heap_size)); std::cout<<"Resize: "<<i<<" Done" <<std::endl; } // allocate & delayed free { EpochOp op(em); e1 = op.reported_epoch(); std::cout << "first epoch " << e1 << std::endl; total_allocs = 0; while (1){ ptr = heap->Alloc(op, alloc_size); if(ptr == 0) break; total_allocs++; heap->Free(op, ptr); } EXPECT_GE (total_allocs, total_shelf * 3); // allocate again, because of delayed free, free will not happen // and the alloc will fail. ptr = heap->Alloc(op, alloc_size); EXPECT_EQ((GlobalPtr)0, ptr); } // Close the heap EXPECT_EQ(NO_ERROR, heap->Close()); // Open the heap EXPECT_EQ(NO_ERROR, heap->Open()); // wait a few epoches and make sure the background thread picks up this // chunk and frees it EpochCounter e2; while (1) { { // Begin epoch in a new scope block so that we exit the epoch when // we out of scope and don't block others when we then sleep. { EpochOp op(em); e2 = op.reported_epoch(); } if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) { std::cout << "sleeping at epoch " << e2 << std::endl; sleep(2); // making sure the background thread wakes up in this // epoch break; } } } while (1) { { EpochOp op(em); EpochCounter e3 = op.reported_epoch(); if (e3 > e2) { break; } } } // now the ptr that was delayed freed must have been actually freed { EpochOp op(em); std::cout << "final epoch " << op.reported_epoch() << std::endl; // Alloc should from first shelf. Verify. for(int i = 0;i < total_allocs;i++) { GlobalPtr ptr = heap->Alloc(op, alloc_size); EXPECT_NE(ptr,(GlobalPtr)0); heap->Free(op, ptr); } // This allocate should fail ptr = heap->Alloc(op, alloc_size); EXPECT_EQ((GlobalPtr)0, ptr); } // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } #endif // TEST(EpochZoneHeap, Permissions) { PoolId pool_id = 1; size_t size = 128 * 1024 * 1024LLU; // 128 MB MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size, 128, S_IRUSR | S_IWUSR | S_IRGRP )); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size)); EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); mode_t mode; EXPECT_EQ(NO_ERROR, heap->GetPermission(&mode)); EXPECT_NE((mode_t)0, mode & S_IRGRP); EXPECT_EQ((mode_t)0, mode & S_IWGRP); EXPECT_EQ(NO_ERROR, heap->SetPermission(mode | S_IWGRP)); EXPECT_EQ(NO_ERROR, heap->GetPermission(&mode)); EXPECT_NE((mode_t)0, mode & S_IWGRP); EXPECT_EQ(NO_ERROR,heap->Resize(size * 2)); EXPECT_EQ(NO_ERROR, heap->SetPermission(S_IRUSR | S_IWUSR)); EXPECT_EQ(NO_ERROR, heap->GetPermission(&mode)); EXPECT_EQ((mode_t)0, mode & (S_IRGRP | S_IWGRP)); EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // merge TEST(EpochZoneHeap, Merge) { PoolId pool_id = 1; size_t size = 128 * 1024 * 1024LLU; // 128 MB MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); // in unit of 64-byte: // [0, 8) has been allocated to the header // [4096, 8192) has been allocated to the merge bitmap uint64_t min_obj_size = heap->MinAllocSize(); // merge at levels < max_zone_level-2 // allocate 64 byte x 24, covering [8, 32) GlobalPtr ptr[24]; GlobalPtr new_ptr; #if 0 for(int i=0; i<24; i++) { ptr[i]= heap->Alloc(min_obj_size); } // free 64 byte x 24 for(int i=0; i<24; i++) { heap->Free(ptr[i]); } // before merge, allocate 1024 bytes new_ptr = heap->Alloc(16*min_obj_size); EXPECT_EQ(32*min_obj_size, new_ptr.GetOffset()); // merge heap->Merge(); // after merge, allocate 1024 bytes new_ptr = heap->Alloc(16*min_obj_size); EXPECT_EQ(16*min_obj_size, new_ptr.GetOffset()); #endif // merge at the last 3 levels // allocate 16MB x 7 for (int i = 0; i < 7; i++) { ptr[i] = heap->Alloc(262144 * min_obj_size); } // free 16MB x 7 for (int i = 0; i < 7; i++) { heap->Free(ptr[i]); } // before merge, allocate 64MB new_ptr = heap->Alloc(1048576 * min_obj_size); EXPECT_EQ(0UL, new_ptr.GetOffset()); // merge heap->Merge(); // after merge, allocate 64MB new_ptr = heap->Alloc(1048576 * min_obj_size); EXPECT_EQ(1048576 * min_obj_size, new_ptr.GetOffset()); // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // Test large pool id TEST(EpochZoneHeap, LargePoolId) { MemoryManager *mm = MemoryManager::GetInstance(); PoolId pool_id = 1; for (PoolId i = 10; i <= 14; i++) { pool_id = PoolId(1 << i); if (i == 14) pool_id = PoolId((1 << i) - 1); std::cout << "Creating heap with pool id=" << pool_id << "\n"; size_t size = 128 * 1024 * 1024; // 128MB #ifdef LFSWORKAROUND sleep(10); #endif ErrorCode ret = mm->CreateHeap(pool_id, size); assert(ret == NO_ERROR); // acquire the heap Heap *heap = NULL; ret = mm->FindHeap(pool_id, &heap); assert(ret == NO_ERROR); // open the heap ret = heap->Open(); assert(ret == NO_ERROR); // use the heap GlobalPtr ptr = heap->Alloc( sizeof(int)); // Alloc returns a GlobalPtr consisting of a shelf ID // and offset assert(ptr.IsValid() == true); int *int_ptr = (int *)mm->GlobalToLocal( ptr); // convert the GlobalPtr into a local pointer *int_ptr = 123; assert(*int_ptr == 123); heap->Free(ptr); // close the heap ret = heap->Close(); assert(ret == NO_ERROR); // release the heap delete heap; // delete the heap ret = mm->DestroyHeap(pool_id); assert(ret == NO_ERROR); } } // Larger data item size TEST(EpochZoneHeap, Largeallocsize) { PoolId pool_id = 1; size_t size = 128 * 1024 * 1024LLU; // 128 MB MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size,512)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size,512)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); // allocate & free GlobalPtr ptr = heap->Alloc(sizeof(int)); // allocate again, This offset should 512 + ptr GlobalPtr ptr1 = heap->Alloc(sizeof(int)); std::cout<<"ptr :"<<ptr.GetOffset()<<std::endl; std::cout<<"ptr1 :"<<ptr1.GetOffset()<<std::endl; EXPECT_EQ(ptr.GetOffset()+512, ptr1.GetOffset()); heap->Free(ptr); heap->Free(ptr1); // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } void AllocFree(Heap *heap, int cnt) { std::cout << "Thread " << std::this_thread::get_id() << " started" << std::endl; std::list<GlobalPtr> ptrs; for (int i = 0; i < cnt; i++) { if (rand_uint64(0, 1) == 1) { GlobalPtr ptr = heap->Alloc(rand_uint64(0, 1024 * 1024)); if (ptr) ptrs.push_back(ptr); } else { if (!ptrs.empty()) { GlobalPtr ptr = ptrs.front(); ptrs.pop_front(); heap->Free(ptr); } } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } for (auto ptr : ptrs) { heap->Free(ptr); } std::cout << "Thread " << std::this_thread::get_id() << " ended" << std::endl; } // merge and concurrent alloc and free TEST(EpochZoneHeap, MergeAllocFree) { PoolId pool_id = 1; size_t size = 1024 * 1024 * 1024LLU; // 1024 MB int thread_cnt = 16; int loop_cnt = 1000; MemoryManager *mm = MemoryManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open()); // start the threads std::vector<std::thread> workers; for (int i = 0; i < thread_cnt; i++) { workers.push_back(std::thread(AllocFree, heap, loop_cnt)); } for (int i = 0; i < 5; i++) { heap->Merge(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } for (auto &worker : workers) { if (worker.joinable()) worker.join(); } heap->Merge(); // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } // No delayed free - Disable backgroundWorker thread TEST(EpochZoneHeap, NoDelayedFree) { PoolId pool_id = 1; size_t size = 128 * 1024 * 1024LLU; // 128 MB MemoryManager *mm = MemoryManager::GetInstance(); EpochManager *em = EpochManager::GetInstance(); Heap *heap = NULL; // create a heap EXPECT_EQ(ID_NOT_FOUND, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, mm->CreateHeap(pool_id, size)); EXPECT_EQ(ID_FOUND, mm->CreateHeap(pool_id, size)); // get the heap EXPECT_EQ(NO_ERROR, mm->FindHeap(pool_id, &heap)); EXPECT_EQ(NO_ERROR, heap->Open(NVMM_NO_BG_THREAD)); EpochCounter e1; GlobalPtr ptr1; // allocate & delayed free { EpochOp op(em); e1 = op.reported_epoch(); std::cout << "first epoch " << e1 << std::endl; ptr1 = heap->Alloc(op, sizeof(int)); heap->Free(op, ptr1); } // wait a few epoches and make sure the background thread (if it had existed) // picks up this chunk and frees it EpochCounter e2; while (1) { { // Begin epoch in a new scope block so that we exit the epoch when // we out of scope and don't block others when we then sleep. { EpochOp op(em); e2 = op.reported_epoch(); } if (e2 - e1 >= 3 && e2 % 5 == (e1 + 3) % 5) { std::cout << "sleeping at epoch " << e2 << std::endl; sleep(1); // making sure the background thread wakes up in this // epoch. break; } } } while (1) { { EpochOp op(em); EpochCounter e3 = op.reported_epoch(); if (e3 > e2) { break; } } } // Since BackgroundWorker thread is disabled, delayed free will not take place. // Next allocation will get different pointer. { EpochOp op(em); std::cout << "final epoch " << op.reported_epoch() << std::endl; GlobalPtr ptr2 = heap->Alloc(op, sizeof(int)); EXPECT_NE(ptr1, ptr2); heap->Free(ptr2); } // Call Offline Free - It frees delayed freed data items heap->OfflineFree(); { EpochOp op(em); std::cout << "final epoch " << op.reported_epoch() << std::endl; GlobalPtr ptr2 = heap->Alloc(op, sizeof(int)); std::cout << "ptr2: "<<ptr2<<" ptr1: "<<ptr1<<std::endl; // Offline free should have freed it, So ptr1 will be re-allocated. EXPECT_EQ(ptr1, ptr2); heap->Free(ptr2); } // destroy the heap EXPECT_EQ(NO_ERROR, heap->Close()); delete heap; EXPECT_EQ(NO_ERROR, mm->DestroyHeap(pool_id)); EXPECT_EQ(ID_NOT_FOUND, mm->DestroyHeap(pool_id)); } int main(int argc, char **argv) { InitTest(nvmm::trace, false); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
31.251152
90
0.602989
LaudateCorpus1
442a57ff64a6f8baded266e3cdc995a8bf515340
1,521
cpp
C++
masteruser/zoo.cpp
JasonPap/Buffer-Overflows
e8d2a981fb0f09512b85b06f8caf40e865274a94
[ "MIT" ]
14
2015-03-13T15:55:47.000Z
2021-06-01T20:08:01.000Z
masteruser/zoo.cpp
JasonPap/Buffer-Overflows
e8d2a981fb0f09512b85b06f8caf40e865274a94
[ "MIT" ]
4
2015-03-14T16:32:45.000Z
2015-03-15T18:04:13.000Z
masteruser/zoo.cpp
JasonPap/Buffer-Overflows
e8d2a981fb0f09512b85b06f8caf40e865274a94
[ "MIT" ]
4
2015-09-14T06:20:25.000Z
2021-06-16T23:40:17.000Z
#include <iostream> #include <cstdlib> #include <cstring> #include <getopt.h> #define MAX_BUFFER_SIZE 256 class Animal{ private: char name[MAX_BUFFER_SIZE]; public: Animal() { strcpy(name, "Ylvis"); } void set_name(char *nname) { strcpy(name, nname); } char *get_name() { return name; } virtual void speak() = 0; }; class Cow : public Animal{ public: void speak(); }; class Fox : public Animal{ public: void speak(); }; void Cow::speak() { std::cout << get_name() << " says Moo.\n"; return; } void Fox::speak() { std::cout << get_name() << " says Hatee-hatee-hatee-ho.\n"; return; } void usage() { std::cout << "Usage: zoo [options]\n" << "Options:\n" << "\t-c <name> : Set cow name\n" << "\t-f <name> : Set fox name\n" << "\t-s : Instruct animals to speak\n" << "\t-h : Print options\n"; return; } int main(int argc, char *argv[]) { Animal *a1, *a2; bool speak = false; char c; if (argc < 2){ usage(); return 1; } a1 = new Cow; a2 = new Fox; while ((c = getopt(argc, argv, "hsc:f:")) != -1){ switch (c){ case 'h': usage(); return 0; case 's': speak = true; break; case 'c': a1 -> set_name(optarg); break; case 'f': a2 -> set_name(optarg); break; case '?': usage(); return 1; } } if (speak){ a1 -> speak(); a2 -> speak(); }else std::cout <<"Another silent night in the zoo\n"; delete a2; delete a1; return 0; }
15.680412
61
0.535174
JasonPap
442ab6973bd178895d04eb4c8bad071d6ce5c757
3,890
cpp
C++
DearPyGui/src/core/AppItems/basic/mvSelectable.cpp
liu-kan/DearPyGui
dbbf03519b4eff6fc3e8fc56e31c27aa29ac7a39
[ "MIT" ]
null
null
null
DearPyGui/src/core/AppItems/basic/mvSelectable.cpp
liu-kan/DearPyGui
dbbf03519b4eff6fc3e8fc56e31c27aa29ac7a39
[ "MIT" ]
null
null
null
DearPyGui/src/core/AppItems/basic/mvSelectable.cpp
liu-kan/DearPyGui
dbbf03519b4eff6fc3e8fc56e31c27aa29ac7a39
[ "MIT" ]
null
null
null
#include <utility> #include "mvSelectable.h" #include "mvApp.h" #include "mvItemRegistry.h" namespace Marvel { void mvSelectable::InsertParser(std::map<std::string, mvPythonParser>* parsers) { parsers->insert({ "add_selectable", mvPythonParser({ {mvPythonDataType::String, "name"}, {mvPythonDataType::KeywordOnly}, {mvPythonDataType::Bool, "default_value", "", "False"}, {mvPythonDataType::Callable, "callback", "Registers a callback", "None"}, {mvPythonDataType::Object, "callback_data", "Callback data", "None"}, {mvPythonDataType::String, "parent", "Parent this item will be added to. (runtime adding)", "''"}, {mvPythonDataType::String, "before", "This item will be displayed before the specified item in the parent. (runtime adding)", "''"}, {mvPythonDataType::String, "source", "", "''"}, {mvPythonDataType::Bool, "enabled", "Display grayed out text so selectable cannot be selected", "True"}, {mvPythonDataType::String, "label", "", "''"}, {mvPythonDataType::Bool, "show", "Attempt to render", "True"}, {mvPythonDataType::Bool, "span_columns", "span all columns", "False"}, }, "Adds a selectable.", "None", "Adding Widgets") }); } mvSelectable::mvSelectable(const std::string& name, bool default_value, const std::string& dataSource) : mvBoolPtrBase(name, default_value) { m_description.disableAllowed = true; } void mvSelectable::setEnabled(bool value) { if (value) m_flags &= ~ImGuiSelectableFlags_Disabled; else m_flags |= ImGuiSelectableFlags_Disabled; m_core_config.enabled = value; } void mvSelectable::draw() { auto styleManager = m_styleManager.getScopedStyleManager(); ScopedID id; mvImGuiThemeScope scope(this); if (ImGui::Selectable(m_label.c_str(), m_value.get(), m_flags)) mvApp::GetApp()->getCallbackRegistry().addCallback(m_core_config.callback, m_core_config.name, m_core_config.callback_data); } #ifndef MV_CPP void mvSelectable::setExtraConfigDict(PyObject* dict) { if (dict == nullptr) return; // helper for bit flipping auto flagop = [dict](const char* keyword, int flag, int& flags, bool flip) { if (PyObject* item = PyDict_GetItemString(dict, keyword)) ToBool(item) ? flags |= flag : flags &= ~flag; }; // window flags flagop("span_columns", ImGuiSelectableFlags_SpanAllColumns, m_flags, false); } void mvSelectable::getExtraConfigDict(PyObject* dict) { if (dict == nullptr) return; // helper to check and set bit auto checkbitset = [dict](const char* keyword, int flag, const int& flags, bool flip) { PyDict_SetItemString(dict, keyword, ToPyBool(flags & flag)); }; // window flags checkbitset("span_columns", ImGuiSelectableFlags_SpanAllColumns, m_flags, false); } PyObject* add_selectable(PyObject* self, PyObject* args, PyObject* kwargs) { const char* name; int default_value = false; PyObject* callback = nullptr; PyObject* callback_data = nullptr; const char* before = ""; const char* parent = ""; const char* source = ""; int enabled = true; const char* label = ""; int show = true; int span_columns = false; //ImGuiSelectableFlags flags = ImGuiSelectableFlags_None; if (!(*mvApp::GetApp()->getParsers())["add_selectable"].parse(args, kwargs, __FUNCTION__, &name, &default_value, &callback, &callback_data, &parent, &before, &source, &enabled, &label, &show, &span_columns)) return ToPyBool(false); auto item = CreateRef<mvSelectable>(name, default_value, source); if (callback) Py_XINCREF(callback); item->setCallback(callback); if (callback_data) Py_XINCREF(callback_data); item->setCallbackData(callback_data); item->checkConfigDict(kwargs); item->setConfigDict(kwargs); item->setExtraConfigDict(kwargs); mvApp::GetApp()->getItemRegistry().addItemWithRuntimeChecks(item, parent, before); return GetPyNone(); } #endif // !MV_CPP }
30.155039
135
0.70437
liu-kan
442b44e77ac38337fa0e6d69bb518d1671499481
472
cpp
C++
projeto1/src/SyntaxTree.cpp
lucaspetry/lukasiewicz-compiler
7029cc26f48c20a8479d27579a07a9e88e177bff
[ "MIT" ]
null
null
null
projeto1/src/SyntaxTree.cpp
lucaspetry/lukasiewicz-compiler
7029cc26f48c20a8479d27579a07a9e88e177bff
[ "MIT" ]
null
null
null
projeto1/src/SyntaxTree.cpp
lucaspetry/lukasiewicz-compiler
7029cc26f48c20a8479d27579a07a9e88e177bff
[ "MIT" ]
null
null
null
#include "SyntaxTree.h" SyntaxTree::SyntaxTree() { } SyntaxTree::~SyntaxTree() { } void SyntaxTree::print() { for (TreeNode* line: lines) { std::string toPrint = line->printPreOrder(); if(toPrint.back() == ' ') { toPrint = toPrint.substr(0, toPrint.length()-1); } std::cout << toPrint << std::endl; } } void SyntaxTree::insertLine(TreeNode* line) { this->lines.insert(lines.begin(), line); }
20.521739
60
0.559322
lucaspetry
442b8734c611d250bdd535cbb037af12fd964656
12,534
cpp
C++
src/sysGCU/P2DScreen.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/sysGCU/P2DScreen.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/sysGCU/P2DScreen.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "JSystem/JUT/JUTException.h" #include "P2DScreen.h" #include "System.h" #include "types.h" /* Generated from dpostproc .section .rodata # 0x804732E0 - 0x8049E220 .global lbl_8049A6C0 lbl_8049A6C0: .4byte 0x50324453 .4byte 0x63726565 .4byte 0x6E2E6370 .4byte 0x70000000 .global lbl_8049A6D0 lbl_8049A6D0: .asciz "P2Assert" .skip 3 .4byte 0x00000000 .section .data, "wa" # 0x8049E220 - 0x804EFC20 .global __vt__Q29P2DScreen10Mgr_tuning __vt__Q29P2DScreen10Mgr_tuning: .4byte 0 .4byte 0 .4byte __dt__Q29P2DScreen10Mgr_tuningFv .4byte getTypeID__9J2DScreenCFv .4byte move__7J2DPaneFff .4byte add__7J2DPaneFff .4byte resize__7J2DPaneFff .4byte setCullBack__7J2DPaneFb .4byte setCullBack__7J2DPaneF11_GXCullMode .4byte setAlpha__7J2DPaneFUc .4byte setConnectParent__7J2DPaneFb .4byte calcMtx__9J2DScreenFv .4byte update__Q29P2DScreen3MgrFv .4byte drawSelf__7J2DPaneFff .4byte drawSelf__9J2DScreenFffPA3_A4_f .4byte search__9J2DScreenFUx .4byte searchUserInfo__9J2DScreenFUx .4byte makeMatrix__7J2DPaneFff .4byte makeMatrix__7J2DPaneFffff .4byte isUsed__9J2DScreenFPC7ResTIMG .4byte isUsed__9J2DScreenFPC7ResFONT .4byte clearAnmTransform__9J2DScreenFv .4byte rewriteAlpha__7J2DPaneFv .4byte setAnimation__9J2DScreenFP10J2DAnmBase .4byte setAnimation__9J2DScreenFP15J2DAnmTransform .4byte setAnimation__9J2DScreenFP11J2DAnmColor .4byte setAnimation__9J2DScreenFP16J2DAnmTexPattern .4byte setAnimation__9J2DScreenFP19J2DAnmTextureSRTKey .4byte setAnimation__9J2DScreenFP15J2DAnmTevRegKey .4byte setAnimation__9J2DScreenFP20J2DAnmVisibilityFull .4byte setAnimation__9J2DScreenFP14J2DAnmVtxColor .4byte animationTransform__7J2DPaneFPC15J2DAnmTransform .4byte setVisibileAnimation__7J2DPaneFP20J2DAnmVisibilityFull .4byte setAnimationVF__9J2DScreenFP20J2DAnmVisibilityFull .4byte setVtxColorAnimation__7J2DPaneFP14J2DAnmVtxColor .4byte setAnimationVC__9J2DScreenFP14J2DAnmVtxColor .4byte animationPane__7J2DPaneFPC15J2DAnmTransform .4byte createPane__9J2DScreenFRC18J2DScrnBlockHeaderP20JSURandomInputStreamP7J2DPaneUl .4byte createPane__9J2DScreenFRC18J2DScrnBlockHeaderP20JSURandomInputStreamP7J2DPaneUlP10JKRArchive .4byte draw__Q29P2DScreen10Mgr_tuningFR8GraphicsR14J2DGrafContext .global __vt__Q29P2DScreen3Mgr __vt__Q29P2DScreen3Mgr: .4byte 0 .4byte 0 .4byte __dt__Q29P2DScreen3MgrFv .4byte getTypeID__9J2DScreenCFv .4byte move__7J2DPaneFff .4byte add__7J2DPaneFff .4byte resize__7J2DPaneFff .4byte setCullBack__7J2DPaneFb .4byte setCullBack__7J2DPaneF11_GXCullMode .4byte setAlpha__7J2DPaneFUc .4byte setConnectParent__7J2DPaneFb .4byte calcMtx__9J2DScreenFv .4byte update__Q29P2DScreen3MgrFv .4byte drawSelf__7J2DPaneFff .4byte drawSelf__9J2DScreenFffPA3_A4_f .4byte search__9J2DScreenFUx .4byte searchUserInfo__9J2DScreenFUx .4byte makeMatrix__7J2DPaneFff .4byte makeMatrix__7J2DPaneFffff .4byte isUsed__9J2DScreenFPC7ResTIMG .4byte isUsed__9J2DScreenFPC7ResFONT .4byte clearAnmTransform__9J2DScreenFv .4byte rewriteAlpha__7J2DPaneFv .4byte setAnimation__9J2DScreenFP10J2DAnmBase .4byte setAnimation__9J2DScreenFP15J2DAnmTransform .4byte setAnimation__9J2DScreenFP11J2DAnmColor .4byte setAnimation__9J2DScreenFP16J2DAnmTexPattern .4byte setAnimation__9J2DScreenFP19J2DAnmTextureSRTKey .4byte setAnimation__9J2DScreenFP15J2DAnmTevRegKey .4byte setAnimation__9J2DScreenFP20J2DAnmVisibilityFull .4byte setAnimation__9J2DScreenFP14J2DAnmVtxColor .4byte animationTransform__7J2DPaneFPC15J2DAnmTransform .4byte setVisibileAnimation__7J2DPaneFP20J2DAnmVisibilityFull .4byte setAnimationVF__9J2DScreenFP20J2DAnmVisibilityFull .4byte setVtxColorAnimation__7J2DPaneFP14J2DAnmVtxColor .4byte setAnimationVC__9J2DScreenFP14J2DAnmVtxColor .4byte animationPane__7J2DPaneFPC15J2DAnmTransform .4byte createPane__9J2DScreenFRC18J2DScrnBlockHeaderP20JSURandomInputStreamP7J2DPaneUl .4byte createPane__9J2DScreenFRC18J2DScrnBlockHeaderP20JSURandomInputStreamP7J2DPaneUlP10JKRArchive .4byte draw__Q29P2DScreen3MgrFR8GraphicsR14J2DGrafContext .section .sdata2, "a" # 0x80516360 - 0x80520E40 .global lbl_80520790 lbl_80520790: .4byte 0x00000000 .global mstTuningScaleX__Q29P2DScreen10Mgr_tuning mstTuningScaleX__Q29P2DScreen10Mgr_tuning: .4byte 0x3F733333 .global mstTuningScaleY__Q29P2DScreen10Mgr_tuning mstTuningScaleY__Q29P2DScreen10Mgr_tuning: .4byte 0x3F733333 .global mstTuningTransX__Q29P2DScreen10Mgr_tuning mstTuningTransX__Q29P2DScreen10Mgr_tuning: .4byte 0xC1733333 .global mstTuningTransY__Q29P2DScreen10Mgr_tuning mstTuningTransY__Q29P2DScreen10Mgr_tuning: .4byte 0xC1733333 .global lbl_805207A4 lbl_805207A4: .4byte 0x3F733333 .global lbl_805207A8 lbl_805207A8: .4byte 0xC1733333 .global lbl_805207AC lbl_805207AC: .float 0.5 .global lbl_805207B0 lbl_805207B0: .4byte 0x43300000 .4byte 0x00000000 */ /* __ct * --INFO-- * Address: 80434AC0 * Size: 000064 */ P2DScreen::Mgr::Mgr() : J2DScreen() , _118() { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 stw r30, 8(r1) bl __ct__9J2DScreenFv lis r3, __vt__Q29P2DScreen3Mgr@ha addi r30, r31, 0x118 addi r0, r3, __vt__Q29P2DScreen3Mgr@l stw r0, 0(r31) mr r3, r30 bl __ct__5CNodeFv lis r3, __vt__Q29P2DScreen4Node@ha li r0, 0 addi r4, r3, __vt__Q29P2DScreen4Node@l mr r3, r31 stw r4, 0(r30) stw r0, 0x18(r30) lwz r31, 0xc(r1) lwz r30, 8(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 80434B24 * Size: 000138 */ J2DPane* P2DScreen::Mgr::addCallBack(u64 tag, P2DScreen::Node* node) { P2ASSERTLINE(73, (node != nullptr)); J2DPane* pane = search(tag); if (pane != nullptr) { node->_18 = pane; node->doInit(); _118.add(node); } else { // TODO: There's stuff here... of some sort, at least. } return pane; /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) stw r30, 0x18(r1) or. r30, r7, r7 stw r29, 0x14(r1) mr r29, r3 stw r5, 8(r1) stw r6, 0xc(r1) bne lbl_80434B6C lis r3, lbl_8049A6C0@ha lis r5, lbl_8049A6D0@ha addi r3, r3, lbl_8049A6C0@l li r4, 0x49 addi r5, r5, lbl_8049A6D0@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_80434B6C: mr r3, r29 lwz r5, 8(r1) lwz r12, 0(r29) lwz r6, 0xc(r1) lwz r12, 0x3c(r12) mtctr r12 bctrl or. r31, r3, r3 beq lbl_80434BB8 stw r31, 0x18(r30) mr r3, r30 lwz r12, 0(r30) lwz r12, 0x18(r12) mtctr r12 bctrl mr r4, r30 addi r3, r29, 0x118 bl add__5CNodeFP5CNode b lbl_80434C3C lbl_80434BB8: lbz r3, 8(r1) li r0, 0x3f extsb. r3, r3 bne lbl_80434BCC stb r0, 8(r1) lbl_80434BCC: lbz r3, 9(r1) extsb. r3, r3 bne lbl_80434BDC stb r0, 9(r1) lbl_80434BDC: lbz r3, 0xa(r1) extsb. r3, r3 bne lbl_80434BEC stb r0, 0xa(r1) lbl_80434BEC: lbz r3, 0xb(r1) extsb. r3, r3 bne lbl_80434BFC stb r0, 0xb(r1) lbl_80434BFC: lbz r3, 0xc(r1) extsb. r3, r3 bne lbl_80434C0C stb r0, 0xc(r1) lbl_80434C0C: lbz r3, 0xd(r1) extsb. r3, r3 bne lbl_80434C1C stb r0, 0xd(r1) lbl_80434C1C: lbz r3, 0xe(r1) extsb. r3, r3 bne lbl_80434C2C stb r0, 0xe(r1) lbl_80434C2C: lbz r3, 0xf(r1) extsb. r3, r3 bne lbl_80434C3C stb r0, 0xf(r1) lbl_80434C3C: lwz r0, 0x24(r1) mr r3, r31 lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 80434C5C * Size: 000084 */ void P2DScreen::Mgr::addCallBackPane(J2DPane* pane, P2DScreen::Node* node) { P2ASSERTLINE(97, (node != nullptr)); node->_18 = pane; node->doInit(); _118.add(node); } /* * --INFO-- * Address: 80434CE0 * Size: 00004C */ void P2DScreen::Mgr::update(void) { for (Node* node = (Node*)_118.m_child; node != nullptr; node = (Node*)node->m_next) { node->update(); } } /* * --INFO-- * Address: 80434D2C * Size: 000080 */ void P2DScreen::Mgr::draw(Graphics& gfx, J2DGrafContext& context) { J2DScreen::draw(0.0f, 0.0f, &context); for (Node* node = (Node*)_118.m_child; node != nullptr; node = (Node*)node->m_next) { node->draw(gfx, context); } } /* * --INFO-- * Address: 80434DAC * Size: 000088 */ P2DScreen::Mgr_tuning::Mgr_tuning(void) : Mgr() , m_widthMaybe(0.95f) , m_heightMaybe(0.95f) , m_someX(-15.2f) , m_someY(-15.2f) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 stw r30, 8(r1) bl __ct__9J2DScreenFv lis r3, __vt__Q29P2DScreen3Mgr@ha addi r30, r31, 0x118 addi r0, r3, __vt__Q29P2DScreen3Mgr@l stw r0, 0(r31) mr r3, r30 bl __ct__5CNodeFv lis r4, __vt__Q29P2DScreen4Node@ha lis r3, __vt__Q29P2DScreen10Mgr_tuning@ha addi r0, r4, __vt__Q29P2DScreen4Node@l li r4, 0 stw r0, 0(r30) addi r0, r3, __vt__Q29P2DScreen10Mgr_tuning@l lfs f1, lbl_805207A4@sda21(r2) mr r3, r31 stw r4, 0x18(r30) lfs f0, lbl_805207A8@sda21(r2) stw r0, 0(r31) stfs f1, 0x138(r31) stfs f1, 0x13c(r31) stfs f0, 0x140(r31) stfs f0, 0x144(r31) lwz r31, 0xc(r1) lwz r30, 8(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* draw__Q29P2DScreen10Mgr_tuningFR8GraphicsR14J2DGrafContext * --INFO-- * Address: 80434E34 * Size: 000128 */ void P2DScreen::Mgr_tuning::draw(Graphics& gfx, J2DGrafContext& context) { float xfb = (float)System::getRenderModeObj()->xfbHeight; float efb = (float)System::getRenderModeObj()->efbHeight; rotate(xfb * 0.5f, efb * 0.5f, 0x7A, 0.0f); m_scale.x = m_widthMaybe; m_scale.y = m_heightMaybe; calcMtx(); _0D4[0] = m_someX; _0D4[1] = m_someY; calcMtx(); Mgr::draw(gfx, context); /* stwu r1, -0x30(r1) mflr r0 stw r0, 0x34(r1) stw r31, 0x2c(r1) stw r30, 0x28(r1) mr r30, r5 stw r29, 0x24(r1) mr r29, r4 stw r28, 0x20(r1) mr r28, r3 bl getRenderModeObj__6SystemFv lhz r31, 4(r3) bl getRenderModeObj__6SystemFv lhz r5, 6(r3) lis r0, 0x4330 stw r31, 0xc(r1) mr r3, r28 lfd f2, lbl_805207B0@sda21(r2) li r4, 0x7a stw r0, 8(r1) lfs f4, lbl_805207AC@sda21(r2) lfd f0, 8(r1) stw r5, 0x14(r1) fsubs f1, f0, f2 lfs f3, lbl_80520790@sda21(r2) stw r0, 0x10(r1) lfd f0, 0x10(r1) fmuls f1, f4, f1 fsubs f0, f0, f2 fmuls f2, f4, f0 bl rotate__7J2DPaneFff13J2DRotateAxisf lfs f1, 0x13c(r28) mr r3, r28 lfs f0, 0x138(r28) stfs f0, 0xcc(r28) stfs f1, 0xd0(r28) lwz r12, 0(r28) lwz r12, 0x2c(r12) mtctr r12 bctrl lfs f1, 0x144(r28) mr r3, r28 lfs f0, 0x140(r28) stfs f0, 0xd4(r28) stfs f1, 0xd8(r28) lwz r12, 0(r28) lwz r12, 0x2c(r12) mtctr r12 bctrl lfs f1, lbl_80520790@sda21(r2) mr r3, r28 mr r4, r30 fmr f2, f1 bl draw__9J2DScreenFffPC14J2DGrafContext lwz r31, 0x128(r28) b lbl_80434F34 lbl_80434F14: mr r3, r31 mr r4, r29 lwz r12, 0(r31) mr r5, r30 lwz r12, 0x14(r12) mtctr r12 bctrl lwz r31, 4(r31) lbl_80434F34: cmplwi r31, 0 bne lbl_80434F14 lwz r0, 0x34(r1) lwz r31, 0x2c(r1) lwz r30, 0x28(r1) lwz r29, 0x24(r1) lwz r28, 0x20(r1) mtlr r0 addi r1, r1, 0x30 blr */ }
25.737166
95
0.655258
projectPiki
442d9a027b4d6a25aebd2c64f082ac438d192a60
3,960
cc
C++
tutorials/t1.cc
dianpeng/hge-unix
0cade62a3494f1508cdaaa620714e69ae151e0c1
[ "Zlib" ]
null
null
null
tutorials/t1.cc
dianpeng/hge-unix
0cade62a3494f1508cdaaa620714e69ae151e0c1
[ "Zlib" ]
null
null
null
tutorials/t1.cc
dianpeng/hge-unix
0cade62a3494f1508cdaaa620714e69ae151e0c1
[ "Zlib" ]
null
null
null
/* ** Haaf's Game Engine 1.8 ** Copyright (C) 2003-2007, Relish Games ** hge.relishgames.com ** ** hge_tut05 - Using distortion mesh */ // Copy the files "particles.png", "menu.wav", // "font1.fnt", "font1.png" and "trail.psi" from // the folder "precompiled" to the folder with // executable file. Also copy hge.dll and bass.dll // to the same folder. #include <hge/hge.h> #include <hge/hgefont.h> #include <hge/hgedistort.h> #include <math.h> // Pointer to the HGE interface. // Helper classes require this to work. HGE *hge=0; HTEXTURE tex; // Pointers to the HGE objects we will use hgeDistortionMesh* dis; hgeFont* fnt; // Some "gameplay" variables const int nRows=16; const int nCols=16; const float cellw=512.0f/(nCols-1); const float cellh=512.0f/(nRows-1); const float meshx=144; const float meshy=44; bool FrameFunc() { float dt=hge->Timer_GetDelta(); static float t=0.0f; static int trans=0; int i, j, col; float r, a, dx, dy; t+=dt; // Process keys switch(hge->Input_GetKey()) { case HGEK_ESCAPE: return true; case HGEK_SPACE: if(++trans > 2) trans=0; dis->Clear(0xFF000000); break; } // Calculate new displacements and coloring for one of the three effects switch(trans) { case 0: for(i=1;i<nRows-1;i++) for(j=1;j<nCols-1;j++) { dis->SetDisplacement(j,i,cosf(t*10+(i+j)/2)*5,sinf(t*10+(i+j)/2)*5,HGEDISP_NODE); } break; case 1: for(i=0;i<nRows;i++) for(j=1;j<nCols-1;j++) { dis->SetDisplacement(j,i,cosf(t*5+j/2)*15,0,HGEDISP_NODE); col=int((cosf(t*5+(i+j)/2)+1)*35); dis->SetColor(j,i,0xFF<<24 | col<<16 | col<<8 | col); } break; case 2: for(i=0;i<nRows;i++) for(j=0;j<nCols;j++) { r=sqrtf(powf(j-(float)nCols/2,2)+powf(i-(float)nRows/2,2)); a=r*cosf(t*2)*0.1f; dx=sinf(a)*(i*cellh-256)+cosf(a)*(j*cellw-256); dy=cosf(a)*(i*cellh-256)-sinf(a)*(j*cellw-256); dis->SetDisplacement(j,i,dx,dy,HGEDISP_CENTER); col=int((cos(r+t*4)+1)*40); dis->SetColor(j,i,0xFF<<24 | col<<16 | (col/2)<<8); } break; } return false; } bool RenderFunc() { // Render graphics hge->Gfx_BeginScene(); hge->Gfx_Clear(0); dis->Render(meshx, meshy); fnt->printf(5, 5, HGETEXT_LEFT, "dt:%.3f\nFPS:%d\n\nUse your\nSPACE!", hge->Timer_GetDelta(), hge->Timer_GetFPS()); hge->Gfx_EndScene(); return false; } #ifdef PLATFORM_UNIX int main(int argc, char *argv[]) #else int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) #endif { hge = hgeCreate(HGE_VERSION); hge->System_SetState(HGE_LOGFILE, "hge_tut05.log"); hge->System_SetState(HGE_FRAMEFUNC, FrameFunc); hge->System_SetState(HGE_RENDERFUNC, RenderFunc); hge->System_SetState(HGE_TITLE, "HGE Tutorial 05 - Using distortion mesh"); hge->System_SetState(HGE_WINDOWED, true); hge->System_SetState(HGE_SCREENWIDTH, 800); hge->System_SetState(HGE_SCREENHEIGHT, 600); hge->System_SetState(HGE_SCREENBPP, 32); hge->System_SetState(HGE_USESOUND, false); if(hge->System_Initiate()) { // Load sound and texture tex=hge->Texture_Load("texture.jpg"); if(!tex) { // If one of the data files is not found, display // an error message and shutdown. #ifdef PLATFORM_UNIX fprintf(stderr, "Error: Can't load texture.jpg\n"); #else MessageBox(NULL, "Can't load texture.jpg", "Error", MB_OK | MB_ICONERROR | MB_APPLMODAL); #endif hge->System_Shutdown(); hge->Release(); return 0; } // Create a distortion mesh dis=new hgeDistortionMesh(nCols, nRows); dis->SetTexture(tex); dis->SetTextureRect(0,0,512,512); dis->SetBlendMode(BLEND_COLORADD | BLEND_ALPHABLEND | BLEND_ZWRITE); dis->Clear(0xFF000000); // Load a font fnt=new hgeFont("font1.fnt"); // Let's rock now! hge->System_Start(); // Delete created objects and free loaded resources delete fnt; delete dis; hge->Texture_Free(tex); } // Clean up and shutdown hge->System_Shutdown(); hge->Release(); return 0; }
22.372881
116
0.658586
dianpeng
442e79aacca64364cf997543eca13ef35318ad63
4,525
cpp
C++
homework/Kulagin/07/main.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
10
2017-09-21T15:17:33.000Z
2021-01-11T13:11:55.000Z
homework/Kulagin/07/main.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
null
null
null
homework/Kulagin/07/main.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
22
2017-09-21T15:45:08.000Z
2019-02-21T19:15:25.000Z
#include <iostream> #include <cmath> #include <cstring> #include "src/calc.cpp" using namespace std; const double precision = 1e-15; template<typename T> void is(std::string text, T value, bool positive = true) { const char* text_ptr = text.c_str(); Calculator<T> calc; try { auto result = calc.eval((char*)text_ptr); if (abs(result - value) < precision) { if (positive) { cout << "'" << text << "'" << " == " << value << " - "; cout << "ok" << endl; } else { cout << "'" << text << "'" << " != " << value << " - "; cout << "not ok" << " " << "(got: " << result << ")" << endl; } } else { if (positive) { cout << "'" << text << "'" << " == " << value << " - "; cout << "not ok" << " " << "(got: " << result << ")" << endl; } else { cout << "'" << text << "'" << " != " << value << " - "; cout << "ok" << endl; } } } catch (Error& e) { if (positive) { cout << "'" << text << "'" << " == " << value << " - "; cout << "not ok " << endl; } else { cout << "'" << text << "'" << " != " << value << " - "; cout << "ok " << endl; } cout << e.err_msg() << endl; } } template <typename T> void check_calc() { const double Pi = 3.14; const double e = 2.7; // POSITIVE TESTS cout << "POSITIVE TESTS:" << endl; is<T>("1", 1); is<T>(" 1", 1); is<T>("+1", 1); is<T>("-1", -1); is<T>("1+2", 3); is<T>("1 + 2", 3); is<T>(" +1 + +2", 3); is<T>(" -1 + -2", -3); is<T>(" -1 - 2", -3); is<T>(" -1 - -2", 1); is<T>("2 - 6 * 2 / 2", -4); is<T>("2 - 6 / 2 * 2", -4); is<T>("3 + 4 * 2 - -1", 12); is<T>("2*-2", -4); is<T>(" +2 * -2", -4); is<T>(" -2 * +2", -4); is<T>("Pi", (T)Pi); is<T>("e", (T)e); is<T>("Pi + e", (T)Pi + (T)e); is<T>("Pi + 3", (T)Pi + 3); is<T>("-Pi + 4", -(T)Pi + 4); is<T>(" +5 + Pi", 5 + (T)Pi); is<T>(" +6 + -Pi", 6 - (T)Pi); is<T>(" -7 - +Pi", -7 - (T)Pi); is<T>("(1)", 1); is<T>("(-1)", -1); is<T>("-(1)", -1); is<T>("-(-1)", 1); is<T>("(Pi)", (T)Pi); is<T>("(-Pi)", -(T)Pi); is<T>("-(Pi)", -(T)Pi); is<T>("-(-Pi)", (T)Pi); is<T>("(e)", (T)e); is<T>("(-e)", -(T)e); is<T>("-(e)", -(T)e); is<T>("-(-e)", (T)e); is<T>(" ( e+3 ) + 5", (T)e + 3 + 5); is<T>(" ( e*3 ) + 5", (T)e * 3 + 5); is<T>("e + (3) + 4", (T)e + 3 + 4); is<T>("e + (3 + 4) ", (T)e + (3 + 4)); is<T>("e / (5) ", (T)((T)e / 5)); is<T>("e / (6 + 7) ", (T)((T)e / (6 + 7))); is<T>("(8 - e) / (9 + 10) ", (T)((8 - (T)e) / (9 + 10))); is<T>("2.5", (T)2.5); is<T>("(2.5)", (T)2.5); is<T>("(-2.5)", -(T)2.5); is<T>("-(2.5)", -(T)2.5); is<T>("2.5 + 2.5", (T)5); is<T>("2.5 + -2.5", 0); is<T>(" -2.5 + 2.5", 0); is<T>(" -2.5 + -2.5", (T) - 5); is<T>(" -2.5 - -2.5", 0); is<T>(" -2.5 * 3.25", (T)((T) - 2.5 * (T)3.25)); is<T>("2.445332664432 - 1223.434545634", (T)((T)2.445332664432 - (T)1223.434545634)); is<T>("5 + 0.", 5); is<T>("5 + 0.", 5); is<T>("5 + +0.", 5); is<T>("5 + +.0", 5); is<T>("5 - +0.", 5); is<T>("5 - +.0", 5); is<T>("5 - +1.", 4); is<T>("5 - +.6", (T)4.4); is<T>("22323232137128931", (T)22323232137128931); cout << endl; // NEGATIVE TESTS cout << "NEGATIVE TESTS:" << endl; is<T>("1 + +1", 0, false); is<T>("2 2", 0, false); is<T>("((3+3", 0, false); is<T>("3+3))", 0, false); is<T>("(3)+3)", 0, false); is<T>("(3)+4/(5-0)", 0, false); is<T>(".5 + 2", 0, false); is<T>("(1 + 2", 0, false); is<T>(")1 + 2", 0, false); is<T>("4*+ 5", 0, false); is<T>("5 + .", 5, false); is<T>("2..+* 2", 0, false); is<T>("r", 12, false); } int main(int argc, char** argv) { if (argc < 3) { cout << "Testing for 'int' type:" << endl << endl; check_calc<int>(); cout << endl << endl << endl; cout << "Testing for 'long' type:" << endl << endl; check_calc<long>(); cout << endl << endl << endl; cout << "Testing for 'double' type:" << endl; check_calc<double>(); cout << endl; } else { const char* type = argv[2]; if (strcmp(type, "int") == 0 || strcmp(type, "Int") == 0) { Calculator<int> calc; cout << calc.eval((char*) argv[1]) << endl; } else if (strcmp(type, "long") == 0 || strcmp(type, "Long") == 0) { Calculator<int> calc; cout << calc.eval((char*) argv[1]) << endl; } else if (strcmp(type, "double") == 0 || strcmp(type, "Double") == 0) { Calculator<double> calc; cout << calc.eval((char*) argv[1]) << endl; } else { cout << "Usage: ./a.out <expression> <type>" << endl << endl; cout << "<type>: int, long, double" << endl << endl; cout << "Example: ./a.out '1+2' int" << endl; } } return 0; }
23.086735
86
0.417901
mtrempoltsev
442f94ea5083e8f9b8e8d2d90652d22d4b0240d5
8,270
cpp
C++
process.cpp
mastmees/reflow_oven
87cd23341e7fd70a18ddf194d513ae281879e9f3
[ "MIT" ]
2
2019-02-22T18:41:05.000Z
2019-05-17T14:45:56.000Z
process.cpp
mastmees/reflow_oven
87cd23341e7fd70a18ddf194d513ae281879e9f3
[ "MIT" ]
null
null
null
process.cpp
mastmees/reflow_oven
87cd23341e7fd70a18ddf194d513ae281879e9f3
[ "MIT" ]
null
null
null
/* The MIT License (MIT) Copyright (c) 2017 Madis Kaal <mast@nomad.ee> 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 "process.hpp" #include "settings.hpp" extern Button startbutton; PID pidcontroller(10.0,0.0,0.0); extern Oven oven; #define SHOWPROFILE1() (PORTD|=_BV(PD4)) #define SHOWPROFILE0() (PORTD&=(~_BV(PD4))) #define FAULT_BLINK() (PORTD^=_BV(PD4)) // assume starting at 25degC // normal heating rate 2 degC/sec // normal cooling rate 3 degC/sec struct ProfileStep leadedsteps[] = { { ProfileStep::DOOR_CLOSE, 0}, { 100, 60 }, // heat up to 100, this will lag and overshoot { 120, 30 }, // ride the overshoot to up to 150 { 150, 40 }, // get to preheat temperature, still overshooting here { 150, 60 }, // stay at preheat { 185, 30 }, // ramp to reflow { 210, 20 }, // fast towards peak reflow, this will also overshoot { 228, 10 }, // reset controller then take last step { 228, 3 }, // reset controller then take last step { ProfileStep::DOOR_OPEN, 0}, { 60, 60 }, // rapid cooldown { ProfileStep::PROCESS_DONE, 0 } // done }; struct ProfileStep leadfreesteps[] = { { ProfileStep::DOOR_CLOSE,0 }, { 100, 60 }, { 125, 30 }, { 160, 20 }, { 180, 30 }, { 200,30 }, // preheat, ramp to 200 in 90 seconds { 200,5 }, // hold for 5 seconds { 210,25 }, // ramp up to reflow temp at nominal rate { 235,10 }, { 250,10 }, // ramp up to peak reflow at faster rate { 250,4 }, // stay at peak for 4 seconds { ProfileStep::DOOR_OPEN,0 }, { 60,60 }, // cool down to 60deg { ProfileStep::PROCESS_DONE, 0 } // done }; struct Profile leadedprofile = { &leadedsteps[0], 160, 200 }; struct Profile leadfreeprofile = { &leadfreesteps[0], 190, 215 }; void Process::SetProfile(Profile *p) { profile=p; step=&p->steps[0]; while (1) { if (step->temp==ProfileStep::PROCESS_DONE) { state=STOPPING; serial.print("#no steps in process?\n"); return; } if (step->temp==ProfileStep::DOOR_OPEN) { oven.CoolerOn(); serial.print("#opening door\n"); step++; continue; } if (step->temp==ProfileStep::DOOR_CLOSE) { oven.CoolerOff(); serial.print("#closing door\n"); step++; continue; } if (step->temp>0) break; step++; // safeguard for special steps not handled here } targettemp=step->temp; setpoint=oven.Temperature(); if (step->seconds==0) setpointstep=targettemp-setpoint; else setpointstep=(targettemp-setpoint)/step->seconds; pidcontroller.SetSetPoint(setpoint); pidcontroller.Reset(); runningtime=0; } void Process::ProcessTick() { float v=oven.Temperature(); if (step->seconds>runningtime) { // minimum time not expired yet setpoint+=setpointstep; pidcontroller.SetSetPoint(setpoint); } else { pidcontroller.SetSetPoint(targettemp); setpoint=targettemp; if (setpointstep>=0.0) { // ramping upwards if (v>=targettemp) { while (1) { step++; if (step->temp==ProfileStep::PROCESS_DONE) { state=STOPPING; serial.print("#last step reached\n"); return; } if (step->temp==ProfileStep::DOOR_OPEN) { oven.CoolerOn(); serial.print("#opening door\n"); continue; } if (step->temp==ProfileStep::DOOR_CLOSE) { oven.CoolerOff(); serial.print("#closing door\n"); continue; } if (step->temp>0) break; } if (step->temp==targettemp) setpointstep=0.0; else { targettemp=step->temp; if (step->seconds) setpointstep=(targettemp-v)/step->seconds; else setpointstep=(targettemp-v); } runningtime=0; pidcontroller.Reset(); } } else { // ramping downwards or steady if (v<=targettemp) { while (1) { step++; if (step->temp==ProfileStep::PROCESS_DONE) { state=STOPPING; serial.print("#last step reached\n"); return; } if (step->temp==ProfileStep::DOOR_OPEN) { oven.CoolerOn(); serial.print("#opening door\n"); continue; } if (step->temp==ProfileStep::DOOR_CLOSE) { oven.CoolerOff(); serial.print("#closing door\n"); continue; } if (step->temp>0) break; } if (step->temp==targettemp) setpointstep=0.0; else { targettemp=step->temp; if (step->seconds) setpointstep=(targettemp-v)/step->seconds; else setpointstep=targettemp-v; } runningtime=0; pidcontroller.Reset(); } } } runningtime++; } Process::Process() { state=STOPPING; timestamp=(unsigned int)-1; pidoutput=0; profile=NULL; pwmcounter=0; targettemp=0.0; setpointstep=0.0; setpoint=0.0; } void Process::Run() { float v; switch (state) { case STOPPING: serial.print("Stopping\n"); oven.Reset(); startbutton.Clear(); state=STOPPED; break; case STOPPED: if (oven.IsFaulty()) { state=FAULT; break; } if (profilebutton.Pressed()) SHOWPROFILE1(); else SHOWPROFILE0(); if (startbutton.Read()) state=STARTING; break; case STARTING: pidcontroller.SetOutputLimits(-127,127); pidcontroller.SetCoefficents(settings.P,settings.I,settings.D); if (profilebutton.Pressed()) { serial.print("#Lead-free profile\n"); SetProfile(&leadfreeprofile); SHOWPROFILE1(); } else { serial.print("#Leaded profile\n"); SetProfile(&leadedprofile); SHOWPROFILE0(); } serial.print("Starting\n"); serial.print("time#i4,target#f4,setpoint#f4,temperature#f4,pidoutput#i4\n"); second_counter=0; oven.ConvectionOn(); oven.CoolerOff(); state=RUNNING; break; case RUNNING: if (oven.IsFaulty()) { state=FAULT; break; } // if (startbutton.Read()) state=STOPPING; // if (timestamp!=second_counter && targettemp>=0.0) { v=oven.Temperature(); pidoutput=pidcontroller.ProcessInput(v); if (pidoutput>=0) { oven.SetPWM(pidoutput); } else { oven.SetPWM(0); } ProcessTick(); serial.print(second_counter); serial.send(','); serial.print(targettemp); serial.send(','); serial.print(setpoint); serial.send(','); serial.print(v); serial.send(','); serial.print((int32_t)pidoutput); serial.send('\n'); } break; case FAULT: serial.print("#Fault\n"); oven.Reset(); state=BLINKING; break; case BLINKING: if (timestamp!=second_counter) { FAULT_BLINK(); } if (!oven.IsFaulty()) { serial.print("#Fault cleared\n"); state=STOPPING; } break; } timestamp=second_counter; }
26.850649
82
0.586699
mastmees
443291baa2a8a1f8c4d2c2d3e4a7761b7f1eae63
2,922
hpp
C++
Programming Guide/Headers/Siv3D/GUITextField.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
38
2016-01-14T13:51:13.000Z
2021-12-29T01:49:30.000Z
Programming Guide/Headers/Siv3D/GUITextField.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
null
null
null
Programming Guide/Headers/Siv3D/GUITextField.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
16
2016-01-15T11:07:51.000Z
2021-12-29T01:49:37.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2016 Ryo Suzuki // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Fwd.hpp" # include "IWidget.hpp" # include "WidgetStyle.hpp" namespace s3d { class GUITextField : public IWidget { private: Optional<size_t> m_maxLength; size_t m_cursorPos = 0; String m_text; double m_pressedPressure = 0.0; double m_scaling = 0.0; bool m_mouseOver = false; bool m_hasChanged = false; bool m_enabled = true; bool m_active = false; Point ItemSize() const; Point TextRegion() const; Rect MarginBox(const Point& offset) const; Rect PaddingBox(const Point& offset) const; Rect ItemBox(const Point& offset) const; public: static const String& Name() { static const String name = L"TextField"; return name; } static std::shared_ptr<GUITextField> Create(const Optional<size_t>& maxLength, const WidgetStyle& style = WidgetStyle()) { return std::make_shared<GUITextField>(maxLength, true, style); } static std::shared_ptr<GUITextField> Create(const Optional<size_t>& maxLength, bool enabled, const WidgetStyle& style = WidgetStyle()) { return std::make_shared<GUITextField>(maxLength, enabled, style); } GUITextField() {} GUITextField(const Optional<size_t>& maxLength, bool enabled, const WidgetStyle& style); const String& getWidgetName() const override; Size getSize() const override; bool forceNewLineBefore() const override; bool forceNewLineAfter() const override; void update(const WidgetState& state) override; void draw(const WidgetState& state) const override; bool& getEnabled(); bool& getActive(); const String& getText() const; void setText(const String& text); const Optional<size_t>& getMaxLength() const; void setMaxLength(const Optional<size_t>& length); Property_Get(bool, mouseOver) const; Property_Get(bool, hasChanged) const; }; class GUITextFieldWrapper { public: using WidgetType = GUITextField; private: friend class GUI; std::shared_ptr<WidgetType> m_widget; GUITextFieldWrapper(const std::shared_ptr<WidgetType>& widget) : m_widget(widget ? widget : std::make_shared<WidgetType>()) , enabled(m_widget->getEnabled()) , active(m_widget->getActive()) , style(m_widget->m_style) {} GUITextFieldWrapper& operator = (const GUITextFieldWrapper&) = delete; static const String& WidgetTypeName() { return WidgetType::Name(); } public: bool& enabled; bool& active; WidgetStyle& style; Property_Get(bool, mouseOver) const; Property_Get(bool, hasChanged) const; Property_Get(const String&, text) const; void setText(const String& text); Property_Get(Optional<size_t>, maxLength) const; void setMaxLength(const Optional<size_t>& length); }; }
19.877551
136
0.689254
Reputeless
443388b6babb77ef756c43f749b560bb5f1b63f6
12,598
cpp
C++
PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gelss.cpp
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
[ "MIT" ]
null
null
null
PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gelss.cpp
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
[ "MIT" ]
null
null
null
PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gelss.cpp
diku-dk/PROX
c6be72cc253ff75589a1cac28e4e91e788376900
[ "MIT" ]
null
null
null
// // Copyright Jesse Manning 2007 // // 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) // #include "convenience.h" #include <boost/numeric/bindings/lapack/gelss.hpp> // set to 1 to write test output to file, otherwise outputs to console #define OUTPUT_TO_FILE 0 // determines which tests to run #define TEST_SQUARE 1 #define TEST_UNDERDETERMINED 1 #define TEST_OVERDETERMINED 1 #define TEST_MULTIPLE_SOLUTION_VECTORS 1 // determines if optimal, minimal, or both workspaces are used for testing #define USE_OPTIMAL_WORKSPACE 1 #define USE_MINIMAL_WORKSPACE 1 namespace lapack = boost::numeric::bindings::lapack; // test function declarations template <typename StreamType, typename MatrType, typename VecType> int test_square_gelss(StreamType& oss); template <typename StreamType, typename MatType, typename VecType> int test_under_gelss(StreamType& oss); template <typename StreamType, typename MatType, typename VecType> int test_over_gelss(StreamType& oss); template <typename StreamType, typename MatType, typename VecType> int test_multiple_gelss(StreamType& oss); template <typename StreamType, typename MatType, typename VecType> int test_transpose_gel(StreamType& oss, const char& trans); int main() { // stream for test output typedef std::ostringstream stream_t; stream_t oss; #if TEST_SQUARE oss << "Start Square Matrix Least Squares Tests" << std::endl; oss << "Testing sgelss" << std::endl; if (test_square_gelss<stream_t, fmat_t, fvec_t>(oss) == 0) { oss << "sgelss passed." << std::endl; } oss << "End sgelss tests" << std::endl; oss << std::endl; oss << "Testing dgelss" << std::endl; if (test_square_gelss<stream_t, dmat_t, dvec_t>(oss) == 0) { oss << "dgelss passed." << std::endl; } oss << "End dgelss tests" << std::endl; oss << std::endl; oss << "Testing cgelss" << std::endl; if (test_square_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0) { oss << "cgelss passed." << std::endl; } oss << "End cgelss tests" << std::endl; oss << std::endl; oss << "Testing zgelss" << std::endl; if (test_square_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0) { oss << "zgelss passed." << std::endl; } oss << "End zgelss tests" << std::endl; oss << std::endl; oss << "End Square Matrix Least Squares Tests" << std::endl; #endif #if TEST_UNDERDETERMINED oss << std::endl; oss << "Start Under-determined Matrix Least Squares Test" << std::endl; oss << "Testing sgelss" << std::endl; if (test_under_gelss<stream_t, fmat_t, fvec_t>(oss) == 0) { oss << "sgelss passed." << std::endl; } oss << "End sgelss tests" << std::endl; oss << std::endl; oss << "Testing dgelss" << std::endl; if (test_under_gelss<stream_t, dmat_t, dvec_t>(oss) == 0) { oss << "dgelss passed." << std::endl; } oss << "End dgelss tests" << std::endl; oss << std::endl; oss << "Testing cgelss" << std::endl; if (test_under_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0) { oss << "cgelss passed." << std::endl; } oss << "End cgelss tests" << std::endl; oss << std::endl; oss << "Testing zgelss" << std::endl; if (test_under_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0) { oss << "zgelss passed." << std::endl; } oss << "End zgelss tests" << std::endl; oss << std::endl; oss << "End Underdetermined Matrix Least Squares Tests" << std::endl; #endif #if TEST_OVERDETERMINED oss << std::endl; oss << "Start Overdetermined Matrix Least Squares Test" << std::endl; oss << "Testing sgelss" << std::endl; if (test_over_gelss<stream_t, fmat_t, fvec_t>(oss) == 0) { oss << "sgelss passed." << std::endl; } oss << "End sgelss tests" << std::endl; oss << std::endl; oss << "Testing dgelss" << std::endl; if (test_over_gelss<stream_t, dmat_t, dvec_t>(oss) == 0) { oss << "dgelss passed." << std::endl; } oss << "End dgelss tests" << std::endl; oss << std::endl; oss << "Testing cgelss" << std::endl; if (test_over_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0) { oss << "cgelss passed." << std::endl; } oss << "End cgelss tests" << std::endl; oss << std::endl; oss << "Testing zgelss" << std::endl; if (test_over_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0) { oss << "zgelss passed." << std::endl; } oss << "End zgelss tests" << std::endl; oss << std::endl; oss << "End Overdetermined Matrix Least Squares Test" << std::endl; #endif #if TEST_MULTIPLE_SOLUTION_VECTORS oss << std::endl; oss << "Start Multiple Solution Vectors Least Squares Test" << std::endl; oss << "Testing sgelss" << std::endl; if (test_multiple_gelss<stream_t, fmat_t, fvec_t>(oss) == 0) { oss << "sgelss passed." << std::endl; } oss << "End sgelss tests" << std::endl; oss << std::endl; oss << "Testing dgelss" << std::endl; if (test_multiple_gelss<stream_t, dmat_t, dvec_t>(oss) == 0) { oss << "dgelss passed." << std::endl; } oss << "End dgelss tests" << std::endl; oss << std::endl; oss << "Testing cgelss" << std::endl; if (test_multiple_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0) { oss << "cgelss passed." << std::endl; } oss << "End cgelss tests" << std::endl; oss << std::endl; oss << "Testing zgelss" << std::endl; if (test_multiple_gelss<stream_t, fcmat_t, fcvec_t>(oss) == 0) { oss << "zgelss passed." << std::endl; } oss << "End zgelss tests" << std::endl; oss << std::endl; oss << "End Multiple Solution Vectors Least Squares Test" << std::endl; #endif #if OUTPUT_TO_FILE // Finished testing std::cout << std::endl; std::cout << "Tests Completed." << std::endl; std::cout << std::endl; std::string filename; std::cout << "Enter filename to write test results: "; std::getline(std::cin, filename); std::ofstream testFile(filename.c_str()); if (testFile) { testFile << oss.str(); testFile.close(); } #else std::cout << oss.str() << std::endl; // Finished testing std::cout << std::endl; std::cout << "Tests Completed." << std::endl; std::cout << std::endl; #endif // wait for user to finish // std::string done; // std::cout << "Press Enter to exit"; // std::getline(std::cin, done); } // tests square system (m-by-n where m == n) template <typename StreamType, typename MatType, typename VecType> int test_square_gelss(StreamType& oss) { // return value int err = 0; // square matrix test MatType mat(MatrixGenerator<MatType>()(row_size, col_size)); VecType vec(VectorGenerator<VecType>()(row_size)); //const int m = traits::matrix_size1(mat); const int n = traits::matrix_size2(mat); #if USE_OPTIMAL_WORKSPACE MatType optimalmat(mat); VecType optimalvec(vec); err += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace()); VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n))); VecType optimal_check = ublas::prod(mat, optimalanswer); #endif #if USE_MINIMAL_WORKSPACE MatType minimalmat(mat); VecType minimalvec(vec); err += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace()); VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n))); VecType minimal_check = ublas::prod(mat, minimalanswer); #endif matrix_print(oss, "A", mat); oss << std::endl; vector_print(oss, "B", vec); oss << std::endl; #if USE_OPTIMAL_WORKSPACE vector_print(oss, "optimal workspace x", optimalanswer); oss << std::endl; #endif #if USE_MINIMAL_WORKSPACE vector_print(oss, "minimal workspace x", minimalanswer); oss << std::endl; #endif #if USE_OPTIMAL_WORKSPACE // check A*x=B vector_print(oss, "optimal A*x=B", optimal_check); oss << std::endl; #endif #if USE_MINIMAL_WORKSPACE vector_print(oss, "minimal A*x=B", minimal_check); oss << std::endl; #endif return err; } // tests overdetermined system (m-by-n where m < n) template <typename StreamType, typename MatType, typename VecType> int test_under_gelss(StreamType& oss) { // return value int err = 0; // under-determined matrix test MatType mat(MatrixGenerator<MatType>()(row_range, col_size)); VecType vec(VectorGenerator<VecType>()(row_size)); //const int m = traits::matrix_size1(mat); const int n = traits::matrix_size2(mat); #if USE_OPTIMAL_WORKSPACE MatType optimalmat(mat); VecType optimalvec(vec); err += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace()); VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n))); VecType optimal_check = ublas::prod(mat, optimalanswer); #endif #if USE_MINIMAL_WORKSPACE MatType minimalmat(mat); VecType minimalvec(vec); err += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace()); VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n))); VecType minimal_check = ublas::prod(mat, minimalanswer); #endif matrix_print(oss, "A", mat); oss << std::endl; vector_print(oss, "B", vec); oss << std::endl; #if USE_OPTIMAL_WORKSPACE vector_print(oss, "optimal workspace x", optimalanswer); oss << std::endl; #endif #if USE_MINIMAL_WORKSPACE vector_print(oss, "minimal workspace x", minimalanswer); oss << std::endl; #endif #if USE_OPTIMAL_WORKSPACE // check A*x=B vector_print(oss, "optimal A*x=B", optimal_check); oss << std::endl; #endif #if USE_MINIMAL_WORKSPACE vector_print(oss, "minimal A*x=B", minimal_check); oss << std::endl; #endif return err; } // tests overdetermined system (m-by-n where m > n) template <typename StreamType, typename MatType, typename VecType> int test_over_gelss(StreamType& oss) { // return value int err = 0; // overdetermined matrix test MatType mat(MatrixGenerator<MatType>()(row_size, col_range)); VecType vec(VectorGenerator<VecType>()(row_size)); //const int m = traits::matrix_size1(mat); const int n = traits::matrix_size2(mat); #if USE_OPTIMAL_WORKSPACE MatType optimalmat(mat); VecType optimalvec(vec); err += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace()); VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n))); VecType optimal_check = ublas::prod(mat, optimalanswer); #endif #if USE_MINIMAL_WORKSPACE MatType minimalmat(mat); VecType minimalvec(vec); err += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace()); VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n))); VecType minimal_check = ublas::prod(mat, minimalanswer); #endif matrix_print(oss, "A", mat); oss << std::endl; vector_print(oss, "B", vec); oss << std::endl; #if USE_OPTIMAL_WORKSPACE vector_print(oss, "optimal workspace x", optimalanswer); oss << std::endl; #endif #if USE_MINIMAL_WORKSPACE vector_print(oss, "minimal workspace x", minimalanswer); oss << std::endl; #endif #if USE_OPTIMAL_WORKSPACE // check A*x=B vector_print(oss, "optimal A*x=B", optimal_check); oss << std::endl; #endif #if USE_MINIMAL_WORKSPACE vector_print(oss, "minimal A*x=B", minimal_check); oss << std::endl; #endif return err; } // tests multiple solution vectors stored column-wise in B for equation A*x=B template <typename StreamType, typename MatType, typename VecType> int test_multiple_gelss(StreamType& oss) { // return value int err = 0; // multiple solutions vectors test MatType mat(MatrixGenerator<MatType>()(row_size, col_size)); MatType vec(mat.size1(), 2); ublas::column(vec, 0) = VectorGenerator<VecType>()(mat.size1()); ublas::column(vec, 1) = VectorGenerator<VecType>()(mat.size1()); //const int m = traits::matrix_size1(mat); const int n = traits::matrix_size2(mat); const int nrhs = traits::matrix_size2(vec); #if USE_OPTIMAL_WORKSPACE MatType optimalmat(mat); MatType optimalvec(vec); err += lapack::gelss(optimalmat, optimalvec, lapack::optimal_workspace()); MatType optimalanswer(ublas::project(optimalvec, ublas::range(0, n), ublas::range(0, nrhs))); MatType optimal_check = ublas::prod(mat, optimalanswer); #endif #if USE_MINIMAL_WORKSPACE MatType minimalmat(mat); MatType minimalvec(vec); err += lapack::gelss(minimalmat, minimalvec, lapack::minimal_workspace()); MatType minimalanswer(ublas::project(minimalvec, ublas::range(0, n), ublas::range(0, nrhs))); MatType minimal_check = ublas::prod(mat, minimalanswer); #endif matrix_print(oss, "A", mat); oss << std::endl; matrix_print(oss, "B", vec); oss << std::endl; #if USE_OPTIMAL_WORKSPACE matrix_print(oss, "optimal workspace x", optimalanswer); oss << std::endl; #endif #if USE_MINIMAL_WORKSPACE matrix_print(oss, "minimal workspace x", minimalanswer); oss << std::endl; #endif #if USE_OPTIMAL_WORKSPACE // check A*x=B matrix_print(oss, "optimal A*x=B", optimal_check); oss << std::endl; #endif #if USE_MINIMAL_WORKSPACE matrix_print(oss, "minimal A*x=B", minimal_check); oss << std::endl; #endif return err; }
28.631818
94
0.698285
diku-dk
4433de13cab58b0713671dab27b56af01cbcca59
3,282
cpp
C++
Crossy_Roads/WaterParticles.cpp
Daryan7/Crossy_Roads
af816aa73ba29241fb1db4722940e42be8a76102
[ "MIT" ]
1
2018-04-18T12:54:33.000Z
2018-04-18T12:54:33.000Z
Crossy_Roads/WaterParticles.cpp
Daryan7/Crossy_Roads
af816aa73ba29241fb1db4722940e42be8a76102
[ "MIT" ]
null
null
null
Crossy_Roads/WaterParticles.cpp
Daryan7/Crossy_Roads
af816aa73ba29241fb1db4722940e42be8a76102
[ "MIT" ]
null
null
null
#include "WaterParticles.h" #include "Utils.h" #include "Object.h" using namespace glm; inline void compileShader(ShaderProgram& program, const string& fileName) { Shader vShader, fShader; string path = "shaders/" + fileName; vShader.initFromFile(VERTEX_SHADER, path + ".vert"); if (!vShader.isCompiled()) { cout << "Vertex Shader " + fileName + " Error" << endl; cout << "" << vShader.log() << endl << endl; } fShader.initFromFile(FRAGMENT_SHADER, path + ".frag"); if (!fShader.isCompiled()) { cout << "Fragment Shader " + fileName + " Error" << endl; cout << "" << fShader.log() << endl << endl; } program.init(); program.addShader(vShader); program.addShader(fShader); program.link(); if (!program.isLinked()) { cout << "Shader " + fileName + " Linking Error" << endl; cout << "" << program.log() << endl << endl; } vShader.free(); fShader.free(); for (uint i = 0; i < sizeof(uniformOrder) / sizeof(string); ++i) { program.addUniform(uniformOrder[i]); } } void WaterParticleSystem::firstInit() { compileShader(program, "simpleColor"); program.bindFragmentOutput("outColor"); colorLoc = program.addUniform("color"); lightLoc = program.addUniform("lightDir"); } void WaterParticleSystem::init(const Assets & assets) { GameObject::init(); mesh = assets.getCubeMesh(); texture = assets.getTexture("water_plane"); } void WaterParticleSystem::trigger(vec3 pos, uint numParticles, vec4 color) { this->color = color; pos.y += mesh->getbbSize().y*0.3f/2; this->pos = pos; uint nParticles = numParticles + between(-5, 5); particles.resize(nParticles); for (uint i = 0; i < nParticles; ++i) { float horzAngle = between(0.f, 2 * PI); float vertAngle = between(0.f, PI / 2); particles[i].position = pos; particles[i].speed = vec3(cos(horzAngle)*0.2f, sin(vertAngle), sin(horzAngle)*0.2f); particles[i].lifetime = (uint)ceil(2 * (-particles[i].speed.y / g)); particles[i].scale = 0.3f; particles[i].state = Falling; } } void WaterParticleSystem::update() { uint j = 0; for (uint i = 0; i < particles.size(); i++) { particles[i].lifetime -= 1; switch (particles[i].state) { case Falling: particles[i] = particles[j]; if (particles[j].lifetime > 0) { particles[j].speed.y += g; particles[j].position += particles[j].speed; } else { particles[j].position.y = pos.y; particles[j].state = Stopped; particles[j].lifetime = uint(particles[i].scale / 0.01f); } ++j; break; case Stopped: if (particles[i].lifetime > 0) { particles[j] = particles[i]; particles[j].scale += -0.01f; ++j; } break; } } particles.resize(j); } void WaterParticleSystem::render(const mat4& VP, vec3 lightDir) { if (particles.size() == 0) return; program.use(); program.setUniformMatrix4f(viewProjectionLoc, VP); program.setUniform4f(colorLoc, color); program.setUniform3f(lightLoc, lightDir); Object object; mesh->setProgramParams(program); texture->use(); for (uint i = 0; i < particles.size(); ++i) { object.setPos(particles[i].position); object.setScale(vec3(particles[i].scale)); program.setUniformMatrix4f(modelLoc, *object.getModel()); mesh->render(); } } WaterParticleSystem::WaterParticleSystem() { } WaterParticleSystem::~WaterParticleSystem() { }
26.467742
86
0.661792
Daryan7
443473d3a57398771341de47c25e2c5042956da2
6,187
cpp
C++
src/geometry/FilePLY.cpp
mgradysaunders/precept
966eb19d3c8b713e11be0885cabda632cefe9878
[ "BSD-2-Clause" ]
null
null
null
src/geometry/FilePLY.cpp
mgradysaunders/precept
966eb19d3c8b713e11be0885cabda632cefe9878
[ "BSD-2-Clause" ]
null
null
null
src/geometry/FilePLY.cpp
mgradysaunders/precept
966eb19d3c8b713e11be0885cabda632cefe9878
[ "BSD-2-Clause" ]
null
null
null
#include <pre/geometry/FilePLY> #include <pre/string> #include "rply.h" namespace pre { static void error_cb(p_ply, const char* message) { throw std::runtime_error(message); } static int vertex2_cb(p_ply_argument arg) { void* pointer = nullptr; long index = 0; ply_get_argument_user_data(arg, &pointer, &index); FilePLY::Buffer2* buffer = static_cast<FilePLY::Buffer2*>(pointer); if (index == 0) buffer->emplace_back(); buffer->back()[index] = ply_get_argument_value(arg); return 1; } static int vertex3_cb(p_ply_argument arg) { void* pointer = nullptr; long index = 0; ply_get_argument_user_data(arg, &pointer, &index); FilePLY::Buffer3* buffer = static_cast<FilePLY::Buffer3*>(pointer); if (index == 0) buffer->emplace_back(); buffer->back()[index] = ply_get_argument_value(arg); return 1; } static int face_cb(p_ply_argument arg) { void* pointer = nullptr; long count = 0; long index = 0; ply_get_argument_user_data(arg, &pointer, nullptr); ply_get_argument_property(arg, nullptr, &count, &index); FilePLY* ply = static_cast<FilePLY*>(pointer); if (index == -1) ply->face_sizes.push_back(count); else { double value = ply_get_argument_value(arg); if (not(value >= 0 and value == std::uint32_t(value))) throw std::runtime_error("Bad index"); ply->face_indexes.push_back(std::uint32_t(value)); } return 1; } void FilePLY::read(const std::string& filename) { clear(); p_ply ply = ply_open(filename.c_str(), error_cb, 0, nullptr); Scoped remember_to_close([] {}, [&] { ply_close(ply); }); if (not ply) throw make_exception("can't open "s + quote(filename)); try { if (not ply_read_header(ply)) throw std::runtime_error("Bad header"); ply_set_read_cb(ply, "vertex", "x", vertex3_cb, &positions, 0); ply_set_read_cb(ply, "vertex", "y", vertex3_cb, &positions, 1); ply_set_read_cb(ply, "vertex", "z", vertex3_cb, &positions, 2); ply_set_read_cb(ply, "vertex", "nx", vertex3_cb, &normals, 0); ply_set_read_cb(ply, "vertex", "ny", vertex3_cb, &normals, 1); ply_set_read_cb(ply, "vertex", "nz", vertex3_cb, &normals, 2); ply_set_read_cb(ply, "vertex", "s", vertex2_cb, &uvs, 0); ply_set_read_cb(ply, "vertex", "t", vertex2_cb, &uvs, 1); ply_set_read_cb(ply, "vertex", "r", vertex3_cb, &colors, 0); ply_set_read_cb(ply, "vertex", "g", vertex3_cb, &colors, 1); ply_set_read_cb(ply, "vertex", "b", vertex3_cb, &colors, 2); ply_set_read_cb(ply, "face", "vertex_indices", face_cb, this, 0); if (not ply_read(ply)) throw std::runtime_error("Unknown failure reason"); } catch (const std::runtime_error& error) { throw make_exception( "can't read "s + quote(filename) + " ("s + error.what() + ")"s); } } void FilePLY::write(const std::string& filename) const { p_ply ply = ply_create(filename.c_str(), PLY_LITTLE_ENDIAN, error_cb, 0, nullptr); Scoped remember_to_close([] {}, [&] { ply_close(ply); }); try { ply_add_element(ply, "vertex", positions.size()); ply_add_scalar_property(ply, "x", PLY_FLOAT); ply_add_scalar_property(ply, "y", PLY_FLOAT); ply_add_scalar_property(ply, "z", PLY_FLOAT); if (normals.size() > 0) { ply_add_scalar_property(ply, "nx", PLY_FLOAT); ply_add_scalar_property(ply, "ny", PLY_FLOAT); ply_add_scalar_property(ply, "nz", PLY_FLOAT); } if (uvs.size() > 0) { ply_add_scalar_property(ply, "s", PLY_FLOAT); ply_add_scalar_property(ply, "t", PLY_FLOAT); } if (colors.size() > 0) { ply_add_scalar_property(ply, "r", PLY_FLOAT); ply_add_scalar_property(ply, "g", PLY_FLOAT); ply_add_scalar_property(ply, "b", PLY_FLOAT); } ply_add_element(ply, "face", face_sizes.size()); ply_add_list_property(ply, "vertex_indices", PLY_UCHAR, PLY_UINT); if (not ply_write_header(ply)) throw std::runtime_error("Bad header"); for (size_t index = 0; index < positions.size(); index++) { ply_write(ply, positions[index][0]); ply_write(ply, positions[index][1]); ply_write(ply, positions[index][2]); if (normals.size() > 0) { ply_write(ply, normals[index][0]); ply_write(ply, normals[index][1]); ply_write(ply, normals[index][2]); } if (uvs.size() > 0) { ply_write(ply, uvs[index][0]); ply_write(ply, uvs[index][1]); } if (colors.size() > 0) { ply_write(ply, colors[index][0]); ply_write(ply, colors[index][1]); ply_write(ply, colors[index][2]); } } auto face_index = face_indexes.begin(); for (size_t face_size : face_sizes) { ply_write(ply, face_size); while (face_size-- != 0) ply_write(ply, *face_index++); } } catch (const std::runtime_error& error) { throw make_exception( "can't write "s + quote(filename) + " ("s + error.what() + ")"s); } } void FilePLY::triangulate() { std::uint32_t offset = 0; std::vector<std::uint8_t> new_face_sizes; std::vector<std::uint32_t> new_face_indexes; new_face_sizes.reserve(face_sizes.size()); new_face_indexes.reserve(face_indexes.size()); for (std::uint8_t face_size : face_sizes) { for (std::uint8_t local = 1; local + 1 < face_size; local++) { new_face_indexes.push_back(face_indexes[offset]); new_face_indexes.push_back(face_indexes[offset + local]); new_face_indexes.push_back(face_indexes[offset + local + 1]); new_face_sizes.push_back(3); } offset += face_size; } std::swap(face_sizes, new_face_sizes); std::swap(face_indexes, new_face_indexes); } void FilePLY::normalize_normals() { for (Vec3<float>& v : normals) v = normalize(v); } } // namespace pre
38.91195
78
0.604008
mgradysaunders
44398e5574da7e2691795d3d9841388a54cbf729
5,694
cpp
C++
WebLayoutCore/Source/WebCore/platform/win/SystemInfo.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
1
2020-05-25T16:06:49.000Z
2020-05-25T16:06:49.000Z
WebLayoutCore/Source/WebCore/platform/win/SystemInfo.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
null
null
null
WebLayoutCore/Source/WebCore/platform/win/SystemInfo.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
1
2018-07-10T10:53:18.000Z
2018-07-10T10:53:18.000Z
/* * Copyright (C) 2009 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "SystemInfo.h" #include <windows.h> #include <wtf/text/WTFString.h> namespace WebCore { WindowsVersion windowsVersion(int* major, int* minor) { static bool initialized = false; static WindowsVersion version; static int majorVersion, minorVersion; if (!initialized) { initialized = true; OSVERSIONINFOEX versionInfo; ZeroMemory(&versionInfo, sizeof(versionInfo)); versionInfo.dwOSVersionInfoSize = sizeof(versionInfo); GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&versionInfo)); majorVersion = versionInfo.dwMajorVersion; minorVersion = versionInfo.dwMinorVersion; if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32s) version = Windows3_1; else if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { if (!minorVersion) version = Windows95; else version = (minorVersion == 10) ? Windows98 : WindowsME; } else { if (majorVersion == 5) { if (!minorVersion) version = Windows2000; else version = (minorVersion == 1) ? WindowsXP : WindowsServer2003; } else if (majorVersion >= 6) { if (versionInfo.wProductType == VER_NT_WORKSTATION) version = (majorVersion == 6 && !minorVersion) ? WindowsVista : Windows7; else version = WindowsServer2008; } else version = (majorVersion == 4) ? WindowsNT4 : WindowsNT3; } } if (major) *major = majorVersion; if (minor) *minor = minorVersion; return version; } static String osVersionForUAString() { int major, minor; WindowsVersion version = windowsVersion(&major, &minor); switch (version) { case WindowsCE1: case WindowsCE2: case WindowsCE3: return "Windows CE"; case WindowsCE4: return "Windows CE .NET"; case Windows3_1: return "Windows 3.1"; case Windows95: return "Windows 95"; case Windows98: return "Windows 98"; case WindowsME: return "Windows 98; Win 9x 4.90"; case WindowsNT4: return "WinNT4.0"; } const char* familyName = (version >= WindowsNT3) ? "Windows NT " : "Windows CE "; return familyName + String::number(major) + '.' + String::number(minor); } static bool isWOW64() { static bool initialized = false; static bool wow64 = false; if (!initialized) { initialized = true; HMODULE kernel32Module = GetModuleHandleA("kernel32.dll"); if (!kernel32Module) return wow64; typedef BOOL (WINAPI* IsWow64ProcessFunc)(HANDLE, PBOOL); IsWow64ProcessFunc isWOW64Process = reinterpret_cast<IsWow64ProcessFunc>(GetProcAddress(kernel32Module, "IsWow64Process")); if (isWOW64Process) { BOOL result = FALSE; wow64 = isWOW64Process(GetCurrentProcess(), &result) && result; } } return wow64; } static WORD processorArchitecture() { static bool initialized = false; static WORD architecture = PROCESSOR_ARCHITECTURE_INTEL; if (!initialized) { initialized = true; HMODULE kernel32Module = GetModuleHandleA("kernel32.dll"); if (!kernel32Module) return architecture; typedef VOID (WINAPI* GetNativeSystemInfoFunc)(LPSYSTEM_INFO); GetNativeSystemInfoFunc getNativeSystemInfo = reinterpret_cast<GetNativeSystemInfoFunc>(GetProcAddress(kernel32Module, "GetNativeSystemInfo")); if (getNativeSystemInfo) { SYSTEM_INFO systemInfo; ZeroMemory(&systemInfo, sizeof(systemInfo)); getNativeSystemInfo(&systemInfo); architecture = systemInfo.wProcessorArchitecture; } } return architecture; } static String architectureTokenForUAString() { if (isWOW64()) return "; WOW64"; if (processorArchitecture() == PROCESSOR_ARCHITECTURE_AMD64) return "; Win64; x64"; if (processorArchitecture() == PROCESSOR_ARCHITECTURE_IA64) return "; Win64; IA64"; return String(); } String windowsVersionForUAString() { return osVersionForUAString() + architectureTokenForUAString(); } } // namespace WebCore
34.095808
151
0.659993
gubaojian
4439fbfbae24e450c574bb98996663db71c45fcd
1,568
cpp
C++
src/main.cpp
waneon/magfy
2ebb905cf1730a5e6f66ad9164248e303bd051c4
[ "MIT" ]
1
2022-02-27T17:41:18.000Z
2022-02-27T17:41:18.000Z
src/main.cpp
waneon/magfy
2ebb905cf1730a5e6f66ad9164248e303bd051c4
[ "MIT" ]
null
null
null
src/main.cpp
waneon/magfy
2ebb905cf1730a5e6f66ad9164248e303bd051c4
[ "MIT" ]
null
null
null
#include <fstream> #include <spdlog/spdlog.h> #include <yaml-cpp/exceptions.h> #include <yaml-cpp/yaml.h> #if defined(MAGFY_WINDOWS) #include <spdlog/sinks/basic_file_sink.h> #include <windows.h> #else #include <spdlog/sinks/stdout_color_sinks.h> #endif #include "Config.h" #include "core.h" // global logger object std::shared_ptr<spdlog::logger> logger; // global hInstance object for Windows #if defined(MAGFY_WINDOWS) HINSTANCE g_hInstance = NULL; #endif #if defined(MAGFY_WINDOWS) int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR pCmdLine, int nCmdShow) { #else int main() { #endif // vendor-specific configure #if defined(MAGFY_WINDOWS) logger = spdlog::basic_logger_mt("magfy", get_log_file()); spdlog::flush_every(std::chrono::seconds(3)); g_hInstance = hInstance; #else logger = spdlog::stderr_color_mt("magfy"); #endif // parse config.yaml file Config config; try { YAML::Node root = YAML::LoadFile(get_config_file()); config = root.as<Config>(); } catch (YAML::BadFile ex) { logger->error("Config file must be placed in proper directory."); return 1; } catch (YAML::Exception ex) { logger->error("Parse error => {}", ex.msg); return 1; } logger->info("Successfully loaded the config file."); // run magfy try { run(config); logger->info("Terminated normally."); return 0; } catch (std::exception ex) { logger->error("Terminated abnormally."); return 1; } }
24.888889
80
0.654337
waneon
443c8776f2e1c50afd1b5db3494cc0b27f391644
3,381
cpp
C++
src/pos_normalizer.cpp
andre-nguyen/an_ros_tools
ddfd99405821065cc811c8698c3bfb84880a8c78
[ "MIT" ]
null
null
null
src/pos_normalizer.cpp
andre-nguyen/an_ros_tools
ddfd99405821065cc811c8698c3bfb84880a8c78
[ "MIT" ]
null
null
null
src/pos_normalizer.cpp
andre-nguyen/an_ros_tools
ddfd99405821065cc811c8698c3bfb84880a8c78
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include <dji_sdk/GlobalPosition.h> #include <dji_sdk/LocalPosition.h> #include <nav_msgs/Odometry.h> #include <eigen3/Eigen/Dense> #include "transform.h" dji_sdk::GlobalPosition global_pos_ref; dji_sdk::LocalPosition local_pos_ref; bool first_pos_rcvd = false; ros::Publisher odom_norm_pub, odom_norm_ENU_pub; void callback(const dji_sdk::GlobalPositionConstPtr& global_pos, const nav_msgs::OdometryConstPtr& odometry) { if(!first_pos_rcvd) { global_pos_ref = *global_pos; first_pos_rcvd = true; } nav_msgs::Odometry odom_norm = *odometry; local_pos_ref = gps_convert_ned(*global_pos, global_pos_ref); odom_norm.pose.pose.position.x = local_pos_ref.x; odom_norm.pose.pose.position.y = local_pos_ref.y; odom_norm.pose.pose.position.z = -local_pos_ref.z; odom_norm.twist.twist.linear.z *= -1; odom_norm_pub.publish(odom_norm); // god dammit dji nav_msgs::Odometry odom_norm_ENU = *odometry; // The code above was for NED now convert to ENU Eigen::Vector3d position_ENU = ned2enu(Eigen::Vector3d(local_pos_ref.x, local_pos_ref.y, -local_pos_ref.z)); Eigen::Quaterniond orientation_ENU = ned2enu(Eigen::Quaterniond( odom_norm.pose.pose.orientation.w, odom_norm.pose.pose.orientation.x, odom_norm.pose.pose.orientation.y, odom_norm.pose.pose.orientation.z)); // wtf is this NEU? NED? Eigen::Vector3d velocity_ENU = ned2enu(Eigen::Vector3d( odom_norm.twist.twist.linear.x, odom_norm.twist.twist.linear.y, -odom_norm.twist.twist.linear.z)); odom_norm_ENU.pose.pose.position.x = position_ENU(0); odom_norm_ENU.pose.pose.position.y = position_ENU(1); odom_norm_ENU.pose.pose.position.z = position_ENU(2); odom_norm_ENU.pose.pose.orientation.w = orientation_ENU.w(); odom_norm_ENU.pose.pose.orientation.x = orientation_ENU.x(); odom_norm_ENU.pose.pose.orientation.y = orientation_ENU.y(); odom_norm_ENU.pose.pose.orientation.z = orientation_ENU.z(); odom_norm_ENU.twist.twist.linear.x = velocity_ENU(0); odom_norm_ENU.twist.twist.linear.y = velocity_ENU(1); odom_norm_ENU.twist.twist.linear.z = velocity_ENU(2); odom_norm_ENU_pub.publish(odom_norm_ENU); } int main(int argc, char** argv) { ros::init(argc, argv, "pos_normalizer"); ros::NodeHandle nh; odom_norm_pub = nh.advertise<nav_msgs::Odometry> ("/dji_sdk/odometry_normalized_NED", 10); odom_norm_ENU_pub = nh.advertise<nav_msgs::Odometry> ("/dji_sdk/odometry_normalized_ENU", 10); message_filters::Subscriber<dji_sdk::GlobalPosition> global_sub(nh, "/dji_sdk/global_position", 10); message_filters::Subscriber<nav_msgs::Odometry> odom_sub (nh, "/dji_sdk/odometry", 10); typedef message_filters::sync_policies::ApproximateTime <dji_sdk::GlobalPosition, nav_msgs::Odometry> MySyncPolicy; message_filters::Synchronizer<MySyncPolicy> sync(MySyncPolicy(10), global_sub, odom_sub); sync.registerCallback(boost::bind(&callback, _1, _2)); ros::spin(); return 0; }
40.25
79
0.699201
andre-nguyen
443d71fbc939af001e7c7c70bdc863a830b41e26
8,085
cpp
C++
src/common/network_manager.cpp
blackccpie/neurocl
cfbb1978ba92d5085796330846d997944f604c93
[ "MIT" ]
2
2016-01-01T22:19:04.000Z
2018-12-12T19:06:24.000Z
src/common/network_manager.cpp
blackccpie/neurocl
cfbb1978ba92d5085796330846d997944f604c93
[ "MIT" ]
null
null
null
src/common/network_manager.cpp
blackccpie/neurocl
cfbb1978ba92d5085796330846d997944f604c93
[ "MIT" ]
1
2020-10-19T08:17:54.000Z
2020-10-19T08:17:54.000Z
/* The MIT License Copyright (c) 2015-2017 Albert Murienne 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 "network_manager.h" #include "interfaces/network_interface.h" #include "interfaces/network_file_handler_interface.h" #include "common/network_exception.h" #include "common/samples_manager.h" #include "common/logger.h" #include <chrono> #include <iostream> //#define TRAIN_CHRONO namespace neurocl { class scoped_training { public: scoped_training( std::shared_ptr<network_interface> net ) : m_net( net ) { m_net->set_training( true ); } virtual ~scoped_training() { m_net->set_training( false ); } private: std::shared_ptr<network_interface> m_net; }; void network_manager::_assert_loaded() { if ( !m_network_loaded ) throw network_exception( "no network loaded!" ); } void network_manager::set_training( bool training, key_training ) { m_net->set_training( training ); } void network_manager::load_network( const std::string& topology_path, const std::string& weights_path ) { m_net_file_handler->load_network_topology( topology_path ); m_net_file_handler->load_network_weights( weights_path ); m_network_loaded = true; LOGGER(info) << "network_manager::load_network - network loaded" << std::endl; } void network_manager::save_network() { _assert_loaded(); m_net_file_handler->save_network_weights(); } void network_manager::batch_train( const samples_manager& smp_manager, const size_t& epoch_size, const size_t& batch_size, t_progress_fct progress_fct ) { _assert_loaded(); scoped_training _scoped_training( m_net ); std::shared_ptr<samples_augmenter> smp_augmenter;// = smp_manager.get_augmenter(); size_t progress_size = 0; const size_t pbm_size = epoch_size * smp_manager.samples_size(); for ( size_t i=0; i<epoch_size; i++ ) { while ( true ) { std::vector<neurocl::sample> samples = smp_manager.get_next_batch( batch_size ); // end of training set management if ( samples.empty() ) break; prepare_training_epoch(); _train_batch( samples, smp_augmenter ); finalize_training_epoch(); progress_size += samples.size(); int progress = ( ( 100 * progress_size ) / pbm_size ); if ( progress_fct ) progress_fct( progress ); std::cout << "\rnetwork_manager::batch_train - progress: " << progress << "% loss: " << m_net->loss(); } std::cout << "\r"; LOGGER(info) << "network_manager::batch_train - EPOCH " << (i+1) << "/" << epoch_size << " loss: " << m_net->loss() << std::endl; smp_manager.rewind(); smp_manager.shuffle(); } std::cout << std::endl; save_network(); } void network_manager::prepare_training_epoch() { m_net->clear_gradients(); } void network_manager::finalize_training_epoch() { m_net->gradient_descent(); } void network_manager::train( const sample& s, key_training ) { _assert_loaded(); _train_single( s ); } void network_manager::_train_batch( const std::vector<sample>& training_set, const std::shared_ptr<samples_augmenter>& smp_augmenter ) { _assert_loaded(); size_t index = 0; for( const auto& s : training_set ) { //LOGGER(info) << "network_manager::_train_batch - training sample " << (index+1) << "/" << training_set.size() << std::endl; if ( !smp_augmenter ) { _train_single( s ); } else { //sample _s = smp_augmenter->translate( s, samples_augmenter::rand_shift(), samples_augmenter::rand_shift() ); sample _s = smp_augmenter->rotate( s, samples_augmenter::rand_shift() ); _train_single( _s ); } ++index; } } void network_manager::_train_single( const sample& s ) { #ifdef TRAIN_CHRONO namespace sc = std::chrono; sc::system_clock::time_point start = sc::system_clock::now(); sc::milliseconds duration; #endif // set input/output m_net->set_input( s.isample_size, s.isample ); m_net->set_output( s.osample_size, s.osample ); // forward/backward propagation m_net->feed_forward(); m_net->back_propagate(); #ifdef TRAIN_CHRONO duration = sc::duration_cast<sc::milliseconds>( sc::system_clock::now() - start ); LOGGER(info) << "network_manager::_train_single - training successfull in " << duration.count() << "ms"<< std::endl; #endif } void network_manager::compute_augmented_output( sample& s, const std::shared_ptr<samples_augmenter>& smp_augmenter ) { // ONLY ROTATION AUGMENTATION IS IMPLEMENTED YET std::vector<int> rotations{ -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 }; std::vector<output_ptr> outputs; for ( auto& rot : rotations ) { sample _s = smp_augmenter->rotate( s, rot ); m_net->set_input( _s.isample_size, _s.isample ); m_net->feed_forward(); outputs.emplace_back( m_net->output() ); //output_layer += m_net->output(); } // TODO-CNN : not very proud of the efficiency of this code section... // still it is temporary as computing a mean image alos makes sense! int i = 0; int l = 0; float max = std::numeric_limits<float>::min(); for ( const auto& output : outputs ) { float _tmp_max = output.max_comp_val(); LOGGER(info) << "network_manager::compute_augmented_output - " << _tmp_max << " " << output.max_comp_idx() << std::endl; if ( _tmp_max > max ) { l = i; max = _tmp_max; } i++; } std::copy( outputs[l].outputs.get(), outputs[l].outputs.get() + outputs[l].num_outputs, const_cast<float*>( s.osample ) ); } void network_manager::compute_output( sample& s ) { _assert_loaded(); m_net->set_input( s.isample_size, s.isample ); m_net->feed_forward(); output_ptr output_layer = m_net->output(); std::copy( output_layer.outputs.get(), output_layer.outputs.get() + output_layer.num_outputs, const_cast<float*>( s.osample ) ); } void network_manager::compute_output( std::vector<sample>& s ) { _assert_loaded(); // NOT IMPLEMENTED YET //m_net->batch_feed_forward( std::vector<input_ptr>&, std::vector<output_ptr>& ); } void network_manager::gradient_check( const sample& s ) { _assert_loaded(); m_net->set_input( s.isample_size, s.isample ); m_net->set_output( s.osample_size, s.osample ); output_ptr out_ref( s.osample_size ); std::copy( s.osample, s.osample + s.osample_size, out_ref.outputs.get() ); m_net->gradient_check( out_ref ); } void network_manager::dump_weights() { _assert_loaded(); std::cout << m_net->dump_weights(); } void network_manager::dump_bias() { _assert_loaded(); std::cout << m_net->dump_bias(); } void network_manager::dump_activations() { _assert_loaded(); std::cout << m_net->dump_activations(); } } /*namespace neurocl*/
27.688356
137
0.660977
blackccpie
443df983b7b87d5189021884753eae575099751f
1,080
cpp
C++
src/timereference.cpp
hrxcodes/cbftp
bf2784007dcc4cc42775a2d40157c51b80383f81
[ "MIT" ]
8
2019-04-30T00:37:00.000Z
2022-02-03T13:35:31.000Z
src/timereference.cpp
Xtravaganz/cbftp
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
[ "MIT" ]
2
2019-11-19T12:46:13.000Z
2019-12-20T22:13:57.000Z
src/timereference.cpp
Xtravaganz/cbftp
31a3465e2cd539f6cf35a5d9a0bb9c5c2f639cd5
[ "MIT" ]
9
2020-01-15T02:38:36.000Z
2022-02-15T20:05:20.000Z
#include "timereference.h" #include <ctime> #include "core/tickpoke.h" #include "globalcontext.h" #define INTERVAL 50 static int currentyear = 0; static int currentmonth = 0; static int currentday = 0; TimeReference::TimeReference() { global->getTickPoke()->startPoke(this, "TimeReference", INTERVAL, 0); } void TimeReference::tick(int) { timeticker += INTERVAL; } unsigned long long TimeReference::timeReference() const { return timeticker; } unsigned long long TimeReference::timePassedSince(unsigned long long timestamp) const { if (timestamp > timeticker) { return 0 - timestamp + timeticker; } return timeticker - timestamp; } void TimeReference::updateTime() { time_t rawtime; time(&rawtime); struct tm timedata; localtime_r(&rawtime, &timedata); currentyear = timedata.tm_year + 1900; currentmonth = timedata.tm_mon + 1; currentday = timedata.tm_mday; } int TimeReference::currentYear() { return currentyear; } int TimeReference::currentMonth() { return currentmonth; } int TimeReference::currentDay() { return currentday; }
20
87
0.730556
hrxcodes
443e0803e8359c4d4a766b9033599397bebf7154
155
cpp
C++
regression/esbmc-cpp/try_catch/try-catch_pointer_01/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
regression/esbmc-cpp/try_catch/try-catch_pointer_01/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
regression/esbmc-cpp/try_catch/try-catch_pointer_01/main.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
#include<cassert> int main() { try { int x = 5; int *py = &x; throw py; } catch(int*) { } catch(void*) { assert(0); } return 0; }
10.333333
29
0.470968
shmarovfedor
4441450f2bde5590471e665b70f77992f4e9d033
2,192
cpp
C++
Linux/Ubuntu/64bit/AVAPI/AvapiExamples/MIDPOINT_Example.cpp
AvapiDotNet/AvapiCpp
2157ccbe750cac077098a6f1aa401d80fc943ff5
[ "MIT" ]
15
2018-01-31T16:58:36.000Z
2021-08-19T21:37:08.000Z
Linux/Ubuntu/64bit/AVAPI/AvapiExamples/MIDPOINT_Example.cpp
AvapiDotNet/AvapiCpp
2157ccbe750cac077098a6f1aa401d80fc943ff5
[ "MIT" ]
null
null
null
Linux/Ubuntu/64bit/AVAPI/AvapiExamples/MIDPOINT_Example.cpp
AvapiDotNet/AvapiCpp
2157ccbe750cac077098a6f1aa401d80fc943ff5
[ "MIT" ]
4
2018-01-31T17:06:26.000Z
2020-05-03T20:59:27.000Z
#include <string> #include <iostream> #include <sstream> #include "Avapi/AvapiConnection.hpp" #include "Avapi/TECHNICAL_INDICATOR/MIDPOINT.hpp" using namespace std; using namespace Avapi; int main() { string lastHttpRequest = ""; AvapiConnection* avapi_connection; try { avapi_connection = AvapiConnection::getInstance(); avapi_connection->set_ApiKey("Your Alpha Vantage API Key !!!!"); } catch(AvapiConnectionError& e) { cout << e.get_error() << endl; return EXIT_FAILURE; } auto& QueryObject = avapi_connection->GetQueryObject_MIDPOINT(); auto Response = QueryObject.Query( "MSFT" ,Const_MIDPOINT_interval::n_60min ,"10" ,Const_MIDPOINT_series_type::close); cout << endl << "******** RAW DATA MIDPOINT ********"<< endl; cout << Response.get_RawData() << endl << endl; cout << "******** STRUCTURED DATA MIDPOINT ********"<< endl; if(Response.get_Data().isError()) { cerr << Response.get_Data().get_ErrorMessage() << endl; } else { auto& MetaData = Response.get_Data().get_MetaData(); auto& TechnicalIndicator = Response.get_Data().get_TechnicalIndicator(); cout << "========================" << endl; cout << "Symbol: " << MetaData.get_Symbol() << endl; cout << "Indicator: " << MetaData.get_Indicator() << endl; cout << "LastRefreshed: " << MetaData.get_LastRefreshed() << endl; cout << "Interval: " << MetaData.get_Interval() << endl; cout << "TimePeriod: " << MetaData.get_TimePeriod() << endl; cout << "SeriesType: " << MetaData.get_SeriesType() << endl; cout << "TimeZone: " << MetaData.get_TimeZone() << endl; cout << "========================" << endl; cout << "========================" << endl; for(auto& element : TechnicalIndicator) { cout << "MIDPOINT: " << element.get_MIDPOINT() << endl; cout << "DateTime: " << element.get_DateTime() << endl; cout << "========================" << endl; } } return EXIT_SUCCESS; }
31.768116
80
0.542883
AvapiDotNet
44420bebdb449f361fb5c6a31d16e35145661e35
227
hpp
C++
tests/zcc/decl.C99/Error_class_forward_def_const_volatile9.hpp
zaimoni/Z.C-
7ca97ec0af14d092c87a25e07d7ed486c7912266
[ "BSL-1.0" ]
null
null
null
tests/zcc/decl.C99/Error_class_forward_def_const_volatile9.hpp
zaimoni/Z.C-
7ca97ec0af14d092c87a25e07d7ed486c7912266
[ "BSL-1.0" ]
4
2019-12-07T08:08:29.000Z
2021-01-22T00:19:10.000Z
tests/zcc/decl.C99/Error_class_forward_def_const_volatile9.hpp
zaimoni/Z.C-
7ca97ec0af14d092c87a25e07d7ed486c7912266
[ "BSL-1.0" ]
null
null
null
// decl.C99\Error_class_forward_def_const_volatile9.hpp // using singly defined class // (C)2010 Kenneth Boyd, license: MIT.txt class good_test; const class good_test volatile; class good_test { int x_factor; };
18.916667
56
0.735683
zaimoni
4442b1f6b5e4f7b158a81f02dc74691e453564e2
4,138
cpp
C++
android/library/maply/src/main/cpp/MapboxVectorTileParser_jni.cpp
freebird-airlines/WhirlyGlobe
3e1dd7cf27654558caeb1c5a2c8616bc1a3dbbb4
[ "Apache-2.0" ]
2
2019-05-16T18:52:21.000Z
2020-10-10T14:08:53.000Z
android/library/maply/src/main/cpp/MapboxVectorTileParser_jni.cpp
freebird-airlines/WhirlyGlobe
3e1dd7cf27654558caeb1c5a2c8616bc1a3dbbb4
[ "Apache-2.0" ]
null
null
null
android/library/maply/src/main/cpp/MapboxVectorTileParser_jni.cpp
freebird-airlines/WhirlyGlobe
3e1dd7cf27654558caeb1c5a2c8616bc1a3dbbb4
[ "Apache-2.0" ]
1
2020-10-22T12:09:24.000Z
2020-10-22T12:09:24.000Z
/* * MapboxVectorTileParser_jni.cpp * WhirlyGlobeLib * * Created by Steve Gifford on 5/25/16. * Copyright 2011-2016 mousebird consulting * * 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. * */ #import <jni.h> #import "Maply_jni.h" #import "Maply_utils_jni.h" #import "com_mousebird_maply_MapboxVectorTileParser.h" #import "WhirlyGlobe.h" using namespace Eigen; using namespace WhirlyKit; using namespace Maply; JNIEXPORT void JNICALL Java_com_mousebird_maply_MapboxVectorTileParser_nativeInit (JNIEnv *env, jclass cls) { MapboxVectorTileParserClassInfo::getClassInfo(env,cls); } JNIEXPORT void JNICALL Java_com_mousebird_maply_MapboxVectorTileParser_initialise (JNIEnv *env, jobject obj) { try { MapboxVectorTileParserClassInfo *classInfo = MapboxVectorTileParserClassInfo::getClassInfo(); MapboxVectorTileParser *inst = new MapboxVectorTileParser(); classInfo->setHandle(env,obj,inst); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in MapboxVectorTileParser::initialise()"); } } static std::mutex disposeMutex; JNIEXPORT void JNICALL Java_com_mousebird_maply_MapboxVectorTileParser_dispose (JNIEnv *env, jobject obj) { try { MapboxVectorTileParserClassInfo *classInfo = MapboxVectorTileParserClassInfo::getClassInfo(); { std::lock_guard<std::mutex> lock(disposeMutex); MapboxVectorTileParser *inst = classInfo->getObject(env,obj); if (!inst) return; delete inst; classInfo->clearHandle(env,obj); } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in MapboxVectorTileParser::dispose()"); } } JNIEXPORT jobjectArray JNICALL Java_com_mousebird_maply_MapboxVectorTileParser_parseDataNative (JNIEnv *env, jobject obj, jbyteArray data, jdouble minX, jdouble minY, jdouble maxX, jdouble maxY) { try { MapboxVectorTileParserClassInfo *classInfo = MapboxVectorTileParserClassInfo::getClassInfo(); MapboxVectorTileParser *inst = classInfo->getObject(env,obj); if (!inst || !data) return NULL; Mbr mbr; mbr.addPoint(Point2f(minX,minY)); mbr.addPoint(Point2f(maxX,maxY)); // Parse vector tile and create vector objects jbyte *bytes = env->GetByteArrayElements(data,NULL); RawDataWrapper rawData(bytes,env->GetArrayLength(data),false); std::vector<VectorObject *> vecObjs; bool ret = inst->parseVectorTile(&rawData,vecObjs,mbr); env->ReleaseByteArrayElements(data,bytes, 0); if (vecObjs.empty()) { return NULL; } else { VectorObjectClassInfo *vecClassInfo = VectorObjectClassInfo::getClassInfo(); if (!vecClassInfo) vecClassInfo = VectorObjectClassInfo::getClassInfo(env,"com/mousebird/maply/VectorObject"); jobjectArray retArr = env->NewObjectArray(vecObjs.size(), vecClassInfo->getClass(), NULL); int which = 0; for (VectorObject *vecObj : vecObjs) { jobject vecObjObj = MakeVectorObject(env,vecObj); env->SetObjectArrayElement( retArr, which, vecObjObj); env->DeleteLocalRef( vecObjObj); which++; } return retArr; } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in MapboxVectorTileParser::parseDataNative()"); } return NULL; }
33.104
112
0.666989
freebird-airlines
4444314756842c9712972696314dc2510a2f8c1c
1,050
cpp
C++
src/test/ex.cpp
jar-ben/z3
7baa4f88b0cb4458461596d147e1f71853d77126
[ "MIT" ]
7,746
2015-03-26T18:59:33.000Z
2022-03-31T15:34:48.000Z
src/test/ex.cpp
jar-ben/z3
7baa4f88b0cb4458461596d147e1f71853d77126
[ "MIT" ]
5,162
2015-03-27T01:12:48.000Z
2022-03-31T14:56:16.000Z
src/test/ex.cpp
jar-ben/z3
7baa4f88b0cb4458461596d147e1f71853d77126
[ "MIT" ]
1,529
2015-03-26T18:45:30.000Z
2022-03-31T15:35:16.000Z
/*++ Copyright (c) 2006 Microsoft Corporation Module Name: ex.cpp Abstract: <abstract> Author: Leonardo de Moura (leonardo) 2011-04-28 Revision History: --*/ #include<iostream> #include "util/z3_exception.h" class ex { public: virtual ~ex() {} virtual char const * msg() const = 0; }; class ex1 : public ex { char const * m_msg; public: ex1(char const * m):m_msg(m) {} char const * msg() const override { return m_msg; } }; class ex2 : public ex { std::string m_msg; public: ex2(char const * m):m_msg(m) {} char const * msg() const override { return m_msg.c_str(); } }; static void th() { throw ex2("testing exception"); } static void tst1() { try { th(); } catch (ex & e) { std::cerr << e.msg() << "\n"; } } static void tst2() { try { throw default_exception(default_exception::fmt(), "Format %d %s", 12, "twelve"); } catch (z3_exception& ex) { std::cerr << ex.msg() << "\n"; } } void tst_ex() { tst1(); tst2(); }
15.441176
88
0.561905
jar-ben
4444a57baf0d204dd179fa6c987b85c9d5c67f9a
1,038
cpp
C++
CodeForces/879/C - Short Program.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-02-24T06:45:56.000Z
2018-05-29T04:47:39.000Z
CodeForces/879/C - Short Program.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
null
null
null
CodeForces/879/C - Short Program.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-06-28T09:53:27.000Z
2022-03-23T13:29:57.000Z
#include <bits/stdc++.h> using namespace std; #pragma comment(linker,"/stack:1024000000,1024000000") #define db(x) cout<<(x)<<endl #define pf(x) push_front(x) #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define ms(x,y) memset(x,y,sizeof x) typedef long long LL; const double pi=acos(-1),eps=1e-9; const LL inf=0x3f3f3f3f,mod=1e9+7,maxn=512345; struct node{ char s[5]; int x; }p[maxn],ans[12]; int n,t,a,b=1023,x=1023,y,z; int main(){ ios::sync_with_stdio(0); cin.tie(0); cin>>n; for(int i=0;i<n;i++){ cin>>p[i].s>>p[i].x; if(p[i].s[0]=='&') a&=p[i].x,b&=p[i].x; else if(p[i].s[0]=='|') a|=p[i].x,b|=p[i].x; else a^=p[i].x,b^=p[i].x; } for(int i=0;i<10;i++) if(((a>>i)&1)&&!((b>>i)&1)) z^=1<<i; else if(((a>>i)&1)&&((b>>i)&1)) y|=1<<i; else if(!((a>>i)&1)&&!((b>>i)&1)) x&=~(1<<i); if(x<1023) ans[t].s[0]='&',ans[t++].x=x; if(y) ans[t].s[0]='|',ans[t++].x=y; if(z) ans[t].s[0]='^',ans[t++].x=z; db(t); for(int i=0;i<t;i++) printf("%s %d\n",ans[i].s,ans[i].x); return 0; }
22.085106
54
0.528902
QAQrz
44456312ddfb23804aa0335935d2e5c606a39d3d
4,183
hpp
C++
include/RAJA/policy/loop/sort.hpp
stu314159/RAJA
773be9829a92062db989a6e976ed6d95e4d4bb22
[ "BSD-3-Clause" ]
null
null
null
include/RAJA/policy/loop/sort.hpp
stu314159/RAJA
773be9829a92062db989a6e976ed6d95e4d4bb22
[ "BSD-3-Clause" ]
null
null
null
include/RAJA/policy/loop/sort.hpp
stu314159/RAJA
773be9829a92062db989a6e976ed6d95e4d4bb22
[ "BSD-3-Clause" ]
null
null
null
/*! ****************************************************************************** * * \file * * \brief Header file providing RAJA sort declarations. * ****************************************************************************** */ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2016-21, Lawrence Livermore National Security, LLC // and RAJA project contributors. See the RAJA/COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// #ifndef RAJA_sort_loop_HPP #define RAJA_sort_loop_HPP #include "RAJA/config.hpp" #include <algorithm> #include <functional> #include <iterator> #include "RAJA/util/macros.hpp" #include "RAJA/util/concepts.hpp" #include "RAJA/util/zip.hpp" #include "RAJA/util/sort.hpp" #include "RAJA/policy/loop/policy.hpp" namespace RAJA { namespace impl { namespace sort { namespace detail { /*! \brief Functional that performs an unstable sort with the given arguments, uses RAJA::intro_sort */ struct UnstableSorter { template < typename... Args > RAJA_INLINE void operator()(Args&&... args) const { RAJA::detail::intro_sort(std::forward<Args>(args)...); } }; /*! \brief Functional that performs a stable sort with the given arguments, calls RAJA::merge_sort */ struct StableSorter { template < typename... Args > RAJA_INLINE void operator()(Args&&... args) const { RAJA::detail::merge_sort(std::forward<Args>(args)...); } }; } // namespace detail /*! \brief sort given range using comparison function */ template <typename ExecPolicy, typename Iter, typename Compare> concepts::enable_if_t<resources::EventProxy<resources::Host>, type_traits::is_loop_policy<ExecPolicy>> unstable( resources::Host host_res, const ExecPolicy&, Iter begin, Iter end, Compare comp) { detail::UnstableSorter{}(begin, end, comp); return resources::EventProxy<resources::Host>(host_res); } /*! \brief stable sort given range using comparison function */ template <typename ExecPolicy, typename Iter, typename Compare> concepts::enable_if_t<resources::EventProxy<resources::Host>, type_traits::is_loop_policy<ExecPolicy>> stable( resources::Host host_res, const ExecPolicy&, Iter begin, Iter end, Compare comp) { detail::StableSorter{}(begin, end, comp); return resources::EventProxy<resources::Host>(host_res); } /*! \brief sort given range of pairs using comparison function on keys */ template <typename ExecPolicy, typename KeyIter, typename ValIter, typename Compare> concepts::enable_if_t<resources::EventProxy<resources::Host>, type_traits::is_loop_policy<ExecPolicy>> unstable_pairs( resources::Host host_res, const ExecPolicy&, KeyIter keys_begin, KeyIter keys_end, ValIter vals_begin, Compare comp) { auto begin = RAJA::zip(keys_begin, vals_begin); auto end = RAJA::zip(keys_end, vals_begin+(keys_end-keys_begin)); using zip_ref = RAJA::detail::IterRef<camp::decay<decltype(begin)>>; detail::UnstableSorter{}(begin, end, RAJA::compare_first<zip_ref>(comp)); return resources::EventProxy<resources::Host>(host_res); } /*! \brief stable sort given range of pairs using comparison function on keys */ template <typename ExecPolicy, typename KeyIter, typename ValIter, typename Compare> concepts::enable_if_t<resources::EventProxy<resources::Host>, type_traits::is_loop_policy<ExecPolicy>> stable_pairs( resources::Host host_res, const ExecPolicy&, KeyIter keys_begin, KeyIter keys_end, ValIter vals_begin, Compare comp) { auto begin = RAJA::zip(keys_begin, vals_begin); auto end = RAJA::zip(keys_end, vals_begin+(keys_end-keys_begin)); using zip_ref = RAJA::detail::IterRef<camp::decay<decltype(begin)>>; detail::StableSorter{}(begin, end, RAJA::compare_first<zip_ref>(comp)); return resources::EventProxy<resources::Host>(host_res); } } // namespace sort } // namespace impl } // namespace RAJA #endif
25.506098
84
0.648339
stu314159
4445f4fe81631651dbad0e6e04930d0403ac9f9a
4,061
cpp
C++
LibFFmpeg/demo/FFplayer2/player.cpp
sim9108/SDKS
2823124fa0a22f8a77d131e7a2fb7f4aba59129c
[ "MIT" ]
2
2015-03-23T01:08:49.000Z
2015-03-23T02:28:17.000Z
LibFFmpeg/demo/FFplayer2/player.cpp
sim9108/SDKS
2823124fa0a22f8a77d131e7a2fb7f4aba59129c
[ "MIT" ]
null
null
null
LibFFmpeg/demo/FFplayer2/player.cpp
sim9108/SDKS
2823124fa0a22f8a77d131e7a2fb7f4aba59129c
[ "MIT" ]
null
null
null
#include "player.h" #include <chrono> #include <iostream> #include <algorithm> extern "C" { #include <libavutil/time.h> } using std::string; using std::unique_ptr; using std::function; using std::thread; using std::chrono::milliseconds; using std::this_thread::sleep_for; using std::exception; using std::cerr; using std::endl; using std::runtime_error; using std::max; Player::Player(const string &file_name) : container_(new Container(file_name)), display_(new Display(container_->get_width(), container_->get_height())), timer_(new Timer), packet_queue_(new PacketQueue(queue_size_)), frame_queue_(new FrameQueue(queue_size_)) { stages_.push_back(thread(&Player::demultiplex, this)); stages_.push_back(thread(&Player::decode_video, this)); video(); } Player::~Player() { frame_queue_->quit(); packet_queue_->quit(); for (auto &stage : stages_) { stage.join(); } } void Player::demultiplex() { try { for (;;) { // Create AVPacket unique_ptr<AVPacket, function<void(AVPacket*)>> packet( new AVPacket, [](AVPacket* p){ av_free_packet(p); delete p; }); av_init_packet(packet.get()); packet->data = nullptr; // Read frame into AVPacket if (!container_->read_frame(*packet)) { packet_queue_->finished(); break; } // Move into queue if first video stream if (packet->stream_index == container_->get_video_stream()) { if (!packet_queue_->push(move(packet))) { break; } } } } catch (exception &e) { cerr << "Demuxing error: " << e.what() << endl; exit(1); } } void Player::decode_video() { const AVRational microseconds = {1, 1000000}; try { for (;;) { // Create AVFrame and AVQueue unique_ptr<AVFrame, function<void(AVFrame*)>> frame_decoded( av_frame_alloc(), [](AVFrame* f){ av_frame_free(&f); }); unique_ptr<AVPacket, function<void(AVPacket*)>> packet( nullptr, [](AVPacket* p){ av_free_packet(p); delete p; }); // Read packet from queue if (!packet_queue_->pop(packet)) { frame_queue_->finished(); break; } // Decode packet int finished_frame; container_->decode_frame( frame_decoded.get(), finished_frame, packet.get()); // If a whole frame has been decoded, // adjust time stamps and add to queue if (finished_frame) { frame_decoded->pts = av_rescale_q( frame_decoded->pkt_dts, container_->get_container_time_base(), microseconds); unique_ptr<AVFrame, function<void(AVFrame*)>> frame_converted( av_frame_alloc(), [](AVFrame* f){ avpicture_free( reinterpret_cast<AVPicture*>(f)); av_frame_free(&f); }); if (av_frame_copy_props(frame_converted.get(), frame_decoded.get()) < 0) { throw runtime_error("Copying frame properties"); } if (avpicture_alloc( reinterpret_cast<AVPicture*>(frame_converted.get()), container_->get_pixel_format(), container_->get_width(), container_->get_height()) < 0) { throw runtime_error("Allocating picture"); } container_->convert_frame( frame_decoded.get(), frame_converted.get()); if (!frame_queue_->push(move(frame_converted))) { break; } } } } catch (exception &e) { cerr << "Decoding error: " << e.what() << endl; exit(1); } } void Player::video() { try { int64_t last_pts = 0; for (uint64_t frame_number = 0;; ++frame_number) { display_->input(); if (display_->get_quit()) { break; } else if (display_->get_play()) { unique_ptr<AVFrame, function<void(AVFrame*)>> frame( nullptr, [](AVFrame* f){ av_frame_free(&f); }); if (!frame_queue_->pop(frame)) { break; } if (frame_number) { int64_t frame_delay = frame->pts - last_pts; last_pts = frame->pts; timer_->wait(frame_delay); } else { last_pts = frame->pts; timer_->update(); } display_->refresh(*frame); } else { milliseconds sleep(10); sleep_for(sleep); timer_->update(); } } } catch (exception &e) { cerr << "Display error: " << e.what() << endl; exit(1); } }
22.814607
75
0.642206
sim9108
4446ef31fa0e31a790a26a26e115c2a9c225ef3c
2,730
cpp
C++
World/PolygonBackground.cpp
jess22664/x3ogre
9de430859d877407ae0308908390c9fa004b0e84
[ "MIT" ]
1
2021-09-18T12:50:35.000Z
2021-09-18T12:50:35.000Z
World/PolygonBackground.cpp
jess22664/x3ogre
9de430859d877407ae0308908390c9fa004b0e84
[ "MIT" ]
null
null
null
World/PolygonBackground.cpp
jess22664/x3ogre
9de430859d877407ae0308908390c9fa004b0e84
[ "MIT" ]
null
null
null
/* * ImageBackground.cpp * * Created on: 08.09.2014 * Author: baudenri */ #include "PolygonBackground.h" #include <World/Scene.h> #include <OgreMaterialManager.h> #include <OgrePass.h> #include <OgreRenderQueue.h> #include <OgreAxisAlignedBox.h> #include <OgreSceneNode.h> #include <OgreTechnique.h> #include <OgreLogManager.h> using namespace X3D; const std::string PolygonBackground::_sceneNodeName = "X3D_PolygonBackground_SceneNode"; void PolygonBackground::initialise(World& world) { if (_init) { return; } if (not _appearance) { // If no appearance present, ImageBackground cann't be initialised. return; } // Create Appearance for Polygon background _appearance->initialise(world); _appearance->create(); // Create background rectangle covering the whole screen _rect.reset(new Ogre::Rectangle2D(true)); _rect->setCorners(-1, 1, 1, -1); _rect->setMaterial(_appearance->getOgreMaterial()); // Render the background before everything else _rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND); // Render everything even if background is closer to camera than other objects _appearance->pass()->setDepthCheckEnabled(false); _appearance->pass()->setDepthWriteEnabled(false); // Apply texCoordinates if (_appearance->getTexture()) { // Set Lighting disabled only for Texture Background // Otherwise the pass will not be rendered which results in a white background _appearance->pass()->setLightingEnabled(false); if (_texCoords.size()==4) { _rect->setUVs(Ogre::Vector2(_texCoords[3].x,_texCoords[3].y), Ogre::Vector2(_texCoords[0].x,_texCoords[0].y), Ogre::Vector2(_texCoords[2].x,_texCoords[2].y), Ogre::Vector2(_texCoords[1].x,_texCoords[1].y) ); } else { if (not _texCoords.empty()) { Ogre::LogManager::getSingleton().logMessage("PolygonBackground: Texture Coordinates have wrong size", Ogre::LML_NORMAL); } _rect->setUVs(Ogre::Vector2(0,1),Ogre::Vector2(0,0), Ogre::Vector2(1,1), Ogre::Vector2(1,0)); } } // Use infinite AAB to always stay visible. Ogre::AxisAlignedBox aabInf; aabInf.setInfinite(); _rect->setBoundingBox(aabInf); // Attach background to the scene _root = world.sceneManager()->getRootSceneNode(); BindableNode<PolygonBackground>::initialise(world); _init = true; } void PolygonBackground::texCoords(const std::vector<Ogre::Vector3>& textureCoords) { _texCoords = textureCoords; } void PolygonBackground::setAppearance(const std::shared_ptr<Appearance>& appearance) { _appearance = appearance; } void PolygonBackground::onBound(Scene& scene) { if (_root) _root->attachObject(_rect.get()); } void PolygonBackground::onUnbound(Scene& scene) { if (_root) _root->detachObject(_rect.get()); }
28.14433
127
0.734432
jess22664
444787f8524a6cd27193bf0c6eff4521bd785e45
4,453
cpp
C++
openstudiocore/src/utilities/units/test/BTUUnit_GTest.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/utilities/units/test/BTUUnit_GTest.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/utilities/units/test/BTUUnit_GTest.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include <utilities/units/test/UnitsFixture.hpp> #include <utilities/units/BTUUnit.hpp> #include <utilities/units/Scale.hpp> #include <utilities/core/Exception.hpp> using openstudio::Unit; using openstudio::UnitSystem; using openstudio::BTUExpnt; using openstudio::BTUUnit; using openstudio::Exception; using openstudio::createBTULength; using openstudio::createBTUTime; using openstudio::createBTUTemperature; using openstudio::createBTUPeople; using openstudio::createBTUEnergy; using openstudio::createBTUPower; TEST_F(UnitsFixture,BTUUnit_Constructors) { LOG(Debug,"BTUUnit_Constructors"); BTUUnit l1(BTUExpnt(0,1)); BTUUnit P1(BTUExpnt(1,0,-1,0),-3); // mBtu/h BTUUnit E1("k",BTUExpnt(1)); // kBtu EXPECT_EQ(0,l1.baseUnitExponent("Btu")); EXPECT_EQ(1,l1.baseUnitExponent("ft")); l1.setBaseUnitExponent("R",-1); EXPECT_EQ(-1,l1.baseUnitExponent("R")); EXPECT_THROW(l1.setBaseUnitExponent("m",1),Exception); EXPECT_EQ("Btu/h",P1.standardString(false)); EXPECT_EQ("mBtu/h",P1.standardString()); EXPECT_EQ(UnitSystem::BTU,P1.system().value()); EXPECT_EQ(0,P1.baseUnitExponent("R")); BTUUnit P2(P1); EXPECT_EQ(UnitSystem::BTU,P2.system().value()); EXPECT_EQ("",E1.prettyString()); EXPECT_EQ("kBtu",E1.standardString()); EXPECT_EQ(0,E1.baseUnitExponent("ft")); } TEST_F(UnitsFixture,BTUUnit_ArithmeticOperators) { LOG(Debug,"BTUUnit_ArithmeticOperators"); // /= BTUUnit P1(BTUExpnt(1)); BTUUnit t1(BTUExpnt(0,0,1)); P1 /= t1; EXPECT_EQ("Btu/h",P1.standardString(false)); EXPECT_EQ(1,P1.baseUnitExponent("Btu")); EXPECT_EQ(-1,P1.baseUnitExponent("h")); EXPECT_EQ(0,P1.baseUnitExponent("ft")); EXPECT_EQ(0,P1.baseUnitExponent("m")); // * Unit E1 = P1 * t1; EXPECT_TRUE(E1.system() == UnitSystem::BTU); EXPECT_EQ("Btu",E1.standardString(false)); EXPECT_EQ("",E1.prettyString()); // / Unit u = P1/E1; u /= t1; EXPECT_TRUE(u.system() == UnitSystem::BTU); EXPECT_EQ("1/h^2",u.standardString(false)); EXPECT_EQ(-2,u.baseUnitExponent("h")); EXPECT_EQ(0,u.baseUnitExponent("Btu")); // pow u.pow(-1,2); EXPECT_EQ("h",u.standardString(false)); EXPECT_EQ(1,u.baseUnitExponent("h")); } TEST_F(UnitsFixture,BTUUnit_CreateFunctions) { BTUUnit u; u = createBTULength(); EXPECT_EQ(1,u.baseUnitExponent("ft")); EXPECT_EQ(0,u.scale().exponent); EXPECT_EQ("ft",u.standardString(false)); EXPECT_EQ("",u.prettyString()); u = createBTUTime(); EXPECT_EQ(1,u.baseUnitExponent("h")); EXPECT_EQ(0,u.scale().exponent); EXPECT_EQ("h",u.standardString(false)); EXPECT_EQ("",u.prettyString()); u = createBTUTemperature(); EXPECT_EQ(1,u.baseUnitExponent("R")); EXPECT_EQ(0,u.scale().exponent); EXPECT_EQ("R",u.standardString(false)); EXPECT_EQ("",u.prettyString()); u = createBTUPeople(); EXPECT_EQ(1,u.baseUnitExponent("people")); EXPECT_EQ(0,u.scale().exponent); EXPECT_EQ("people",u.standardString(false)); EXPECT_EQ("",u.prettyString()); u.pow(-1); EXPECT_EQ("1/person",u.standardString(false)); u = createBTUEnergy(); EXPECT_EQ(0,u.scale().exponent); EXPECT_EQ("Btu",u.standardString(false)); EXPECT_EQ("",u.prettyString()); u = createBTUPower(); EXPECT_EQ(0,u.scale().exponent); EXPECT_EQ("Btu/h",u.standardString(false)); EXPECT_EQ("",u.prettyString()); }
30.710345
82
0.665619
ORNL-BTRIC
44483bc7c56dcad829971fef6fc2e2e9028614aa
209
cpp
C++
id1068_Sum/main.cpp
adogadaev/timus
eeadeb3ac60b7259988fe579422d386b95c4ca9d
[ "Apache-2.0" ]
null
null
null
id1068_Sum/main.cpp
adogadaev/timus
eeadeb3ac60b7259988fe579422d386b95c4ca9d
[ "Apache-2.0" ]
null
null
null
id1068_Sum/main.cpp
adogadaev/timus
eeadeb3ac60b7259988fe579422d386b95c4ca9d
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main() { int nNum; int nSize; cin >> nNum; nSize = (nNum <= 0) ? (abs(nNum) + 2) : nNum; cout << nSize*(1+nNum)/2 << endl; return 0; }
12.294118
46
0.578947
adogadaev
4448d909d1fc488f10a97031e0c10101927d739d
940
cc
C++
quiche/spdy/core/spdy_pinnable_buffer_piece.cc
ktprime/quiche-1
abf85ce22e1409a870b1bf470cb5a68cbdb28e50
[ "BSD-3-Clause" ]
null
null
null
quiche/spdy/core/spdy_pinnable_buffer_piece.cc
ktprime/quiche-1
abf85ce22e1409a870b1bf470cb5a68cbdb28e50
[ "BSD-3-Clause" ]
null
null
null
quiche/spdy/core/spdy_pinnable_buffer_piece.cc
ktprime/quiche-1
abf85ce22e1409a870b1bf470cb5a68cbdb28e50
[ "BSD-3-Clause" ]
null
null
null
// 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 "quiche/spdy/core/spdy_pinnable_buffer_piece.h" #include <new> namespace spdy { SpdyPinnableBufferPiece::SpdyPinnableBufferPiece() : buffer_(nullptr), length_(0) {} SpdyPinnableBufferPiece::~SpdyPinnableBufferPiece() = default; void SpdyPinnableBufferPiece::Pin() { if (!storage_ && buffer_ != nullptr && length_ != 0) { storage_.reset(new char[length_]); std::copy(buffer_, buffer_ + length_, storage_.get()); buffer_ = storage_.get(); } } void SpdyPinnableBufferPiece::Swap(SpdyPinnableBufferPiece* other) { size_t length = length_; length_ = other->length_; other->length_ = length; const char* buffer = buffer_; buffer_ = other->buffer_; other->buffer_ = buffer; storage_.swap(other->storage_); } } // namespace spdy
25.405405
73
0.718085
ktprime
444d04dea76bdfbaccccc24835f7a78694f004b3
158
hpp
C++
include/mockitopp/mockitopp.hpp
tpounds/mockitopp
775b151fa746c81c8762faea2de3429d6f3f46af
[ "MIT" ]
82
2015-03-19T06:28:00.000Z
2021-08-20T17:40:11.000Z
include/mockitopp/mockitopp.hpp
tpounds/mockitopp
775b151fa746c81c8762faea2de3429d6f3f46af
[ "MIT" ]
6
2015-03-19T08:46:46.000Z
2019-06-04T14:24:52.000Z
include/mockitopp/mockitopp.hpp
tpounds/mockitopp
775b151fa746c81c8762faea2de3429d6f3f46af
[ "MIT" ]
12
2015-03-19T08:15:32.000Z
2021-02-04T11:53:16.000Z
#ifndef __MOCKITOPP_HPP__ #define __MOCKITOPP_HPP__ #include "exceptions.hpp" #include "matchers.hpp" #include "mock_object.hpp" #endif //__MOCKITOPP_HPP__
17.555556
26
0.803797
tpounds
444e6554949ac26cb677efaea689b392b5c1b935
446
cpp
C++
src/system/system_details_to_json_converter.cpp
connected-digital-energy-meter/connected-digital-energy-meter
e3ce164a10a261efc1d34486abeb0e047f11f31b
[ "MIT" ]
1
2021-06-06T21:25:31.000Z
2021-06-06T21:25:31.000Z
src/system/system_details_to_json_converter.cpp
connected-digital-energy-meter/connected-digital-energy-meter
e3ce164a10a261efc1d34486abeb0e047f11f31b
[ "MIT" ]
10
2021-06-04T07:56:41.000Z
2021-12-20T18:12:06.000Z
src/system/system_details_to_json_converter.cpp
connected-digital-energy-meter/connected-digital-energy-meter
e3ce164a10a261efc1d34486abeb0e047f11f31b
[ "MIT" ]
null
null
null
#include "system_details_to_json_converter.h" #include <ArduinoJson.h> namespace CDEM { String SystemDetailsToJsonConverter::to_json_string(String ip, String mac, String libVersion, String pcbVersion) { StaticJsonDocument<128> json; json["ip"] = ip; json["mac"] = mac; json["lib-version"] = libVersion; json["pcb-version"] = pcbVersion; String result = ""; serializeJson(json, result); return result; } };
23.473684
116
0.688341
connected-digital-energy-meter
44505eaf01b941f116f412cecad8c862c80ebec4
20,448
cpp
C++
routing/routing_tests/index_graph_test.cpp
romanblanco/omim
62321c2c51b6cbb677278a6a68d15c73ae3f086e
[ "Apache-2.0" ]
null
null
null
routing/routing_tests/index_graph_test.cpp
romanblanco/omim
62321c2c51b6cbb677278a6a68d15c73ae3f086e
[ "Apache-2.0" ]
null
null
null
routing/routing_tests/index_graph_test.cpp
romanblanco/omim
62321c2c51b6cbb677278a6a68d15c73ae3f086e
[ "Apache-2.0" ]
null
null
null
#include "testing/testing.hpp" #include "routing/base/astar_algorithm.hpp" #include "routing/edge_estimator.hpp" #include "routing/index_graph.hpp" #include "routing/index_graph_serialization.hpp" #include "routing/index_graph_starter.hpp" #include "routing/vehicle_mask.hpp" #include "routing/routing_tests/index_graph_tools.hpp" #include "routing_common/car_model.hpp" #include "geometry/point2d.hpp" #include "coding/reader.hpp" #include "coding/writer.hpp" #include "base/assert.hpp" #include "base/math.hpp" #include "std/algorithm.hpp" #include "std/cstdint.hpp" #include "std/unique_ptr.hpp" #include "std/unordered_map.hpp" #include "std/vector.hpp" using namespace std; namespace { using namespace routing; using namespace routing_test; using Edge = TestIndexGraphTopology::Edge; void TestRoute(IndexGraphStarter::FakeVertex const & start, IndexGraphStarter::FakeVertex const & finish, size_t expectedLength, vector<Segment> const * expectedRoute, WorldGraph & graph) { IndexGraphStarter starter(start, finish, graph); vector<Segment> route; double timeSec; auto const resultCode = CalculateRoute(starter, route, timeSec); TEST_EQUAL(resultCode, AStarAlgorithm<IndexGraphStarter>::Result::OK, ()); TEST_GREATER(route.size(), 2, ()); // Erase fake points. route.erase(route.begin()); route.pop_back(); TEST_EQUAL(route.size(), expectedLength, ("route =", route)); if (expectedRoute) TEST_EQUAL(route, *expectedRoute, ()); } void TestEdges(IndexGraph & graph, Segment const & segment, vector<Segment> const & expectedTargets, bool isOutgoing) { ASSERT(segment.IsForward() || !graph.GetGeometry().GetRoad(segment.GetFeatureId()).IsOneWay(), ()); vector<SegmentEdge> edges; graph.GetEdgeList(segment, isOutgoing, edges); vector<Segment> targets; for (SegmentEdge const & edge : edges) targets.push_back(edge.GetTarget()); sort(targets.begin(), targets.end()); vector<Segment> sortedExpectedTargets(expectedTargets); sort(sortedExpectedTargets.begin(), sortedExpectedTargets.end()); TEST_EQUAL(targets, sortedExpectedTargets, ()); } void TestOutgoingEdges(IndexGraph & graph, Segment const & segment, vector<Segment> const & expectedTargets) { TestEdges(graph, segment, expectedTargets, true /* isOutgoing */); } void TestIngoingEdges(IndexGraph & graph, Segment const & segment, vector<Segment> const & expectedTargets) { TestEdges(graph, segment, expectedTargets, false /* isOutgoing */); } uint32_t AbsDelta(uint32_t v0, uint32_t v1) { return v0 > v1 ? v0 - v1 : v1 - v0; } } // namespace namespace routing_test { // R4 (one way down) // // R1 J2--------J3 -1 // ^ v // ^ v // R0 *---J0----*---J1----* 0 // ^ v // ^ v // R2 J4--------J5 1 // // R3 (one way up) y // // x: 0 1 2 3 4 // UNIT_TEST(EdgesTest) { unique_ptr<TestGeometryLoader> loader = make_unique<TestGeometryLoader>(); loader->AddRoad( 0 /* featureId */, false, 1.0 /* speed */, RoadGeometry::Points({{0.0, 0.0}, {1.0, 0.0}, {2.0, 0.0}, {3.0, 0.0}, {4.0, 0.0}})); loader->AddRoad(1 /* featureId */, false, 1.0 /* speed */, RoadGeometry::Points({{1.0, -1.0}, {3.0, -1.0}})); loader->AddRoad(2 /* featureId */, false, 1.0 /* speed */, RoadGeometry::Points({{1.0, -1.0}, {3.0, -1.0}})); loader->AddRoad(3 /* featureId */, true, 1.0 /* speed */, RoadGeometry::Points({{1.0, 1.0}, {1.0, 0.0}, {1.0, -1.0}})); loader->AddRoad(4 /* featureId */, true, 1.0 /* speed */, RoadGeometry::Points({{3.0, -1.0}, {3.0, 0.0}, {3.0, 1.0}})); traffic::TrafficCache const trafficCache; IndexGraph graph(move(loader), CreateEstimatorForCar(trafficCache)); vector<Joint> joints; joints.emplace_back(MakeJoint({{0, 1}, {3, 1}})); // J0 joints.emplace_back(MakeJoint({{0, 3}, {4, 1}})); // J1 joints.emplace_back(MakeJoint({{1, 0}, {3, 2}})); // J2 joints.emplace_back(MakeJoint({{1, 1}, {4, 0}})); // J3 joints.emplace_back(MakeJoint({{2, 0}, {3, 0}})); // J4 joints.emplace_back(MakeJoint({{2, 1}, {4, 2}})); // J5 graph.Import(joints); TestOutgoingEdges( graph, {kTestNumMwmId, 0 /* featureId */, 0 /* segmentIdx */, true /* forward */}, {{kTestNumMwmId, 0, 0, false}, {kTestNumMwmId, 0, 1, true}, {kTestNumMwmId, 3, 1, true}}); TestIngoingEdges(graph, {kTestNumMwmId, 0, 0, true}, {{kTestNumMwmId, 0, 0, false}}); TestOutgoingEdges(graph, {kTestNumMwmId, 0, 0, false}, {{kTestNumMwmId, 0, 0, true}}); TestIngoingEdges( graph, {kTestNumMwmId, 0, 0, false}, {{kTestNumMwmId, 0, 0, true}, {kTestNumMwmId, 0, 1, false}, {kTestNumMwmId, 3, 0, true}}); TestOutgoingEdges( graph, {kTestNumMwmId, 0, 2, true}, {{kTestNumMwmId, 0, 2, false}, {kTestNumMwmId, 0, 3, true}, {kTestNumMwmId, 4, 1, true}}); TestIngoingEdges(graph, {kTestNumMwmId, 0, 2, true}, {{kTestNumMwmId, 0, 1, true}}); TestOutgoingEdges(graph, {kTestNumMwmId, 0, 2, false}, {{kTestNumMwmId, 0, 1, false}}); TestIngoingEdges( graph, {kTestNumMwmId, 0, 2, false}, {{kTestNumMwmId, 0, 2, true}, {kTestNumMwmId, 0, 3, false}, {kTestNumMwmId, 4, 0, true}}); TestOutgoingEdges( graph, {kTestNumMwmId, 3, 0, true}, {{kTestNumMwmId, 3, 1, true}, {kTestNumMwmId, 0, 0, false}, {kTestNumMwmId, 0, 1, true}}); TestIngoingEdges(graph, {kTestNumMwmId, 3, 0, true}, {{kTestNumMwmId, 2, 0, false}}); TestOutgoingEdges(graph, {kTestNumMwmId, 4, 1, true}, {{kTestNumMwmId, 2, 0, false}}); TestIngoingEdges( graph, {kTestNumMwmId, 4, 1, true}, {{kTestNumMwmId, 4, 0, true}, {kTestNumMwmId, 0, 2, true}, {kTestNumMwmId, 0, 3, false}}); } // Roads R1: // // -2 // -1 // R0 -2 -1 0 1 2 // 1 // 2 // UNIT_TEST(FindPathCross) { unique_ptr<TestGeometryLoader> loader = make_unique<TestGeometryLoader>(); loader->AddRoad( 0 /* featureId */, false, 1.0 /* speed */, RoadGeometry::Points({{-2.0, 0.0}, {-1.0, 0.0}, {0.0, 0.0}, {1.0, 0.0}, {2.0, 0.0}})); loader->AddRoad( 1 /* featureId */, false, 1.0 /* speed */, RoadGeometry::Points({{0.0, -2.0}, {0.0, -1.0}, {0.0, 0.0}, {0.0, 1.0}, {0.0, 2.0}})); traffic::TrafficCache const trafficCache; shared_ptr<EdgeEstimator> estimator = CreateEstimatorForCar(trafficCache); unique_ptr<WorldGraph> worldGraph = BuildWorldGraph(move(loader), estimator, {MakeJoint({{0, 2}, {1, 2}})}); vector<IndexGraphStarter::FakeVertex> endPoints; for (uint32_t i = 0; i < 4; ++i) { endPoints.emplace_back(kTestNumMwmId, 0, i, m2::PointD(-1.5 + i, 0.0)); endPoints.emplace_back(kTestNumMwmId, 1, i, m2::PointD(0.0, -1.5 + i)); } for (auto const & start : endPoints) { for (auto const & finish : endPoints) { uint32_t expectedLength = 0; if (start.GetFeatureId() == finish.GetFeatureId()) { expectedLength = AbsDelta(start.GetSegmentIdxForTesting(), finish.GetSegmentIdxForTesting()) + 1; } else { if (start.GetSegmentIdxForTesting() < 2) expectedLength += 2 - start.GetSegmentIdxForTesting(); else expectedLength += start.GetSegmentIdxForTesting() - 1; if (finish.GetSegmentIdxForTesting() < 2) expectedLength += 2 - finish.GetSegmentIdxForTesting(); else expectedLength += finish.GetSegmentIdxForTesting() - 1; } TestRoute(start, finish, expectedLength, nullptr, *worldGraph); } } } // Roads R4 R5 R6 R7 // // R0 0 - * - * - * // | | | | // R1 * - 1 - * - * // | | | | // R2 * - * - 2 - * // | | | | // R3 * - * - * - 3 // UNIT_TEST(FindPathManhattan) { uint32_t constexpr kCitySize = 4; unique_ptr<TestGeometryLoader> loader = make_unique<TestGeometryLoader>(); for (uint32_t i = 0; i < kCitySize; ++i) { RoadGeometry::Points street; RoadGeometry::Points avenue; for (uint32_t j = 0; j < kCitySize; ++j) { street.emplace_back(static_cast<double>(j), static_cast<double>(i)); avenue.emplace_back(static_cast<double>(i), static_cast<double>(j)); } loader->AddRoad(i, false, 1.0 /* speed */, street); loader->AddRoad(i + kCitySize, false, 1.0 /* speed */, avenue); } traffic::TrafficCache const trafficCache; shared_ptr<EdgeEstimator> estimator = CreateEstimatorForCar(trafficCache); vector<Joint> joints; for (uint32_t i = 0; i < kCitySize; ++i) { for (uint32_t j = 0; j < kCitySize; ++j) joints.emplace_back(MakeJoint({{i, j}, {j + kCitySize, i}})); } unique_ptr<WorldGraph> worldGraph = BuildWorldGraph(move(loader), estimator, joints); vector<IndexGraphStarter::FakeVertex> endPoints; for (uint32_t featureId = 0; featureId < kCitySize; ++featureId) { for (uint32_t segmentId = 0; segmentId < kCitySize - 1; ++segmentId) { endPoints.emplace_back(kTestNumMwmId, featureId, segmentId, m2::PointD(0.5 + segmentId, featureId)); endPoints.emplace_back(kTestNumMwmId, featureId + kCitySize, segmentId, m2::PointD(featureId, 0.5 + segmentId)); } } for (auto const & start : endPoints) { for (auto const & finish : endPoints) { uint32_t expectedLength = 0; auto const startFeatureOffset = start.GetFeatureId() < kCitySize ? start.GetFeatureId() : start.GetFeatureId() - kCitySize; auto const finishFeatureOffset = finish.GetFeatureId() < kCitySize ? finish.GetFeatureId() : finish.GetFeatureId() - kCitySize; if (start.GetFeatureId() < kCitySize == finish.GetFeatureId() < kCitySize) { uint32_t segDelta = AbsDelta(start.GetSegmentIdxForTesting(), finish.GetSegmentIdxForTesting()); if (segDelta == 0 && start.GetFeatureId() != finish.GetFeatureId()) segDelta = 1; expectedLength += segDelta; expectedLength += AbsDelta(startFeatureOffset, finishFeatureOffset) + 1; } else { if (start.GetSegmentIdxForTesting() < finishFeatureOffset) expectedLength += finishFeatureOffset - start.GetSegmentIdxForTesting(); else expectedLength += start.GetSegmentIdxForTesting() - finishFeatureOffset + 1; if (finish.GetSegmentIdxForTesting() < startFeatureOffset) expectedLength += startFeatureOffset - finish.GetSegmentIdxForTesting(); else expectedLength += finish.GetSegmentIdxForTesting() - startFeatureOffset + 1; } TestRoute(start, finish, expectedLength, nullptr, *worldGraph); } } } // Roads y: // // fast road R0 * - * - * -1 // / \ // slow road R1 * - - * - - * - - * - - * 0 // J0 J1 // // x: 0 1 2 3 4 5 6 // UNIT_TEST(RoadSpeed) { unique_ptr<TestGeometryLoader> loader = make_unique<TestGeometryLoader>(); loader->AddRoad( 0 /* featureId */, false, 10.0 /* speed */, RoadGeometry::Points({{1.0, 0.0}, {2.0, -1.0}, {3.0, -1.0}, {4.0, -1.0}, {5.0, 0.0}})); loader->AddRoad( 1 /* featureId */, false, 1.0 /* speed */, RoadGeometry::Points({{0.0, 0.0}, {1.0, 0.0}, {3.0, 0.0}, {5.0, 0.0}, {6.0, 0.0}})); traffic::TrafficCache const trafficCache; shared_ptr<EdgeEstimator> estimator = CreateEstimatorForCar(trafficCache); vector<Joint> joints; joints.emplace_back(MakeJoint({{0, 0}, {1, 1}})); // J0 joints.emplace_back(MakeJoint({{0, 4}, {1, 3}})); // J1 unique_ptr<WorldGraph> worldGraph = BuildWorldGraph(move(loader), estimator, joints); IndexGraphStarter::FakeVertex const start(kTestNumMwmId, 1, 0, m2::PointD(0.5, 0)); IndexGraphStarter::FakeVertex const finish(kTestNumMwmId, 1, 3, m2::PointD(5.5, 0)); vector<Segment> const expectedRoute({{kTestNumMwmId, 1, 0, true}, {kTestNumMwmId, 0, 0, true}, {kTestNumMwmId, 0, 1, true}, {kTestNumMwmId, 0, 2, true}, {kTestNumMwmId, 0, 3, true}, {kTestNumMwmId, 1, 3, true}}); TestRoute(start, finish, 6, &expectedRoute, *worldGraph); } // Roads y: // // R0 * - - - - - - - - * 0 // ^ ^ // start finish // // x: 0 1 2 3 // UNIT_TEST(OneSegmentWay) { unique_ptr<TestGeometryLoader> loader = make_unique<TestGeometryLoader>(); loader->AddRoad(0 /* featureId */, false, 1.0 /* speed */, RoadGeometry::Points({{0.0, 0.0}, {3.0, 0.0}})); traffic::TrafficCache const trafficCache; shared_ptr<EdgeEstimator> estimator = CreateEstimatorForCar(trafficCache); unique_ptr<WorldGraph> worldGraph = BuildWorldGraph(move(loader), estimator, vector<Joint>()); IndexGraphStarter::FakeVertex const start(kTestNumMwmId, 0, 0, m2::PointD(1, 0)); IndexGraphStarter::FakeVertex const finish(kTestNumMwmId, 0, 0, m2::PointD(2, 0)); vector<Segment> const expectedRoute({{kTestNumMwmId, 0, 0, true}}); TestRoute(start, finish, 1 /* expectedLength */, &expectedRoute, *worldGraph); } // // Road R0 (ped) R1 (car) R2 (car) // 0----------1 * 0----------1 * 0----------1 // Joints J0 J1 // UNIT_TEST(SerializeSimpleGraph) { vector<uint8_t> buffer; { IndexGraph graph; vector<Joint> joints = { MakeJoint({{0, 1}, {1, 0}}), MakeJoint({{1, 1}, {2, 0}}), }; graph.Import(joints); unordered_map<uint32_t, VehicleMask> masks; masks[0] = kPedestrianMask; masks[1] = kCarMask; masks[2] = kCarMask; MemWriter<vector<uint8_t>> writer(buffer); IndexGraphSerializer::Serialize(graph, masks, writer); } { IndexGraph graph; MemReader reader(buffer.data(), buffer.size()); ReaderSource<MemReader> source(reader); IndexGraphSerializer::Deserialize(graph, source, kAllVehiclesMask); TEST_EQUAL(graph.GetNumRoads(), 3, ()); TEST_EQUAL(graph.GetNumJoints(), 2, ()); TEST_EQUAL(graph.GetNumPoints(), 4, ()); TEST_EQUAL(graph.GetJointId({0, 0}), Joint::kInvalidId, ()); TEST_EQUAL(graph.GetJointId({0, 1}), 1, ()); TEST_EQUAL(graph.GetJointId({1, 0}), 1, ()); TEST_EQUAL(graph.GetJointId({1, 1}), 0, ()); TEST_EQUAL(graph.GetJointId({2, 0}), 0, ()); TEST_EQUAL(graph.GetJointId({2, 1}), Joint::kInvalidId, ()); } { IndexGraph graph; MemReader reader(buffer.data(), buffer.size()); ReaderSource<MemReader> source(reader); IndexGraphSerializer::Deserialize(graph, source, kCarMask); TEST_EQUAL(graph.GetNumRoads(), 2, ()); TEST_EQUAL(graph.GetNumJoints(), 1, ()); TEST_EQUAL(graph.GetNumPoints(), 2, ()); TEST_EQUAL(graph.GetJointId({0, 0}), Joint::kInvalidId, ()); TEST_EQUAL(graph.GetJointId({0, 1}), Joint::kInvalidId, ()); TEST_EQUAL(graph.GetJointId({1, 0}), Joint::kInvalidId, ()); TEST_EQUAL(graph.GetJointId({1, 1}), 0, ()); TEST_EQUAL(graph.GetJointId({2, 0}), 0, ()); TEST_EQUAL(graph.GetJointId({2, 1}), Joint::kInvalidId, ()); } } // Finish // 0.0004 * // ^ // | // F2 // | // | // 0.0003 6*---------*5 // | | // | | // | | // | | // | | // 0.0002 7* *4 // | | // | | // 0.00015 8* F0 *3 // \ / // \ / 1 0 // 0.0001 9*---F0-*----* // 2 ^ // | // F1 // | // | // 0 * Start // 0 0.0001 0.0002 // F0 is a two-way feature with a loop and F1 and F2 are an one-way one-segment features. unique_ptr<WorldGraph> BuildLoopGraph() { unique_ptr<TestGeometryLoader> loader = make_unique<TestGeometryLoader>(); loader->AddRoad(0 /* feature id */, false /* one way */, 100.0 /* speed */, RoadGeometry::Points({{0.0002, 0.0001}, {0.00015, 0.0001}, {0.0001, 0.0001}, {0.00015, 0.00015}, {0.00015, 0.0002}, {0.00015, 0.0003}, {0.00005, 0.0003}, {0.00005, 0.0002}, {0.00005, 0.00015}, {0.0001, 0.0001}})); loader->AddRoad(1 /* feature id */, true /* one way */, 100.0 /* speed */, RoadGeometry::Points({{0.0002, 0.0}, {0.0002, 0.0001}})); loader->AddRoad(2 /* feature id */, true /* one way */, 100.0 /* speed */, RoadGeometry::Points({{0.00005, 0.0003}, {0.00005, 0.0004}})); vector<Joint> const joints = { MakeJoint({{0 /* feature id */, 2 /* point id */}, {0, 9}}), /* joint at point (0.0002, 0) */ MakeJoint({{1, 1}, {0, 0}}), /* joint at point (0.0002, 0.0001) */ MakeJoint({{0, 6}, {2, 0}}), /* joint at point (0.00005, 0.0003) */ MakeJoint({{2, 1}}), /* joint at point (0.00005, 0.0004) */ }; traffic::TrafficCache const trafficCache; shared_ptr<EdgeEstimator> estimator = CreateEstimatorForCar(trafficCache); return BuildWorldGraph(move(loader), estimator, joints); } // This test checks that the route from Start to Finish doesn't make an extra loop in F0. // If it was so the route time had been much more. UNIT_CLASS_TEST(RestrictionTest, LoopGraph) { Init(BuildLoopGraph()); SetStarter(routing::IndexGraphStarter::FakeVertex(kTestNumMwmId, 1, 0 /* seg id */, m2::PointD(0.0002, 0)) /* start */, routing::IndexGraphStarter::FakeVertex(kTestNumMwmId, 2, 0 /* seg id */, m2::PointD(0.00005, 0.0004)) /* finish */); vector<Segment> const expectedRoute = {{kTestNumMwmId, 1, 0, true}, {kTestNumMwmId, 0, 0, true}, {kTestNumMwmId, 0, 1, true}, {kTestNumMwmId, 0, 8, false}, {kTestNumMwmId, 0, 7, false}, {kTestNumMwmId, 0, 6, false}, {kTestNumMwmId, 2, 0, true}}; TestRoute(m_starter->GetStartVertex(), m_starter->GetFinishVertex(), 7, &expectedRoute, m_starter->GetGraph()); } UNIT_TEST(IndexGraph_OnlyTopology_1) { // Add edges to the graph in the following format: (from, to, weight). uint32_t const numVertices = 5; TestIndexGraphTopology graph(numVertices); graph.AddDirectedEdge(0, 1, 1.0); graph.AddDirectedEdge(0, 2, 2.0); graph.AddDirectedEdge(1, 3, 1.0); graph.AddDirectedEdge(2, 3, 2.0); double const expectedWeight = 2.0; vector<Edge> const expectedEdges = {{0, 1}, {1, 3}}; TestTopologyGraph(graph, 0, 3, true /* pathFound */, expectedWeight, expectedEdges); TestTopologyGraph(graph, 0, 4, false /* pathFound */, 0.0, {}); } UNIT_TEST(IndexGraph_OnlyTopology_2) { uint32_t const numVertices = 1; TestIndexGraphTopology graph(numVertices); graph.AddDirectedEdge(0, 0, 100.0); double const expectedWeight = 0.0; vector<Edge> const expectedEdges = {}; TestTopologyGraph(graph, 0, 0, true /* pathFound */, expectedWeight, expectedEdges); } UNIT_TEST(IndexGraph_OnlyTopology_3) { uint32_t const numVertices = 2; TestIndexGraphTopology graph(numVertices); graph.AddDirectedEdge(0, 1, 1.0); graph.AddDirectedEdge(1, 0, 1.0); double const expectedWeight = 1.0; vector<Edge> const expectedEdges = {{0, 1}}; TestTopologyGraph(graph, 0, 1, true /* pathFound */, expectedWeight, expectedEdges); } } // namespace routing_test
36.319716
100
0.574237
romanblanco
44534609931fd2e6c6add7f200def448e3a19f8b
11,564
cpp
C++
projects/game-invader/gamestate/gameState.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
15
2019-01-13T16:07:27.000Z
2021-09-27T15:18:58.000Z
projects/game-invader/gamestate/gameState.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
1
2019-03-14T00:36:35.000Z
2020-12-29T11:48:09.000Z
projects/game-invader/gamestate/gameState.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
3
2020-03-02T21:28:56.000Z
2021-09-27T15:18:50.000Z
#include "gameState.h" #include <stdio.h> /* o gameState de cada fase possui um cen�rio, um conjunto de alienigenas(inimigos), um conjunto de objetos (stuff) que podem ser lan�ados pelos inimigos ou pela nave principal a nave principal ** ao passar a token init_cg pode ser pelo loadGame ou NewGame ------ <init_cg> ------------------- |Menu| *----------------> | CG Antes Jogo | ------ ------------------- ^ * ^ | <init_play>| |<init_cg> | v | | ------- <pause> ------ | |-* |Pause| <-----------> |Jogo| | | ------- ------ | | * <stage_clear> * * | | | | | | | -----------------------------| | | | | <to_menu>| |---------- | | | v | | | ----------------- | | |-----* | fase completa | *-------| | ----------------- | | | | | | <bad_stage>| | | v | | ------------------- | |---------* | fase incompleta | *-- ------------------- */ //------------------------------------------------------------------------------ const char* gamestateToStr(GAMESTATE_STATES_ENUM state) { switch (state) { case GS_MENU:return "menu"; case GS_CG_BEFORE_PLAY:return "cg_before_play"; case GS_PLAY:return "play"; case GS_PAUSE:return "pause"; case GS_STAGE_COMPLETE:return "stage complete"; case GS_STAGE_INCOMPLETE:return "stage incomplete"; case GS_CONGRATULATIONS: return "congratulations"; } return "unknown state"; } //------------------------------------------------------------------------------ GameState::GameState(SpaceInvader *si) : menu(si), cgReproducer(si), playState(si), pauseState(si) { globalGamestate = GS_MENU; this->spaceInvader = si; } //------------------------------------------------------------------------------ void GameState::resizeWindow(int w, int h) { /* deve atualizar todos os componentes internos */ playState.resizeWindow(w, h); pauseState.resizeWindow(w, h); cgReproducer.resizeWindow(w, h); } //------------------------------------------------------------------------------ /* tem efeito no estado: PLAY */ //void GameState::setNaveMovingInput(MovingParserInput movingInput){ // if (globalGamestate != GS_PLAY) return; // playState.gamePlay.getNavePrincipal()->setInput(movingInput); // navePrincipal.setInput(movingInput); //} //------------------------------------------------------------------------------ /* tem efeito no estado: PLAY */ //void GameState::setNaveShootingInput(ShootingParserInput shootInput){ // if (globalGamestate != GS_PLAY) return; // playState.gamePlay.getNavePrincipal()->setShootInput(shootInput); // navePrincipal.setShootInput(shootInput); //} //------------------------------------------------------------------------------ /* tem efeito no estado: PLAY */ //void GameState::setNaveLifeInput(LifeParserInput lifeInput){ // if (globalGamestate != GS_PLAY) return; // navePrincipal.setLifeInput(lifeInput); //} //------------------------------------------------------------------------------ /* retorna true se for para sair do jogo tem efeito somente no estado: MENU */ bool GameState::setMenuInput(MENU_TOKENS menuInput) { if (globalGamestate != GS_MENU) return false; if (menu.inputMenu(menuInput)) { //OK switch (menu.getMenuState()) { case MS_NEW_GAME: //reset playState code spaceInvader->resources->setMusic(1); globalGamestate = GS_CG_BEFORE_PLAY; cgReproducer.setScoreLeve(0, 1); playState.resetPlayState(); return false; case MS_LOAD_GAME: //load playState code // globalGamestate = GS_CG_BEFORE_PLAY; return false; case MS_EXIT_GAME: return true; default: break; } } return false; } //------------------------------------------------------------------------------ /* tem efeito no estado: CG_BEFORE_PLAY */ bool GameState::cgReproducerIsTerminatedCheck() { if (globalGamestate != GS_CG_BEFORE_PLAY) return false; if (cgReproducer.cgReproducerIsTerminated()) { spaceInvader->resources->setMusic(2); globalGamestate = GS_PLAY; playState.createPlaystate(); return true; } return false; } //------------------------------------------------------------------------------ /* tem efeito no estado: PLAY PAUSE */ void GameState::postPauseToken() { // if (globalGamestate != GS_PLAY && globalGamestate != GS_PAUSE) return; parseGS(GS_pause); } //------------------------------------------------------------------------------ /* tem efeito no estado: PAUSE STAGE_COMPLETE STAGE_INCOMPLETE */ void GameState::postToMenuToken() { // if (globalGamestate != GS_PAUSE && // globalGamestate != GS_STAGE_COMPLETE && // globalGamestate != GS_STAGE_INCOMPLETE ) return; parseGS(GS_to_menu); } //------------------------------------------------------------------------------ /* m�todo que � chamado sempre que � para se fazer o calculo de um movimento no jogo */ void GameState::simulationTick() { switch (globalGamestate) { case GS_MENU: return; case GS_CG_BEFORE_PLAY: return; case GS_PLAY: playState.simulationTick(); if (playState.scene.isLevelComplete()) { spaceInvader->resources->setMusic(1); parseGS(GS_stage_clear); } // navePrincipal.simulationTick(); return; case GS_PAUSE: return; case GS_STAGE_COMPLETE: return; case GS_STAGE_INCOMPLETE: return; default: break; } } //------------------------------------------------------------------------------ void GameState::printState() { printf("GAME STATE\n"); printf(" globalGamestate = %s\n", gamestateToStr(globalGamestate)); printf("\n"); switch (globalGamestate) { case GS_MENU: menu.printState(); return; case GS_CG_BEFORE_PLAY: cgReproducer.printState(); return; case GS_PLAY: playState.printState(); //navePrincipal.printState(); return; case GS_PAUSE: return; case GS_STAGE_COMPLETE: return; case GS_STAGE_INCOMPLETE: return; default: break; } } //------------------------------------------------------------------------------ void GameState::render(float deltaTime, const vec2& screenCenter) { switch (globalGamestate) { case GS_MENU: menu.render(deltaTime); return; case GS_CG_BEFORE_PLAY: cgReproducer.render(deltaTime, screenCenter); // menu.render(time); return; case GS_PLAY: playState.render(deltaTime, screenCenter*2.0f); // navePrincipal.render(); return; case GS_PAUSE: pauseState.render(deltaTime, screenCenter); return; case GS_STAGE_COMPLETE: return; case GS_STAGE_INCOMPLETE: return; case GS_CONGRATULATIONS: playState.scene.renderCongratulations(screenCenter, deltaTime); return; } } //------------------------------------------------------------------------------ void GameState::parseGS(GAMESTATE_TOKENS_ENUM token) { switch (globalGamestate) { //menu case GS_MENU: switch (token) { case GS_init_cg: spaceInvader->resources->setMusic(1); playState.scene.clear(); cgReproducer.setScoreLeve(0, 1); globalGamestate = GS_CG_BEFORE_PLAY; return; default: break; } return; //cg_before_play case GS_CG_BEFORE_PLAY: switch (token) { case GS_init_play: spaceInvader->resources->setMusic(2); globalGamestate = GS_PLAY; return; default: break; } return; //play case GS_PLAY: switch (token) { case GS_pause: globalGamestate = GS_PAUSE; return; case GS_stage_clear: if (playState.resetPlayStateToNextLevel()) { //zero o jogo globalGamestate = GS_CONGRATULATIONS; return; } cgReproducer.setScoreLeve(playState.scene.score, playState.level); globalGamestate = GS_CG_BEFORE_PLAY;//GS_STAGE_COMPLETE; return; case GS_bad_stage: globalGamestate = GS_STAGE_INCOMPLETE; return; default: break; } return; //pause case GS_PAUSE: switch (token) { case GS_init_cg: spaceInvader->resources->setMusic(1); globalGamestate = GS_CG_BEFORE_PLAY; return; case GS_pause: globalGamestate = GS_PLAY; return; case GS_to_menu: spaceInvader->resources->setMusic(0); globalGamestate = GS_MENU; return; default: break; } return; //stage complete case GS_STAGE_COMPLETE: switch (token) { case GS_init_cg: spaceInvader->resources->setMusic(1); globalGamestate = GS_CG_BEFORE_PLAY; return; case GS_to_menu: spaceInvader->resources->setMusic(0); globalGamestate = GS_MENU; return; default: break; } return; //stage incomplete case GS_STAGE_INCOMPLETE: switch (token) { case GS_init_cg: spaceInvader->resources->setMusic(1); globalGamestate = GS_CG_BEFORE_PLAY; return; case GS_to_menu: spaceInvader->resources->setMusic(0); globalGamestate = GS_MENU; return; default: break; } return; default: break; } } //------------------------------------------------------------------------------ void GameState::shoot() { if (globalGamestate != GS_PLAY) return; playState.shoot(); } //------------------------------------------------------------------------------ void GameState::moveSpaceShip(float velocity) { if (globalGamestate != GS_PLAY) return; playState.moveSpaceShip(velocity); } //------------------------------------------------------------------------------ void GameState::enterPress() { if (globalGamestate == GS_PLAY) { if (!playState.scene.activateSpaceShip()) { spaceInvader->resources->setMusic(0); globalGamestate = GS_MENU; } } else if (globalGamestate == GS_CONGRATULATIONS) { spaceInvader->resources->setMusic(0); globalGamestate = GS_MENU; } } //------------------------------------------------------------------------------
31.856749
98
0.473971
A-Ribeiro
44537f53f1daf89001b5c70fa6f6854aeef40f10
1,479
hpp
C++
include/lexy/input/range_input.hpp
IohannRabeson/lexy
881beb56f030e8f4761514e70cb50d809ac4ad17
[ "BSL-1.0" ]
null
null
null
include/lexy/input/range_input.hpp
IohannRabeson/lexy
881beb56f030e8f4761514e70cb50d809ac4ad17
[ "BSL-1.0" ]
null
null
null
include/lexy/input/range_input.hpp
IohannRabeson/lexy
881beb56f030e8f4761514e70cb50d809ac4ad17
[ "BSL-1.0" ]
null
null
null
// Copyright (C) 2020-2021 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef LEXY_INPUT_RANGE_INPUT_HPP_INCLUDED #define LEXY_INPUT_RANGE_INPUT_HPP_INCLUDED #include <lexy/error.hpp> #include <lexy/input/base.hpp> #include <lexy/lexeme.hpp> namespace lexy { template <typename Encoding, typename Iterator, typename Sentinel = Iterator> class range_input { public: using encoding = Encoding; using char_type = typename encoding::char_type; using iterator = Iterator; //=== constructors ===// constexpr range_input() noexcept : _begin(), _end() {} constexpr range_input(Iterator begin, Sentinel end) noexcept : _begin(begin), _end(end) {} //=== access ===// constexpr iterator begin() const noexcept { return _begin; } constexpr iterator end() const noexcept { return _end; } //=== reader ===// constexpr auto reader() const& noexcept { return _detail::range_reader<Encoding, Iterator, Sentinel>(_begin, _end); } private: Iterator _begin; LEXY_EMPTY_MEMBER Sentinel _end; }; template <typename Iterator, typename Sentinel> range_input(Iterator begin, Sentinel end) -> range_input<deduce_encoding<std::decay_t<decltype(*begin)>>, Iterator, Sentinel>; } // namespace lexy #endif // LEXY_INPUT_RANGE_INPUT_HPP_INCLUDED
25.947368
94
0.698445
IohannRabeson
4453e435c0123f74a599736a86a840844104da98
10,278
hpp
C++
libuavcan/include/uavcan/util/templates.hpp
hsteinhaus/uavcan
e2e358bb069be4d52442e590fb14a6ceb1b9d65f
[ "MIT" ]
null
null
null
libuavcan/include/uavcan/util/templates.hpp
hsteinhaus/uavcan
e2e358bb069be4d52442e590fb14a6ceb1b9d65f
[ "MIT" ]
null
null
null
libuavcan/include/uavcan/util/templates.hpp
hsteinhaus/uavcan
e2e358bb069be4d52442e590fb14a6ceb1b9d65f
[ "MIT" ]
null
null
null
/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #pragma once #include <climits> #include <cstddef> #include <cmath> #include <uavcan/build_config.hpp> #ifndef UAVCAN_CPP_VERSION # error UAVCAN_CPP_VERSION #endif #if UAVCAN_CPP_VERSION < UAVCAN_CPP11 # include <float.h> // cfloat may not be available #else # include <cfloat> // C++11 mode assumes that all standard headers are available #endif namespace uavcan { /** * Usage: * StaticAssert<expression>::check(); */ template <bool Value> struct UAVCAN_EXPORT StaticAssert; template <> struct UAVCAN_EXPORT StaticAssert<true> { static void check() { } }; /** * Usage: * ShowIntegerAsError<integer_expression>::foobar(); */ template <long N> struct ShowIntegerAsError; /** * Prevents copying when inherited */ class UAVCAN_EXPORT Noncopyable { Noncopyable(const Noncopyable&); Noncopyable& operator=(const Noncopyable&); protected: Noncopyable() { } ~Noncopyable() { } }; /** * Compile time conditions */ template <bool B, typename T = void> struct UAVCAN_EXPORT EnableIf { }; template <typename T> struct UAVCAN_EXPORT EnableIf<true, T> { typedef T Type; }; /** * Lightweight type categorization. */ template <typename T, typename R = void> struct UAVCAN_EXPORT EnableIfType { typedef R Type; }; /** * Compile-time type selection (Alexandrescu) */ template <bool Condition, typename TrueType, typename FalseType> struct UAVCAN_EXPORT Select; template <typename TrueType, typename FalseType> struct UAVCAN_EXPORT Select<true, TrueType, FalseType> { typedef TrueType Result; }; template <typename TrueType, typename FalseType> struct UAVCAN_EXPORT Select<false, TrueType, FalseType> { typedef FalseType Result; }; /** * Value types */ template <bool> struct UAVCAN_EXPORT BooleanType { }; typedef BooleanType<true> TrueType; typedef BooleanType<false> FalseType; /** * Relations */ template <typename T1, typename T2> class UAVCAN_EXPORT IsImplicitlyConvertibleFromTo { template <typename U> static U returner(); struct True_ { char x[2]; }; struct False_ { }; static True_ test(const T2 &); static False_ test(...); public: enum { Result = sizeof(True_) == sizeof(IsImplicitlyConvertibleFromTo<T1, T2>::test(returner<T1>())) }; }; /** * try_implicit_cast<>(From) * try_implicit_cast<>(From, To) * @{ */ template <typename From, typename To> struct UAVCAN_EXPORT TryImplicitCastImpl { static To impl(const From& from, const To&, TrueType) { return To(from); } static To impl(const From&, const To& default_, FalseType) { return default_; } }; /** * If possible, performs an implicit cast from the type From to the type To. * If the cast is not possible, returns default_ of type To. */ template <typename To, typename From> UAVCAN_EXPORT To try_implicit_cast(const From& from, const To& default_) { return TryImplicitCastImpl<From, To>::impl(from, default_, BooleanType<IsImplicitlyConvertibleFromTo<From, To>::Result>()); } /** * If possible, performs an implicit cast from the type From to the type To. * If the cast is not possible, returns a default constructed object of the type To. */ template <typename To, typename From> UAVCAN_EXPORT To try_implicit_cast(const From& from) { return TryImplicitCastImpl<From, To>::impl(from, To(), BooleanType<IsImplicitlyConvertibleFromTo<From, To>::Result>()); } /** * @} */ /** * Compile time square root for integers. * Useful for operations on square matrices. */ template <unsigned Value> struct UAVCAN_EXPORT CompileTimeIntSqrt; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<4> { enum { Result = 2 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<9> { enum { Result = 3 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<16> { enum { Result = 4 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<25> { enum { Result = 5 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<36> { enum { Result = 6 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<49> { enum { Result = 7 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<64> { enum { Result = 8 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<81> { enum { Result = 9 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<100> { enum { Result = 10 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<121> { enum { Result = 11 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<144> { enum { Result = 12 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<169> { enum { Result = 13 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<196> { enum { Result = 14 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<225> { enum { Result = 15 }; }; template <> struct UAVCAN_EXPORT CompileTimeIntSqrt<256> { enum { Result = 16 }; }; /** * Replacement for std::copy(..) */ template <typename InputIt, typename OutputIt> UAVCAN_EXPORT OutputIt copy(InputIt first, InputIt last, OutputIt result) { while (first != last) { *result = *first; ++first; ++result; } return result; } /** * Replacement for std::fill(..) */ template <typename ForwardIt, typename T> UAVCAN_EXPORT void fill(ForwardIt first, ForwardIt last, const T& value) { while (first != last) { *first = value; ++first; } } /** * Replacement for std::fill_n(..) */ template<typename OutputIt, typename T> UAVCAN_EXPORT void fill_n(OutputIt first, std::size_t n, const T& value) { while (n--) { *first++ = value; } } /** * Replacement for std::min(..) */ template <typename T> UAVCAN_EXPORT const T& min(const T& a, const T& b) { return (b < a) ? b : a; } /** * Replacement for std::max(..) */ template <typename T> UAVCAN_EXPORT const T& max(const T& a, const T& b) { return (a < b) ? b : a; } /** * Replacement for std::lexicographical_compare(..) */ template<typename InputIt1, typename InputIt2> UAVCAN_EXPORT bool lexicographical_compare(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) { while ((first1 != last1) && (first2 != last2)) { if (*first1 < *first2) { return true; } if (*first2 < *first1) { return false; } ++first1; ++first2; } return (first1 == last1) && (first2 != last2); } /** * Replacement for std::equal(..) */ template<typename InputIt1, typename InputIt2> UAVCAN_EXPORT bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2) { while (first1 != last1) { if (*first1 != *first2) { return false; } ++first1; ++first2; } return true; } /** * Numeric traits, like std::numeric_limits<> */ template <typename T> struct UAVCAN_EXPORT NumericTraits; /// char template <> struct UAVCAN_EXPORT NumericTraits<char> { enum { IsSigned = 1 }; enum { IsInteger = 1 }; static char max() { return CHAR_MAX; } static char min() { return CHAR_MIN; } }; template <> struct UAVCAN_EXPORT NumericTraits<signed char> { enum { IsSigned = 1 }; enum { IsInteger = 1 }; static signed char max() { return SCHAR_MAX; } static signed char min() { return SCHAR_MIN; } }; template <> struct UAVCAN_EXPORT NumericTraits<unsigned char> { enum { IsSigned = 0 }; enum { IsInteger = 1 }; static unsigned char max() { return UCHAR_MAX; } static unsigned char min() { return 0; } }; /// short template <> struct UAVCAN_EXPORT NumericTraits<short> { enum { IsSigned = 1 }; enum { IsInteger = 1 }; static short max() { return SHRT_MAX; } static short min() { return SHRT_MIN; } }; template <> struct UAVCAN_EXPORT NumericTraits<unsigned short> { enum { IsSigned = 0 }; enum { IsInteger = 1 }; static unsigned short max() { return USHRT_MAX; } static unsigned short min() { return 0; } }; /// int template <> struct UAVCAN_EXPORT NumericTraits<int> { enum { IsSigned = 1 }; enum { IsInteger = 1 }; static int max() { return INT_MAX; } static int min() { return INT_MIN; } }; template <> struct UAVCAN_EXPORT NumericTraits<unsigned int> { enum { IsSigned = 0 }; enum { IsInteger = 1 }; static unsigned int max() { return UINT_MAX; } static unsigned int min() { return 0; } }; /// long template <> struct UAVCAN_EXPORT NumericTraits<long> { enum { IsSigned = 1 }; enum { IsInteger = 1 }; static long max() { return LONG_MAX; } static long min() { return LONG_MIN; } }; template <> struct UAVCAN_EXPORT NumericTraits<unsigned long> { enum { IsSigned = 0 }; enum { IsInteger = 1 }; static unsigned long max() { return ULONG_MAX; } static unsigned long min() { return 0; } }; /// long long template <> struct UAVCAN_EXPORT NumericTraits<long long> { enum { IsSigned = 1 }; enum { IsInteger = 1 }; static long long max() { return LLONG_MAX; } static long long min() { return LLONG_MIN; } }; template <> struct UAVCAN_EXPORT NumericTraits<unsigned long long> { enum { IsSigned = 0 }; enum { IsInteger = 1 }; static unsigned long long max() { return ULLONG_MAX; } static unsigned long long min() { return 0; } }; /// float template <> struct UAVCAN_EXPORT NumericTraits<float> { enum { IsSigned = 1 }; enum { IsInteger = 0 }; static float max() { return FLT_MAX; } static float min() { return FLT_MIN; } static float infinity() { return INFINITY; } }; /// double template <> struct UAVCAN_EXPORT NumericTraits<double> { enum { IsSigned = 1 }; enum { IsInteger = 0 }; static double max() { return DBL_MAX; } static double min() { return DBL_MIN; } static double infinity() { return static_cast<double>(INFINITY) * static_cast<double>(INFINITY); } }; /// long double template <> struct UAVCAN_EXPORT NumericTraits<long double> { enum { IsSigned = 1 }; enum { IsInteger = 0 }; static long double max() { return LDBL_MAX; } static long double min() { return LDBL_MIN; } static long double infinity() { return static_cast<long double>(INFINITY) * static_cast<long double>(INFINITY); } }; }
24.413302
117
0.659759
hsteinhaus
445537ca757d1ff5e980bf6addabe0fe56aa9cfe
531
hpp
C++
include/RED4ext/Scripting/Natives/Generated/ink/anim/TextReplaceInterpolator.hpp
WSSDude420/RED4ext.SDK
eaca8bdf7b92c48422b18431ed8cd0876f53bdb3
[ "MIT" ]
null
null
null
include/RED4ext/Scripting/Natives/Generated/ink/anim/TextReplaceInterpolator.hpp
WSSDude420/RED4ext.SDK
eaca8bdf7b92c48422b18431ed8cd0876f53bdb3
[ "MIT" ]
null
null
null
include/RED4ext/Scripting/Natives/Generated/ink/anim/TextReplaceInterpolator.hpp
WSSDude420/RED4ext.SDK
eaca8bdf7b92c48422b18431ed8cd0876f53bdb3
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Scripting/Natives/Generated/ink/anim/TextInterpolator.hpp> namespace RED4ext { namespace ink::anim { struct TextReplaceInterpolator : ink::anim::TextInterpolator { static constexpr const char* NAME = "inkanimTextReplaceInterpolator"; static constexpr const char* ALIAS = NAME; }; RED4EXT_ASSERT_SIZE(TextReplaceInterpolator, 0x70); } // namespace ink::anim } // namespace RED4ext
25.285714
76
0.772128
WSSDude420
4456531ac161c56394b87b25ee4fb50db2206350
500
cpp
C++
C++/Win32/SingletonProcess2.cpp
mzlogin/snippets
5302142d1b6591a513b7cbcd0400f0d3caeac0d1
[ "MIT" ]
4
2016-06-22T05:58:18.000Z
2021-05-23T23:11:18.000Z
C++/Win32/SingletonProcess2.cpp
mzlogin/snippets
5302142d1b6591a513b7cbcd0400f0d3caeac0d1
[ "MIT" ]
1
2017-11-30T02:01:36.000Z
2017-11-30T02:01:36.000Z
C++/Win32/SingletonProcess2.cpp
mzlogin/snippets
5302142d1b6591a513b7cbcd0400f0d3caeac0d1
[ "MIT" ]
null
null
null
#include <Windows.h> int main(int argc, char *argv[]) { HANDLE hMutex = NULL; do { hMutex = CreateMutex(NULL, FALSE, "Global\\73E21C80-1960-472F-BF0B-3EE7CC7AF17E"); DWORD dwError = GetLastError(); if (ERROR_ALREADY_EXISTS == dwError || ERROR_ACCESS_DENIED == dwError) { break; } // do something here // ... } while (false); if (NULL != hMutex) { CloseHandle(hMutex); } return 0; }
16.666667
90
0.528
mzlogin
445733050f0f57c71a36e3c270da4a923d6d527a
470
cpp
C++
src/tests/util/trace.cpp
silky/lean
df8b88dca2f8da1a422cb618cd476ef5be730546
[ "Apache-2.0" ]
1
2019-06-27T11:33:01.000Z
2019-06-27T11:33:01.000Z
src/tests/util/trace.cpp
silky/lean
df8b88dca2f8da1a422cb618cd476ef5be730546
[ "Apache-2.0" ]
null
null
null
src/tests/util/trace.cpp
silky/lean
df8b88dca2f8da1a422cb618cd476ef5be730546
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/test.h" #include "util/trace.h" using namespace lean; int main() { lean_assert(!is_trace_enabled("name")); enable_trace("name"); lean_assert(is_trace_enabled("name")); disable_trace("name"); lean_assert(!is_trace_enabled("name")); return has_violations() ? 1 : 0; }
24.736842
67
0.708511
silky
4457cfae8f4457d78b023463a8041c603db490b8
5,671
hpp
C++
modules/gapi/include/opencv2/gapi/gcomputation.hpp
satnamsingh8912/opencv
9c23f2f1a682faa9f0b2c2223a857c7d93ba65a6
[ "BSD-3-Clause" ]
9
2018-11-30T08:06:41.000Z
2020-09-10T09:03:07.000Z
modules/gapi/include/opencv2/gapi/gcomputation.hpp
satnamsingh8912/opencv
9c23f2f1a682faa9f0b2c2223a857c7d93ba65a6
[ "BSD-3-Clause" ]
3
2020-07-08T01:07:18.000Z
2020-07-08T02:11:11.000Z
modules/gapi/include/opencv2/gapi/gcomputation.hpp
satnamsingh8912/opencv
9c23f2f1a682faa9f0b2c2223a857c7d93ba65a6
[ "BSD-3-Clause" ]
3
2018-11-30T08:17:58.000Z
2019-02-23T11:13:48.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #ifndef OPENCV_GAPI_GCOMPUTATION_HPP #define OPENCV_GAPI_GCOMPUTATION_HPP #include <functional> #include "opencv2/gapi/util/util.hpp" #include "opencv2/gapi/gcommon.hpp" #include "opencv2/gapi/gproto.hpp" #include "opencv2/gapi/garg.hpp" #include "opencv2/gapi/gcompiled.hpp" namespace cv { namespace detail { // FIXME: move to algorithm, cover with separate tests // FIXME: replace with O(1) version (both memory and compilation time) template<typename...> struct last_type; template<typename T> struct last_type<T> { using type = T;}; template<typename T, typename... Ts> struct last_type<T, Ts...> { using type = typename last_type<Ts...>::type; }; template<typename... Ts> using last_type_t = typename last_type<Ts...>::type; } class GAPI_EXPORTS GComputation { public: class Priv; typedef std::function<GComputation()> Generator; // Various constructors enable different ways to define a computation: ///// // 1. Generic constructors GComputation(const Generator& gen); // Generator overload GComputation(GProtoInputArgs &&ins, GProtoOutputArgs &&outs); // Arg-to-arg overload // 2. Syntax sugar and compatibility overloads GComputation(GMat in, GMat out); // Unary overload GComputation(GMat in, GScalar out); // Unary overload (scalar) GComputation(GMat in1, GMat in2, GMat out); // Binary overload GComputation(GMat in1, GMat in2, GScalar out); // Binary overload (scalar) GComputation(const std::vector<GMat> &ins, // Compatibility overload const std::vector<GMat> &outs); // Various versions of apply(): //////////////////////////////////////////// // 1. Generic apply() void apply(GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); // Arg-to-arg overload void apply(const std::vector<cv::gapi::own::Mat>& ins, // Compatibility overload const std::vector<cv::gapi::own::Mat>& outs, GCompileArgs &&args = {}); // 2. Syntax sugar and compatibility overloads #if !defined(GAPI_STANDALONE) void apply(cv::Mat in, cv::Mat &out, GCompileArgs &&args = {}); // Unary overload void apply(cv::Mat in, cv::Scalar &out, GCompileArgs &&args = {}); // Unary overload (scalar) void apply(cv::Mat in1, cv::Mat in2, cv::Mat &out, GCompileArgs &&args = {}); // Binary overload void apply(cv::Mat in1, cv::Mat in2, cv::Scalar &out, GCompileArgs &&args = {}); // Binary overload (scalar) void apply(const std::vector<cv::Mat>& ins, // Compatibility overload const std::vector<cv::Mat>& outs, GCompileArgs &&args = {}); #endif // !defined(GAPI_STANDALONE) // Various versions of compile(): ////////////////////////////////////////// // 1. Generic compile() - requires metas to be passed as vector GCompiled compile(GMetaArgs &&in_metas, GCompileArgs &&args = {}); // 2. Syntax sugar - variadic list of metas, no extra compile args template<typename... Ts> auto compile(const Ts&... metas) -> typename std::enable_if<detail::are_meta_descrs<Ts...>::value, GCompiled>::type { return compile(GMetaArgs{GMetaArg(metas)...}, GCompileArgs()); } // 3. Syntax sugar - variadic list of metas, extra compile args // (seems optional parameters don't work well when there's an variadic template // comes first) // // Ideally it should look like: // // template<typename... Ts> // GCompiled compile(const Ts&... metas, GCompileArgs &&args) // // But not all compilers can hande this (and seems they shouldn't be able to). template<typename... Ts> auto compile(const Ts&... meta_and_compile_args) -> typename std::enable_if<detail::are_meta_descrs_but_last<Ts...>::value && std::is_same<GCompileArgs, detail::last_type_t<Ts...> >::value, GCompiled>::type { //FIXME: wrapping meta_and_compile_args into a tuple to unwrap them inside a helper function is the overkill return compile(std::make_tuple(meta_and_compile_args...), typename detail::MkSeq<sizeof...(Ts)-1>::type()); } // Internal use only Priv& priv(); const Priv& priv() const; protected: // 4. Helper method for (3) template<typename... Ts, int... IIs> GCompiled compile(const std::tuple<Ts...> &meta_and_compile_args, detail::Seq<IIs...>) { GMetaArgs meta_args = {GMetaArg(std::get<IIs>(meta_and_compile_args))...}; GCompileArgs comp_args = std::get<sizeof...(Ts)-1>(meta_and_compile_args); return compile(std::move(meta_args), std::move(comp_args)); } std::shared_ptr<Priv> m_priv; }; namespace gapi { // Declare an Island tagged with `name` and defined from `ins` to `outs` // (exclusively, as ins/outs are data objects, and regioning is done on // operations level). // Throws if any operation between `ins` and `outs` are already assigned // to another island. void GAPI_EXPORTS island(const std::string &name, GProtoInputArgs &&ins, GProtoOutputArgs &&outs); } // namespace gapi } // namespace cv #endif // OPENCV_GAPI_GCOMPUTATION_HPP
40.507143
116
0.623347
satnamsingh8912
44594ccebfa308ad020a264d2c2dbdef58ca7d68
2,219
cpp
C++
SymbolExtractorAndRenamer/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.cpp
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
SymbolExtractorAndRenamer/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.cpp
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
SymbolExtractorAndRenamer/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionVariable.cpp
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
//===-- ClangExpressionVariable.cpp -----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ClangExpressionVariable.h" #include "lldb/Core/ConstString.h" #include "lldb/Core/DataExtractor.h" #include "lldb/Core/Stream.h" #include "lldb/Core/Value.h" #include "lldb/Core/ValueObjectConstResult.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" #include "clang/AST/ASTContext.h" using namespace lldb_private; using namespace clang; ClangExpressionVariable::ClangExpressionVariable( ExecutionContextScope *exe_scope, lldb::ByteOrder byte_order, uint32_t addr_byte_size) : ExpressionVariable(LLVMCastKind::eKindClang), m_parser_vars(), m_jit_vars() { m_flags = EVNone; m_frozen_sp = ValueObjectConstResult::Create(exe_scope, byte_order, addr_byte_size); } ClangExpressionVariable::ClangExpressionVariable( ExecutionContextScope *exe_scope, Value &value, const ConstString &name, uint16_t flags) : ExpressionVariable(LLVMCastKind::eKindClang), m_parser_vars(), m_jit_vars() { m_flags = flags; m_frozen_sp = ValueObjectConstResult::Create(exe_scope, value, name); } ClangExpressionVariable::ClangExpressionVariable( const lldb::ValueObjectSP &valobj_sp) : ExpressionVariable(LLVMCastKind::eKindClang), m_parser_vars(), m_jit_vars() { m_flags = EVNone; m_frozen_sp = valobj_sp; } ClangExpressionVariable::ClangExpressionVariable( ExecutionContextScope *exe_scope, const ConstString &name, const TypeFromUser &user_type, lldb::ByteOrder byte_order, uint32_t addr_byte_size) : ExpressionVariable(LLVMCastKind::eKindClang), m_parser_vars(), m_jit_vars() { m_flags = EVNone; m_frozen_sp = ValueObjectConstResult::Create(exe_scope, byte_order, addr_byte_size); SetName(name); SetCompilerType(user_type); } TypeFromUser ClangExpressionVariable::GetTypeFromUser() { TypeFromUser tfu(m_frozen_sp->GetCompilerType()); return tfu; }
32.632353
80
0.714736
Polidea
4459e1160f69ac012c8cbca47d18980c16f92971
948
cpp
C++
answers/leetcode/Insert Interval/Insert Interval.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
3
2015-09-04T21:32:31.000Z
2020-12-06T00:37:32.000Z
answers/leetcode/Insert Interval/Insert Interval.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
null
null
null
answers/leetcode/Insert Interval/Insert Interval.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
null
null
null
//@result 151 / 151 test cases passed. Status: Accepted Runtime: 580 ms Submitted: 1 minute ago You are here! Your runtime beats 65.83% of cpp submissions. /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval> ans; size_t i = 0; for (i = 0; i < intervals.size() && intervals[i].end < newInterval.start; ++i) { ans.push_back(intervals[i]); } for (; i < intervals.size() && intervals[i].start <= newInterval.end; ++i) { newInterval.start = std::min(newInterval.start, intervals[i].start); newInterval.end = std::max(newInterval.end, intervals[i].end); } ans.push_back(newInterval); for (; i < intervals.size(); ++i) { ans.push_back(intervals[i]); } return ans; } };
30.580645
155
0.642405
FeiZhan
445a56ad79f0bd72ae5e851c60f116459daa68ec
2,664
cpp
C++
deps/spidermonkey/xpconnect/tests/components/xpctest_const.cpp
havocp/hwf
a99e9a0461983226717b278513cfd9f1e53ba0f1
[ "MIT" ]
1
2015-04-19T10:49:48.000Z
2015-04-19T10:49:48.000Z
deps/spidermonkey/xpconnect/tests/components/xpctest_const.cpp
havocp/hwf
a99e9a0461983226717b278513cfd9f1e53ba0f1
[ "MIT" ]
null
null
null
deps/spidermonkey/xpconnect/tests/components/xpctest_const.cpp
havocp/hwf
a99e9a0461983226717b278513cfd9f1e53ba0f1
[ "MIT" ]
null
null
null
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * John Bandhauer <jband@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "nsISupports.h" #include "xpctest_const.h" #include "xpctest_private.h" class xpcTestConst : public nsIXPCTestConst { public: NS_DECL_ISUPPORTS NS_DECL_NSIXPCTESTCONST xpcTestConst(); }; NS_IMPL_ISUPPORTS1(xpcTestConst, nsIXPCTestConst) xpcTestConst :: xpcTestConst() { NS_ADDREF_THIS(); } nsresult xpctest::ConstructXPCTestConst(nsISupports *aOuter, REFNSIID aIID, void **aResult) { nsresult rv; NS_ASSERTION(aOuter == nsnull, "no aggregation"); xpcTestConst *obj = new xpcTestConst(); if(obj) { rv = obj->QueryInterface(aIID, aResult); NS_ASSERTION(NS_SUCCEEDED(rv), "unable to find correct interface"); NS_RELEASE(obj); } else { *aResult = nsnull; rv = NS_ERROR_OUT_OF_MEMORY; } return rv; }
34.597403
82
0.712462
havocp
445c1d637e995b4dc455720fc9c006232d0307db
312,429
cpp
C++
test/tailoring_rule_test_zh_big5han_012.cpp
jan-moeller/text
c61e51c82dfb0ae6e74200c01ce040fa6db730c4
[ "BSL-1.0" ]
null
null
null
test/tailoring_rule_test_zh_big5han_012.cpp
jan-moeller/text
c61e51c82dfb0ae6e74200c01ce040fa6db730c4
[ "BSL-1.0" ]
1
2021-03-05T12:56:59.000Z
2021-03-05T13:11:53.000Z
test/tailoring_rule_test_zh_big5han_012.cpp
jan-moeller/text
c61e51c82dfb0ae6e74200c01ce040fa6db730c4
[ "BSL-1.0" ]
3
2019-10-30T18:38:15.000Z
2021-03-05T12:10:13.000Z
// Warning! This file is autogenerated. #include <boost/text/collation_table.hpp> #include <boost/text/collate.hpp> #include <boost/text/data/all.hpp> #ifndef LIMIT_TESTING_FOR_CI #include <boost/text/save_load_table.hpp> #include <boost/filesystem.hpp> #endif #include <gtest/gtest.h> using namespace boost::text; auto const error = [](string const & s) { std::cout << s; }; auto const warning = [](string const & s) {}; collation_table make_save_load_table() { #ifdef LIMIT_TESTING_FOR_CI string const table_str(data::zh::big5han_collation_tailoring()); return tailored_collation_table( table_str, "zh::big5han_collation_tailoring()", error, warning); #else if (!exists(boost::filesystem::path("zh_big5han.table"))) { string const table_str(data::zh::big5han_collation_tailoring()); collation_table table = tailored_collation_table( table_str, "zh::big5han_collation_tailoring()", error, warning); save_table(table, "zh_big5han.table.12"); boost::filesystem::rename("zh_big5han.table.12", "zh_big5han.table"); } return load_table("zh_big5han.table"); #endif } collation_table const & table() { static collation_table retval = make_save_load_table(); return retval; } TEST(tailoring, zh_big5han_011_000) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9beb); auto const rel = std::vector<uint32_t>(1, 0x9be0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9be0); auto const rel = std::vector<uint32_t>(1, 0x9bde); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bde); auto const rel = std::vector<uint32_t>(1, 0x9be4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9be4); auto const rel = std::vector<uint32_t>(1, 0x9be6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9be6); auto const rel = std::vector<uint32_t>(1, 0x9be2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9be2); auto const rel = std::vector<uint32_t>(1, 0x9bf0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bf0); auto const rel = std::vector<uint32_t>(1, 0x9bd4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bd4); auto const rel = std::vector<uint32_t>(1, 0x9bd7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bd7); auto const rel = std::vector<uint32_t>(1, 0x9bec); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bec); auto const rel = std::vector<uint32_t>(1, 0x9bdc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bdc); auto const rel = std::vector<uint32_t>(1, 0x9bd9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bd9); auto const rel = std::vector<uint32_t>(1, 0x9be5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9be5); auto const rel = std::vector<uint32_t>(1, 0x9bd5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bd5); auto const rel = std::vector<uint32_t>(1, 0x9be1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9be1); auto const rel = std::vector<uint32_t>(1, 0x9bda); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bda); auto const rel = std::vector<uint32_t>(1, 0x9d77); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d77); auto const rel = std::vector<uint32_t>(1, 0x9d81); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d81); auto const rel = std::vector<uint32_t>(1, 0x9d8a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d8a); auto const rel = std::vector<uint32_t>(1, 0x9d84); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d84); auto const rel = std::vector<uint32_t>(1, 0x9d88); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d88); auto const rel = std::vector<uint32_t>(1, 0x9d71); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d71); auto const rel = std::vector<uint32_t>(1, 0x9d80); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d80); auto const rel = std::vector<uint32_t>(1, 0x9d78); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d78); auto const rel = std::vector<uint32_t>(1, 0x9d86); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d86); auto const rel = std::vector<uint32_t>(1, 0x9d8b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d8b); auto const rel = std::vector<uint32_t>(1, 0x9d8c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d8c); auto const rel = std::vector<uint32_t>(1, 0x9d7d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d7d); auto const rel = std::vector<uint32_t>(1, 0x9d6b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d6b); auto const rel = std::vector<uint32_t>(1, 0x9d74); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d74); auto const rel = std::vector<uint32_t>(1, 0x9d75); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d75); auto const rel = std::vector<uint32_t>(1, 0x9d70); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d70); auto const rel = std::vector<uint32_t>(1, 0x9d69); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d69); auto const rel = std::vector<uint32_t>(1, 0x9d85); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d85); auto const rel = std::vector<uint32_t>(1, 0x9d73); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d73); auto const rel = std::vector<uint32_t>(1, 0x9d7b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d7b); auto const rel = std::vector<uint32_t>(1, 0x9d82); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d82); auto const rel = std::vector<uint32_t>(1, 0x9d6f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d6f); auto const rel = std::vector<uint32_t>(1, 0x9d79); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d79); auto const rel = std::vector<uint32_t>(1, 0x9d7f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d7f); auto const rel = std::vector<uint32_t>(1, 0x9d87); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d87); auto const rel = std::vector<uint32_t>(1, 0x9d68); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d68); auto const rel = std::vector<uint32_t>(1, 0x9e94); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e94); auto const rel = std::vector<uint32_t>(1, 0x9e91); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e91); auto const rel = std::vector<uint32_t>(1, 0x9ec0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ec0); auto const rel = std::vector<uint32_t>(1, 0x9efc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9efc); auto const rel = std::vector<uint32_t>(1, 0x9f2d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f2d); auto const rel = std::vector<uint32_t>(1, 0x9f40); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f40); auto const rel = std::vector<uint32_t>(1, 0x9f41); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f41); auto const rel = std::vector<uint32_t>(1, 0x9f4d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f4d); auto const rel = std::vector<uint32_t>(1, 0x9f56); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f56); auto const rel = std::vector<uint32_t>(1, 0x9f57); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_001) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f57); auto const rel = std::vector<uint32_t>(1, 0x9f58); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f58); auto const rel = std::vector<uint32_t>(1, 0x5337); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5337); auto const rel = std::vector<uint32_t>(1, 0x56b2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56b2); auto const rel = std::vector<uint32_t>(1, 0x56b5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56b5); auto const rel = std::vector<uint32_t>(1, 0x56b3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56b3); auto const rel = std::vector<uint32_t>(1, 0x58e3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58e3); auto const rel = std::vector<uint32_t>(1, 0x5b45); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b45); auto const rel = std::vector<uint32_t>(1, 0x5dc6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5dc6); auto const rel = std::vector<uint32_t>(1, 0x5dc7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5dc7); auto const rel = std::vector<uint32_t>(1, 0x5eee); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5eee); auto const rel = std::vector<uint32_t>(1, 0x5eef); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5eef); auto const rel = std::vector<uint32_t>(1, 0x5fc0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5fc0); auto const rel = std::vector<uint32_t>(1, 0x5fc1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5fc1); auto const rel = std::vector<uint32_t>(1, 0x61f9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x61f9); auto const rel = std::vector<uint32_t>(1, 0x6517); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6517); auto const rel = std::vector<uint32_t>(1, 0x6516); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6516); auto const rel = std::vector<uint32_t>(1, 0x6515); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6515); auto const rel = std::vector<uint32_t>(1, 0x6513); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6513); auto const rel = std::vector<uint32_t>(1, 0x65df); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x65df); auto const rel = std::vector<uint32_t>(1, 0x66e8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66e8); auto const rel = std::vector<uint32_t>(1, 0x66e3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66e3); auto const rel = std::vector<uint32_t>(1, 0x66e4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66e4); auto const rel = std::vector<uint32_t>(1, 0x6af3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6af3); auto const rel = std::vector<uint32_t>(1, 0x6af0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6af0); auto const rel = std::vector<uint32_t>(1, 0x6aea); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6aea); auto const rel = std::vector<uint32_t>(1, 0x6ae8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6ae8); auto const rel = std::vector<uint32_t>(1, 0x6af9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6af9); auto const rel = std::vector<uint32_t>(1, 0x6af1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6af1); auto const rel = std::vector<uint32_t>(1, 0x6aee); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6aee); auto const rel = std::vector<uint32_t>(1, 0x6aef); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6aef); auto const rel = std::vector<uint32_t>(1, 0x703c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x703c); auto const rel = std::vector<uint32_t>(1, 0x7035); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7035); auto const rel = std::vector<uint32_t>(1, 0x702f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x702f); auto const rel = std::vector<uint32_t>(1, 0x7037); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7037); auto const rel = std::vector<uint32_t>(1, 0x7034); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7034); auto const rel = std::vector<uint32_t>(1, 0x7031); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7031); auto const rel = std::vector<uint32_t>(1, 0x7042); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7042); auto const rel = std::vector<uint32_t>(1, 0x7038); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7038); auto const rel = std::vector<uint32_t>(1, 0x703f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x703f); auto const rel = std::vector<uint32_t>(1, 0x703a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x703a); auto const rel = std::vector<uint32_t>(1, 0x7039); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7039); auto const rel = std::vector<uint32_t>(1, 0x7040); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7040); auto const rel = std::vector<uint32_t>(1, 0x703b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x703b); auto const rel = std::vector<uint32_t>(1, 0x7033); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7033); auto const rel = std::vector<uint32_t>(1, 0x7041); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7041); auto const rel = std::vector<uint32_t>(1, 0x7213); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7213); auto const rel = std::vector<uint32_t>(1, 0x7214); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7214); auto const rel = std::vector<uint32_t>(1, 0x72a8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x72a8); auto const rel = std::vector<uint32_t>(1, 0x737d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x737d); auto const rel = std::vector<uint32_t>(1, 0x737c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x737c); auto const rel = std::vector<uint32_t>(1, 0x74ba); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_002) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x74ba); auto const rel = std::vector<uint32_t>(1, 0x76ab); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76ab); auto const rel = std::vector<uint32_t>(1, 0x76aa); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76aa); auto const rel = std::vector<uint32_t>(1, 0x76be); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76be); auto const rel = std::vector<uint32_t>(1, 0x76ed); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76ed); auto const rel = std::vector<uint32_t>(1, 0x77cc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77cc); auto const rel = std::vector<uint32_t>(1, 0x77ce); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77ce); auto const rel = std::vector<uint32_t>(1, 0x77cf); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77cf); auto const rel = std::vector<uint32_t>(1, 0x77cd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77cd); auto const rel = std::vector<uint32_t>(1, 0x77f2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77f2); auto const rel = std::vector<uint32_t>(1, 0x7925); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7925); auto const rel = std::vector<uint32_t>(1, 0x7923); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7923); auto const rel = std::vector<uint32_t>(1, 0x7927); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7927); auto const rel = std::vector<uint32_t>(1, 0x7928); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7928); auto const rel = std::vector<uint32_t>(1, 0x7924); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7924); auto const rel = std::vector<uint32_t>(1, 0x7929); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7929); auto const rel = std::vector<uint32_t>(1, 0x79b2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x79b2); auto const rel = std::vector<uint32_t>(1, 0x7a6e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a6e); auto const rel = std::vector<uint32_t>(1, 0x7a6c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a6c); auto const rel = std::vector<uint32_t>(1, 0x7a6d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a6d); auto const rel = std::vector<uint32_t>(1, 0x7af7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7af7); auto const rel = std::vector<uint32_t>(1, 0x7c49); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c49); auto const rel = std::vector<uint32_t>(1, 0x7c48); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c48); auto const rel = std::vector<uint32_t>(1, 0x7c4a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c4a); auto const rel = std::vector<uint32_t>(1, 0x7c47); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c47); auto const rel = std::vector<uint32_t>(1, 0x7c45); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c45); auto const rel = std::vector<uint32_t>(1, 0x7cee); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7cee); auto const rel = std::vector<uint32_t>(1, 0x7e7b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e7b); auto const rel = std::vector<uint32_t>(1, 0x7e7e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e7e); auto const rel = std::vector<uint32_t>(1, 0x7e81); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e81); auto const rel = std::vector<uint32_t>(1, 0x7e80); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e80); auto const rel = std::vector<uint32_t>(1, 0x7fba); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7fba); auto const rel = std::vector<uint32_t>(1, 0x7fff); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7fff); auto const rel = std::vector<uint32_t>(1, 0x8079); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8079); auto const rel = std::vector<uint32_t>(1, 0x81db); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x81db); auto const rel = std::vector<uint32_t>(1, 0x81d9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x81d9); auto const rel = std::vector<uint32_t>(1, 0x820b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x820b); auto const rel = std::vector<uint32_t>(1, 0x8268); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8268); auto const rel = std::vector<uint32_t>(1, 0x8269); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8269); auto const rel = std::vector<uint32_t>(1, 0x8622); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8622); auto const rel = std::vector<uint32_t>(1, 0x85ff); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85ff); auto const rel = std::vector<uint32_t>(1, 0x8601); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8601); auto const rel = std::vector<uint32_t>(1, 0x85fe); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85fe); auto const rel = std::vector<uint32_t>(1, 0x861b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x861b); auto const rel = std::vector<uint32_t>(1, 0x8600); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8600); auto const rel = std::vector<uint32_t>(1, 0x85f6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85f6); auto const rel = std::vector<uint32_t>(1, 0x8604); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8604); auto const rel = std::vector<uint32_t>(1, 0x8609); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8609); auto const rel = std::vector<uint32_t>(1, 0x8605); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8605); auto const rel = std::vector<uint32_t>(1, 0x860c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x860c); auto const rel = std::vector<uint32_t>(1, 0x85fd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x85fd); auto const rel = std::vector<uint32_t>(1, 0x8819); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_003) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8819); auto const rel = std::vector<uint32_t>(1, 0x8810); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8810); auto const rel = std::vector<uint32_t>(1, 0x8811); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8811); auto const rel = std::vector<uint32_t>(1, 0x8817); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8817); auto const rel = std::vector<uint32_t>(1, 0x8813); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8813); auto const rel = std::vector<uint32_t>(1, 0x8816); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8816); auto const rel = std::vector<uint32_t>(1, 0x8963); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8963); auto const rel = std::vector<uint32_t>(1, 0x8966); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8966); auto const rel = std::vector<uint32_t>(1, 0x89b9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x89b9); auto const rel = std::vector<uint32_t>(1, 0x89f7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x89f7); auto const rel = std::vector<uint32_t>(1, 0x8b60); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b60); auto const rel = std::vector<uint32_t>(1, 0x8b6a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b6a); auto const rel = std::vector<uint32_t>(1, 0x8b5d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b5d); auto const rel = std::vector<uint32_t>(1, 0x8b68); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b68); auto const rel = std::vector<uint32_t>(1, 0x8b63); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b63); auto const rel = std::vector<uint32_t>(1, 0x8b65); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b65); auto const rel = std::vector<uint32_t>(1, 0x8b67); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b67); auto const rel = std::vector<uint32_t>(1, 0x8b6d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b6d); auto const rel = std::vector<uint32_t>(1, 0x8dae); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8dae); auto const rel = std::vector<uint32_t>(1, 0x8e86); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e86); auto const rel = std::vector<uint32_t>(1, 0x8e88); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e88); auto const rel = std::vector<uint32_t>(1, 0x8e84); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e84); auto const rel = std::vector<uint32_t>(1, 0x8f59); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f59); auto const rel = std::vector<uint32_t>(1, 0x8f56); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f56); auto const rel = std::vector<uint32_t>(1, 0x8f57); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f57); auto const rel = std::vector<uint32_t>(1, 0x8f55); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f55); auto const rel = std::vector<uint32_t>(1, 0x8f58); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f58); auto const rel = std::vector<uint32_t>(1, 0x8f5a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f5a); auto const rel = std::vector<uint32_t>(1, 0x908d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x908d); auto const rel = std::vector<uint32_t>(1, 0x9143); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9143); auto const rel = std::vector<uint32_t>(1, 0x9141); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9141); auto const rel = std::vector<uint32_t>(1, 0x91b7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91b7); auto const rel = std::vector<uint32_t>(1, 0x91b5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91b5); auto const rel = std::vector<uint32_t>(1, 0x91b2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91b2); auto const rel = std::vector<uint32_t>(1, 0x91b3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91b3); auto const rel = std::vector<uint32_t>(1, 0x940b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x940b); auto const rel = std::vector<uint32_t>(1, 0x9413); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9413); auto const rel = std::vector<uint32_t>(1, 0x93fb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93fb); auto const rel = std::vector<uint32_t>(1, 0x9420); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9420); auto const rel = std::vector<uint32_t>(1, 0x940f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x940f); auto const rel = std::vector<uint32_t>(1, 0x9414); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9414); auto const rel = std::vector<uint32_t>(1, 0x93fe); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93fe); auto const rel = std::vector<uint32_t>(1, 0x9415); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9415); auto const rel = std::vector<uint32_t>(1, 0x9410); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9410); auto const rel = std::vector<uint32_t>(1, 0x9428); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9428); auto const rel = std::vector<uint32_t>(1, 0x9419); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9419); auto const rel = std::vector<uint32_t>(1, 0x940d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x940d); auto const rel = std::vector<uint32_t>(1, 0x93f5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93f5); auto const rel = std::vector<uint32_t>(1, 0x9400); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9400); auto const rel = std::vector<uint32_t>(1, 0x93f7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93f7); auto const rel = std::vector<uint32_t>(1, 0x9407); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9407); auto const rel = std::vector<uint32_t>(1, 0x940e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_004) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x940e); auto const rel = std::vector<uint32_t>(1, 0x9416); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9416); auto const rel = std::vector<uint32_t>(1, 0x9412); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9412); auto const rel = std::vector<uint32_t>(1, 0x93fa); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93fa); auto const rel = std::vector<uint32_t>(1, 0x9409); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9409); auto const rel = std::vector<uint32_t>(1, 0x93f8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93f8); auto const rel = std::vector<uint32_t>(1, 0x940a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x940a); auto const rel = std::vector<uint32_t>(1, 0x93ff); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93ff); auto const rel = std::vector<uint32_t>(1, 0x93fc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93fc); auto const rel = std::vector<uint32_t>(1, 0x940c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x940c); auto const rel = std::vector<uint32_t>(1, 0x93f6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x93f6); auto const rel = std::vector<uint32_t>(1, 0x9411); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9411); auto const rel = std::vector<uint32_t>(1, 0x9406); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9406); auto const rel = std::vector<uint32_t>(1, 0x95de); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x95de); auto const rel = std::vector<uint32_t>(1, 0x95e0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x95e0); auto const rel = std::vector<uint32_t>(1, 0x95df); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x95df); auto const rel = std::vector<uint32_t>(1, 0x972e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x972e); auto const rel = std::vector<uint32_t>(1, 0x972f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x972f); auto const rel = std::vector<uint32_t>(1, 0x97b9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97b9); auto const rel = std::vector<uint32_t>(1, 0x97bb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97bb); auto const rel = std::vector<uint32_t>(1, 0x97fd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97fd); auto const rel = std::vector<uint32_t>(1, 0x97fe); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97fe); auto const rel = std::vector<uint32_t>(1, 0x9860); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9860); auto const rel = std::vector<uint32_t>(1, 0x9862); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9862); auto const rel = std::vector<uint32_t>(1, 0x9863); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9863); auto const rel = std::vector<uint32_t>(1, 0x985f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x985f); auto const rel = std::vector<uint32_t>(1, 0x98c1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98c1); auto const rel = std::vector<uint32_t>(1, 0x98c2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98c2); auto const rel = std::vector<uint32_t>(1, 0x9950); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9950); auto const rel = std::vector<uint32_t>(1, 0x994e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x994e); auto const rel = std::vector<uint32_t>(1, 0x9959); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9959); auto const rel = std::vector<uint32_t>(1, 0x994c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x994c); auto const rel = std::vector<uint32_t>(1, 0x994b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x994b); auto const rel = std::vector<uint32_t>(1, 0x9953); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9953); auto const rel = std::vector<uint32_t>(1, 0x9a32); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a32); auto const rel = std::vector<uint32_t>(1, 0x9a34); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a34); auto const rel = std::vector<uint32_t>(1, 0x9a31); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a31); auto const rel = std::vector<uint32_t>(1, 0x9a2c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a2c); auto const rel = std::vector<uint32_t>(1, 0x9a2a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a2a); auto const rel = std::vector<uint32_t>(1, 0x9a36); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a36); auto const rel = std::vector<uint32_t>(1, 0x9a29); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a29); auto const rel = std::vector<uint32_t>(1, 0x9a2e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a2e); auto const rel = std::vector<uint32_t>(1, 0x9a38); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a38); auto const rel = std::vector<uint32_t>(1, 0x9a2d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a2d); auto const rel = std::vector<uint32_t>(1, 0x9ac7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ac7); auto const rel = std::vector<uint32_t>(1, 0x9aca); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9aca); auto const rel = std::vector<uint32_t>(1, 0x9ac6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ac6); auto const rel = std::vector<uint32_t>(1, 0x9b10); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b10); auto const rel = std::vector<uint32_t>(1, 0x9b12); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b12); auto const rel = std::vector<uint32_t>(1, 0x9b11); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b11); auto const rel = std::vector<uint32_t>(1, 0x9c0b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c0b); auto const rel = std::vector<uint32_t>(1, 0x9c08); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_005) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c08); auto const rel = std::vector<uint32_t>(1, 0x9bf7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bf7); auto const rel = std::vector<uint32_t>(1, 0x9c05); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c05); auto const rel = std::vector<uint32_t>(1, 0x9c12); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c12); auto const rel = std::vector<uint32_t>(1, 0x9bf8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9bf8); auto const rel = std::vector<uint32_t>(1, 0x9c40); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c40); auto const rel = std::vector<uint32_t>(1, 0x9c07); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c07); auto const rel = std::vector<uint32_t>(1, 0x9c0e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c0e); auto const rel = std::vector<uint32_t>(1, 0x9c06); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c06); auto const rel = std::vector<uint32_t>(1, 0x9c17); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c17); auto const rel = std::vector<uint32_t>(1, 0x9c14); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c14); auto const rel = std::vector<uint32_t>(1, 0x9c09); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c09); auto const rel = std::vector<uint32_t>(1, 0x9d9f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d9f); auto const rel = std::vector<uint32_t>(1, 0x9d99); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d99); auto const rel = std::vector<uint32_t>(1, 0x9da4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9da4); auto const rel = std::vector<uint32_t>(1, 0x9d9d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d9d); auto const rel = std::vector<uint32_t>(1, 0x9d92); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d92); auto const rel = std::vector<uint32_t>(1, 0x9d98); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d98); auto const rel = std::vector<uint32_t>(1, 0x9d90); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d90); auto const rel = std::vector<uint32_t>(1, 0x9d9b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d9b); auto const rel = std::vector<uint32_t>(1, 0x9da0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9da0); auto const rel = std::vector<uint32_t>(1, 0x9d94); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d94); auto const rel = std::vector<uint32_t>(1, 0x9d9c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d9c); auto const rel = std::vector<uint32_t>(1, 0x9daa); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9daa); auto const rel = std::vector<uint32_t>(1, 0x9d97); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d97); auto const rel = std::vector<uint32_t>(1, 0x9da1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9da1); auto const rel = std::vector<uint32_t>(1, 0x9d9a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d9a); auto const rel = std::vector<uint32_t>(1, 0x9da2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9da2); auto const rel = std::vector<uint32_t>(1, 0x9da8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9da8); auto const rel = std::vector<uint32_t>(1, 0x9d9e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d9e); auto const rel = std::vector<uint32_t>(1, 0x9da3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9da3); auto const rel = std::vector<uint32_t>(1, 0x9dbf); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dbf); auto const rel = std::vector<uint32_t>(1, 0x9da9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9da9); auto const rel = std::vector<uint32_t>(1, 0x9d96); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9d96); auto const rel = std::vector<uint32_t>(1, 0x9da6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9da6); auto const rel = std::vector<uint32_t>(1, 0x9da7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9da7); auto const rel = std::vector<uint32_t>(1, 0x9e99); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e99); auto const rel = std::vector<uint32_t>(1, 0x9e9b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e9b); auto const rel = std::vector<uint32_t>(1, 0x9e9a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e9a); auto const rel = std::vector<uint32_t>(1, 0x9ee5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ee5); auto const rel = std::vector<uint32_t>(1, 0x9ee4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ee4); auto const rel = std::vector<uint32_t>(1, 0x9ee7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ee7); auto const rel = std::vector<uint32_t>(1, 0x9ee6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ee6); auto const rel = std::vector<uint32_t>(1, 0x9f30); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f30); auto const rel = std::vector<uint32_t>(1, 0x9f2e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f2e); auto const rel = std::vector<uint32_t>(1, 0x9f5b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f5b); auto const rel = std::vector<uint32_t>(1, 0x9f60); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f60); auto const rel = std::vector<uint32_t>(1, 0x9f5e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f5e); auto const rel = std::vector<uint32_t>(1, 0x9f5d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f5d); auto const rel = std::vector<uint32_t>(1, 0x9f59); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f59); auto const rel = std::vector<uint32_t>(1, 0x9f91); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f91); auto const rel = std::vector<uint32_t>(1, 0x513a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_006) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x513a); auto const rel = std::vector<uint32_t>(1, 0x5139); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5139); auto const rel = std::vector<uint32_t>(1, 0x5298); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5298); auto const rel = std::vector<uint32_t>(1, 0x5297); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5297); auto const rel = std::vector<uint32_t>(1, 0x56c3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56c3); auto const rel = std::vector<uint32_t>(1, 0x56bd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56bd); auto const rel = std::vector<uint32_t>(1, 0x56be); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56be); auto const rel = std::vector<uint32_t>(1, 0x5b48); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b48); auto const rel = std::vector<uint32_t>(1, 0x5b47); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b47); auto const rel = std::vector<uint32_t>(1, 0x5dcb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5dcb); auto const rel = std::vector<uint32_t>(1, 0x5dcf); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5dcf); auto const rel = std::vector<uint32_t>(1, 0x5ef1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ef1); auto const rel = std::vector<uint32_t>(1, 0x61fd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x61fd); auto const rel = std::vector<uint32_t>(1, 0x651b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x651b); auto const rel = std::vector<uint32_t>(1, 0x6b02); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b02); auto const rel = std::vector<uint32_t>(1, 0x6afc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6afc); auto const rel = std::vector<uint32_t>(1, 0x6b03); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b03); auto const rel = std::vector<uint32_t>(1, 0x6af8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6af8); auto const rel = std::vector<uint32_t>(1, 0x6b00); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b00); auto const rel = std::vector<uint32_t>(1, 0x7043); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7043); auto const rel = std::vector<uint32_t>(1, 0x7044); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7044); auto const rel = std::vector<uint32_t>(1, 0x704a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x704a); auto const rel = std::vector<uint32_t>(1, 0x7048); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7048); auto const rel = std::vector<uint32_t>(1, 0x7049); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7049); auto const rel = std::vector<uint32_t>(1, 0x7045); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7045); auto const rel = std::vector<uint32_t>(1, 0x7046); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7046); auto const rel = std::vector<uint32_t>(1, 0x721d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x721d); auto const rel = std::vector<uint32_t>(1, 0x721a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x721a); auto const rel = std::vector<uint32_t>(1, 0x7219); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7219); auto const rel = std::vector<uint32_t>(1, 0x737e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x737e); auto const rel = std::vector<uint32_t>(1, 0x7517); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7517); auto const rel = std::vector<uint32_t>(1, 0x766a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x766a); auto const rel = std::vector<uint32_t>(1, 0x77d0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77d0); auto const rel = std::vector<uint32_t>(1, 0x792d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x792d); auto const rel = std::vector<uint32_t>(1, 0x7931); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7931); auto const rel = std::vector<uint32_t>(1, 0x792f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x792f); auto const rel = std::vector<uint32_t>(1, 0x7c54); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c54); auto const rel = std::vector<uint32_t>(1, 0x7c53); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c53); auto const rel = std::vector<uint32_t>(1, 0x7cf2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7cf2); auto const rel = std::vector<uint32_t>(1, 0x7e8a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e8a); auto const rel = std::vector<uint32_t>(1, 0x7e87); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e87); auto const rel = std::vector<uint32_t>(1, 0x7e88); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e88); auto const rel = std::vector<uint32_t>(1, 0x7e8b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e8b); auto const rel = std::vector<uint32_t>(1, 0x7e86); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e86); auto const rel = std::vector<uint32_t>(1, 0x7e8d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e8d); auto const rel = std::vector<uint32_t>(1, 0x7f4d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7f4d); auto const rel = std::vector<uint32_t>(1, 0x7fbb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7fbb); auto const rel = std::vector<uint32_t>(1, 0x8030); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8030); auto const rel = std::vector<uint32_t>(1, 0x81dd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x81dd); auto const rel = std::vector<uint32_t>(1, 0x8618); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8618); auto const rel = std::vector<uint32_t>(1, 0x862a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x862a); auto const rel = std::vector<uint32_t>(1, 0x8626); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_007) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8626); auto const rel = std::vector<uint32_t>(1, 0x861f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x861f); auto const rel = std::vector<uint32_t>(1, 0x8623); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8623); auto const rel = std::vector<uint32_t>(1, 0x861c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x861c); auto const rel = std::vector<uint32_t>(1, 0x8619); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8619); auto const rel = std::vector<uint32_t>(1, 0x8627); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8627); auto const rel = std::vector<uint32_t>(1, 0x862e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x862e); auto const rel = std::vector<uint32_t>(1, 0x8621); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8621); auto const rel = std::vector<uint32_t>(1, 0x8620); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8620); auto const rel = std::vector<uint32_t>(1, 0x8629); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8629); auto const rel = std::vector<uint32_t>(1, 0x861e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x861e); auto const rel = std::vector<uint32_t>(1, 0x8625); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8625); auto const rel = std::vector<uint32_t>(1, 0x8829); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8829); auto const rel = std::vector<uint32_t>(1, 0x881d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x881d); auto const rel = std::vector<uint32_t>(1, 0x881b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x881b); auto const rel = std::vector<uint32_t>(1, 0x8820); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8820); auto const rel = std::vector<uint32_t>(1, 0x8824); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8824); auto const rel = std::vector<uint32_t>(1, 0x881c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x881c); auto const rel = std::vector<uint32_t>(1, 0x882b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x882b); auto const rel = std::vector<uint32_t>(1, 0x884a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x884a); auto const rel = std::vector<uint32_t>(1, 0x896d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x896d); auto const rel = std::vector<uint32_t>(1, 0x8969); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8969); auto const rel = std::vector<uint32_t>(1, 0x896e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x896e); auto const rel = std::vector<uint32_t>(1, 0x896b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x896b); auto const rel = std::vector<uint32_t>(1, 0x89fa); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x89fa); auto const rel = std::vector<uint32_t>(1, 0x8b79); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b79); auto const rel = std::vector<uint32_t>(1, 0x8b78); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b78); auto const rel = std::vector<uint32_t>(1, 0x8b45); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b45); auto const rel = std::vector<uint32_t>(1, 0x8b7a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b7a); auto const rel = std::vector<uint32_t>(1, 0x8b7b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b7b); auto const rel = std::vector<uint32_t>(1, 0x8d10); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8d10); auto const rel = std::vector<uint32_t>(1, 0x8d14); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8d14); auto const rel = std::vector<uint32_t>(1, 0x8daf); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8daf); auto const rel = std::vector<uint32_t>(1, 0x8e8e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e8e); auto const rel = std::vector<uint32_t>(1, 0x8e8c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e8c); auto const rel = std::vector<uint32_t>(1, 0x8f5e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f5e); auto const rel = std::vector<uint32_t>(1, 0x8f5b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f5b); auto const rel = std::vector<uint32_t>(1, 0x8f5d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f5d); auto const rel = std::vector<uint32_t>(1, 0x9146); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9146); auto const rel = std::vector<uint32_t>(1, 0x9144); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9144); auto const rel = std::vector<uint32_t>(1, 0x9145); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9145); auto const rel = std::vector<uint32_t>(1, 0x91b9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91b9); auto const rel = std::vector<uint32_t>(1, 0x943f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x943f); auto const rel = std::vector<uint32_t>(1, 0x943b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x943b); auto const rel = std::vector<uint32_t>(1, 0x9436); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9436); auto const rel = std::vector<uint32_t>(1, 0x9429); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9429); auto const rel = std::vector<uint32_t>(1, 0x943d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x943d); auto const rel = std::vector<uint32_t>(1, 0x943c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x943c); auto const rel = std::vector<uint32_t>(1, 0x9430); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9430); auto const rel = std::vector<uint32_t>(1, 0x9439); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9439); auto const rel = std::vector<uint32_t>(1, 0x942a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x942a); auto const rel = std::vector<uint32_t>(1, 0x9437); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_008) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9437); auto const rel = std::vector<uint32_t>(1, 0x942c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x942c); auto const rel = std::vector<uint32_t>(1, 0x9440); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9440); auto const rel = std::vector<uint32_t>(1, 0x9431); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9431); auto const rel = std::vector<uint32_t>(1, 0x95e5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x95e5); auto const rel = std::vector<uint32_t>(1, 0x95e4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x95e4); auto const rel = std::vector<uint32_t>(1, 0x95e3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x95e3); auto const rel = std::vector<uint32_t>(1, 0x9735); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9735); auto const rel = std::vector<uint32_t>(1, 0x973a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x973a); auto const rel = std::vector<uint32_t>(1, 0x97bf); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97bf); auto const rel = std::vector<uint32_t>(1, 0x97e1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97e1); auto const rel = std::vector<uint32_t>(1, 0x9864); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9864); auto const rel = std::vector<uint32_t>(1, 0x98c9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98c9); auto const rel = std::vector<uint32_t>(1, 0x98c6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98c6); auto const rel = std::vector<uint32_t>(1, 0x98c0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98c0); auto const rel = std::vector<uint32_t>(1, 0x9958); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9958); auto const rel = std::vector<uint32_t>(1, 0x9956); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9956); auto const rel = std::vector<uint32_t>(1, 0x9a39); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a39); auto const rel = std::vector<uint32_t>(1, 0x9a3d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a3d); auto const rel = std::vector<uint32_t>(1, 0x9a46); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a46); auto const rel = std::vector<uint32_t>(1, 0x9a44); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a44); auto const rel = std::vector<uint32_t>(1, 0x9a42); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a42); auto const rel = std::vector<uint32_t>(1, 0x9a41); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a41); auto const rel = std::vector<uint32_t>(1, 0x9a3a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a3a); auto const rel = std::vector<uint32_t>(1, 0x9a3f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a3f); auto const rel = std::vector<uint32_t>(1, 0x9acd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9acd); auto const rel = std::vector<uint32_t>(1, 0x9b15); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b15); auto const rel = std::vector<uint32_t>(1, 0x9b17); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b17); auto const rel = std::vector<uint32_t>(1, 0x9b18); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b18); auto const rel = std::vector<uint32_t>(1, 0x9b16); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b16); auto const rel = std::vector<uint32_t>(1, 0x9b3a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b3a); auto const rel = std::vector<uint32_t>(1, 0x9b52); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b52); auto const rel = std::vector<uint32_t>(1, 0x9c2b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c2b); auto const rel = std::vector<uint32_t>(1, 0x9c1d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c1d); auto const rel = std::vector<uint32_t>(1, 0x9c1c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c1c); auto const rel = std::vector<uint32_t>(1, 0x9c2c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c2c); auto const rel = std::vector<uint32_t>(1, 0x9c23); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c23); auto const rel = std::vector<uint32_t>(1, 0x9c28); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c28); auto const rel = std::vector<uint32_t>(1, 0x9c29); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c29); auto const rel = std::vector<uint32_t>(1, 0x9c24); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c24); auto const rel = std::vector<uint32_t>(1, 0x9c21); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c21); auto const rel = std::vector<uint32_t>(1, 0x9db7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9db7); auto const rel = std::vector<uint32_t>(1, 0x9db6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9db6); auto const rel = std::vector<uint32_t>(1, 0x9dbc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dbc); auto const rel = std::vector<uint32_t>(1, 0x9dc1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dc1); auto const rel = std::vector<uint32_t>(1, 0x9dc7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dc7); auto const rel = std::vector<uint32_t>(1, 0x9dca); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dca); auto const rel = std::vector<uint32_t>(1, 0x9dcf); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dcf); auto const rel = std::vector<uint32_t>(1, 0x9dbe); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dbe); auto const rel = std::vector<uint32_t>(1, 0x9dc5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dc5); auto const rel = std::vector<uint32_t>(1, 0x9dc3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dc3); auto const rel = std::vector<uint32_t>(1, 0x9dbb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_009) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dbb); auto const rel = std::vector<uint32_t>(1, 0x9db5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9db5); auto const rel = std::vector<uint32_t>(1, 0x9dce); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dce); auto const rel = std::vector<uint32_t>(1, 0x9db9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9db9); auto const rel = std::vector<uint32_t>(1, 0x9dba); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dba); auto const rel = std::vector<uint32_t>(1, 0x9dac); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dac); auto const rel = std::vector<uint32_t>(1, 0x9dc8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dc8); auto const rel = std::vector<uint32_t>(1, 0x9db1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9db1); auto const rel = std::vector<uint32_t>(1, 0x9dad); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dad); auto const rel = std::vector<uint32_t>(1, 0x9dcc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dcc); auto const rel = std::vector<uint32_t>(1, 0x9db3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9db3); auto const rel = std::vector<uint32_t>(1, 0x9dcd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dcd); auto const rel = std::vector<uint32_t>(1, 0x9db2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9db2); auto const rel = std::vector<uint32_t>(1, 0x9e7a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e7a); auto const rel = std::vector<uint32_t>(1, 0x9e9c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e9c); auto const rel = std::vector<uint32_t>(1, 0x9eeb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9eeb); auto const rel = std::vector<uint32_t>(1, 0x9eee); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9eee); auto const rel = std::vector<uint32_t>(1, 0x9eed); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9eed); auto const rel = std::vector<uint32_t>(1, 0x9f1b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f1b); auto const rel = std::vector<uint32_t>(1, 0x9f18); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f18); auto const rel = std::vector<uint32_t>(1, 0x9f1a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f1a); auto const rel = std::vector<uint32_t>(1, 0x9f31); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f31); auto const rel = std::vector<uint32_t>(1, 0x9f4e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f4e); auto const rel = std::vector<uint32_t>(1, 0x9f65); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f65); auto const rel = std::vector<uint32_t>(1, 0x9f64); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f64); auto const rel = std::vector<uint32_t>(1, 0x9f92); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f92); auto const rel = std::vector<uint32_t>(1, 0x4eb9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x4eb9); auto const rel = std::vector<uint32_t>(1, 0x56c6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56c6); auto const rel = std::vector<uint32_t>(1, 0x56c5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56c5); auto const rel = std::vector<uint32_t>(1, 0x56cb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56cb); auto const rel = std::vector<uint32_t>(1, 0x5971); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5971); auto const rel = std::vector<uint32_t>(1, 0x5b4b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b4b); auto const rel = std::vector<uint32_t>(1, 0x5b4c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b4c); auto const rel = std::vector<uint32_t>(1, 0x5dd5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5dd5); auto const rel = std::vector<uint32_t>(1, 0x5dd1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5dd1); auto const rel = std::vector<uint32_t>(1, 0x5ef2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5ef2); auto const rel = std::vector<uint32_t>(1, 0x6521); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6521); auto const rel = std::vector<uint32_t>(1, 0x6520); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6520); auto const rel = std::vector<uint32_t>(1, 0x6526); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6526); auto const rel = std::vector<uint32_t>(1, 0x6522); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6522); auto const rel = std::vector<uint32_t>(1, 0x6b0b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b0b); auto const rel = std::vector<uint32_t>(1, 0x6b08); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b08); auto const rel = std::vector<uint32_t>(1, 0x6b09); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b09); auto const rel = std::vector<uint32_t>(1, 0x6c0d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6c0d); auto const rel = std::vector<uint32_t>(1, 0x7055); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7055); auto const rel = std::vector<uint32_t>(1, 0x7056); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7056); auto const rel = std::vector<uint32_t>(1, 0x7057); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7057); auto const rel = std::vector<uint32_t>(1, 0x7052); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7052); auto const rel = std::vector<uint32_t>(1, 0x721e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x721e); auto const rel = std::vector<uint32_t>(1, 0x721f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x721f); auto const rel = std::vector<uint32_t>(1, 0x72a9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x72a9); auto const rel = std::vector<uint32_t>(1, 0x737f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_010) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x737f); auto const rel = std::vector<uint32_t>(1, 0x74d8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x74d8); auto const rel = std::vector<uint32_t>(1, 0x74d5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x74d5); auto const rel = std::vector<uint32_t>(1, 0x74d9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x74d9); auto const rel = std::vector<uint32_t>(1, 0x74d7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x74d7); auto const rel = std::vector<uint32_t>(1, 0x766d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x766d); auto const rel = std::vector<uint32_t>(1, 0x76ad); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x76ad); auto const rel = std::vector<uint32_t>(1, 0x7935); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7935); auto const rel = std::vector<uint32_t>(1, 0x79b4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x79b4); auto const rel = std::vector<uint32_t>(1, 0x7a70); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a70); auto const rel = std::vector<uint32_t>(1, 0x7a71); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7a71); auto const rel = std::vector<uint32_t>(1, 0x7c57); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c57); auto const rel = std::vector<uint32_t>(1, 0x7c5c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c5c); auto const rel = std::vector<uint32_t>(1, 0x7c59); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c59); auto const rel = std::vector<uint32_t>(1, 0x7c5b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c5b); auto const rel = std::vector<uint32_t>(1, 0x7c5a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c5a); auto const rel = std::vector<uint32_t>(1, 0x7cf4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7cf4); auto const rel = std::vector<uint32_t>(1, 0x7cf1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7cf1); auto const rel = std::vector<uint32_t>(1, 0x7e91); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e91); auto const rel = std::vector<uint32_t>(1, 0x7f4f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7f4f); auto const rel = std::vector<uint32_t>(1, 0x7f87); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7f87); auto const rel = std::vector<uint32_t>(1, 0x81de); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x81de); auto const rel = std::vector<uint32_t>(1, 0x826b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x826b); auto const rel = std::vector<uint32_t>(1, 0x8634); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8634); auto const rel = std::vector<uint32_t>(1, 0x8635); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8635); auto const rel = std::vector<uint32_t>(1, 0x8633); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8633); auto const rel = std::vector<uint32_t>(1, 0x862c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x862c); auto const rel = std::vector<uint32_t>(1, 0x8632); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8632); auto const rel = std::vector<uint32_t>(1, 0x8636); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8636); auto const rel = std::vector<uint32_t>(1, 0x882c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x882c); auto const rel = std::vector<uint32_t>(1, 0x8828); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8828); auto const rel = std::vector<uint32_t>(1, 0x8826); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8826); auto const rel = std::vector<uint32_t>(1, 0x882a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x882a); auto const rel = std::vector<uint32_t>(1, 0x8825); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8825); auto const rel = std::vector<uint32_t>(1, 0x8971); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8971); auto const rel = std::vector<uint32_t>(1, 0x89bf); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x89bf); auto const rel = std::vector<uint32_t>(1, 0x89be); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x89be); auto const rel = std::vector<uint32_t>(1, 0x89fb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x89fb); auto const rel = std::vector<uint32_t>(1, 0x8b7e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b7e); auto const rel = std::vector<uint32_t>(1, 0x8b84); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b84); auto const rel = std::vector<uint32_t>(1, 0x8b82); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b82); auto const rel = std::vector<uint32_t>(1, 0x8b86); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b86); auto const rel = std::vector<uint32_t>(1, 0x8b85); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b85); auto const rel = std::vector<uint32_t>(1, 0x8b7f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b7f); auto const rel = std::vector<uint32_t>(1, 0x8d15); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8d15); auto const rel = std::vector<uint32_t>(1, 0x8e95); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e95); auto const rel = std::vector<uint32_t>(1, 0x8e94); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e94); auto const rel = std::vector<uint32_t>(1, 0x8e9a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e9a); auto const rel = std::vector<uint32_t>(1, 0x8e92); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e92); auto const rel = std::vector<uint32_t>(1, 0x8e90); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e90); auto const rel = std::vector<uint32_t>(1, 0x8e96); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e96); auto const rel = std::vector<uint32_t>(1, 0x8e97); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_011) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e97); auto const rel = std::vector<uint32_t>(1, 0x8f60); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f60); auto const rel = std::vector<uint32_t>(1, 0x8f62); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f62); auto const rel = std::vector<uint32_t>(1, 0x9147); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9147); auto const rel = std::vector<uint32_t>(1, 0x944c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x944c); auto const rel = std::vector<uint32_t>(1, 0x9450); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9450); auto const rel = std::vector<uint32_t>(1, 0x944a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x944a); auto const rel = std::vector<uint32_t>(1, 0x944b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x944b); auto const rel = std::vector<uint32_t>(1, 0x944f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x944f); auto const rel = std::vector<uint32_t>(1, 0x9447); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9447); auto const rel = std::vector<uint32_t>(1, 0x9445); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9445); auto const rel = std::vector<uint32_t>(1, 0x9448); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9448); auto const rel = std::vector<uint32_t>(1, 0x9449); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9449); auto const rel = std::vector<uint32_t>(1, 0x9446); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9446); auto const rel = std::vector<uint32_t>(1, 0x973f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x973f); auto const rel = std::vector<uint32_t>(1, 0x97e3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97e3); auto const rel = std::vector<uint32_t>(1, 0x986a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x986a); auto const rel = std::vector<uint32_t>(1, 0x9869); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9869); auto const rel = std::vector<uint32_t>(1, 0x98cb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98cb); auto const rel = std::vector<uint32_t>(1, 0x9954); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9954); auto const rel = std::vector<uint32_t>(1, 0x995b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x995b); auto const rel = std::vector<uint32_t>(1, 0x9a4e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a4e); auto const rel = std::vector<uint32_t>(1, 0x9a53); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a53); auto const rel = std::vector<uint32_t>(1, 0x9a54); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a54); auto const rel = std::vector<uint32_t>(1, 0x9a4c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a4c); auto const rel = std::vector<uint32_t>(1, 0x9a4f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a4f); auto const rel = std::vector<uint32_t>(1, 0x9a48); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a48); auto const rel = std::vector<uint32_t>(1, 0x9a4a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a4a); auto const rel = std::vector<uint32_t>(1, 0x9a49); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a49); auto const rel = std::vector<uint32_t>(1, 0x9a52); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a52); auto const rel = std::vector<uint32_t>(1, 0x9a50); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a50); auto const rel = std::vector<uint32_t>(1, 0x9ad0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ad0); auto const rel = std::vector<uint32_t>(1, 0x9b19); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b19); auto const rel = std::vector<uint32_t>(1, 0x9b2b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b2b); auto const rel = std::vector<uint32_t>(1, 0x9b3b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b3b); auto const rel = std::vector<uint32_t>(1, 0x9b56); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b56); auto const rel = std::vector<uint32_t>(1, 0x9b55); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b55); auto const rel = std::vector<uint32_t>(1, 0x9c46); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c46); auto const rel = std::vector<uint32_t>(1, 0x9c48); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c48); auto const rel = std::vector<uint32_t>(1, 0x9c3f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c3f); auto const rel = std::vector<uint32_t>(1, 0x9c44); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c44); auto const rel = std::vector<uint32_t>(1, 0x9c39); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c39); auto const rel = std::vector<uint32_t>(1, 0x9c33); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c33); auto const rel = std::vector<uint32_t>(1, 0x9c41); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c41); auto const rel = std::vector<uint32_t>(1, 0x9c3c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c3c); auto const rel = std::vector<uint32_t>(1, 0x9c37); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c37); auto const rel = std::vector<uint32_t>(1, 0x9c34); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c34); auto const rel = std::vector<uint32_t>(1, 0x9c32); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c32); auto const rel = std::vector<uint32_t>(1, 0x9c3d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c3d); auto const rel = std::vector<uint32_t>(1, 0x9c36); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c36); auto const rel = std::vector<uint32_t>(1, 0x9ddb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ddb); auto const rel = std::vector<uint32_t>(1, 0x9dd2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_012) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd2); auto const rel = std::vector<uint32_t>(1, 0x9dde); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dde); auto const rel = std::vector<uint32_t>(1, 0x9dda); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dda); auto const rel = std::vector<uint32_t>(1, 0x9dcb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dcb); auto const rel = std::vector<uint32_t>(1, 0x9dd0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd0); auto const rel = std::vector<uint32_t>(1, 0x9ddc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ddc); auto const rel = std::vector<uint32_t>(1, 0x9dd1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd1); auto const rel = std::vector<uint32_t>(1, 0x9ddf); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ddf); auto const rel = std::vector<uint32_t>(1, 0x9de9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9de9); auto const rel = std::vector<uint32_t>(1, 0x9dd9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd9); auto const rel = std::vector<uint32_t>(1, 0x9dd8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd8); auto const rel = std::vector<uint32_t>(1, 0x9dd6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd6); auto const rel = std::vector<uint32_t>(1, 0x9df5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9df5); auto const rel = std::vector<uint32_t>(1, 0x9dd5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dd5); auto const rel = std::vector<uint32_t>(1, 0x9ddd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ddd); auto const rel = std::vector<uint32_t>(1, 0x9eb6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9eb6); auto const rel = std::vector<uint32_t>(1, 0x9ef0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ef0); auto const rel = std::vector<uint32_t>(1, 0x9f35); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f35); auto const rel = std::vector<uint32_t>(1, 0x9f33); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f33); auto const rel = std::vector<uint32_t>(1, 0x9f32); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f32); auto const rel = std::vector<uint32_t>(1, 0x9f42); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f42); auto const rel = std::vector<uint32_t>(1, 0x9f6b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f6b); auto const rel = std::vector<uint32_t>(1, 0x9f95); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f95); auto const rel = std::vector<uint32_t>(1, 0x9fa2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9fa2); auto const rel = std::vector<uint32_t>(1, 0x513d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x513d); auto const rel = std::vector<uint32_t>(1, 0x5299); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5299); auto const rel = std::vector<uint32_t>(1, 0x58e8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58e8); auto const rel = std::vector<uint32_t>(1, 0x58e7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x58e7); auto const rel = std::vector<uint32_t>(1, 0x5972); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5972); auto const rel = std::vector<uint32_t>(1, 0x5b4d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b4d); auto const rel = std::vector<uint32_t>(1, 0x5dd8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5dd8); auto const rel = std::vector<uint32_t>(1, 0x882f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x882f); auto const rel = std::vector<uint32_t>(1, 0x5f4f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5f4f); auto const rel = std::vector<uint32_t>(1, 0x6201); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6201); auto const rel = std::vector<uint32_t>(1, 0x6203); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6203); auto const rel = std::vector<uint32_t>(1, 0x6204); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6204); auto const rel = std::vector<uint32_t>(1, 0x6529); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6529); auto const rel = std::vector<uint32_t>(1, 0x6525); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6525); auto const rel = std::vector<uint32_t>(1, 0x6596); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6596); auto const rel = std::vector<uint32_t>(1, 0x66eb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66eb); auto const rel = std::vector<uint32_t>(1, 0x6b11); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b11); auto const rel = std::vector<uint32_t>(1, 0x6b12); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b12); auto const rel = std::vector<uint32_t>(1, 0x6b0f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b0f); auto const rel = std::vector<uint32_t>(1, 0x6bca); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6bca); auto const rel = std::vector<uint32_t>(1, 0x705b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x705b); auto const rel = std::vector<uint32_t>(1, 0x705a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x705a); auto const rel = std::vector<uint32_t>(1, 0x7222); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7222); auto const rel = std::vector<uint32_t>(1, 0x7382); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7382); auto const rel = std::vector<uint32_t>(1, 0x7381); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7381); auto const rel = std::vector<uint32_t>(1, 0x7383); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7383); auto const rel = std::vector<uint32_t>(1, 0x7670); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7670); auto const rel = std::vector<uint32_t>(1, 0x77d4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_013) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77d4); auto const rel = std::vector<uint32_t>(1, 0x7c67); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c67); auto const rel = std::vector<uint32_t>(1, 0x7c66); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c66); auto const rel = std::vector<uint32_t>(1, 0x7e95); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e95); auto const rel = std::vector<uint32_t>(1, 0x826c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x826c); auto const rel = std::vector<uint32_t>(1, 0x863a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x863a); auto const rel = std::vector<uint32_t>(1, 0x8640); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8640); auto const rel = std::vector<uint32_t>(1, 0x8639); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8639); auto const rel = std::vector<uint32_t>(1, 0x863c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x863c); auto const rel = std::vector<uint32_t>(1, 0x8631); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8631); auto const rel = std::vector<uint32_t>(1, 0x863b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x863b); auto const rel = std::vector<uint32_t>(1, 0x863e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x863e); auto const rel = std::vector<uint32_t>(1, 0x8830); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8830); auto const rel = std::vector<uint32_t>(1, 0x8832); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8832); auto const rel = std::vector<uint32_t>(1, 0x882e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x882e); auto const rel = std::vector<uint32_t>(1, 0x8833); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8833); auto const rel = std::vector<uint32_t>(1, 0x8976); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8976); auto const rel = std::vector<uint32_t>(1, 0x8974); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8974); auto const rel = std::vector<uint32_t>(1, 0x8973); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8973); auto const rel = std::vector<uint32_t>(1, 0x89fe); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x89fe); auto const rel = std::vector<uint32_t>(1, 0x8b8c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b8c); auto const rel = std::vector<uint32_t>(1, 0x8b8e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b8e); auto const rel = std::vector<uint32_t>(1, 0x8b8b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b8b); auto const rel = std::vector<uint32_t>(1, 0x8b88); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b88); auto const rel = std::vector<uint32_t>(1, 0x8c45); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c45); auto const rel = std::vector<uint32_t>(1, 0x8d19); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8d19); auto const rel = std::vector<uint32_t>(1, 0x8e98); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e98); auto const rel = std::vector<uint32_t>(1, 0x8f64); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f64); auto const rel = std::vector<uint32_t>(1, 0x8f63); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8f63); auto const rel = std::vector<uint32_t>(1, 0x91bc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91bc); auto const rel = std::vector<uint32_t>(1, 0x9462); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9462); auto const rel = std::vector<uint32_t>(1, 0x9455); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9455); auto const rel = std::vector<uint32_t>(1, 0x945d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x945d); auto const rel = std::vector<uint32_t>(1, 0x9457); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9457); auto const rel = std::vector<uint32_t>(1, 0x945e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x945e); auto const rel = std::vector<uint32_t>(1, 0x97c4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97c4); auto const rel = std::vector<uint32_t>(1, 0x97c5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97c5); auto const rel = std::vector<uint32_t>(1, 0x9800); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9800); auto const rel = std::vector<uint32_t>(1, 0x9a56); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a56); auto const rel = std::vector<uint32_t>(1, 0x9a59); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a59); auto const rel = std::vector<uint32_t>(1, 0x9b1e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b1e); auto const rel = std::vector<uint32_t>(1, 0x9b1f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b1f); auto const rel = std::vector<uint32_t>(1, 0x9b20); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b20); auto const rel = std::vector<uint32_t>(1, 0x9c52); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c52); auto const rel = std::vector<uint32_t>(1, 0x9c58); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c58); auto const rel = std::vector<uint32_t>(1, 0x9c50); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c50); auto const rel = std::vector<uint32_t>(1, 0x9c4a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c4a); auto const rel = std::vector<uint32_t>(1, 0x9c4d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c4d); auto const rel = std::vector<uint32_t>(1, 0x9c4b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c4b); auto const rel = std::vector<uint32_t>(1, 0x9c55); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c55); auto const rel = std::vector<uint32_t>(1, 0x9c59); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c59); auto const rel = std::vector<uint32_t>(1, 0x9c4c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_014) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c4c); auto const rel = std::vector<uint32_t>(1, 0x9c4e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c4e); auto const rel = std::vector<uint32_t>(1, 0x9dfb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dfb); auto const rel = std::vector<uint32_t>(1, 0x9df7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9df7); auto const rel = std::vector<uint32_t>(1, 0x9def); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9def); auto const rel = std::vector<uint32_t>(1, 0x9de3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9de3); auto const rel = std::vector<uint32_t>(1, 0x9deb); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9deb); auto const rel = std::vector<uint32_t>(1, 0x9df8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9df8); auto const rel = std::vector<uint32_t>(1, 0x9de4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9de4); auto const rel = std::vector<uint32_t>(1, 0x9df6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9df6); auto const rel = std::vector<uint32_t>(1, 0x9de1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9de1); auto const rel = std::vector<uint32_t>(1, 0x9dee); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dee); auto const rel = std::vector<uint32_t>(1, 0x9de6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9de6); auto const rel = std::vector<uint32_t>(1, 0x9df2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9df2); auto const rel = std::vector<uint32_t>(1, 0x9df0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9df0); auto const rel = std::vector<uint32_t>(1, 0x9de2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9de2); auto const rel = std::vector<uint32_t>(1, 0x9dec); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dec); auto const rel = std::vector<uint32_t>(1, 0x9df4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9df4); auto const rel = std::vector<uint32_t>(1, 0x9df3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9df3); auto const rel = std::vector<uint32_t>(1, 0x9de8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9de8); auto const rel = std::vector<uint32_t>(1, 0x9ded); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ded); auto const rel = std::vector<uint32_t>(1, 0x9ec2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ec2); auto const rel = std::vector<uint32_t>(1, 0x9ed0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ed0); auto const rel = std::vector<uint32_t>(1, 0x9ef2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ef2); auto const rel = std::vector<uint32_t>(1, 0x9ef3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ef3); auto const rel = std::vector<uint32_t>(1, 0x9f06); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f06); auto const rel = std::vector<uint32_t>(1, 0x9f1c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f1c); auto const rel = std::vector<uint32_t>(1, 0x9f38); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f38); auto const rel = std::vector<uint32_t>(1, 0x9f37); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f37); auto const rel = std::vector<uint32_t>(1, 0x9f36); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f36); auto const rel = std::vector<uint32_t>(1, 0x9f43); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f43); auto const rel = std::vector<uint32_t>(1, 0x9f4f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f4f); auto const rel = std::vector<uint32_t>(1, 0x9f71); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f71); auto const rel = std::vector<uint32_t>(1, 0x9f70); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f70); auto const rel = std::vector<uint32_t>(1, 0x9f6e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f6e); auto const rel = std::vector<uint32_t>(1, 0x9f6f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f6f); auto const rel = std::vector<uint32_t>(1, 0x56d3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56d3); auto const rel = std::vector<uint32_t>(1, 0x56cd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56cd); auto const rel = std::vector<uint32_t>(1, 0x5b4e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5b4e); auto const rel = std::vector<uint32_t>(1, 0x5c6d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x5c6d); auto const rel = std::vector<uint32_t>(1, 0x652d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x652d); auto const rel = std::vector<uint32_t>(1, 0x66ed); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66ed); auto const rel = std::vector<uint32_t>(1, 0x66ee); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x66ee); auto const rel = std::vector<uint32_t>(1, 0x6b13); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b13); auto const rel = std::vector<uint32_t>(1, 0x705f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x705f); auto const rel = std::vector<uint32_t>(1, 0x7061); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7061); auto const rel = std::vector<uint32_t>(1, 0x705d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x705d); auto const rel = std::vector<uint32_t>(1, 0x7060); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7060); auto const rel = std::vector<uint32_t>(1, 0x7223); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7223); auto const rel = std::vector<uint32_t>(1, 0x74db); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x74db); auto const rel = std::vector<uint32_t>(1, 0x74e5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x74e5); auto const rel = std::vector<uint32_t>(1, 0x77d5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_015) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77d5); auto const rel = std::vector<uint32_t>(1, 0x7938); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7938); auto const rel = std::vector<uint32_t>(1, 0x79b7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x79b7); auto const rel = std::vector<uint32_t>(1, 0x79b6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x79b6); auto const rel = std::vector<uint32_t>(1, 0x7c6a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c6a); auto const rel = std::vector<uint32_t>(1, 0x7e97); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e97); auto const rel = std::vector<uint32_t>(1, 0x7f89); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7f89); auto const rel = std::vector<uint32_t>(1, 0x826d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x826d); auto const rel = std::vector<uint32_t>(1, 0x8643); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8643); auto const rel = std::vector<uint32_t>(1, 0x8838); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8838); auto const rel = std::vector<uint32_t>(1, 0x8837); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8837); auto const rel = std::vector<uint32_t>(1, 0x8835); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8835); auto const rel = std::vector<uint32_t>(1, 0x884b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x884b); auto const rel = std::vector<uint32_t>(1, 0x8b94); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b94); auto const rel = std::vector<uint32_t>(1, 0x8b95); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b95); auto const rel = std::vector<uint32_t>(1, 0x8e9e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e9e); auto const rel = std::vector<uint32_t>(1, 0x8e9f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e9f); auto const rel = std::vector<uint32_t>(1, 0x8ea0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ea0); auto const rel = std::vector<uint32_t>(1, 0x8e9d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8e9d); auto const rel = std::vector<uint32_t>(1, 0x91be); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91be); auto const rel = std::vector<uint32_t>(1, 0x91bd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91bd); auto const rel = std::vector<uint32_t>(1, 0x91c2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91c2); auto const rel = std::vector<uint32_t>(1, 0x946b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x946b); auto const rel = std::vector<uint32_t>(1, 0x9468); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9468); auto const rel = std::vector<uint32_t>(1, 0x9469); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9469); auto const rel = std::vector<uint32_t>(1, 0x96e5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x96e5); auto const rel = std::vector<uint32_t>(1, 0x9746); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9746); auto const rel = std::vector<uint32_t>(1, 0x9743); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9743); auto const rel = std::vector<uint32_t>(1, 0x9747); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9747); auto const rel = std::vector<uint32_t>(1, 0x97c7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97c7); auto const rel = std::vector<uint32_t>(1, 0x97e5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x97e5); auto const rel = std::vector<uint32_t>(1, 0x9a5e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a5e); auto const rel = std::vector<uint32_t>(1, 0x9ad5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ad5); auto const rel = std::vector<uint32_t>(1, 0x9b59); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b59); auto const rel = std::vector<uint32_t>(1, 0x9c63); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c63); auto const rel = std::vector<uint32_t>(1, 0x9c67); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c67); auto const rel = std::vector<uint32_t>(1, 0x9c66); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c66); auto const rel = std::vector<uint32_t>(1, 0x9c62); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c62); auto const rel = std::vector<uint32_t>(1, 0x9c5e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c5e); auto const rel = std::vector<uint32_t>(1, 0x9c60); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c60); auto const rel = std::vector<uint32_t>(1, 0x9e02); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e02); auto const rel = std::vector<uint32_t>(1, 0x9dfe); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dfe); auto const rel = std::vector<uint32_t>(1, 0x9e07); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e07); auto const rel = std::vector<uint32_t>(1, 0x9e03); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e03); auto const rel = std::vector<uint32_t>(1, 0x9e06); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e06); auto const rel = std::vector<uint32_t>(1, 0x9e05); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e05); auto const rel = std::vector<uint32_t>(1, 0x9e00); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e00); auto const rel = std::vector<uint32_t>(1, 0x9e01); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e01); auto const rel = std::vector<uint32_t>(1, 0x9e09); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e09); auto const rel = std::vector<uint32_t>(1, 0x9dff); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dff); auto const rel = std::vector<uint32_t>(1, 0x9dfd); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9dfd); auto const rel = std::vector<uint32_t>(1, 0x9e04); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_016) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e04); auto const rel = std::vector<uint32_t>(1, 0x9ea0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ea0); auto const rel = std::vector<uint32_t>(1, 0x9f1e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f1e); auto const rel = std::vector<uint32_t>(1, 0x9f46); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f46); auto const rel = std::vector<uint32_t>(1, 0x9f74); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f74); auto const rel = std::vector<uint32_t>(1, 0x9f75); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f75); auto const rel = std::vector<uint32_t>(1, 0x9f76); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f76); auto const rel = std::vector<uint32_t>(1, 0x56d4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x56d4); auto const rel = std::vector<uint32_t>(1, 0x652e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x652e); auto const rel = std::vector<uint32_t>(1, 0x65b8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x65b8); auto const rel = std::vector<uint32_t>(1, 0x6b18); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b18); auto const rel = std::vector<uint32_t>(1, 0x6b19); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b19); auto const rel = std::vector<uint32_t>(1, 0x6b17); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b17); auto const rel = std::vector<uint32_t>(1, 0x6b1a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b1a); auto const rel = std::vector<uint32_t>(1, 0x7062); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7062); auto const rel = std::vector<uint32_t>(1, 0x7226); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7226); auto const rel = std::vector<uint32_t>(1, 0x72aa); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x72aa); auto const rel = std::vector<uint32_t>(1, 0x77d8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77d8); auto const rel = std::vector<uint32_t>(1, 0x77d9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x77d9); auto const rel = std::vector<uint32_t>(1, 0x7939); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7939); auto const rel = std::vector<uint32_t>(1, 0x7c69); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c69); auto const rel = std::vector<uint32_t>(1, 0x7c6b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c6b); auto const rel = std::vector<uint32_t>(1, 0x7cf6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7cf6); auto const rel = std::vector<uint32_t>(1, 0x7e9a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e9a); auto const rel = std::vector<uint32_t>(1, 0x7e98); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e98); auto const rel = std::vector<uint32_t>(1, 0x7e9b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e9b); auto const rel = std::vector<uint32_t>(1, 0x7e99); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7e99); auto const rel = std::vector<uint32_t>(1, 0x81e0); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x81e0); auto const rel = std::vector<uint32_t>(1, 0x81e1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x81e1); auto const rel = std::vector<uint32_t>(1, 0x8646); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8646); auto const rel = std::vector<uint32_t>(1, 0x8647); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8647); auto const rel = std::vector<uint32_t>(1, 0x8648); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8648); auto const rel = std::vector<uint32_t>(1, 0x8979); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8979); auto const rel = std::vector<uint32_t>(1, 0x897a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x897a); auto const rel = std::vector<uint32_t>(1, 0x897c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x897c); auto const rel = std::vector<uint32_t>(1, 0x897b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x897b); auto const rel = std::vector<uint32_t>(1, 0x89ff); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x89ff); auto const rel = std::vector<uint32_t>(1, 0x8b98); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b98); auto const rel = std::vector<uint32_t>(1, 0x8b99); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b99); auto const rel = std::vector<uint32_t>(1, 0x8ea5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ea5); auto const rel = std::vector<uint32_t>(1, 0x8ea4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ea4); auto const rel = std::vector<uint32_t>(1, 0x8ea3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ea3); auto const rel = std::vector<uint32_t>(1, 0x946e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x946e); auto const rel = std::vector<uint32_t>(1, 0x946d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x946d); auto const rel = std::vector<uint32_t>(1, 0x946f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x946f); auto const rel = std::vector<uint32_t>(1, 0x9471); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9471); auto const rel = std::vector<uint32_t>(1, 0x9473); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9473); auto const rel = std::vector<uint32_t>(1, 0x9749); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9749); auto const rel = std::vector<uint32_t>(1, 0x9872); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9872); auto const rel = std::vector<uint32_t>(1, 0x995f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x995f); auto const rel = std::vector<uint32_t>(1, 0x9c68); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c68); auto const rel = std::vector<uint32_t>(1, 0x9c6e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_017) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c6e); auto const rel = std::vector<uint32_t>(1, 0x9c6d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c6d); auto const rel = std::vector<uint32_t>(1, 0x9e0b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e0b); auto const rel = std::vector<uint32_t>(1, 0x9e0d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e0d); auto const rel = std::vector<uint32_t>(1, 0x9e10); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e10); auto const rel = std::vector<uint32_t>(1, 0x9e0f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e0f); auto const rel = std::vector<uint32_t>(1, 0x9e12); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e12); auto const rel = std::vector<uint32_t>(1, 0x9e11); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e11); auto const rel = std::vector<uint32_t>(1, 0x9ea1); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ea1); auto const rel = std::vector<uint32_t>(1, 0x9ef5); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ef5); auto const rel = std::vector<uint32_t>(1, 0x9f09); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f09); auto const rel = std::vector<uint32_t>(1, 0x9f47); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f47); auto const rel = std::vector<uint32_t>(1, 0x9f78); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f78); auto const rel = std::vector<uint32_t>(1, 0x9f7b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f7b); auto const rel = std::vector<uint32_t>(1, 0x9f7a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f7a); auto const rel = std::vector<uint32_t>(1, 0x9f79); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f79); auto const rel = std::vector<uint32_t>(1, 0x571e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x571e); auto const rel = std::vector<uint32_t>(1, 0x7066); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7066); auto const rel = std::vector<uint32_t>(1, 0x7c6f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7c6f); auto const rel = std::vector<uint32_t>(1, 0x883c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x883c); auto const rel = std::vector<uint32_t>(1, 0x8db2); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8db2); auto const rel = std::vector<uint32_t>(1, 0x8ea6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ea6); auto const rel = std::vector<uint32_t>(1, 0x91c3); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x91c3); auto const rel = std::vector<uint32_t>(1, 0x9474); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9474); auto const rel = std::vector<uint32_t>(1, 0x9478); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9478); auto const rel = std::vector<uint32_t>(1, 0x9476); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9476); auto const rel = std::vector<uint32_t>(1, 0x9475); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9475); auto const rel = std::vector<uint32_t>(1, 0x9a60); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a60); auto const rel = std::vector<uint32_t>(1, 0x9c74); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c74); auto const rel = std::vector<uint32_t>(1, 0x9c73); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c73); auto const rel = std::vector<uint32_t>(1, 0x9c71); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c71); auto const rel = std::vector<uint32_t>(1, 0x9c75); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c75); auto const rel = std::vector<uint32_t>(1, 0x9e14); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e14); auto const rel = std::vector<uint32_t>(1, 0x9e13); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e13); auto const rel = std::vector<uint32_t>(1, 0x9ef6); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ef6); auto const rel = std::vector<uint32_t>(1, 0x9f0a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f0a); auto const rel = std::vector<uint32_t>(1, 0x9fa4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9fa4); auto const rel = std::vector<uint32_t>(1, 0x7068); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7068); auto const rel = std::vector<uint32_t>(1, 0x7065); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7065); auto const rel = std::vector<uint32_t>(1, 0x7cf7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7cf7); auto const rel = std::vector<uint32_t>(1, 0x866a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x866a); auto const rel = std::vector<uint32_t>(1, 0x883e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x883e); auto const rel = std::vector<uint32_t>(1, 0x883d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x883d); auto const rel = std::vector<uint32_t>(1, 0x883f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x883f); auto const rel = std::vector<uint32_t>(1, 0x8b9e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b9e); auto const rel = std::vector<uint32_t>(1, 0x8c9c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8c9c); auto const rel = std::vector<uint32_t>(1, 0x8ea9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ea9); auto const rel = std::vector<uint32_t>(1, 0x8ec9); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ec9); auto const rel = std::vector<uint32_t>(1, 0x974b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x974b); auto const rel = std::vector<uint32_t>(1, 0x9873); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9873); auto const rel = std::vector<uint32_t>(1, 0x9874); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9874); auto const rel = std::vector<uint32_t>(1, 0x98cc); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } } TEST(tailoring, zh_big5han_012_018) { { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x98cc); auto const rel = std::vector<uint32_t>(1, 0x9961); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9961); auto const rel = std::vector<uint32_t>(1, 0x99ab); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x99ab); auto const rel = std::vector<uint32_t>(1, 0x9a64); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a64); auto const rel = std::vector<uint32_t>(1, 0x9a66); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a66); auto const rel = std::vector<uint32_t>(1, 0x9a67); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a67); auto const rel = std::vector<uint32_t>(1, 0x9b24); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b24); auto const rel = std::vector<uint32_t>(1, 0x9e15); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e15); auto const rel = std::vector<uint32_t>(1, 0x9e17); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e17); auto const rel = std::vector<uint32_t>(1, 0x9f48); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f48); auto const rel = std::vector<uint32_t>(1, 0x6207); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6207); auto const rel = std::vector<uint32_t>(1, 0x6b1e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x6b1e); auto const rel = std::vector<uint32_t>(1, 0x7227); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7227); auto const rel = std::vector<uint32_t>(1, 0x864c); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x864c); auto const rel = std::vector<uint32_t>(1, 0x8ea8); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8ea8); auto const rel = std::vector<uint32_t>(1, 0x9482); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9482); auto const rel = std::vector<uint32_t>(1, 0x9480); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9480); auto const rel = std::vector<uint32_t>(1, 0x9481); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9481); auto const rel = std::vector<uint32_t>(1, 0x9a69); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a69); auto const rel = std::vector<uint32_t>(1, 0x9a68); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a68); auto const rel = std::vector<uint32_t>(1, 0x9b2e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9b2e); auto const rel = std::vector<uint32_t>(1, 0x9e19); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e19); auto const rel = std::vector<uint32_t>(1, 0x7229); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7229); auto const rel = std::vector<uint32_t>(1, 0x864b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x864b); auto const rel = std::vector<uint32_t>(1, 0x8b9f); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x8b9f); auto const rel = std::vector<uint32_t>(1, 0x9483); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9483); auto const rel = std::vector<uint32_t>(1, 0x9c79); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c79); auto const rel = std::vector<uint32_t>(1, 0x9eb7); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9eb7); auto const rel = std::vector<uint32_t>(1, 0x7675); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7675); auto const rel = std::vector<uint32_t>(1, 0x9a6b); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9a6b); auto const rel = std::vector<uint32_t>(1, 0x9c7a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9c7a); auto const rel = std::vector<uint32_t>(1, 0x9e1d); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9e1d); auto const rel = std::vector<uint32_t>(1, 0x7069); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x7069); auto const rel = std::vector<uint32_t>(1, 0x706a); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x706a); auto const rel = std::vector<uint32_t>(1, 0x9ea4); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9ea4); auto const rel = std::vector<uint32_t>(1, 0x9f7e); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f7e); auto const rel = std::vector<uint32_t>(1, 0x9f49); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } { // greater than (or equal to, for =) preceeding cps auto const res = std::vector<uint32_t>(1, 0x9f49); auto const rel = std::vector<uint32_t>(1, 0x9f98); EXPECT_EQ(collate( res.begin(), res.end(), rel.begin(), rel.end(), table(), collation_strength::primary), -1); } }
32.312442
77
0.564141
jan-moeller
445c5b28cf5f020ce8ce8385241892b1c2887c11
13,925
cpp
C++
gen/blink/bindings/core/v8/V8SVGPreserveAspectRatio.cpp
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
gen/blink/bindings/core/v8/V8SVGPreserveAspectRatio.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
gen/blink/bindings/core/v8/V8SVGPreserveAspectRatio.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.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. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8SVGPreserveAspectRatio.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/V8DOMConfiguration.h" #include "bindings/core/v8/V8ObjectConstructor.h" #include "bindings/core/v8/V8SVGElement.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "core/frame/UseCounter.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo V8SVGPreserveAspectRatio::wrapperTypeInfo = { gin::kEmbedderBlink, V8SVGPreserveAspectRatio::domTemplate, V8SVGPreserveAspectRatio::refObject, V8SVGPreserveAspectRatio::derefObject, V8SVGPreserveAspectRatio::trace, 0, V8SVGPreserveAspectRatio::visitDOMWrapper, V8SVGPreserveAspectRatio::preparePrototypeObject, V8SVGPreserveAspectRatio::installConditionallyEnabledProperties, "SVGPreserveAspectRatio", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Dependent, WrapperTypeInfo::WillBeGarbageCollectedObject }; #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in SVGPreserveAspectRatioTearOff.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // bindings/core/v8/ScriptWrappable.h. const WrapperTypeInfo& SVGPreserveAspectRatioTearOff::s_wrapperTypeInfo = V8SVGPreserveAspectRatio::wrapperTypeInfo; namespace SVGPreserveAspectRatioTearOffV8Internal { static void alignAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); SVGPreserveAspectRatioTearOff* impl = V8SVGPreserveAspectRatio::toImpl(holder); v8SetReturnValueUnsigned(info, impl->align()); } static void alignAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter"); SVGPreserveAspectRatioTearOffV8Internal::alignAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void alignAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); ExceptionState exceptionState(ExceptionState::SetterContext, "align", "SVGPreserveAspectRatio", holder, info.GetIsolate()); SVGPreserveAspectRatioTearOff* impl = V8SVGPreserveAspectRatio::toImpl(holder); unsigned cppValue = toUInt16(info.GetIsolate(), v8Value, NormalConversion, exceptionState); if (exceptionState.throwIfNeeded()) return; impl->setAlign(cppValue, exceptionState); exceptionState.throwIfNeeded(); } static void alignAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Value> v8Value = info[0]; TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter"); SVGPreserveAspectRatioTearOffV8Internal::alignAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void meetOrSliceAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); SVGPreserveAspectRatioTearOff* impl = V8SVGPreserveAspectRatio::toImpl(holder); v8SetReturnValueUnsigned(info, impl->meetOrSlice()); } static void meetOrSliceAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter"); SVGPreserveAspectRatioTearOffV8Internal::meetOrSliceAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void meetOrSliceAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); ExceptionState exceptionState(ExceptionState::SetterContext, "meetOrSlice", "SVGPreserveAspectRatio", holder, info.GetIsolate()); SVGPreserveAspectRatioTearOff* impl = V8SVGPreserveAspectRatio::toImpl(holder); unsigned cppValue = toUInt16(info.GetIsolate(), v8Value, NormalConversion, exceptionState); if (exceptionState.throwIfNeeded()) return; impl->setMeetOrSlice(cppValue, exceptionState); exceptionState.throwIfNeeded(); } static void meetOrSliceAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Value> v8Value = info[0]; TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter"); SVGPreserveAspectRatioTearOffV8Internal::meetOrSliceAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } } // namespace SVGPreserveAspectRatioTearOffV8Internal void V8SVGPreserveAspectRatio::visitDOMWrapper(v8::Isolate* isolate, ScriptWrappable* scriptWrappable, const v8::Persistent<v8::Object>& wrapper) { SVGPreserveAspectRatioTearOff* impl = scriptWrappable->toImpl<SVGPreserveAspectRatioTearOff>(); v8::Local<v8::Object> creationContext = v8::Local<v8::Object>::New(isolate, wrapper); V8WrapperInstantiationScope scope(creationContext, isolate); SVGElement* contextElement = impl->contextElement(); if (contextElement) { if (DOMDataStore::containsWrapper(contextElement, isolate)) DOMDataStore::setWrapperReference(wrapper, contextElement, isolate); } } static const V8DOMConfiguration::AccessorConfiguration V8SVGPreserveAspectRatioAccessors[] = { {"align", SVGPreserveAspectRatioTearOffV8Internal::alignAttributeGetterCallback, SVGPreserveAspectRatioTearOffV8Internal::alignAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, {"meetOrSlice", SVGPreserveAspectRatioTearOffV8Internal::meetOrSliceAttributeGetterCallback, SVGPreserveAspectRatioTearOffV8Internal::meetOrSliceAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, }; static void installV8SVGPreserveAspectRatioTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; if (!RuntimeEnabledFeatures::svg1DOMEnabled()) defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "SVGPreserveAspectRatio", v8::Local<v8::FunctionTemplate>(), V8SVGPreserveAspectRatio::internalFieldCount, 0, 0, 0, 0, 0, 0); else defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "SVGPreserveAspectRatio", v8::Local<v8::FunctionTemplate>(), V8SVGPreserveAspectRatio::internalFieldCount, 0, 0, V8SVGPreserveAspectRatioAccessors, WTF_ARRAY_LENGTH(V8SVGPreserveAspectRatioAccessors), 0, 0); v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); static const V8DOMConfiguration::ConstantConfiguration V8SVGPreserveAspectRatioConstants[] = { {"SVG_PRESERVEASPECTRATIO_UNKNOWN", 0, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_NONE", 1, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_XMINYMIN", 2, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_XMIDYMIN", 3, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_XMAXYMIN", 4, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_XMINYMID", 5, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_XMIDYMID", 6, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_XMAXYMID", 7, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_XMINYMAX", 8, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_XMIDYMAX", 9, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_PRESERVEASPECTRATIO_XMAXYMAX", 10, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_MEETORSLICE_UNKNOWN", 0, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_MEETORSLICE_MEET", 1, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, {"SVG_MEETORSLICE_SLICE", 2, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedShort}, }; V8DOMConfiguration::installConstants(isolate, functionTemplate, prototypeTemplate, V8SVGPreserveAspectRatioConstants, WTF_ARRAY_LENGTH(V8SVGPreserveAspectRatioConstants)); static_assert(0 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_UNKNOWN, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_UNKNOWN does not match with implementation"); static_assert(1 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_NONE, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_NONE does not match with implementation"); static_assert(2 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_XMINYMIN, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_XMINYMIN does not match with implementation"); static_assert(3 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_XMIDYMIN, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_XMIDYMIN does not match with implementation"); static_assert(4 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_XMAXYMIN, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_XMAXYMIN does not match with implementation"); static_assert(5 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_XMINYMID, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_XMINYMID does not match with implementation"); static_assert(6 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_XMIDYMID, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_XMIDYMID does not match with implementation"); static_assert(7 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_XMAXYMID, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_XMAXYMID does not match with implementation"); static_assert(8 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_XMINYMAX, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_XMINYMAX does not match with implementation"); static_assert(9 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_XMIDYMAX, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_XMIDYMAX does not match with implementation"); static_assert(10 == SVGPreserveAspectRatioTearOff::SVG_PRESERVEASPECTRATIO_XMAXYMAX, "the value of SVGPreserveAspectRatioTearOff_SVG_PRESERVEASPECTRATIO_XMAXYMAX does not match with implementation"); static_assert(0 == SVGPreserveAspectRatioTearOff::SVG_MEETORSLICE_UNKNOWN, "the value of SVGPreserveAspectRatioTearOff_SVG_MEETORSLICE_UNKNOWN does not match with implementation"); static_assert(1 == SVGPreserveAspectRatioTearOff::SVG_MEETORSLICE_MEET, "the value of SVGPreserveAspectRatioTearOff_SVG_MEETORSLICE_MEET does not match with implementation"); static_assert(2 == SVGPreserveAspectRatioTearOff::SVG_MEETORSLICE_SLICE, "the value of SVGPreserveAspectRatioTearOff_SVG_MEETORSLICE_SLICE does not match with implementation"); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Local<v8::FunctionTemplate> V8SVGPreserveAspectRatio::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8SVGPreserveAspectRatioTemplate); } bool V8SVGPreserveAspectRatio::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Local<v8::Object> V8SVGPreserveAspectRatio::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } SVGPreserveAspectRatioTearOff* V8SVGPreserveAspectRatio::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value) { return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0; } void V8SVGPreserveAspectRatio::refObject(ScriptWrappable* scriptWrappable) { #if !ENABLE(OILPAN) scriptWrappable->toImpl<SVGPreserveAspectRatioTearOff>()->ref(); #endif } void V8SVGPreserveAspectRatio::derefObject(ScriptWrappable* scriptWrappable) { #if !ENABLE(OILPAN) scriptWrappable->toImpl<SVGPreserveAspectRatioTearOff>()->deref(); #endif } } // namespace blink
64.467593
625
0.792316
wenfeifei
445d9f9e02c6b310eb9827706576d492dff6345a
62,881
cc
C++
src/breakpad/src/third_party/glog/src/logging.cc
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
46
2015-01-08T14:32:34.000Z
2022-02-05T16:48:26.000Z
src/breakpad/src/third_party/glog/src/logging.cc
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
72
2015-02-05T11:42:13.000Z
2015-12-09T22:18:41.000Z
src/breakpad/src/third_party/glog/src/logging.cc
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
22
2015-01-04T10:37:36.000Z
2021-08-16T11:46:32.000Z
// Copyright (c) 1999, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #define _GNU_SOURCE 1 // needed for O_NOFOLLOW and pread()/pwrite() #include "utilities.h" #include <assert.h> #include <iomanip> #include <string> #ifdef HAVE_UNISTD_H # include <unistd.h> // For _exit. #endif #include <climits> #include <sys/types.h> #include <sys/stat.h> #ifdef HAVE_SYS_UTSNAME_H # include <sys/utsname.h> // For uname. #endif #include <fcntl.h> #include <cstdio> #include <iostream> #include <stdarg.h> #include <stdlib.h> #ifdef HAVE_PWD_H # include <pwd.h> #endif #ifdef HAVE_SYSLOG_H # include <syslog.h> #endif #include <vector> #include <errno.h> // for errno #include <sstream> #include "base/commandlineflags.h" // to get the program name #include "glog/logging.h" #include "glog/raw_logging.h" #include "base/googleinit.h" #ifdef HAVE_STACKTRACE # include "stacktrace.h" #endif using std::string; using std::vector; using std::ostrstream; using std::setw; using std::setfill; using std::hex; using std::dec; using std::min; using std::ostream; using std::ostringstream; using std::strstream; // There is no thread annotation support. #define EXCLUSIVE_LOCKS_REQUIRED(mu) static bool BoolFromEnv(const char *varname, bool defval) { const char* const valstr = getenv(varname); if (!valstr) { return defval; } return memchr("tTyY1\0", valstr[0], 6) != NULL; } GLOG_DEFINE_bool(logtostderr, BoolFromEnv("GOOGLE_LOGTOSTDERR", false), "log messages go to stderr instead of logfiles"); GLOG_DEFINE_bool(alsologtostderr, BoolFromEnv("GOOGLE_ALSOLOGTOSTDERR", false), "log messages go to stderr in addition to logfiles"); #ifdef OS_LINUX GLOG_DEFINE_bool(drop_log_memory, true, "Drop in-memory buffers of log contents. " "Logs can grow very quickly and they are rarely read before they " "need to be evicted from memory. Instead, drop them from memory " "as soon as they are flushed to disk."); _START_GOOGLE_NAMESPACE_ namespace logging { static const int64 kPageSize = getpagesize(); } _END_GOOGLE_NAMESPACE_ #endif // By default, errors (including fatal errors) get logged to stderr as // well as the file. // // The default is ERROR instead of FATAL so that users can see problems // when they run a program without having to look in another file. DEFINE_int32(stderrthreshold, GOOGLE_NAMESPACE::ERROR, "log messages at or above this level are copied to stderr in " "addition to logfiles. This flag obsoletes --alsologtostderr."); GLOG_DEFINE_string(alsologtoemail, "", "log messages go to these email addresses " "in addition to logfiles"); GLOG_DEFINE_bool(log_prefix, true, "Prepend the log prefix to the start of each log line"); GLOG_DEFINE_int32(minloglevel, 0, "Messages logged at a lower level than this don't " "actually get logged anywhere"); GLOG_DEFINE_int32(logbuflevel, 0, "Buffer log messages logged at this level or lower" " (-1 means don't buffer; 0 means buffer INFO only;" " ...)"); GLOG_DEFINE_int32(logbufsecs, 30, "Buffer log messages for at most this many seconds"); GLOG_DEFINE_int32(logemaillevel, 999, "Email log messages logged at this level or higher" " (0 means email all; 3 means email FATAL only;" " ...)"); GLOG_DEFINE_string(logmailer, "/bin/mail", "Mailer used to send logging email"); // Compute the default value for --log_dir static const char* DefaultLogDir() { const char* env; env = getenv("GOOGLE_LOG_DIR"); if (env != NULL && env[0] != '\0') { return env; } env = getenv("TEST_TMPDIR"); if (env != NULL && env[0] != '\0') { return env; } return ""; } GLOG_DEFINE_string(log_dir, DefaultLogDir(), "If specified, logfiles are written into this directory instead " "of the default logging directory."); GLOG_DEFINE_string(log_link, "", "Put additional links to the log " "files in this directory"); GLOG_DEFINE_int32(max_log_size, 1800, "approx. maximum log file size (in MB). A value of 0 will " "be silently overridden to 1."); GLOG_DEFINE_bool(stop_logging_if_full_disk, false, "Stop attempting to log to disk if the disk is full."); GLOG_DEFINE_string(log_backtrace_at, "", "Emit a backtrace when logging at file:linenum."); // TODO(hamaji): consider windows #define PATH_SEPARATOR '/' static void GetHostName(string* hostname) { #if defined(HAVE_SYS_UTSNAME_H) struct utsname buf; if (0 != uname(&buf)) { // ensure null termination on failure *buf.nodename = '\0'; } *hostname = buf.nodename; #elif defined(OS_WINDOWS) char buf[MAX_COMPUTERNAME_LENGTH + 1]; DWORD len = MAX_COMPUTERNAME_LENGTH + 1; if (GetComputerNameA(buf, &len)) { *hostname = buf; } else { hostname->clear(); } #else # warning There is no way to retrieve the host name. *hostname = "(unknown)"; #endif } _START_GOOGLE_NAMESPACE_ // Safely get max_log_size, overriding to 1 if it somehow gets defined as 0 static int32 MaxLogSize() { return (FLAGS_max_log_size > 0 ? FLAGS_max_log_size : 1); } // A mutex that allows only one thread to log at a time, to keep things from // getting jumbled. Some other very uncommon logging operations (like // changing the destination file for log messages of a given severity) also // lock this mutex. Please be sure that anybody who might possibly need to // lock it does so. static Mutex log_mutex; // Number of messages sent at each severity. Under log_mutex. int64 LogMessage::num_messages_[NUM_SEVERITIES] = {0, 0, 0, 0}; // Globally disable log writing (if disk is full) static bool stop_writing = false; const char*const LogSeverityNames[NUM_SEVERITIES] = { "INFO", "WARNING", "ERROR", "FATAL" }; // Has the user called SetExitOnDFatal(true)? static bool exit_on_dfatal = true; const char* GetLogSeverityName(LogSeverity severity) { return LogSeverityNames[severity]; } static bool SendEmailInternal(const char*dest, const char *subject, const char*body, bool use_logging); base::Logger::~Logger() { } namespace { // Encapsulates all file-system related state class LogFileObject : public base::Logger { public: LogFileObject(LogSeverity severity, const char* base_filename); ~LogFileObject(); virtual void Write(bool force_flush, // Should we force a flush here? time_t timestamp, // Timestamp for this entry const char* message, int message_len); // Configuration options void SetBasename(const char* basename); void SetExtension(const char* ext); void SetSymlinkBasename(const char* symlink_basename); // Normal flushing routine virtual void Flush(); // It is the actual file length for the system loggers, // i.e., INFO, ERROR, etc. virtual uint32 LogSize() { MutexLock l(&lock_); return file_length_; } // Internal flush routine. Exposed so that FlushLogFilesUnsafe() // can avoid grabbing a lock. Usually Flush() calls it after // acquiring lock_. void FlushUnlocked(); private: static const uint32 kRolloverAttemptFrequency = 0x20; Mutex lock_; bool base_filename_selected_; string base_filename_; string symlink_basename_; string filename_extension_; // option users can specify (eg to add port#) FILE* file_; LogSeverity severity_; uint32 bytes_since_flush_; uint32 file_length_; unsigned int rollover_attempt_; int64 next_flush_time_; // cycle count at which to flush log // Actually create a logfile using the value of base_filename_ and the // supplied argument time_pid_string // REQUIRES: lock_ is held bool CreateLogfile(const char* time_pid_string); }; } // namespace class LogDestination { public: friend class LogMessage; friend void ReprintFatalMessage(); friend base::Logger* base::GetLogger(LogSeverity); friend void base::SetLogger(LogSeverity, base::Logger*); // These methods are just forwarded to by their global versions. static void SetLogDestination(LogSeverity severity, const char* base_filename); static void SetLogSymlink(LogSeverity severity, const char* symlink_basename); static void AddLogSink(LogSink *destination); static void RemoveLogSink(LogSink *destination); static void SetLogFilenameExtension(const char* filename_extension); static void SetStderrLogging(LogSeverity min_severity); static void SetEmailLogging(LogSeverity min_severity, const char* addresses); static void LogToStderr(); // Flush all log files that are at least at the given severity level static void FlushLogFiles(int min_severity); static void FlushLogFilesUnsafe(int min_severity); // we set the maximum size of our packet to be 1400, the logic being // to prevent fragmentation. // Really this number is arbitrary. static const int kNetworkBytes = 1400; static const string& hostname(); static void DeleteLogDestinations(); private: LogDestination(LogSeverity severity, const char* base_filename); ~LogDestination() { } // Take a log message of a particular severity and log it to stderr // iff it's of a high enough severity to deserve it. static void MaybeLogToStderr(LogSeverity severity, const char* message, size_t len); // Take a log message of a particular severity and log it to email // iff it's of a high enough severity to deserve it. static void MaybeLogToEmail(LogSeverity severity, const char* message, size_t len); // Take a log message of a particular severity and log it to a file // iff the base filename is not "" (which means "don't log to me") static void MaybeLogToLogfile(LogSeverity severity, time_t timestamp, const char* message, size_t len); // Take a log message of a particular severity and log it to the file // for that severity and also for all files with severity less than // this severity. static void LogToAllLogfiles(LogSeverity severity, time_t timestamp, const char* message, size_t len); // Send logging info to all registered sinks. static void LogToSinks(LogSeverity severity, const char *full_filename, const char *base_filename, int line, const struct ::tm* tm_time, const char* message, size_t message_len); // Wait for all registered sinks via WaitTillSent // including the optional one in "data". static void WaitForSinks(LogMessage::LogMessageData* data); static LogDestination* log_destination(LogSeverity severity); LogFileObject fileobject_; base::Logger* logger_; // Either &fileobject_, or wrapper around it static LogDestination* log_destinations_[NUM_SEVERITIES]; static LogSeverity email_logging_severity_; static string addresses_; static string hostname_; // arbitrary global logging destinations. static vector<LogSink*>* sinks_; // Protects the vector sinks_, // but not the LogSink objects its elements reference. static Mutex sink_mutex_; // Disallow LogDestination(const LogDestination&); LogDestination& operator=(const LogDestination&); }; // Errors do not get logged to email by default. LogSeverity LogDestination::email_logging_severity_ = 99999; string LogDestination::addresses_; string LogDestination::hostname_; vector<LogSink*>* LogDestination::sinks_ = NULL; Mutex LogDestination::sink_mutex_; /* static */ const string& LogDestination::hostname() { if (hostname_.empty()) { GetHostName(&hostname_); if (hostname_.empty()) { hostname_ = "(unknown)"; } } return hostname_; } LogDestination::LogDestination(LogSeverity severity, const char* base_filename) : fileobject_(severity, base_filename), logger_(&fileobject_) { } inline void LogDestination::FlushLogFilesUnsafe(int min_severity) { // assume we have the log_mutex or we simply don't care // about it for (int i = min_severity; i < NUM_SEVERITIES; i++) { LogDestination* log = log_destination(i); if (log != NULL) { // Flush the base fileobject_ logger directly instead of going // through any wrappers to reduce chance of deadlock. log->fileobject_.FlushUnlocked(); } } } inline void LogDestination::FlushLogFiles(int min_severity) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); for (int i = min_severity; i < NUM_SEVERITIES; i++) { LogDestination* log = log_destination(i); if (log != NULL) { log->logger_->Flush(); } } } inline void LogDestination::SetLogDestination(LogSeverity severity, const char* base_filename) { assert(severity >= 0 && severity < NUM_SEVERITIES); // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); log_destination(severity)->fileobject_.SetBasename(base_filename); } inline void LogDestination::SetLogSymlink(LogSeverity severity, const char* symlink_basename) { CHECK_GE(severity, 0); CHECK_LT(severity, NUM_SEVERITIES); MutexLock l(&log_mutex); log_destination(severity)->fileobject_.SetSymlinkBasename(symlink_basename); } inline void LogDestination::AddLogSink(LogSink *destination) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&sink_mutex_); if (!sinks_) sinks_ = new vector<LogSink*>; sinks_->push_back(destination); } inline void LogDestination::RemoveLogSink(LogSink *destination) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&sink_mutex_); // This doesn't keep the sinks in order, but who cares? if (sinks_) { for (int i = sinks_->size() - 1; i >= 0; i--) { if ((*sinks_)[i] == destination) { (*sinks_)[i] = (*sinks_)[sinks_->size() - 1]; sinks_->pop_back(); break; } } } } inline void LogDestination::SetLogFilenameExtension(const char* ext) { // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); for ( int severity = 0; severity < NUM_SEVERITIES; ++severity ) { log_destination(severity)->fileobject_.SetExtension(ext); } } inline void LogDestination::SetStderrLogging(LogSeverity min_severity) { assert(min_severity >= 0 && min_severity < NUM_SEVERITIES); // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); FLAGS_stderrthreshold = min_severity; } inline void LogDestination::LogToStderr() { // *Don't* put this stuff in a mutex lock, since SetStderrLogging & // SetLogDestination already do the locking! SetStderrLogging(0); // thus everything is "also" logged to stderr for ( int i = 0; i < NUM_SEVERITIES; ++i ) { SetLogDestination(i, ""); // "" turns off logging to a logfile } } inline void LogDestination::SetEmailLogging(LogSeverity min_severity, const char* addresses) { assert(min_severity >= 0 && min_severity < NUM_SEVERITIES); // Prevent any subtle race conditions by wrapping a mutex lock around // all this stuff. MutexLock l(&log_mutex); LogDestination::email_logging_severity_ = min_severity; LogDestination::addresses_ = addresses; } static void WriteToStderr(const char* message, size_t len) { // Avoid using cerr from this module since we may get called during // exit code, and cerr may be partially or fully destroyed by then. fwrite(message, len, 1, stderr); } inline void LogDestination::MaybeLogToStderr(LogSeverity severity, const char* message, size_t len) { if ((severity >= FLAGS_stderrthreshold) || FLAGS_alsologtostderr) { WriteToStderr(message, len); #ifdef OS_WINDOWS // On Windows, also output to the debugger ::OutputDebugStringA(string(message,len).c_str()); #endif } } inline void LogDestination::MaybeLogToEmail(LogSeverity severity, const char* message, size_t len) { if (severity >= email_logging_severity_ || severity >= FLAGS_logemaillevel) { string to(FLAGS_alsologtoemail); if (!addresses_.empty()) { if (!to.empty()) { to += ","; } to += addresses_; } const string subject(string("[LOG] ") + LogSeverityNames[severity] + ": " + glog_internal_namespace_::ProgramInvocationShortName()); string body(hostname()); body += "\n\n"; body.append(message, len); // should NOT use SendEmail(). The caller of this function holds the // log_mutex and SendEmail() calls LOG/VLOG which will block trying to // acquire the log_mutex object. Use SendEmailInternal() and set // use_logging to false. SendEmailInternal(to.c_str(), subject.c_str(), body.c_str(), false); } } inline void LogDestination::MaybeLogToLogfile(LogSeverity severity, time_t timestamp, const char* message, size_t len) { const bool should_flush = severity > FLAGS_logbuflevel; LogDestination* destination = log_destination(severity); destination->logger_->Write(should_flush, timestamp, message, len); } inline void LogDestination::LogToAllLogfiles(LogSeverity severity, time_t timestamp, const char* message, size_t len) { if ( FLAGS_logtostderr ) // global flag: never log to file WriteToStderr(message, len); else for (int i = severity; i >= 0; --i) LogDestination::MaybeLogToLogfile(i, timestamp, message, len); } inline void LogDestination::LogToSinks(LogSeverity severity, const char *full_filename, const char *base_filename, int line, const struct ::tm* tm_time, const char* message, size_t message_len) { ReaderMutexLock l(&sink_mutex_); if (sinks_) { for (int i = sinks_->size() - 1; i >= 0; i--) { (*sinks_)[i]->send(severity, full_filename, base_filename, line, tm_time, message, message_len); } } } inline void LogDestination::WaitForSinks(LogMessage::LogMessageData* data) { ReaderMutexLock l(&sink_mutex_); if (sinks_) { for (int i = sinks_->size() - 1; i >= 0; i--) { (*sinks_)[i]->WaitTillSent(); } } const bool send_to_sink = (data->send_method_ == &LogMessage::SendToSink) || (data->send_method_ == &LogMessage::SendToSinkAndLog); if (send_to_sink && data->sink_ != NULL) { data->sink_->WaitTillSent(); } } LogDestination* LogDestination::log_destinations_[NUM_SEVERITIES]; inline LogDestination* LogDestination::log_destination(LogSeverity severity) { assert(severity >=0 && severity < NUM_SEVERITIES); if (!log_destinations_[severity]) { log_destinations_[severity] = new LogDestination(severity, NULL); } return log_destinations_[severity]; } void LogDestination::DeleteLogDestinations() { for (int severity = 0; severity < NUM_SEVERITIES; ++severity) { delete log_destinations_[severity]; log_destinations_[severity] = NULL; } } namespace { LogFileObject::LogFileObject(LogSeverity severity, const char* base_filename) : base_filename_selected_(base_filename != NULL), base_filename_((base_filename != NULL) ? base_filename : ""), symlink_basename_(glog_internal_namespace_::ProgramInvocationShortName()), filename_extension_(), file_(NULL), severity_(severity), bytes_since_flush_(0), file_length_(0), rollover_attempt_(kRolloverAttemptFrequency-1), next_flush_time_(0) { assert(severity >= 0); assert(severity < NUM_SEVERITIES); } LogFileObject::~LogFileObject() { MutexLock l(&lock_); if (file_ != NULL) { fclose(file_); file_ = NULL; } } void LogFileObject::SetBasename(const char* basename) { MutexLock l(&lock_); base_filename_selected_ = true; if (base_filename_ != basename) { // Get rid of old log file since we are changing names if (file_ != NULL) { fclose(file_); file_ = NULL; rollover_attempt_ = kRolloverAttemptFrequency-1; } base_filename_ = basename; } } void LogFileObject::SetExtension(const char* ext) { MutexLock l(&lock_); if (filename_extension_ != ext) { // Get rid of old log file since we are changing names if (file_ != NULL) { fclose(file_); file_ = NULL; rollover_attempt_ = kRolloverAttemptFrequency-1; } filename_extension_ = ext; } } void LogFileObject::SetSymlinkBasename(const char* symlink_basename) { MutexLock l(&lock_); symlink_basename_ = symlink_basename; } void LogFileObject::Flush() { MutexLock l(&lock_); FlushUnlocked(); } void LogFileObject::FlushUnlocked(){ if (file_ != NULL) { fflush(file_); bytes_since_flush_ = 0; } // Figure out when we are due for another flush. const int64 next = (FLAGS_logbufsecs * static_cast<int64>(1000000)); // in usec next_flush_time_ = CycleClock_Now() + UsecToCycles(next); } bool LogFileObject::CreateLogfile(const char* time_pid_string) { string string_filename = base_filename_+filename_extension_+ time_pid_string; const char* filename = string_filename.c_str(); int fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0664); if (fd == -1) return false; #ifdef HAVE_FCNTL // Mark the file close-on-exec. We don't really care if this fails fcntl(fd, F_SETFD, FD_CLOEXEC); #endif file_ = fdopen(fd, "a"); // Make a FILE*. if (file_ == NULL) { // Man, we're screwed! close(fd); unlink(filename); // Erase the half-baked evidence: an unusable log file return false; } // We try to create a symlink called <program_name>.<severity>, // which is easier to use. (Every time we create a new logfile, // we destroy the old symlink and create a new one, so it always // points to the latest logfile.) If it fails, we're sad but it's // no error. if (!symlink_basename_.empty()) { // take directory from filename const char* slash = strrchr(filename, PATH_SEPARATOR); const string linkname = symlink_basename_ + '.' + LogSeverityNames[severity_]; string linkpath; if ( slash ) linkpath = string(filename, slash-filename+1); // get dirname linkpath += linkname; unlink(linkpath.c_str()); // delete old one if it exists // We must have unistd.h. #ifdef HAVE_UNISTD_H // Make the symlink be relative (in the same dir) so that if the // entire log directory gets relocated the link is still valid. const char *linkdest = slash ? (slash + 1) : filename; if (symlink(linkdest, linkpath.c_str()) != 0) { // silently ignore failures } // Make an additional link to the log file in a place specified by // FLAGS_log_link, if indicated if (!FLAGS_log_link.empty()) { linkpath = FLAGS_log_link + "/" + linkname; unlink(linkpath.c_str()); // delete old one if it exists if (symlink(filename, linkpath.c_str()) != 0) { // silently ignore failures } } #endif } return true; // Everything worked } void LogFileObject::Write(bool force_flush, time_t timestamp, const char* message, int message_len) { MutexLock l(&lock_); // We don't log if the base_name_ is "" (which means "don't write") if (base_filename_selected_ && base_filename_.empty()) { return; } if (static_cast<int>(file_length_ >> 20) >= MaxLogSize() || PidHasChanged()) { if (file_ != NULL) fclose(file_); file_ = NULL; file_length_ = bytes_since_flush_ = 0; rollover_attempt_ = kRolloverAttemptFrequency-1; } // If there's no destination file, make one before outputting if (file_ == NULL) { // Try to rollover the log file every 32 log messages. The only time // this could matter would be when we have trouble creating the log // file. If that happens, we'll lose lots of log messages, of course! if (++rollover_attempt_ != kRolloverAttemptFrequency) return; rollover_attempt_ = 0; struct ::tm tm_time; localtime_r(&timestamp, &tm_time); // The logfile's filename will have the date/time & pid in it char time_pid_string[256]; // More than enough chars for time, pid, \0 ostrstream time_pid_stream(time_pid_string, sizeof(time_pid_string)); time_pid_stream.fill('0'); time_pid_stream << 1900+tm_time.tm_year << setw(2) << 1+tm_time.tm_mon << setw(2) << tm_time.tm_mday << '-' << setw(2) << tm_time.tm_hour << setw(2) << tm_time.tm_min << setw(2) << tm_time.tm_sec << '.' << GetMainThreadPid() << '\0'; if (base_filename_selected_) { if (!CreateLogfile(time_pid_string)) { perror("Could not create log file"); fprintf(stderr, "COULD NOT CREATE LOGFILE '%s'!\n", time_pid_string); return; } } else { // If no base filename for logs of this severity has been set, use a // default base filename of // "<program name>.<hostname>.<user name>.log.<severity level>.". So // logfiles will have names like // webserver.examplehost.root.log.INFO.19990817-150000.4354, where // 19990817 is a date (1999 August 17), 150000 is a time (15:00:00), // and 4354 is the pid of the logging process. The date & time reflect // when the file was created for output. // // Where does the file get put? Successively try the directories // "/tmp", and "." string stripped_filename( glog_internal_namespace_::ProgramInvocationShortName()); string hostname; GetHostName(&hostname); string uidname = MyUserName(); // We should not call CHECK() here because this function can be // called after holding on to log_mutex. We don't want to // attempt to hold on to the same mutex, and get into a // deadlock. Simply use a name like invalid-user. if (uidname.empty()) uidname = "invalid-user"; stripped_filename = stripped_filename+'.'+hostname+'.' +uidname+".log." +LogSeverityNames[severity_]+'.'; // We're going to (potentially) try to put logs in several different dirs const vector<string> & log_dirs = GetLoggingDirectories(); // Go through the list of dirs, and try to create the log file in each // until we succeed or run out of options bool success = false; for (vector<string>::const_iterator dir = log_dirs.begin(); dir != log_dirs.end(); ++dir) { base_filename_ = *dir + "/" + stripped_filename; if ( CreateLogfile(time_pid_string) ) { success = true; break; } } // If we never succeeded, we have to give up if ( success == false ) { perror("Could not create logging file"); fprintf(stderr, "COULD NOT CREATE A LOGGINGFILE %s!", time_pid_string); return; } } // Write a header message into the log file char file_header_string[512]; // Enough chars for time and binary info ostrstream file_header_stream(file_header_string, sizeof(file_header_string)); file_header_stream.fill('0'); file_header_stream << "Log file created at: " << 1900+tm_time.tm_year << '/' << setw(2) << 1+tm_time.tm_mon << '/' << setw(2) << tm_time.tm_mday << ' ' << setw(2) << tm_time.tm_hour << ':' << setw(2) << tm_time.tm_min << ':' << setw(2) << tm_time.tm_sec << '\n' << "Running on machine: " << LogDestination::hostname() << '\n' << "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu " << "threadid file:line] msg" << '\n' << '\0'; int header_len = strlen(file_header_string); fwrite(file_header_string, 1, header_len, file_); file_length_ += header_len; bytes_since_flush_ += header_len; } // Write to LOG file if ( !stop_writing ) { // fwrite() doesn't return an error when the disk is full, for // messages that are less than 4096 bytes. When the disk is full, // it returns the message length for messages that are less than // 4096 bytes. fwrite() returns 4096 for message lengths that are // greater than 4096, thereby indicating an error. errno = 0; fwrite(message, 1, message_len, file_); if ( FLAGS_stop_logging_if_full_disk && errno == ENOSPC ) { // disk full, stop writing to disk stop_writing = true; // until the disk is return; } else { file_length_ += message_len; bytes_since_flush_ += message_len; } } else { if ( CycleClock_Now() >= next_flush_time_ ) stop_writing = false; // check to see if disk has free space. return; // no need to flush } // See important msgs *now*. Also, flush logs at least every 10^6 chars, // or every "FLAGS_logbufsecs" seconds. if ( force_flush || (bytes_since_flush_ >= 1000000) || (CycleClock_Now() >= next_flush_time_) ) { FlushUnlocked(); #ifdef OS_LINUX if (FLAGS_drop_log_memory) { if (file_length_ >= logging::kPageSize) { // don't evict the most recent page uint32 len = file_length_ & ~(logging::kPageSize - 1); posix_fadvise(fileno(file_), 0, len, POSIX_FADV_DONTNEED); } } #endif } } } // namespace // An arbitrary limit on the length of a single log message. This // is so that streaming can be done more efficiently. const size_t LogMessage::kMaxLogMessageLen = 30000; // Static log data space to avoid alloc failures in a LOG(FATAL) // // Since multiple threads may call LOG(FATAL), and we want to preserve // the data from the first call, we allocate two sets of space. One // for exclusive use by the first thread, and one for shared use by // all other threads. static Mutex fatal_msg_lock; static CrashReason crash_reason; static bool fatal_msg_exclusive = true; static char fatal_msg_buf_exclusive[LogMessage::kMaxLogMessageLen+1]; static char fatal_msg_buf_shared[LogMessage::kMaxLogMessageLen+1]; static LogMessage::LogStream fatal_msg_stream_exclusive( fatal_msg_buf_exclusive, LogMessage::kMaxLogMessageLen, 0); static LogMessage::LogStream fatal_msg_stream_shared( fatal_msg_buf_shared, LogMessage::kMaxLogMessageLen, 0); LogMessage::LogMessageData LogMessage::fatal_msg_data_exclusive_; LogMessage::LogMessageData LogMessage::fatal_msg_data_shared_; LogMessage::LogMessageData::~LogMessageData() { delete[] buf_; delete stream_alloc_; } LogMessage::LogMessage(const char* file, int line, LogSeverity severity, int ctr, void (LogMessage::*send_method)()) { Init(file, line, severity, send_method); data_->stream_->set_ctr(ctr); } LogMessage::LogMessage(const char* file, int line, const CheckOpString& result) { Init(file, line, FATAL, &LogMessage::SendToLog); stream() << "Check failed: " << (*result.str_) << " "; } LogMessage::LogMessage(const char* file, int line) { Init(file, line, INFO, &LogMessage::SendToLog); } LogMessage::LogMessage(const char* file, int line, LogSeverity severity) { Init(file, line, severity, &LogMessage::SendToLog); } LogMessage::LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink, bool also_send_to_log) { Init(file, line, severity, also_send_to_log ? &LogMessage::SendToSinkAndLog : &LogMessage::SendToSink); data_->sink_ = sink; // override Init()'s setting to NULL } LogMessage::LogMessage(const char* file, int line, LogSeverity severity, vector<string> *outvec) { Init(file, line, severity, &LogMessage::SaveOrSendToLog); data_->outvec_ = outvec; // override Init()'s setting to NULL } LogMessage::LogMessage(const char* file, int line, LogSeverity severity, string *message) { Init(file, line, severity, &LogMessage::WriteToStringAndLog); data_->message_ = message; // override Init()'s setting to NULL } void LogMessage::Init(const char* file, int line, LogSeverity severity, void (LogMessage::*send_method)()) { allocated_ = NULL; if (severity != FATAL || !exit_on_dfatal) { allocated_ = new LogMessageData(); data_ = allocated_; data_->buf_ = new char[kMaxLogMessageLen+1]; data_->message_text_ = data_->buf_; data_->stream_alloc_ = new LogStream(data_->message_text_, kMaxLogMessageLen, 0); data_->stream_ = data_->stream_alloc_; data_->first_fatal_ = false; } else { MutexLock l(&fatal_msg_lock); if (fatal_msg_exclusive) { fatal_msg_exclusive = false; data_ = &fatal_msg_data_exclusive_; data_->message_text_ = fatal_msg_buf_exclusive; data_->stream_ = &fatal_msg_stream_exclusive; data_->first_fatal_ = true; } else { data_ = &fatal_msg_data_shared_; data_->message_text_ = fatal_msg_buf_shared; data_->stream_ = &fatal_msg_stream_shared; data_->first_fatal_ = false; } data_->stream_alloc_ = NULL; } stream().fill('0'); data_->preserved_errno_ = errno; data_->severity_ = severity; data_->line_ = line; data_->send_method_ = send_method; data_->sink_ = NULL; data_->outvec_ = NULL; WallTime now = WallTime_Now(); data_->timestamp_ = static_cast<time_t>(now); localtime_r(&data_->timestamp_, &data_->tm_time_); int usecs = static_cast<int>((now - data_->timestamp_) * 1000000); RawLog__SetLastTime(data_->tm_time_, usecs); data_->num_chars_to_log_ = 0; data_->num_chars_to_syslog_ = 0; data_->basename_ = const_basename(file); data_->fullname_ = file; data_->has_been_flushed_ = false; // If specified, prepend a prefix to each line. For example: // I1018 160715 f5d4fbb0 logging.cc:1153] // (log level, GMT month, date, time, thread_id, file basename, line) // We exclude the thread_id for the default thread. if (FLAGS_log_prefix && (line != kNoLogPrefix)) { stream() << LogSeverityNames[severity][0] << setw(2) << 1+data_->tm_time_.tm_mon << setw(2) << data_->tm_time_.tm_mday << ' ' << setw(2) << data_->tm_time_.tm_hour << ':' << setw(2) << data_->tm_time_.tm_min << ':' << setw(2) << data_->tm_time_.tm_sec << "." << setw(6) << usecs << ' ' << setfill(' ') << setw(5) << static_cast<unsigned int>(GetTID()) << setfill('0') << ' ' << data_->basename_ << ':' << data_->line_ << "] "; } data_->num_prefix_chars_ = data_->stream_->pcount(); if (!FLAGS_log_backtrace_at.empty()) { char fileline[128]; snprintf(fileline, sizeof(fileline), "%s:%d", data_->basename_, line); #ifdef HAVE_STACKTRACE if (!strcmp(FLAGS_log_backtrace_at.c_str(), fileline)) { string stacktrace; DumpStackTraceToString(&stacktrace); stream() << " (stacktrace:\n" << stacktrace << ") "; } #endif } } LogMessage::~LogMessage() { Flush(); delete allocated_; } // Flush buffered message, called by the destructor, or any other function // that needs to synchronize the log. void LogMessage::Flush() { if (data_->has_been_flushed_ || data_->severity_ < FLAGS_minloglevel) return; data_->num_chars_to_log_ = data_->stream_->pcount(); data_->num_chars_to_syslog_ = data_->num_chars_to_log_ - data_->num_prefix_chars_; // Do we need to add a \n to the end of this message? bool append_newline = (data_->message_text_[data_->num_chars_to_log_-1] != '\n'); char original_final_char = '\0'; // If we do need to add a \n, we'll do it by violating the memory of the // ostrstream buffer. This is quick, and we'll make sure to undo our // modification before anything else is done with the ostrstream. It // would be preferable not to do things this way, but it seems to be // the best way to deal with this. if (append_newline) { original_final_char = data_->message_text_[data_->num_chars_to_log_]; data_->message_text_[data_->num_chars_to_log_++] = '\n'; } // Prevent any subtle race conditions by wrapping a mutex lock around // the actual logging action per se. { MutexLock l(&log_mutex); (this->*(data_->send_method_))(); ++num_messages_[static_cast<int>(data_->severity_)]; } LogDestination::WaitForSinks(data_); if (append_newline) { // Fix the ostrstream back how it was before we screwed with it. // It's 99.44% certain that we don't need to worry about doing this. data_->message_text_[data_->num_chars_to_log_-1] = original_final_char; } // If errno was already set before we enter the logging call, we'll // set it back to that value when we return from the logging call. // It happens often that we log an error message after a syscall // failure, which can potentially set the errno to some other // values. We would like to preserve the original errno. if (data_->preserved_errno_ != 0) { errno = data_->preserved_errno_; } // Note that this message is now safely logged. If we're asked to flush // again, as a result of destruction, say, we'll do nothing on future calls. data_->has_been_flushed_ = true; } // Copy of first FATAL log message so that we can print it out again // after all the stack traces. To preserve legacy behavior, we don't // use fatal_msg_buf_exclusive. static time_t fatal_time; static char fatal_message[256]; void ReprintFatalMessage() { if (fatal_message[0]) { const int n = strlen(fatal_message); if (!FLAGS_logtostderr) { // Also write to stderr WriteToStderr(fatal_message, n); } LogDestination::LogToAllLogfiles(ERROR, fatal_time, fatal_message, n); } } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { static bool already_warned_before_initgoogle = false; log_mutex.AssertHeld(); RAW_DCHECK(data_->num_chars_to_log_ > 0 && data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); // Messages of a given severity get logged to lower severity logs, too if (!already_warned_before_initgoogle && !IsGoogleLoggingInitialized()) { const char w[] = "WARNING: Logging before InitGoogleLogging() is " "written to STDERR\n"; WriteToStderr(w, strlen(w)); already_warned_before_initgoogle = true; } // global flag: never log to file if set. Also -- don't log to a // file if we haven't parsed the command line flags to get the // program name. if (FLAGS_logtostderr || !IsGoogleLoggingInitialized()) { WriteToStderr(data_->message_text_, data_->num_chars_to_log_); // this could be protected by a flag if necessary. LogDestination::LogToSinks(data_->severity_, data_->fullname_, data_->basename_, data_->line_, &data_->tm_time_, data_->message_text_ + data_->num_prefix_chars_, (data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1)); } else { // log this message to all log files of severity <= severity_ LogDestination::LogToAllLogfiles(data_->severity_, data_->timestamp_, data_->message_text_, data_->num_chars_to_log_); LogDestination::MaybeLogToStderr(data_->severity_, data_->message_text_, data_->num_chars_to_log_); LogDestination::MaybeLogToEmail(data_->severity_, data_->message_text_, data_->num_chars_to_log_); LogDestination::LogToSinks(data_->severity_, data_->fullname_, data_->basename_, data_->line_, &data_->tm_time_, data_->message_text_ + data_->num_prefix_chars_, (data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1)); // NOTE: -1 removes trailing \n } // If we log a FATAL message, flush all the log destinations, then toss // a signal for others to catch. We leave the logs in a state that // someone else can use them (as long as they flush afterwards) if (data_->severity_ == FATAL && exit_on_dfatal) { if (data_->first_fatal_) { // Store crash information so that it is accessible from within signal // handlers that may be invoked later. RecordCrashReason(&crash_reason); SetCrashReason(&crash_reason); // Store shortened fatal message for other logs and GWQ status const int copy = min<int>(data_->num_chars_to_log_, sizeof(fatal_message)-1); memcpy(fatal_message, data_->message_text_, copy); fatal_message[copy] = '\0'; fatal_time = data_->timestamp_; } if (!FLAGS_logtostderr) { for (int i = 0; i < NUM_SEVERITIES; ++i) { if ( LogDestination::log_destinations_[i] ) LogDestination::log_destinations_[i]->logger_->Write(true, 0, "", 0); } } // release the lock that our caller (directly or indirectly) // LogMessage::~LogMessage() grabbed so that signal handlers // can use the logging facility. Alternately, we could add // an entire unsafe logging interface to bypass locking // for signal handlers but this seems simpler. log_mutex.Unlock(); LogDestination::WaitForSinks(data_); const char* message = "*** Check failure stack trace: ***\n"; if (write(STDERR_FILENO, message, strlen(message)) < 0) { // Ignore errors. } Fail(); } } void LogMessage::RecordCrashReason( glog_internal_namespace_::CrashReason* reason) { reason->filename = fatal_msg_data_exclusive_.fullname_; reason->line_number = fatal_msg_data_exclusive_.line_; reason->message = fatal_msg_buf_exclusive + fatal_msg_data_exclusive_.num_prefix_chars_; #ifdef HAVE_STACKTRACE // Retrieve the stack trace, omitting the logging frames that got us here. reason->depth = GetStackTrace(reason->stack, ARRAYSIZE(reason->stack), 4); #else reason->depth = 0; #endif } static void logging_fail() { #if defined(_DEBUG) && defined(_MSC_VER) // When debugging on windows, avoid the obnoxious dialog and make // it possible to continue past a LOG(FATAL) in the debugger _asm int 3 #else abort(); #endif } #ifdef HAVE___ATTRIBUTE__ GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)() __attribute__((noreturn)) = &logging_fail; #else GOOGLE_GLOG_DLL_DECL void (*g_logging_fail_func)() = &logging_fail; #endif void InstallFailureFunction(void (*fail_func)()) { g_logging_fail_func = fail_func; } void LogMessage::Fail() { g_logging_fail_func(); } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SendToSink() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { if (data_->sink_ != NULL) { RAW_DCHECK(data_->num_chars_to_log_ > 0 && data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); data_->sink_->send(data_->severity_, data_->fullname_, data_->basename_, data_->line_, &data_->tm_time_, data_->message_text_ + data_->num_prefix_chars_, (data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1)); } } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SendToSinkAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { SendToSink(); SendToLog(); } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SaveOrSendToLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { if (data_->outvec_ != NULL) { RAW_DCHECK(data_->num_chars_to_log_ > 0 && data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); // Omit prefix of message and trailing newline when recording in outvec_. const char *start = data_->message_text_ + data_->num_prefix_chars_; int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; data_->outvec_->push_back(string(start, len)); } else { SendToLog(); } } void LogMessage::WriteToStringAndLog() EXCLUSIVE_LOCKS_REQUIRED(log_mutex) { if (data_->message_ != NULL) { RAW_DCHECK(data_->num_chars_to_log_ > 0 && data_->message_text_[data_->num_chars_to_log_-1] == '\n', ""); // Omit prefix of message and trailing newline when writing to message_. const char *start = data_->message_text_ + data_->num_prefix_chars_; int len = data_->num_chars_to_log_ - data_->num_prefix_chars_ - 1; data_->message_->assign(start, len); } SendToLog(); } // L >= log_mutex (callers must hold the log_mutex). void LogMessage::SendToSyslogAndLog() { #ifdef HAVE_SYSLOG_H // Before any calls to syslog(), make a single call to openlog() static bool openlog_already_called = false; if (!openlog_already_called) { openlog(glog_internal_namespace_::ProgramInvocationShortName(), LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER); openlog_already_called = true; } // This array maps Google severity levels to syslog levels const int SEVERITY_TO_LEVEL[] = { LOG_INFO, LOG_WARNING, LOG_ERR, LOG_EMERG }; syslog(LOG_USER | SEVERITY_TO_LEVEL[static_cast<int>(data_->severity_)], "%.*s", int(data_->num_chars_to_syslog_), data_->message_text_ + data_->num_prefix_chars_); SendToLog(); #else LOG(ERROR) << "No syslog support: message=" << data_->message_text_; #endif } base::Logger* base::GetLogger(LogSeverity severity) { MutexLock l(&log_mutex); return LogDestination::log_destination(severity)->logger_; } void base::SetLogger(LogSeverity severity, base::Logger* logger) { MutexLock l(&log_mutex); LogDestination::log_destination(severity)->logger_ = logger; } // L < log_mutex. Acquires and releases mutex_. int64 LogMessage::num_messages(int severity) { MutexLock l(&log_mutex); return num_messages_[severity]; } // Output the COUNTER value. This is only valid if ostream is a // LogStream. ostream& operator<<(ostream &os, const PRIVATE_Counter&) { LogMessage::LogStream *log = dynamic_cast<LogMessage::LogStream*>(&os); CHECK(log == log->self()); os << log->ctr(); return os; } ErrnoLogMessage::ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr, void (LogMessage::*send_method)()) : LogMessage(file, line, severity, ctr, send_method) { } ErrnoLogMessage::~ErrnoLogMessage() { // Don't access errno directly because it may have been altered // while streaming the message. char buf[100]; posix_strerror_r(preserved_errno(), buf, sizeof(buf)); stream() << ": " << buf << " [" << preserved_errno() << "]"; } void FlushLogFiles(LogSeverity min_severity) { LogDestination::FlushLogFiles(min_severity); } void FlushLogFilesUnsafe(LogSeverity min_severity) { LogDestination::FlushLogFilesUnsafe(min_severity); } void SetLogDestination(LogSeverity severity, const char* base_filename) { LogDestination::SetLogDestination(severity, base_filename); } void SetLogSymlink(LogSeverity severity, const char* symlink_basename) { LogDestination::SetLogSymlink(severity, symlink_basename); } LogSink::~LogSink() { } void LogSink::WaitTillSent() { // noop default } string LogSink::ToString(LogSeverity severity, const char* file, int line, const struct ::tm* tm_time, const char* message, size_t message_len) { ostringstream stream(string(message, message_len)); stream.fill('0'); // FIXME(jrvb): Updating this to use the correct value for usecs // requires changing the signature for both this method and // LogSink::send(). This change needs to be done in a separate CL // so subclasses of LogSink can be updated at the same time. int usecs = 0; stream << LogSeverityNames[severity][0] << setw(2) << 1+tm_time->tm_mon << setw(2) << tm_time->tm_mday << ' ' << setw(2) << tm_time->tm_hour << ':' << setw(2) << tm_time->tm_min << ':' << setw(2) << tm_time->tm_sec << '.' << setw(6) << usecs << ' ' << setfill(' ') << setw(5) << GetTID() << setfill('0') << ' ' << file << ':' << line << "] "; stream << string(message, message_len); return stream.str(); } void AddLogSink(LogSink *destination) { LogDestination::AddLogSink(destination); } void RemoveLogSink(LogSink *destination) { LogDestination::RemoveLogSink(destination); } void SetLogFilenameExtension(const char* ext) { LogDestination::SetLogFilenameExtension(ext); } void SetStderrLogging(LogSeverity min_severity) { LogDestination::SetStderrLogging(min_severity); } void SetEmailLogging(LogSeverity min_severity, const char* addresses) { LogDestination::SetEmailLogging(min_severity, addresses); } void LogToStderr() { LogDestination::LogToStderr(); } namespace base { namespace internal { bool GetExitOnDFatal() { MutexLock l(&log_mutex); return exit_on_dfatal; } // Determines whether we exit the program for a LOG(DFATAL) message in // debug mode. It does this by skipping the call to Fail/FailQuietly. // This is intended for testing only. // // This can have some effects on LOG(FATAL) as well. Failure messages // are always allocated (rather than sharing a buffer), the crash // reason is not recorded, the "gwq" status message is not updated, // and the stack trace is not recorded. The LOG(FATAL) *will* still // exit the program. Since this function is used only in testing, // these differences are acceptable. void SetExitOnDFatal(bool value) { MutexLock l(&log_mutex); exit_on_dfatal = value; } } // namespace internal } // namespace base // use_logging controls whether the logging functions LOG/VLOG are used // to log errors. It should be set to false when the caller holds the // log_mutex. static bool SendEmailInternal(const char*dest, const char *subject, const char*body, bool use_logging) { if (dest && *dest) { if ( use_logging ) { VLOG(1) << "Trying to send TITLE:" << subject << " BODY:" << body << " to " << dest; } else { fprintf(stderr, "Trying to send TITLE: %s BODY: %s to %s\n", subject, body, dest); } string cmd = FLAGS_logmailer + " -s\"" + subject + "\" " + dest; FILE* pipe = popen(cmd.c_str(), "w"); if (pipe != NULL) { // Add the body if we have one if (body) fwrite(body, sizeof(char), strlen(body), pipe); bool ok = pclose(pipe) != -1; if ( !ok ) { if ( use_logging ) { char buf[100]; posix_strerror_r(errno, buf, sizeof(buf)); LOG(ERROR) << "Problems sending mail to " << dest << ": " << buf; } else { char buf[100]; posix_strerror_r(errno, buf, sizeof(buf)); fprintf(stderr, "Problems sending mail to %s: %s\n", dest, buf); } } return ok; } else { if ( use_logging ) { LOG(ERROR) << "Unable to send mail to " << dest; } else { fprintf(stderr, "Unable to send mail to %s\n", dest); } } } return false; } bool SendEmail(const char*dest, const char *subject, const char*body){ return SendEmailInternal(dest, subject, body, true); } static void GetTempDirectories(vector<string>* list) { list->clear(); #ifdef OS_WINDOWS // On windows we'll try to find a directory in this order: // C:/Documents & Settings/whomever/TEMP (or whatever GetTempPath() is) // C:/TMP/ // C:/TEMP/ // C:/WINDOWS/ or C:/WINNT/ // . char tmp[MAX_PATH]; if (GetTempPathA(MAX_PATH, tmp)) list->push_back(tmp); list->push_back("C:\\tmp\\"); list->push_back("C:\\temp\\"); #else // Directories, in order of preference. If we find a dir that // exists, we stop adding other less-preferred dirs const char * candidates[] = { // Non-null only during unittest/regtest getenv("TEST_TMPDIR"), // Explicitly-supplied temp dirs getenv("TMPDIR"), getenv("TMP"), // If all else fails "/tmp", }; for (int i = 0; i < ARRAYSIZE(candidates); i++) { const char *d = candidates[i]; if (!d) continue; // Empty env var // Make sure we don't surprise anyone who's expecting a '/' string dstr = d; if (dstr[dstr.size() - 1] != '/') { dstr += "/"; } list->push_back(dstr); struct stat statbuf; if (!stat(d, &statbuf) && S_ISDIR(statbuf.st_mode)) { // We found a dir that exists - we're done. return; } } #endif } static vector<string>* logging_directories_list; const vector<string>& GetLoggingDirectories() { // Not strictly thread-safe but we're called early in InitGoogle(). if (logging_directories_list == NULL) { logging_directories_list = new vector<string>; if ( !FLAGS_log_dir.empty() ) { // A dir was specified, we should use it logging_directories_list->push_back(FLAGS_log_dir.c_str()); } else { GetTempDirectories(logging_directories_list); #ifdef OS_WINDOWS char tmp[MAX_PATH]; if (GetWindowsDirectoryA(tmp, MAX_PATH)) logging_directories_list->push_back(tmp); logging_directories_list->push_back(".\\"); #else logging_directories_list->push_back("./"); #endif } } return *logging_directories_list; } void TestOnly_ClearLoggingDirectoriesList() { fprintf(stderr, "TestOnly_ClearLoggingDirectoriesList should only be " "called from test code.\n"); delete logging_directories_list; logging_directories_list = NULL; } void GetExistingTempDirectories(vector<string>* list) { GetTempDirectories(list); vector<string>::iterator i_dir = list->begin(); while( i_dir != list->end() ) { // zero arg to access means test for existence; no constant // defined on windows if ( access(i_dir->c_str(), 0) ) { i_dir = list->erase(i_dir); } else { ++i_dir; } } } void TruncateLogFile(const char *path, int64 limit, int64 keep) { #ifdef HAVE_UNISTD_H struct stat statbuf; const int kCopyBlockSize = 8 << 10; char copybuf[kCopyBlockSize]; int64 read_offset, write_offset; // Don't follow symlinks unless they're our own fd symlinks in /proc int flags = O_RDWR; const char *procfd_prefix = "/proc/self/fd/"; if (strncmp(procfd_prefix, path, strlen(procfd_prefix))) flags |= O_NOFOLLOW; int fd = open(path, flags); if (fd == -1) { if (errno == EFBIG) { // The log file in question has got too big for us to open. The // real fix for this would be to compile logging.cc (or probably // all of base/...) with -D_FILE_OFFSET_BITS=64 but that's // rather scary. // Instead just truncate the file to something we can manage if (truncate(path, 0) == -1) { PLOG(ERROR) << "Unable to truncate " << path; } else { LOG(ERROR) << "Truncated " << path << " due to EFBIG error"; } } else { PLOG(ERROR) << "Unable to open " << path; } return; } if (fstat(fd, &statbuf) == -1) { PLOG(ERROR) << "Unable to fstat()"; goto out_close_fd; } // See if the path refers to a regular file bigger than the // specified limit if (!S_ISREG(statbuf.st_mode)) goto out_close_fd; if (statbuf.st_size <= limit) goto out_close_fd; if (statbuf.st_size <= keep) goto out_close_fd; // This log file is too large - we need to truncate it LOG(INFO) << "Truncating " << path << " to " << keep << " bytes"; // Copy the last "keep" bytes of the file to the beginning of the file read_offset = statbuf.st_size - keep; write_offset = 0; int bytesin, bytesout; while ((bytesin = pread(fd, copybuf, sizeof(copybuf), read_offset)) > 0) { bytesout = pwrite(fd, copybuf, bytesin, write_offset); if (bytesout == -1) { PLOG(ERROR) << "Unable to write to " << path; break; } else if (bytesout != bytesin) { LOG(ERROR) << "Expected to write " << bytesin << ", wrote " << bytesout; } read_offset += bytesin; write_offset += bytesout; } if (bytesin == -1) PLOG(ERROR) << "Unable to read from " << path; // Truncate the remainder of the file. If someone else writes to the // end of the file after our last read() above, we lose their latest // data. Too bad ... if (ftruncate(fd, write_offset) == -1) { PLOG(ERROR) << "Unable to truncate " << path; } out_close_fd: close(fd); #else LOG(ERROR) << "No log truncation support."; #endif } void TruncateStdoutStderr() { #ifdef HAVE_UNISTD_H int64 limit = MaxLogSize() << 20; int64 keep = 1 << 20; TruncateLogFile("/proc/self/fd/1", limit, keep); TruncateLogFile("/proc/self/fd/2", limit, keep); #else LOG(ERROR) << "No log truncation support."; #endif } // Helper functions for string comparisons. #define DEFINE_CHECK_STROP_IMPL(name, func, expected) \ string* Check##func##expected##Impl(const char* s1, const char* s2, \ const char* names) { \ bool equal = s1 == s2 || (s1 && s2 && !func(s1, s2)); \ if (equal == expected) return NULL; \ else { \ strstream ss; \ if (!s1) s1 = ""; \ if (!s2) s2 = ""; \ ss << #name " failed: " << names << " (" << s1 << " vs. " << s2 << ")"; \ return new string(ss.str(), ss.pcount()); \ } \ } DEFINE_CHECK_STROP_IMPL(CHECK_STREQ, strcmp, true) DEFINE_CHECK_STROP_IMPL(CHECK_STRNE, strcmp, false) DEFINE_CHECK_STROP_IMPL(CHECK_STRCASEEQ, strcasecmp, true) DEFINE_CHECK_STROP_IMPL(CHECK_STRCASENE, strcasecmp, false) #undef DEFINE_CHECK_STROP_IMPL int posix_strerror_r(int err, char *buf, size_t len) { // Sanity check input parameters if (buf == NULL || len <= 0) { errno = EINVAL; return -1; } // Reset buf and errno, and try calling whatever version of strerror_r() // is implemented by glibc buf[0] = '\000'; int old_errno = errno; errno = 0; char *rc = reinterpret_cast<char *>(strerror_r(err, buf, len)); // Both versions set errno on failure if (errno) { // Should already be there, but better safe than sorry buf[0] = '\000'; return -1; } errno = old_errno; // POSIX is vague about whether the string will be terminated, although // is indirectly implies that typically ERANGE will be returned, instead // of truncating the string. This is different from the GNU implementation. // We play it safe by always terminating the string explicitly. buf[len-1] = '\000'; // If the function succeeded, we can use its exit code to determine the // semantics implemented by glibc if (!rc) { return 0; } else { // GNU semantics detected if (rc == buf) { return 0; } else { buf[0] = '\000'; #if defined(OS_MACOSX) || defined(OS_FREEBSD) || defined(OS_OPENBSD) if (reinterpret_cast<intptr_t>(rc) < sys_nerr) { // This means an error on MacOSX or FreeBSD. return -1; } #endif strncat(buf, rc, len-1); return 0; } } } LogMessageFatal::LogMessageFatal(const char* file, int line) : LogMessage(file, line, FATAL) {} LogMessageFatal::LogMessageFatal(const char* file, int line, const CheckOpString& result) : LogMessage(file, line, result) {} LogMessageFatal::~LogMessageFatal() { Flush(); LogMessage::Fail(); } void InitGoogleLogging(const char* argv0) { glog_internal_namespace_::InitGoogleLoggingUtilities(argv0); } void ShutdownGoogleLogging() { glog_internal_namespace_::ShutdownGoogleLoggingUtilities(); LogDestination::DeleteLogDestinations(); delete logging_directories_list; logging_directories_list = NULL; } _END_GOOGLE_NAMESPACE_
34.760088
85
0.653965
ant0ine
44610cf127b3f8fa4ef5ac32e46ded27ec671314
3,371
hpp
C++
rocprim/include/rocprim/device/device_merge_sort_config.hpp
arsenm/rocPRIM
02d6006a7951c53ecfd245200d58809d3eee0b48
[ "MIT" ]
null
null
null
rocprim/include/rocprim/device/device_merge_sort_config.hpp
arsenm/rocPRIM
02d6006a7951c53ecfd245200d58809d3eee0b48
[ "MIT" ]
null
null
null
rocprim/include/rocprim/device/device_merge_sort_config.hpp
arsenm/rocPRIM
02d6006a7951c53ecfd245200d58809d3eee0b48
[ "MIT" ]
null
null
null
// Copyright (c) 2018 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #ifndef ROCPRIM_DEVICE_DEVICE_MERGE_SORT_CONFIG_HPP_ #define ROCPRIM_DEVICE_DEVICE_MERGE_SORT_CONFIG_HPP_ #include <type_traits> #include "../config.hpp" #include "../detail/various.hpp" #include "config_types.hpp" /// \addtogroup primitivesmodule_deviceconfigs /// @{ BEGIN_ROCPRIM_NAMESPACE /// \brief Configuration of device-level merge primitives. /// /// \tparam BlockSize - block size used in merge sort. template<unsigned int BlockSize> using merge_sort_config = kernel_config<BlockSize, 1>; namespace detail { template<class Key, class Value> struct merge_sort_config_803 { static constexpr size_t key_value_size = sizeof(Key) + sizeof(Value); static constexpr unsigned int item_scale = ::rocprim::detail::ceiling_div<unsigned int>(key_value_size, 8); using type = merge_sort_config<::rocprim::max(256U, 1024U / item_scale)>; }; template<class Key> struct merge_sort_config_803<Key, empty_type> { static constexpr unsigned int item_scale = ::rocprim::detail::ceiling_div<unsigned int>(sizeof(Key), 8); using type = merge_sort_config<::rocprim::max(256U, 1024U / item_scale)>; }; template<class Key, class Value> struct merge_sort_config_900 { static constexpr size_t key_value_size = sizeof(Key) + sizeof(Value); static constexpr unsigned int item_scale = ::rocprim::detail::ceiling_div<unsigned int>(key_value_size, 16); using type = merge_sort_config<::rocprim::max(256U, 1024U / item_scale)>; }; template<class Key> struct merge_sort_config_900<Key, empty_type> { static constexpr unsigned int item_scale = ::rocprim::detail::ceiling_div<unsigned int>(sizeof(Key), 16); using type = merge_sort_config<::rocprim::max(256U, 1024U / item_scale)>; }; template<unsigned int TargetArch, class Key, class Value> struct default_merge_sort_config : select_arch< TargetArch, select_arch_case<803, merge_sort_config_803<Key, Value>>, select_arch_case<900, merge_sort_config_900<Key, Value>>, merge_sort_config_900<Key, Value> > { }; } // end namespace detail END_ROCPRIM_NAMESPACE /// @} // end of group primitivesmodule_deviceconfigs #endif // ROCPRIM_DEVICE_DEVICE_MERGE_SORT_CONFIG_HPP_
33.71
80
0.750816
arsenm
446236206dc9c12d0027e3f086606c1adfcaa482
934
cpp
C++
POJ/1321/12854802_AC_63ms_708kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
POJ/1321/12854802_AC_63ms_708kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
POJ/1321/12854802_AC_63ms_708kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
/** * @author Moe_Sakiya sakiya@tun.moe * @date 2018-03-01 00:07:15 * */ #include <iostream> #include <string> #include <algorithm> #include <set> #include <map> #include <vector> #include <stack> #include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; char arr[8][9]; int n, k, ans; bool vis[8]; void dfs(int nowRow, int nowCnt) { int i; if (nowCnt == k) { ans++; return; } if (nowRow == n) return; for (i = 0; i < n; i++) if (arr[nowRow][i] == '#' && vis[i] == false) { vis[i] = true; dfs(nowRow + 1, nowCnt + 1); vis[i] = false; } dfs(nowRow + 1, nowCnt); } int main(void) { ios::sync_with_stdio(false); while (~scanf("%d %d", &n, &k)) { if (n == -1 && k == -1) break; getchar(); //init ans = 0; for (int i = 0; i < n; i++) { gets(arr[i]); vis[i] = false; } dfs(0, 0); printf("%d\n", ans ); } return 0; }
15.566667
49
0.543897
BakaErii
446367cf332cb23534c2744c4dd66744d121ef60
6,354
cpp
C++
Surface_mesh_topology/benchmark/Surface_mesh_topology/path_homotopy_with_schema.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
Surface_mesh_topology/benchmark/Surface_mesh_topology/path_homotopy_with_schema.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
Surface_mesh_topology/benchmark/Surface_mesh_topology/path_homotopy_with_schema.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
#include <CGAL/Curves_on_surface_topology.h> #include <CGAL/Path_on_surface.h> #include <CGAL/Polygonal_schema.h> /////////////////////////////////////////////////////////////////////////////// [[ noreturn ]] void usage(int /*argc*/, char** argv) { std::cout<<"usage: "<<argv[0]<<" scheme [-nbdefo D] [-nbedges E] " <<" [-nbtests N] [-seed S] [-time]"<<std::endl <<" Load the given polygonal scheme (by default \"a b -a -b\")," << "compute one random path, deform it " <<"into a second path and test that the two paths are homotope." <<std::endl <<" -nbdefo D: use D deformations to generate the second path (by default a random number between 10 and 100)."<<std::endl <<" -nbedges E: generate paths of length E (by default a random number beween 10 and 100)."<<std::endl <<" -nbtests N: do N tests of homotopy (using 2*N random paths) (by default 1)."<<std::endl <<" -seed S: uses S as seed of random generator. Otherwise use a different seed at each run (based on time)."<<std::endl <<" -time: display computation times."<<std::endl <<std::endl; exit(EXIT_FAILURE); } /////////////////////////////////////////////////////////////////////////////// [[ noreturn ]] void error_command_line(int argc, char** argv, const char* msg) { std::cout<<"ERROR: "<<msg<<std::endl; usage(argc, argv); } /////////////////////////////////////////////////////////////////////////////// void process_command_line(int argc, char** argv, std::string& file, bool& withD, unsigned int& D, bool& withE, unsigned int& E, unsigned int& N, CGAL::Random& random, bool& time) { std::string arg; for (int i=1; i<argc; ++i) { arg=argv[i]; if (arg=="-nbdefo") { if (i==argc-1) { error_command_line(argc, argv, "Error: no number after -nbdefo option."); } withD=true; D=static_cast<unsigned int>(std::stoi(std::string(argv[++i]))); } else if (arg=="-nbedges") { if (i==argc-1) { error_command_line(argc, argv, "Error: no number after -nbedges option."); } withE=true; E=static_cast<unsigned int>(std::stoi(std::string(argv[++i]))); } else if (arg=="-nbtests") { if (i==argc-1) { error_command_line(argc, argv, "Error: no number after -nbtests option."); } N=static_cast<unsigned int>(std::stoi(std::string(argv[++i]))); } else if (arg=="-seed") { if (i==argc-1) { error_command_line(argc, argv, "Error: no number after -seed option."); } random=CGAL::Random(static_cast<unsigned int>(std::stoi(std::string(argv[++i])))); // initialize the random generator with the given seed } else if (arg=="-time") { time=true; } else if (arg=="-h" || arg=="--help" || arg=="-?") { usage(argc, argv); } else if (arg[0]=='-') { std::cout<<"Unknown option "<<arg<<", ignored."<<std::endl; } else { file=arg; } } if (N==0) { N=1; } } /////////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { using namespace CGAL::Surface_mesh_topology; std::string scheme="a b -a -b"; bool withD=false; unsigned int D=0; bool withE=false; unsigned int E=0; unsigned int N=1; CGAL::Random random; // Used when user do not provide its own seed. bool time=false; process_command_line(argc, argv, scheme, withD, D, withE, E, N, random, time); Polygonal_schema_with_combinatorial_map<> cm; cm.add_facet(scheme); std::cout<<"Initial map: "; cm.display_characteristics(std::cout) << ", valid=" << cm.is_valid() << std::endl; Curves_on_surface_topology<Polygonal_schema_with_combinatorial_map<> > smct(cm, time); smct.compute_minimal_quadrangulation(time); std::cout<<"Reduced map: "; smct.get_minimal_quadrangulation().display_characteristics(std::cout) << ", valid="<< smct.get_minimal_quadrangulation().is_valid() << std::endl; unsigned int nbcontractible=0; std::vector<std::size_t> errors_seeds; for (unsigned int i=0; i<N; ++i) { if (i!=0) { random=CGAL::Random(random.get_int(0, std::numeric_limits<int>::max())); } std::cout<<"Random seed: "<<random.get_seed()<<": "; if (!withE) { E=static_cast<unsigned int>(random.get_int (10, std::max(std::size_t(11), cm.number_of_darts()/10))); } if (!withD) { D=static_cast<unsigned int>(random.get_int (10, std::max(std::size_t(11), cm.number_of_darts()/10))); } Path_on_surface<Polygonal_schema_with_combinatorial_map<>> path1(cm); path1.generate_random_closed_path(E, random); std::cout<<"Path1 size: "<<path1.length()<<" (from "<<E<<" darts); "; Path_on_surface<Polygonal_schema_with_combinatorial_map<>> deformed_path1(path1); deformed_path1.update_path_randomly(D, random); std::cout<<"Path2 size: "<<deformed_path1.length()<<" (from "<<D<<" deformations)."; std::cout<<std::endl; if (smct.is_contractible(path1, time)) { ++nbcontractible; } bool res=smct.are_freely_homotopic(path1, deformed_path1, time); if (!res) { errors_seeds.push_back(random.get_seed()); } } if (errors_seeds.empty()) { if (N==1) { std::cout<<"Test OK: both paths are homotopic."<<std::endl; } else { std::cout<<"All the "<<N<<" tests OK: each pair of paths were homotopic."<<std::endl; } } else { std::cout<<"ERRORS for "<<errors_seeds.size()<<" tests among "<<N <<" (i.e. "<<(double)(errors_seeds.size()*100)/double(N)<<"%)."<<std::endl; std::cout<<"Errors for seeds: "; for (std::size_t i=0; i<errors_seeds.size(); ++i) { std::cout<<errors_seeds[i]<<" "; } std::cout<<std::endl; } std::cout<<"Number of contractible paths: "<<nbcontractible<<" among "<<N <<" (i.e. "<<(double)(nbcontractible*100)/double(N)<<"%)."<< std::endl << "==============" <<std::endl; return EXIT_SUCCESS; }
37.597633
143
0.543122
ffteja
44636aa91a85af89ce75f4d27aa12f8fe3040e19
1,274
cpp
C++
oi/Contest/2017-6/2017-6-27/gf-brute.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
oi/Contest/2017-6/2017-6-27/gf-brute.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
oi/Contest/2017-6/2017-6-27/gf-brute.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#define USE_FILE_IO #include <cstdio> #include <cstring> #include <climits> #include <algorithm> using namespace std; typedef long long i64; #define NMAX 200000 #define MOD 998244353 static int n; static int A[NMAX + 10], B[NMAX + 10]; static i64 fac[NMAX + 10]; static i64 inv[NMAX + 10]; inline i64 qpow(i64 a, i64 b) { i64 r = 1; for (; b; b >>= 1, a = a * a % MOD) { if (b & 1) r = r * a % MOD; } return r; } void initialize() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d%d", A + i, B + i); } fac[0] = 1; for (int i = 1; i <= NMAX; i++) { fac[i] = fac[i - 1] * i % MOD; } inv[NMAX] = qpow(fac[NMAX], MOD - 2); for (int i = NMAX - 1; i >= 0; i--) { inv[i] = inv[i + 1] * (i + 1) % MOD; } } int main() { #ifdef USE_FILE_IO freopen("gf.in", "r", stdin); freopen("gf.out", "w", stdout); #endif initialize(); i64 ans = 0; for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { ans = fac[A[i] + A[j] + B[i] + B[j]] * inv[A[i] + A[j]] % MOD * inv[B[i] + B[j]] % MOD; ans %= MOD; } } printf("%lld\n", ans); return 0; }
18.463768
74
0.437206
Riteme
44639c0bf345059cb6f2fe1868bb02c818ac2759
2,425
cpp
C++
gpmp2/obstacle/tests/testPlanarSDF.cpp
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
gpmp2/obstacle/tests/testPlanarSDF.cpp
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
gpmp2/obstacle/tests/testPlanarSDF.cpp
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
/** * @file testPlanarSDFutils.cpp * @author Jing Dong * @date May 8 2016 **/ #include <CppUnitLite/TestHarness.h> #include <gtsam/base/numericalDerivative.h> #include <gtsam/base/Matrix.h> #include <gpmp2/obstacle/PlanarSDF.h> #include <iostream> using namespace std; using namespace gtsam; using namespace gpmp2; double sdf_wrapper(const PlanarSDF& field, const Point2& p) { return field.getSignedDistance(p); } /* ************************************************************************** */ TEST(PlanarSDFutils, test1) { // data Matrix data; data = (Matrix(5, 5) << 1.7321, 1.4142, 1.4142, 1.4142, 1.7321, 1.4142, 1, 1, 1, 1.4142, 1.4142, 1, 1, 1, 1.4142, 1.4142, 1, 1, 1, 1.4142, 1.7321, 1.4142, 1.4142, 1.4142, 1.7321).finished(); Point2 origin(-0.2, -0.2); double cell_size = 0.1; // constructor PlanarSDF field(origin, cell_size, data); EXPECT_LONGS_EQUAL(5, field.x_count()); EXPECT_LONGS_EQUAL(5, field.y_count()); EXPECT_DOUBLES_EQUAL(0.1, field.cell_size(), 1e-9); EXPECT(assert_equal(origin, field.origin())); // access PlanarSDF::float_index idx; idx = field.convertPoint2toCell(Point2(0, 0)); EXPECT_DOUBLES_EQUAL(2, idx.get<0>(), 1e-9); EXPECT_DOUBLES_EQUAL(2, idx.get<1>(), 1e-9); EXPECT_DOUBLES_EQUAL(1, field.signed_distance(idx), 1e-9) idx = field.convertPoint2toCell(Point2(0.18, -0.17)); // tri-linear interpolation EXPECT_DOUBLES_EQUAL(0.3, idx.get<0>(), 1e-9); EXPECT_DOUBLES_EQUAL(3.8, idx.get<1>(), 1e-9); EXPECT_DOUBLES_EQUAL(1.567372, field.signed_distance(idx), 1e-9) idx = boost::make_tuple(1.0, 2.0); EXPECT(assert_equal(Point2(0.0, -0.1), field.convertCelltoPoint2(idx))); // gradient Vector2 grad_act, grad_exp; Point2 p; p = Point2(-0.13, -0.14); field.getSignedDistance(p, grad_act); grad_exp = numericalDerivative11(std::function<double(const Point2&)>( boost::bind(sdf_wrapper, field, _1)), p, 1e-6); EXPECT(assert_equal(grad_exp, grad_act, 1e-6)); p = Point2(0.18, 0.12); field.getSignedDistance(p, grad_act); grad_exp = numericalDerivative11(std::function<double(const Point2&)>( boost::bind(sdf_wrapper, field, _1)), p, 1e-6); EXPECT(assert_equal(grad_exp, grad_act, 1e-6)); } /* ************************************************************************** */ /* main function */ int main() { TestResult tr; return TestRegistry::runAllTests(tr); }
28.529412
85
0.635876
Cryptum169
4464cb0f0394ff009d632a6a195a4c0851dc8e3d
1,168
cpp
C++
src/rectangle.cpp
yudhik11/OpenGL-PacmanKiller
2d7ac47c1560223cdaa7221753f8b41af9856113
[ "MIT" ]
null
null
null
src/rectangle.cpp
yudhik11/OpenGL-PacmanKiller
2d7ac47c1560223cdaa7221753f8b41af9856113
[ "MIT" ]
null
null
null
src/rectangle.cpp
yudhik11/OpenGL-PacmanKiller
2d7ac47c1560223cdaa7221753f8b41af9856113
[ "MIT" ]
null
null
null
#include "rectangle.h" #include "main.h" Rectangle::Rectangle(float x, float y,float x1, float y1,float length, float width, color_t color) { this->position = glm::vec3(x, y, 0); const GLfloat vertex_buffer_data[] = { x1, y1, 0, // vertex 1 x1, y1+width, 0, // vertex 2 x1+length, y1+width, 0, // vertex 3 x1+length, y1+width, 0, // vertex 3 x1, y1, 0, // vertex 1 x1+length, y1, 0, // vertex 1 }; this->object = create3DObject(GL_TRIANGLES, 6, vertex_buffer_data, color, GL_FILL); } void Rectangle::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(0, 0, 1)); rotate = rotate * glm::translate(glm::vec3(0, 0, 1)); Matrices.model *= (translate * rotate); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object); } //void Rectangle::set_position(float x, float y) { // this->position = glm::vec3(x, y, 0); //}
35.393939
100
0.603596
yudhik11